diff --git a/docs/manual/index.md b/docs/manual/index.md index c19b691a..c749cb1b 100644 --- a/docs/manual/index.md +++ b/docs/manual/index.md @@ -36,7 +36,10 @@ Lumina is growing, and this is what works right now: - **Media libraries that scan themselves.** Point Lumina at a folder or a drive, tell it what kind of media lives there, and it gets to work discovering and indexing what it finds. Scans run in the background, report their progress as they go, and can be started, cancelled or resumed. - **Written content.** Add a written content library and Lumina scans it, cataloguing the books and e-books it contains and dressing them up with metadata for browsing in the client. Open one and it renders in the browser through a reader plugin; the EPUB and PDF readers are bundled and can be enabled per library. -- **Music.** Add a music library and Lumina indexes the artists, albums and tracks it contains, reading metadata from the tags inside the audio files. If you want more, enable a metadata provider and Lumina fills in the gaps from online sources, and artwork can come from your folders or from remote sources. +- **Music.** Add a music library and Lumina indexes the artists, albums and tracks it contains, reading metadata from the tags inside the audio files. If you want more, enable a metadata provider and Lumina fills in the gaps from online sources, and artwork can come from your folders or from remote sources. You can also build your own playlists, order them the way you want and play them in the browser. +- **Favorites.** Mark the artists, albums, tracks and books you love as favorites, from their lists or from the player, and come back to them from one page, filtered by kind. Favorites are private to your account. +- **Statistics across your media.** See how much you consumed, how many sessions counted and completed, and which books and music you consumed recently and most, all in one place. Tags and genres are grouped across media kinds and shown lowercase, and administrators can look at any user or at the whole server. +- **Resume where you left off.** A book library can remember the section you reached when its progress tracking is on, which is the default for books. A short reading may not be tracked. A music library can remember the position of a track when you turn progress tracking on for it. - **Metadata and artwork from plugins.** Plugins do the knowing. They supply the metadata and the artwork of a library, and you decide, library by library, which ones are switched on and which one wins when several of them recognize the same item. - **A file system browser.** Reach the drives, folders and files of the server machine from anywhere you can open the client, as if you were sitting right in front of it. Poke around, walk a path to its root or to its parent, and let Lumina generate thumbnails for what it finds. - **Accounts, roles, permissions and policies.** Create accounts, sign in with a password and optional two factor authentication, and hand out access through roles, fine grained permissions and policies that decide who may reach which library or content. Administrators manage all of it from the administration area. diff --git a/docs/manual/installation/index.md b/docs/manual/installation/index.md index dc41f332..f2a933f3 100644 --- a/docs/manual/installation/index.md +++ b/docs/manual/installation/index.md @@ -21,16 +21,17 @@ Lumina ships as two applications that talk to each other over the network: the * > **Not production ready yet.** Lumina is pre-alpha software. Updates are one way and can lose Lumina's data, so read [Updating](#updating) before you install or upgrade. -There are **two ways to install Lumina**. Pick one: +There are **two ways to run Lumina**. Pick one: - **[Option A: run with Docker Compose](#option-a-run-with-docker-compose)**, the recommended route, where a single command brings up the whole system. -- **[Option B: build and run manually](#option-b-build-and-run-manually)**, if you would rather run the applications directly, without containers. +- **[Option B: run the applications directly](#option-b-run-the-applications-directly)**, whether you install a release package or build from source, if you would rather run them without containers. Everything from Configuration onward applies to whichever route you chose. ## Before you start -- **Docker**, if you want the container route, or the **.NET 10 SDK** if you want to build and run from source. +- **Docker**, if you want the container route. For a non-container install, you need the Lumina application files, from a release package or installer, or from your own build, plus the **.NET 10 runtime** unless that package is self-contained. The **.NET 10 SDK** is only needed if you build from source. +- **ffmpeg**, for any non-container install, however you obtained the application files. The API server uses it to remux or transcode audio that the browser cannot play as stored. The Docker API container image already includes it. - By default the **web client listens on port `5012`** and the **API on port `5214`**. You can change either, as long as the two agree on where the API is (see [Configuration](#configuration)). - For anything reachable beyond your own machine, put a **reverse proxy** in front to terminate TLS and forward to the web client. - Lumina needs **no external database server**. It keeps its data in a local SQLite file that is created automatically. @@ -77,15 +78,15 @@ The development configuration embeds throwaway keys so the container route works Set them as environment variables on the `lumina-api` and `lumina-web` services in your own compose file or orchestration. -## Option B: build and run manually +## Option B: run the applications directly -With the .NET 10 SDK installed, build the solution from the `src` directory: +Use a release package or installer when one is available, or, with the .NET 10 SDK installed, build the solution from the `src` directory: ```bash dotnet build Lumina.sln ``` -Run the API and the web client. In development, their addresses come from each project's `launchSettings.json` (`http://localhost:5214` and `http://localhost:5012`). When you run a published build directly on a host, set the addresses yourself, either with `ASPNETCORE_URLS` or with `ASPNETCORE_HTTP_PORTS`: +Run the API and the web client from the installed release package or from the published build. In development, their addresses come from each project's `launchSettings.json` (`http://localhost:5214` and `http://localhost:5012`). When you run a published build directly on a host, set the addresses yourself, either with `ASPNETCORE_URLS` or with `ASPNETCORE_HTTP_PORTS`: ```bash ASPNETCORE_HTTP_PORTS=5012 dotnet Lumina.Presentation.Web.dll @@ -93,6 +94,8 @@ ASPNETCORE_HTTP_PORTS=5012 dotnet Lumina.Presentation.Web.dll The API creates its SQLite database (`Lumina.db`) next to its own binary and applies any pending migrations at startup, so the first launch sets up the schema on its own. +The API server needs **ffmpeg** on its `PATH` to normalize audio that a player cannot play as stored. Install it with your platform's package manager, or point `TranscodingSettings:FfmpegPath` at the binary if it is somewhere else. + ## Configuration Each application reads its own `appsettings.json` and an optional environment specific `appsettings.development.json`, and environment variables override both. The API also loads the `appsettings.shared.json` file (and its development variant), which holds the server side settings that are not specific to a single layer, such as the media, plugins and theme options. @@ -112,10 +115,15 @@ The settings that matter most when installing: | `PluginsSettings:Directory` | API server | Folder holding installed plugin assemblies, `plugins` by default. | | `ThemeEngine:StoragePath`, `ThemeEngine:BundledThemesPath`, `ThemeEngine:DefaultThemeId` | API server | Where installed and bundled themes live, and which theme is activated by default. | | `ThemeEngine:MaxArchiveBytes`, `MaxExpandedBytes`, `MaxSingleFileBytes`, `MaxEntries` | API server | Limits enforced on uploaded theme packs. | +| `TranscodingSettings:FfmpegPath`, `MaxConcurrentJobs`, `MaxConcurrentJobsPerUser`, `MaxCacheBytes`, `JobTimeoutSeconds`, `EvictionGraceSeconds`, `CacheDirectory` | API server | Where the ffmpeg binary is, how many audio normalization jobs may run at once in total and per user, the maximum size of the normalized audio cache in bytes, how long a single job may take in seconds, how long a freshly produced or served cache entry is protected from eviction, and where the cache is stored. When `CacheDirectory` is absent, a private directory under the API account's temporary directory is used. | | `Telemetry:Enabled`, `Telemetry:Otlp:Endpoint`, `Telemetry:TraceSampleRatio`, `Telemetry:ConsoleExporterEnabled` | API server and web client | Telemetry behavior. The OTLP endpoint also falls back to the `OTEL_EXPORTER_OTLP_ENDPOINT` environment variable. Again, while telemetry is enabled as a feature, nothing is sent anywhere. | The `LOG_PATH` environment variable selects where the rolling log files are written. +The normalized audio cache must not be placed inside `MediaSettings:RootDirectory`, because that directory is served at the `/media` route, and it must not contain that directory either, because cleaning the cache would remove the media. The startup configuration also rejects a cache directory that is a filesystem root, the application directory or one of its parents, or that overlaps the logs or plugins directories. The default uses a private directory under the API account's temporary directory and avoids all of these. The cache holds transcoded or remuxed audio only while it is useful: at API startup only the entries the cache itself owns are removed, and a directory is cleaned only when it carries Lumina's cache marker file (`.lumina-transcoding-cache`) or is empty, so a directory that belongs to something else is left untouched. Its total footprint is capped by `TranscodingSettings:MaxCacheBytes`, but an entry that is still being read, or that was just produced when the cache was already at the limit, is kept until it can be removed, so the cache can exceed the cap temporarily. The cache is not part of the media library. + +The default cache directory is scoped to the API account, but the coordinator, the running jobs and the startup cleanup are per process. Run a single API process per account and host, or configure a distinct `CacheDirectory` for each instance. Playback delivery handles are also process local: in a load balanced multi-instance deployment, a track's manifest and its subsequent segment requests must reach the same API instance, so configure sticky routing for them as described for SignalR below. On a multi-user Unix host the directory is created with private permissions, and a pre-existing directory owned by another account is treated as unavailable rather than reused or deleted. + ### Keeping the two applications in step The web client and the API must agree on two addresses, and getting them wrong is the usual cause of a client that loads but never updates live: diff --git a/docs/manual/managing-libraries/index.md b/docs/manual/managing-libraries/index.md index bbd1e238..0c1f1688 100644 --- a/docs/manual/managing-libraries/index.md +++ b/docs/manual/managing-libraries/index.md @@ -51,6 +51,8 @@ Open the Libraries management page, choose to add a library, and fill in the for | Download metadata from the web | on | Whether Lumina may look up the metadata of the items online. This only has an effect when a metadata provider is enabled for the library (see [Plugins](../plugins/index.md)). | | Save metadata in media directories | off | Whether the metadata Lumina fetches is also written next to your media files, so other tools can read it. This is the one option that writes into your media folders. | | Skip unchanged directories during scan | off | An opt-in speedup that skips folders whose own last-modified time has not changed since the last scan. Editing the contents of an existing file in place, without adding, removing or renaming anything in that folder, leaves the folder's time untouched, so that edit can be missed while it is on. | +| Track consumption progress | the type default | Whether the latest playback or reading position of the library's items is remembered, so a user can resume where they left off. | +| Completion threshold | the type default | The percentage of an item that must be consumed for a stopped session to be recorded as completed. Empty means completion is recorded only when it is reported explicitly. | | Path template | the type's ideal structure | Tells Lumina how your folders are arranged on disk. Unless you customize it, it holds the default template of the library type, which is exactly the structure Lumina expects. Optional, and explained in full below. | A library that is disabled or locked is never scanned, so those two settings double as a pause switch, and `Locked` also freezes edits. @@ -130,6 +132,36 @@ Editing a library reopens the same form, and changes take effect on the next sca - Changing the **type** of an existing library also reconciles the metadata, artwork and reader provider settings of that library, so they match the plugins that support the new type. - Changing the **content locations** takes effect on the next scan. Items found under a location you removed are dropped from the catalogue, along with the metadata and artwork Lumina had stored for them, and items under a location you added are picked up. +## Progress tracking and completion thresholds + +Two settings on a library decide whether Lumina remembers where you stopped and when a session is complete. They apply to every user of that library. + +- **Track consumption progress** decides whether the latest playback or reading position of an item is remembered and offered as the resume position. When it is off, Lumina stores no resume point for the library's items. +- **Completion threshold** is the percentage of an item at which a stopped session is recorded as completed instead of stopped. It is set only while tracking is on, and it can be left empty. + +When a session ends, the settings decide its status: + +- **Tracking off**: the session is recorded as stopped, its position is not saved, and the completion threshold is not checked. +- **Tracking on, no threshold**: the session is recorded as stopped and its position is saved, so it can be resumed. It is completed only when completion is reported explicitly. +- **Tracking on with a threshold**: a stop at or above the threshold is recorded as completed and removes the resume point. A stop below the threshold is recorded as stopped and keeps the resume point. + +The defaults by library type are: + +| Library category | Track progress | Completion threshold | +| --- | --- | --- | +| Music audio (Music, Remix, SoundEffect, CoverSongAudio, LiveRecordingAudio, InterviewAudio) | no | none | +| Photo | no | none | +| Written content (Book, EBook, ComicBook, Magazine, Newspaper, Manga, GraphicNovel, AcademicPaper, SheetMusic) | yes | 100 | +| Video (TvShow, Movie, Documentary, Anime, ConcertVideo, TutorialVideo, HomeVideo, YouTubeVideo, MusicVideo, LiveRecordingVideo, InterviewVideo, CoverSongVideo) | yes | 90 | +| Audiobook and podcast (Audiobook, PodcastAudio, PodcastVideo) | yes | 95 | +| Other, non-media or unknown | no | none | + +For now, only Book and Music libraries produce a working catalogue, so the written content and music defaults are the ones you will meet. Other library types can still be created, and their rows are the defaults they will use when their catalogues arrive. A value you set on a library always wins after the library is created. + +When you add a library without changing these fields, Lumina applies the default of its type. When you turn tracking on for a library whose type has no default threshold, the threshold stays empty and completion is recorded only when it is reported explicitly. An empty threshold is not zero: zero would complete every stopped session as soon as it stops. + +The threshold must be a whole number from 0 to 100, and the form refuses any other value. Changing it affects sessions that stop afterwards; a session that was already recorded keeps the status it was recorded with. Turning tracking off clears the threshold. The setting does not change what a library can play or read, only whether a resume point is kept and how a stopped session is recorded. + ## Deleting a library Deleting a library removes it from Lumina: its configuration, its scan history, the items in its catalogue, their metadata and the artwork Lumina stored for them, and its provider settings. The cover image Lumina copied into its own storage is removed as well. Your original files are left untouched. @@ -160,8 +192,11 @@ These are per user settings, each user changes their own from the settings page - **`Skip unchanged directories during scan` can miss in-place edits.** It trusts each folder's own last-modified time, so editing the contents of an existing file without adding, removing or renaming anything in its folder leaves the folder unchanged and it gets skipped. Adding, removing or renaming a file does change the folder, and is still seen. - **`Locked` blocks everything.** A locked library is not scanned and not updated, including by the scheduler. - **`Disabled` hides the library.** A disabled library is neither shown on the dashboard nor touched. -- **Deleting a library removes Lumina's catalogue for it.** The files remain, but the metadata, artwork and history Lumina held for that library do not. +- **Deleting a library removes Lumina's catalogue for it.** The files remain, but the metadata and artwork Lumina held for that library do not. Consumption history and resume points are kept as records of what was consumed. The history shows the items as unavailable until you delete it. **Remove from continue watching** removes every resume point of the selected user, not only the ones from the deleted library. - **Removing a folder from a library, or deleting a file, removes its catalogued items on the next scan.** The catalogue tracks what is on disk, so what disappears from disk also disappears from Lumina, along with the metadata and artwork Lumina stored for it. - **Changing the path template can change how items are read.** Re-scan and check the results after a change. -- **Only Book and Music libraries scan today.** Other types cannot be created into a working library yet. +- **Tracking off means no resume points.** A library that does not track consumption progress never offers a saved position, even if a client reports one. +- **An empty completion threshold is not zero.** Empty means completion is recorded only when it is reported explicitly, while zero completes a stopped session immediately. +- **Deleting history and removing resume points are separate.** Clearing a user's history removes all of that user's recorded sessions and keeps their resume points, while **Remove from continue watching** removes all of that user's resume points and keeps their history. Neither action is limited by the library, media kind or date filters of the statistics page. +- **For now, only Book and Music libraries produce a working catalogue.** Other types can be created, but they do not scan into a usable catalogue yet. - **Not every book format is readable.** Recognized formats are indexed, but only those with an enabled reader plugin can be opened in the browser. diff --git a/docs/manual/using-lumina/index.md b/docs/manual/using-lumina/index.md index 62a45c37..2e157bfb 100644 --- a/docs/manual/using-lumina/index.md +++ b/docs/manual/using-lumina/index.md @@ -60,6 +60,8 @@ The reader opens the book in the browser and gives you a small toolbar and the b A book opens only through an enabled reader for its format. The EPUB and PDF readers are bundled and can be enabled for a library. A scanned PDF has no text to extract, so it can only be shown as page images, which is what the `Render PDFs as images` setting turns on. +Book libraries track consumption progress by default. Reopening a book continues from the last section of a tracked reading session. A short reading, such as opening a book, turning a few pages and closing it, may not reach the minimum needed to be tracked, so it can leave no saved position and the book opens at the beginning. Reaching the library's completion threshold, 100 percent for a book library by default, completes the reading session and removes the saved position. The threshold is a per-library setting, described in [Managing Libraries](../managing-libraries/index.md). + ## Browsing your music Opening a music library shows a page with the library title, a search box, a sort toggle, a count of items, a grid of artist cards, an alphabetical picker down the side, and pagination at the bottom. @@ -69,15 +71,67 @@ Opening a music library shows a page with the library title, a search box, a sor - **The alpha picker** jumps to names starting with a chosen character. It offers All, then the number and symbol keys, then A to Z. You can also press a letter key to filter, and press Escape to clear the filter. - **Pagination** splits the list into pages when you have it enabled, with previous and next buttons and a page indicator. When it is off, the whole list is shown and the count is the total. -Each artist is a card; selecting it opens the artist's page, and the card's actions menu offers **View details** and **Delete**. +Each artist is a card; selecting it opens the artist's page, and the card's actions menu offers **View details**, **Play**, **Shuffle**, **Add to playlist** and **Delete**. The heart on the card marks the artist as a favorite. The artist page is also where you edit the artist. It lists the artist's albums as cards, each leading to its own album page, followed by the artist's general information, contributors, ratings, genres, tags, aliases, areas and identifiers. The album page holds the album's information and its tracks, and the track page holds the track's details. The album page also shows the artwork Lumina stored for the album as a strip of thumbnails beside the main image, and selecting a thumbnail displays that image in place of the cover. Deleting an artist, album or track removes it from Lumina's catalogue; your files are not touched. +The music pages also play what they show. The artist page has a **Play all** control that plays the artist's releases in the order the page presents them, one release after another. The actions menu of a music library card on the home page, of an artist card, and of an album card offers **Play** and **Shuffle**. Play starts the library at its first artist and continues through the remaining artists in artist page order, starts the artist's discography in the order the artist page presents it, or starts the release in disc and track order. Shuffle starts the library, the artist's discography or the release with a list of up to 100 tracks sampled uniformly at random from every track of that scope, and continues in random order without repeating a track that is already queued. The album page has a **Play album** control that plays the release in disc and track order, and every track row has its own play control that plays just that track. The track page has a **Play track** control for the track it shows. Every track row on the album page also has an actions menu: **Add to playlist** opens the playlist picker for that track, **Add to play queue** appends it to the end of the player queue or starts it when the queue is empty, and **Play all from here** replaces the queue with that track and the rest of the album and starts playing. Starting playback opens the player bar at the bottom of the window. It keeps playing while you move between pages, and the bar shows the track name, with the album name underneath when the track belongs to a named album, the progress of the current track, a segmented VU meter that follows the level of the track, and the volume, together with previous, play or pause, stop, next and repeat controls. When you expand it, it also shows the cover art, the current track name, the release type, the release name and year, the artist name, and a carousel of the album's stored artwork, next to the queue, where every entry carries its album cover, including when only one track is queued. Selecting an artwork in the carousel shows it as the main cover. The expanded queue moves the current track to the top whenever playback advances, so it stays visible even in a long list. The current track's favorite is the heart on the bar between the repeat and mute controls, and every entry of the expanded queue carries its own heart. The queue's own playlist picker appends the whole queue, in order, to one of your playlists. The double chevron at the right points up to expand the bar and down to collapse it. Stop is the square control next to play or pause; in the condensed bar it stops playback and slides the bar out of view. + +Music libraries do not remember positions by default. When progress tracking is turned on for a music library, starting a track resumes it from the last reported position, and stopping it at or above the library's completion threshold, when one is set, completes the session instead of saving a position. + +## Playlists + +The **Playlists** entry under Audio opens your playlists. A playlist survives signing out and back in, but the player queue itself does not. A full page reload still starts with an empty queue and a hidden player. + +From the playlists page you can open a playlist or select **Create** to open the dedicated page that creates a new playlist with a name and an optional description. Selecting an existing playlist opens its own page, which shows its tracks in order and lets you: + +- **Add a track** by choosing a music library, then an artist, an album and a track, and selecting **Add**. A track can appear more than once in the same playlist. +- **Reorder the tracks** by dragging a row by its handle, or with the up and down controls on each row. The order is saved immediately. +- **Remove a track** from the playlist. The track itself, and the file behind it, are not touched. +- **Play a single track** with its play control, or **Play playlist** to hand the whole ordered list to the player in one go. Each row also has a heart that marks the track as a favorite and a plus control that adds it to another playlist. While something is playing, the expanded player's **Add to playlist** button appends its current queue to one of your playlists. +- **Add a whole library, artist or album** from the card menu of its page: choose **Add to playlist**, pick a playlist, and the tracks of that scope are appended in catalogue order. The same dialog lets you create a playlist when you have none yet. +- **Edit the name and description**, and **delete the playlist** when you no longer need it. Deleting a playlist never deletes any track. + +The playlist reflects the catalogue at the moment you open it. If a track is deleted from a library after it was added to a playlist, its row stays in the playlist as an unavailable track so you can remove it deliberately. Long playlists are shown in pages; select **Load more** to show the next page. + +## 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, on its row on an album page or in a playlist, on the player bar for the current track, or on any queue entry of the player, 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. + +## Statistics + +The **Statistics** entry under Library opens your consumption statistics. It covers every media kind the server can consume, with music and book sessions appearing side by side and more kinds joining as their catalogues arrive. The statistics are built from the sessions your player and reader report, belong to your account, and are not shared with other regular users; administrators can view any user's statistics. + +A session counts towards the statistics when it completes, or when it reaches the counting rule of its kind. A music track counts after 30 seconds, and a book counts after more than 5 consecutive pages in the reader. A stopped session below the rule is stored but not counted, while the total consumed time still includes the time you spent. Completion is separate from counting: a session can count without the library considering the item complete. + +The page shows: + +- **Total consumed time**, **counted sessions**, **completed sessions** and the **completion rate** of the selected user. +- **By media kind**, the same totals broken down per kind. +- **Genres** and **tags** as bars, grouped across media kinds and shown lowercase. A genre or tag shared by a book and a track appears once. +- **Recently consumed** and **most consumed**, with the kind of each item, its title, creator, collection, cover, last consumption time, counted sessions, completed sessions and consumed time. +- **Filters** for the library, the media kind and a date range, applied to every section. + +Each history row has **Delete from history**, which removes every recorded session of that item. The page also has **Clear history**, which removes every recorded session of the selected user, and **Remove from continue watching**, which removes every saved resume point of the selected user. Each action asks for confirmation, and the page reloads after it. Deleting history does not remove resume points, and removing resume points does not delete history. The resume points themselves are the saved positions described under reading and listening; the statistics page does not list them, it only clears them. + +An administrator sees a user picker with **Me**, every user, and **All users**. Selecting another user shows that user's statistics. Selecting **All users** shows the combined totals and a per-user table, because the history lists and the genre and tag breakdown are only meaningful per user. A regular user sees no picker and only their own statistics. Administrators can read and delete the history of any user; regular users can only read and delete their own. + +An item that was deleted, or whose library you can no longer access, keeps its place in the counts but is shown as unavailable, without display details. Select **Retry** when a section does not load. + ## 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 @@ -87,6 +141,8 @@ Wherever Lumina needs a folder or a file from the server, it opens the file syst The tools section holds your settings and the language picker. -Your **settings** decide how lists and books behave for you. Enable pagination and the number of items per page control how browsing is split. The alpha picker option decides whether titles beginning with "The" are filed under the next word. Theme caching decides whether the theme is fetched fresh each time. Rendering PDFs as images and preserving book styles shape how books are shown, and the metadata and artwork aggregation options decide whether missing fields are completed from your other providers. The ones that touch libraries are described in more detail in [Managing Libraries](../managing-libraries/index.md). +Your **settings** decide how lists and books behave for you. Enable pagination and the number of items per page control how browsing is split. The alpha picker option decides whether titles beginning with "The" are filed under the next word. Theme caching decides whether the theme is fetched fresh each time. Rendering PDFs as images and preserving book styles shape how books are shown, and the metadata and artwork aggregation options decide whether missing fields are completed from your other providers. A final group of options shapes playback: whether the player keeps downloading while it is paused (for a track the server has to normalize, this keeps its bounded one-segment lookahead filled rather than downloading the whole file), whether it continues automatically at the end of an album or artist, whether consecutive tracks play without a gap, how ReplayGain normalizes loudness, and the quality cap used when the server has to normalize a track. That cap applies only when the server re-encodes a track into a lossy format; a remux only repackages the stored audio, and a lossless delivery is not reduced. The ones that touch libraries are described in more detail in [Managing Libraries](../managing-libraries/index.md). + +The **VU meter** group shapes the meter of the player bar. Orientation lays its channels out as columns that grow upwards or rows that grow to the right. Segments per channel sets how finely each channel is divided, and Segment gap sets the space between segments and channels. The medium and high thresholds decide the level at which a segment changes color; the high threshold cannot be lower than the medium one. Show peak keeps a mark at the loudest recent level of each channel. Peak hold is how long that mark stays in place before it falls, in milliseconds, and Level falloff and Peak falloff are how quickly the bars and the peak marks drop once the sound gets quieter, in level units per second. Larger falloff values drop faster. The meter follows the level of the track itself, so muting the player or moving the volume slider does not change the height of the bars, and saving these settings applies them to the player without reloading the page. The **language** picker switches the interface between the languages Lumina ships with, and remembers your choice. diff --git a/docs/technical/api/favorites/Api.Favorites.md b/docs/technical/api/favorites/Api.Favorites.md new file mode 100644 index 00000000..733c5c00 --- /dev/null +++ b/docs/technical/api/favorites/Api.Favorites.md @@ -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 +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 +``` + +| 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 +``` + +| 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 +``` + +| 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, the kind is `None`, 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. diff --git a/docs/technical/api/library/audio-library/music-library/Api.Albums.md b/docs/technical/api/library/audio-library/music-library/Api.Albums.md index cbe5d852..c69b3693 100644 --- a/docs/technical/api/library/audio-library/music-library/Api.Albums.md +++ b/docs/technical/api/library/audio-library/music-library/Api.Albums.md @@ -296,6 +296,7 @@ POST api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b { "id": "e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f", "artistId": "d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a", + "artistName": "Queen", "libraryId": "3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a", "metadata": { "title": "A Night at the Opera", @@ -376,6 +377,7 @@ POST api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b "albumId": "e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f", "libraryId": "3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a", "path": "/music/queen/a-night-at-the-opera/01-bohemian-rhapsody.flac", + "container": "FLAC", "metadata": { "title": "Bohemian Rhapsody", "originalTitle": "Bohemian Rhapsody", @@ -454,6 +456,7 @@ POST api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b "albumId": "e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f", "libraryId": "3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a", "path": "/music/queen/a-night-at-the-opera/07-youre-my-best-friend.flac", + "container": "FLAC", "metadata": { "title": "You're My Best Friend", "originalTitle": "You're My Best Friend", @@ -559,6 +562,7 @@ GET api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b- { "id": "e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f", "artistId": "d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a", + "artistName": "Queen", "libraryId": "3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a", "metadata": { "title": "A Night at the Opera", @@ -639,6 +643,7 @@ GET api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b- "albumId": "e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f", "libraryId": "3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a", "path": "/music/queen/a-night-at-the-opera/01-bohemian-rhapsody.flac", + "container": "FLAC", "metadata": { "title": "Bohemian Rhapsody", "originalTitle": "Bohemian Rhapsody", @@ -717,6 +722,7 @@ GET api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b- "albumId": "e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f", "libraryId": "3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a", "path": "/music/queen/a-night-at-the-opera/07-youre-my-best-friend.flac", + "container": "FLAC", "metadata": { "title": "You're My Best Friend", "originalTitle": "You're My Best Friend", @@ -861,6 +867,7 @@ GET api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b- { "id": "e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f", "artistId": "d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a", + "artistName": "Queen", "libraryId": "3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a", "metadata": { "title": "A Night at the Opera", @@ -941,6 +948,7 @@ GET api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b- "albumId": "e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f", "libraryId": "3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a", "path": "/music/queen/a-night-at-the-opera/01-bohemian-rhapsody.flac", + "container": "FLAC", "metadata": { "title": "Bohemian Rhapsody", "originalTitle": "Bohemian Rhapsody", @@ -1019,6 +1027,7 @@ GET api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b- "albumId": "e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f", "libraryId": "3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a", "path": "/music/queen/a-night-at-the-opera/07-youre-my-best-friend.flac", + "container": "FLAC", "metadata": { "title": "You're My Best Friend", "originalTitle": "You're My Best Friend", @@ -1203,6 +1212,7 @@ PUT api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b- { "id": "e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f", "artistId": "d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a", + "artistName": "Queen", "libraryId": "3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a", "metadata": { "title": "A Night at the Opera", @@ -1283,6 +1293,7 @@ PUT api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b- "albumId": "e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f", "libraryId": "3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a", "path": "/music/queen/a-night-at-the-opera/01-bohemian-rhapsody.flac", + "container": "FLAC", "metadata": { "title": "Bohemian Rhapsody", "originalTitle": "Bohemian Rhapsody", @@ -1361,6 +1372,7 @@ PUT api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b- "albumId": "e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f", "libraryId": "3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a", "path": "/music/queen/a-night-at-the-opera/07-youre-my-best-friend.flac", + "container": "FLAC", "metadata": { "title": "You're My Best Friend", "originalTitle": "You're My Best Friend", @@ -1511,6 +1523,7 @@ GET api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b- "albumId": "e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f", "libraryId": "3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a", "path": "/music/queen/a-night-at-the-opera/01-bohemian-rhapsody.flac", + "container": "FLAC", "metadata": { "title": "Bohemian Rhapsody", "originalTitle": "Bohemian Rhapsody", diff --git a/docs/technical/api/library/audio-library/music-library/Api.Artists.md b/docs/technical/api/library/audio-library/music-library/Api.Artists.md index 3a5fe443..fec7c403 100644 --- a/docs/technical/api/library/audio-library/music-library/Api.Artists.md +++ b/docs/technical/api/library/audio-library/music-library/Api.Artists.md @@ -518,6 +518,7 @@ POST api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists "albumId": "e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f", "libraryId": "3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a", "path": "/music/queen/a-night-at-the-opera/01-bohemian-rhapsody.flac", + "container": "FLAC", "metadata": { "title": "Bohemian Rhapsody", "originalTitle": "Bohemian Rhapsody", @@ -596,6 +597,7 @@ POST api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists "albumId": "e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f", "libraryId": "3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a", "path": "/music/queen/a-night-at-the-opera/07-youre-my-best-friend.flac", + "container": "FLAC", "metadata": { "title": "You're My Best Friend", "originalTitle": "You're My Best Friend", @@ -865,6 +867,7 @@ GET api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists?currentPage=1& "albumId": "e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f", "libraryId": "3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a", "path": "/music/queen/a-night-at-the-opera/01-bohemian-rhapsody.flac", + "container": "FLAC", "metadata": { "title": "Bohemian Rhapsody", "originalTitle": "Bohemian Rhapsody", @@ -943,6 +946,7 @@ GET api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists?currentPage=1& "albumId": "e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f", "libraryId": "3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a", "path": "/music/queen/a-night-at-the-opera/07-youre-my-best-friend.flac", + "container": "FLAC", "metadata": { "title": "You're My Best Friend", "originalTitle": "You're My Best Friend", @@ -1252,6 +1256,7 @@ GET api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/{artistId} "albumId": "e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f", "libraryId": "3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a", "path": "/music/queen/a-night-at-the-opera/01-bohemian-rhapsody.flac", + "container": "FLAC", "metadata": { "title": "Bohemian Rhapsody", "originalTitle": "Bohemian Rhapsody", @@ -1330,6 +1335,7 @@ GET api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/{artistId} "albumId": "e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f", "libraryId": "3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a", "path": "/music/queen/a-night-at-the-opera/07-youre-my-best-friend.flac", + "container": "FLAC", "metadata": { "title": "You're My Best Friend", "originalTitle": "You're My Best Friend", @@ -1916,6 +1922,7 @@ PUT api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/{artistId} "albumId": "e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f", "libraryId": "3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a", "path": "/music/queen/a-night-at-the-opera/01-bohemian-rhapsody.flac", + "container": "FLAC", "metadata": { "title": "Bohemian Rhapsody", "originalTitle": "Bohemian Rhapsody", @@ -1994,6 +2001,7 @@ PUT api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/{artistId} "albumId": "e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f", "libraryId": "3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a", "path": "/music/queen/a-night-at-the-opera/07-youre-my-best-friend.flac", + "container": "FLAC", "metadata": { "title": "You're My Best Friend", "originalTitle": "You're My Best Friend", diff --git a/docs/technical/api/library/audio-library/music-library/Api.Tracks.md b/docs/technical/api/library/audio-library/music-library/Api.Tracks.md index 4cf0d71c..6e8fe848 100644 --- a/docs/technical/api/library/audio-library/music-library/Api.Tracks.md +++ b/docs/technical/api/library/audio-library/music-library/Api.Tracks.md @@ -8,6 +8,18 @@ - [Get Track](#get-track) - [Get Track Request](#get-track-request) - [Get Track Response](#get-track-response) + - [Shuffle Tracks](#shuffle-tracks) + - [Shuffle Tracks Request](#shuffle-tracks-request) + - [Shuffle Tracks Response](#shuffle-tracks-response) + - [Stream Track](#stream-track) + - [Stream Track Request](#stream-track-request) + - [Stream Track Response](#stream-track-response) + - [Stream Track Segment](#stream-track-segment) + - [Stream Track Segment Request](#stream-track-segment-request) + - [Stream Track Segment Response](#stream-track-segment-response) + - [Get Playback Manifest](#get-playback-manifest) + - [Get Playback Manifest Request](#get-playback-manifest-request) + - [Get Playback Manifest Response](#get-playback-manifest-response) - [Update Track](#update-track) - [Update Track Request](#update-track-request) - [Update Track Response](#update-track-response) @@ -126,6 +138,7 @@ POST api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b "albumId": "e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f", "libraryId": "3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a", "path": "/music/queen/a-night-at-the-opera/01-bohemian-rhapsody.flac", + "container": "FLAC", "metadata": { "title": "Bohemian Rhapsody", "originalTitle": "Bohemian Rhapsody", @@ -228,6 +241,7 @@ GET api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b- "albumId": "e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f", "libraryId": "3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a", "path": "/music/queen/a-night-at-the-opera/01-bohemian-rhapsody.flac", + "container": "FLAC", "metadata": { "title": "Bohemian Rhapsody", "originalTitle": "Bohemian Rhapsody", @@ -310,6 +324,167 @@ GET api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b- ``` +### Shuffle Tracks + +#### Shuffle Tracks Request + +```js +POST api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/tracks/shuffle +``` + +```json +{ + "count": 100, + "artistId": null, + "albumId": null, + "excludedTrackIds": [ + "9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f" + ] +} +``` + +Returns a uniformly random selection of tracks from every track of the library, optionally scoped to one artist or one album, and excludes the tracks in `excludedTrackIds`. The database picks the rows at random, so the result is not limited to the albums or artists that happen to be stored or loaded first. `count` must be between 1 and 500. When `artistId` is present, only tracks whose album belongs to that artist are sampled; when `albumId` is present, only tracks of that album are sampled. The tracks are returned to an Admin, who can shuffle all libraries, or to the owner of the library. + +#### Shuffle Tracks Response + +```js +200 Ok +``` + +```json +[ + { + "trackId": "9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f", + "title": "Bohemian Rhapsody", + "durationInSeconds": 354, + "albumId": "e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f", + "albumTitle": "A Night at the Opera", + "artistId": "d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a", + "coverPath": "\\media\\music\\music-3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a\\QUEEN\\Album\\A night at the opera-e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f\\cover.jpg" + } +] +``` + +The response holds at most `count` tracks, and fewer when the scope has fewer tracks that are not excluded. A repeated request returns a different random selection and a different order. + + +### Stream Track + +#### Stream Track Request + +```js +GET api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/albums/e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f/tracks/9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f/stream +Authorization: Bearer +Range: bytes=0-1048575 +``` + +Streams the audio file of the track identified by the route, with HTTP range support. The `Range` header is optional: without it the whole file is streamed, and with it only the requested range is streamed, so that a player can start playback before the whole file is downloaded and can seek within the file. The audio file is streamed to an Admin, who can stream the tracks of all libraries, or to the owner of the library of the track. + +#### Stream Track Response + +```js +200 Ok +``` + +or, when a range is requested: + +```js +206 Partial Content +Content-Range: bytes 0-1048575/3542771 +Accept-Ranges: bytes +``` + +The response is the raw bytes of the audio file, served with the media type of the file when it is an audio type, or `application/octet-stream` otherwise. Every response carries `X-Content-Type-Options: nosniff`, `Cache-Control: private` and `Vary: Authorization`, together with a `Last-Modified` and an `ETag` derived from the size and the modification time of the file. + + +### Stream Track Segment + +#### Stream Track Segment Request + +```js +GET api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/albums/e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f/tracks/9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f/stream/deliveries/8f14e45fceea167a5a36dedd4bea2543/segments/0 +Authorization: Bearer +``` + +Streams one segment of the normalized audio of the track identified by the route. A track the player cannot play as it is stored is delivered as time addressed segments instead of bytes: the server produces the whole track into a temporary cache with a target segment duration of `segmentDurationSeconds` seconds, cutting at the first packet at or after each target boundary, and serves each produced segment as an independent container file. A real segment start can therefore differ from an exact multiple of the target duration, and a consumer must use the start the response reports rather than assume the grid. The segment index is zero based. + +The `deliveryId` is the opaque handle the playback manifest reported in `deliveryId`. It is bound to the user the manifest was issued to and to the track it describes, and it captures the delivery decision, the quality cap, the source file version and the library content locations the manifest declared. The segment route resolves that handle instead of recomputing the delivery from a capability list, so the segments always belong to exactly the delivery the manifest declared. Library ownership is re-evaluated on every segment request, so revoked access stops playback immediately; the track membership and the content locations are the ones captured at manifest time, so a deleted track row whose file remains, or a removed content location, stays streamable until the handle expires, within 12 hours. A handle that is unknown, expired, or was issued to another user or track is reported as not found. A track the manifest declared as a direct play has no delivery handle at all, so a segment request for it is also reported as not found with `PlaybackDeliveryNotFound`, never as the end of the audio. A source file that changed since the manifest declared the delivery is reported as a conflict instead of starting a second production. The handle is exactly 32 lowercase hexadecimal characters, and a value that does not match that format is rejected rather than normalized into another handle. + +A byte range cannot be mapped to a time in this delivery, so a player seeks by choosing the segment that covers the target time. A segment is a small independent container file that is already fetched as a whole, so the player reads it from its first packet and discards the packets that end before the target; it never seeks inside the container itself, because a container that numbers its frames across the whole track would then add that number to the segment offset twice. The playback manifest reports the root relative path of this route in `segmentStreamPathTemplate`, with `{deliveryId}` and `{segmentIndex}` placeholders, and the player expands both from the manifest. A segment is served to an Admin, who can stream the tracks of all libraries, or to the owner of the library of the track. + +#### Stream Track Segment Response + +```js +200 Ok +Content-Type: audio/aac +Content-Length: 240128 +``` + +The response is the raw bytes of one produced segment, served with the media type of the delivered container when the server can name it, or `application/octet-stream` otherwise. Every response carries `X-Content-Type-Options: nosniff`, `Cache-Control: private, no-store`, `Vary: Authorization`, `X-Lumina-Segment-Count`, the number of segments the production holds, and `X-Segment-Start-Seconds`, the exact start of the segment on the track timeline, in seconds. The count tells a player where the audio ends without probing for the end with a request that returns not found, and the start lets it offset the packets of a container that numbers its frames from the start of the track, instead of assuming that a segment starts at an exact multiple of its duration. Range requests are not used: the segment is the addressing unit, and the next segment is a separate request. The first request for a track can take longer than the following ones, because the whole normalized audio is produced and cached before its first segment is published. A segment index that the production does not hold is reported as not found with the `NormalizedTrackSegmentNotFound` detail, which is the only not-found answer that means the end of the audio. A track, library or audio file that disappeared, a delivery handle that is unknown, expired, or was issued to another user or track, and a cache entry that was evicted, are reported with their own not-found details instead, and a request that arrives while every normalization job slot is in use is reported as unavailable (`503`), because it is a transient condition that a player retries. A delivery handle whose captured shape is not time addressed segments is a conflict (`409`), because the segment route cannot index it. + + +### Get Playback Manifest + +#### Get Playback Manifest Request + +```js +GET api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/albums/e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f/tracks/9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f/playback-manifest?capabilities=mp3/mp3,flac/flac,ogg/opus,ogg/vorbis,wav/pcm,mp4/aac +Authorization: Bearer +``` + +Returns the playback manifest of the track identified by the route: the format of its stored audio, the delivery the server decided on for the requesting player, and the path of its stream, so that a player is told what to fetch and how before it fetches any audio. The `capabilities` query parameter is optional, and its value is a comma separated list of the `container/codec` pairs the player advertises it can demux and decode directly, matched case insensitively, with at most 32 pairs read from one request. When the parameter is absent, empty, or lists no valid pair, the default capabilities of the bundled player apply. The manifest is returned to an Admin, who can build the manifest of the tracks of all libraries, or to the owner of the library of the track. + +#### Get Playback Manifest Response + +```js +200 Ok +``` + +```json +{ + "trackId": "9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f", + "durationInSeconds": 354, + "sourceContainer": "FLAC", + "sourceCodec": "FLAC", + "sampleRate": 44100, + "channels": 2, + "bitDepth": 16, + "replayGainTrackGain": -7.5, + "replayGainTrackPeak": 0.9877, + "replayGainAlbumGain": -6.8, + "replayGainAlbumPeak": 0.9999, + "isDirectPlay": true, + "deliveryContainer": null, + "deliveryCodec": null, + "deliveryShape": null, + "segmentDurationSeconds": null, + "isSeekable": true, + "streamPath": "/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/albums/e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f/tracks/9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f/stream", + "deliveryId": null, + "segmentStreamPathTemplate": null +} +``` + +When the player can play the stored audio as it is, `isDirectPlay` is `true`, and `deliveryContainer`, `deliveryCodec`, `deliveryShape`, `segmentDurationSeconds`, `deliveryId` and `segmentStreamPathTemplate` are `null`, because the delivery is the stored file itself, addressed and seeked by byte range. When it cannot, `isDirectPlay` is `false`, and those fields name the container, the codec, the addressing the server produces instead, the length in seconds of each of its time addressed segments, the opaque handle of the delivery, and the root relative path template of the segment route, with `{deliveryId}` and `{segmentIndex}` placeholders. `durationInSeconds` is the probed duration; a normalized production can be slightly longer or shorter, and its exact produced duration is reported by the `X-Lumina-Track-Duration-Seconds` header of its segments. A normalized delivery is always addressed as `TimeAddressedSegments`, and `segmentDurationSeconds` is the nominal length of each of its segments, so that the server that produces the segments and the player that consumes them agree on the target without duplicating the value on both sides. The `deliveryId` binds the delivery to the user and the track, and it captures the quality cap and the source file version that were in effect when the manifest was read, so a segment request addresses exactly that delivery instead of recomputing it. A player that cannot play a track directly fetches each segment from that template in index order and seeks by segment index, never by byte range. `isSeekable` reports whether the delivered audio can be seeked by the player. `streamPath` is relative to the API, without a host or a scheme, so that a client reaches the stream through its own application rather than the API server directly. + +For example, a delivery of a track the player cannot decode is declared as follows: + +```json +{ + "trackId": "9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f", + "isDirectPlay": false, + "deliveryContainer": "AAC", + "deliveryCodec": "AAC", + "deliveryShape": "TimeAddressedSegments", + "segmentDurationSeconds": 6, + "isSeekable": true, + "streamPath": "/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/albums/e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f/tracks/9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f/stream", + "deliveryId": "8f14e45fceea167a5a36dedd4bea2543", + "segmentStreamPathTemplate": "/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/albums/e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f/tracks/9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f/stream/deliveries/{deliveryId}/segments/{segmentIndex}" +} +``` + + ### Update Track #### Update Track Request @@ -320,7 +495,6 @@ PUT api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b- ```json { - "path": "/music/queen/a-night-at-the-opera/01-bohemian-rhapsody.flac", "metadata": { "title": "Bohemian Rhapsody", "originalTitle": "Bohemian Rhapsody", @@ -421,6 +595,7 @@ PUT api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b- "albumId": "e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f", "libraryId": "3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a", "path": "/music/queen/a-night-at-the-opera/01-bohemian-rhapsody.flac", + "container": "FLAC", "metadata": { "title": "Bohemian Rhapsody", "originalTitle": "Bohemian Rhapsody", diff --git a/docs/technical/api/library/management/Api.Libraries.md b/docs/technical/api/library/management/Api.Libraries.md index 4963627e..93dc2a0f 100644 --- a/docs/technical/api/library/management/Api.Libraries.md +++ b/docs/technical/api/library/management/Api.Libraries.md @@ -65,6 +65,8 @@ POST api/v1/libraries "canDownloadMetadataFromWeb": true, "shouldSaveMetadataInMediaDirectories": true, "shouldSkipUnchangedDirectoriesDuringScan": true, + "shouldTrackConsumptionProgress": true, + "completionThresholdPercentage": 100, "pathTemplateParts": [] } ``` @@ -90,6 +92,8 @@ POST api/v1/libraries "canDownloadMetadataFromWeb": true, "shouldSaveMetadataInMediaDirectories": true, "shouldSkipUnchangedDirectoriesDuringScan": true, + "shouldTrackConsumptionProgress": true, + "completionThresholdPercentage": 100, "pathTemplateParts": [], "createdOnUtc": "2025-01-01T12:00:00.0000000Z", "updatedOnUtc": null @@ -126,6 +130,8 @@ GET api/v1/libraries "canDownloadMetadataFromWeb": true, "shouldSaveMetadataInMediaDirectories": true, "shouldSkipUnchangedDirectoriesDuringScan": true, + "shouldTrackConsumptionProgress": true, + "completionThresholdPercentage": 100, "pathTemplateParts": [], "createdOnUtc": "2025-01-01T12:00:00.0000000Z", "updatedOnUtc": null @@ -163,6 +169,8 @@ GET api/v1/libraries/enabled "canDownloadMetadataFromWeb": true, "shouldSaveMetadataInMediaDirectories": true, "shouldSkipUnchangedDirectoriesDuringScan": true, + "shouldTrackConsumptionProgress": true, + "completionThresholdPercentage": 100, "pathTemplateParts": [], "createdOnUtc": "2025-01-01T12:00:00.0000000Z", "updatedOnUtc": null @@ -199,6 +207,8 @@ GET api/v1/libraries/{id} "canDownloadMetadataFromWeb": true, "shouldSaveMetadataInMediaDirectories": true, "shouldSkipUnchangedDirectoriesDuringScan": true, + "shouldTrackConsumptionProgress": true, + "completionThresholdPercentage": 100, "pathTemplateParts": [], "createdOnUtc": "2025-01-01T12:00:00.0000000Z", "updatedOnUtc": null @@ -228,6 +238,8 @@ PUT api/v1/libraries/{id} "canDownloadMetadataFromWeb": true, "shouldSaveMetadataInMediaDirectories": true, "shouldSkipUnchangedDirectoriesDuringScan": true, + "shouldTrackConsumptionProgress": true, + "completionThresholdPercentage": 100, "pathTemplateParts": [] } ``` @@ -253,6 +265,8 @@ PUT api/v1/libraries/{id} "canDownloadMetadataFromWeb": true, "shouldSaveMetadataInMediaDirectories": true, "shouldSkipUnchangedDirectoriesDuringScan": true, + "shouldTrackConsumptionProgress": true, + "completionThresholdPercentage": 100, "pathTemplateParts": [], "createdOnUtc": "2025-01-01T12:00:00.0000000Z", "updatedOnUtc": null diff --git a/docs/technical/api/library/statistics/Api.LibraryStatistics.md b/docs/technical/api/library/statistics/Api.LibraryStatistics.md new file mode 100644 index 00000000..3854f851 --- /dev/null +++ b/docs/technical/api/library/statistics/Api.LibraryStatistics.md @@ -0,0 +1,594 @@ +# Lumina API + +- [Lumina API](#lumina-api) + - [Library Statistics](#library-statistics) + - [When a Session Counts](#when-a-session-counts) + - [Get Recently Consumed](#get-recently-consumed) + - [Get Recently Consumed Request](#get-recently-consumed-request) + - [Get Recently Consumed Response](#get-recently-consumed-response) + - [Get Most Consumed](#get-most-consumed) + - [Get Most Consumed Request](#get-most-consumed-request) + - [Get Most Consumed Response](#get-most-consumed-response) + - [Get Consumption Statistics](#get-consumption-statistics) + - [Get Consumption Statistics Request](#get-consumption-statistics-request) + - [Get Consumption Statistics Response](#get-consumption-statistics-response) + - [Get All Users Consumption Statistics](#get-all-users-consumption-statistics) + - [Get All Users Consumption Statistics Request](#get-all-users-consumption-statistics-request) + - [Get All Users Consumption Statistics Response](#get-all-users-consumption-statistics-response) + - [Get Tag Consumption](#get-tag-consumption) + - [Get Tag Consumption Request](#get-tag-consumption-request) + - [Get Tag Consumption Response](#get-tag-consumption-response) + - [Get Genre Consumption](#get-genre-consumption) + - [Get Genre Consumption Request](#get-genre-consumption-request) + - [Get Genre Consumption Response](#get-genre-consumption-response) + - [Delete Consumption Record](#delete-consumption-record) + - [Delete Consumption Record Request](#delete-consumption-record-request) + - [Delete Consumption Record Response](#delete-consumption-record-response) + - [Delete Consumption Item History](#delete-consumption-item-history) + - [Delete Consumption Item History Request](#delete-consumption-item-history-request) + - [Delete Consumption Item History Response](#delete-consumption-item-history-response) + - [Clear Consumption History](#clear-consumption-history) + - [Clear Consumption History Request](#clear-consumption-history-request) + - [Clear Consumption History Response](#clear-consumption-history-response) + - [Clear Resume Points](#clear-resume-points) + - [Clear Resume Points Request](#clear-resume-points-request) + - [Clear Resume Points Response](#clear-resume-points-response) + - [Pagination](#pagination) + - [Scoping and Authorization](#scoping-and-authorization) + - [Private Responses](#private-responses) + - [Errors](#errors) + - [Concurrency](#concurrency) + +## Library Statistics + +The library statistics read the media consumption history and aggregate it in the application layer. They are media neutral: music and book sessions appear in the same lists and the same summary, and the planned kinds use the same routes when their catalogues exist. The statistics never read a stored counter. Every response is computed from the consumption records on the request, so deleting history changes the statistics immediately, and a changed counting rule applies to the whole history at once. The lifecycle that creates the records, and the read of one resume point, are documented in [Media Consumption](../../media-consumption/Api.MediaConsumption.md). + +The consumed duration is the active listening, watching or reading time reported by the session. It is totalled over every recorded session, including the sessions that do not count towards the statistics, because the time was consumed regardless. The counted sessions, completed sessions, stopped sessions and completion rate use the counting rules below. + +### When a Session Counts + +A session counts towards the statistics when its media kind's rule says so: + +| Media kind | A session counts when | +| --- | --- | +| `MusicTrack` | The session completed, or the consumed duration is at least 30 seconds | +| `PodcastEpisode` | The session completed, or the consumed duration is at least 30 seconds | +| `Audiobook` | The session completed, or the consumed duration is at least 60 seconds | +| `Movie` | The session completed, or the consumed duration is at least 3 minutes | +| `TvEpisode` | The session completed, or the consumed duration is at least 3 minutes | +| `Book` | The session completed, or more than 5 consecutive pages were read | +| `Photo` | Every session counts | +| `Video` | The session completed, or the consumed duration is at least 3 minutes | + +A completed session always counts. A stopped session counts only when it reaches the rule of its kind. A book with 5 consecutive pages does not count, while one with 6 does. The counting rule is separate from the library completion threshold: a session can count as consumed without the library considering the item complete. + +### Get Recently Consumed + +#### Get Recently Consumed Request + +```js +GET api/v1/users/me/consumption-history/recently-consumed?currentPage=1&perPage=50 +Authorization: Bearer +``` + +An administrator can read the history of another user by targeting the per-user route: + +```js +GET api/v1/users/2cff0c0f-3a67-4e30-b94f-f4e948a3b64f/consumption-history/recently-consumed?currentPage=1&perPage=50 +Authorization: Bearer +``` + +| Query parameter | Meaning | +| --- | --- | +| `libraryId` | Optional. The Id of a library to restrict the history to. It must be a non-empty Guid. | +| `mediaKind` | Optional. The name of a media kind to restrict the history to, matched case insensitively. Only member names are accepted, so a numeric value is rejected even when it is a defined enumeration value. `None` is rejected. | +| `currentPage` | Optional. The one based page of distinct media items to return. | +| `perPage` | Optional. The number of distinct media items per page. | +| `fromUtc` | Optional. The inclusive start of the history date range, in UTC. A trailing zone designator is honored and converted to UTC, while a value without one is interpreted as UTC. | +| `toUtc` | Optional. The inclusive end of the history date range, in UTC. A trailing zone designator is honored and converted to UTC, while a value without one is interpreted as UTC. It must not be before `fromUtc`. | + +The same query parameters apply to the per-user route. The route user is the target, and the access policy decides whether the caller may read it. + +The records are grouped to one row per media kind, media item and library before ordering, so an item consumed many times appears once. The rows are ordered by the time of the latest activity, from the most recent, and ties are broken by media kind, media item Id and library Id. + +#### Get Recently Consumed Response + +```js +200 Ok +``` + +```json +{ + "data": [ + { + "mediaKind": "MusicTrack", + "mediaItemId": "9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f", + "libraryId": "3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a", + "isAvailable": true, + "title": "The Show Must Go On", + "collectionTitle": "Innuendo", + "creatorName": "Queen", + "coverPath": "/artwork/albums/e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f/cover.jpg", + "lastConsumedOnUtc": "2026-10-24T12:12:00.0000000Z", + "countedSessionCount": 4, + "completedSessionCount": 3, + "consumedDurationInSeconds": 1424.5 + }, + { + "mediaKind": "Book", + "mediaItemId": "7a6b5c4d-3e2f-4a1b-8c9d-0e1f2a3b4c5d", + "libraryId": "5c6d7e8f-9a0b-4c1d-8e2f-3a4b5c6d7e8f", + "isAvailable": true, + "title": "The Fellowship of the Ring", + "collectionTitle": "", + "creatorName": "J. R. R. Tolkien", + "coverPath": "/artwork/books/7a6b5c4d-3e2f-4a1b-8c9d-0e1f2a3b4c5d/cover.jpg", + "lastConsumedOnUtc": "2026-10-23T20:40:00.0000000Z", + "countedSessionCount": 2, + "completedSessionCount": 1, + "consumedDurationInSeconds": 7320 + } + ], + "currentPage": 1, + "perPage": 50, + "count": 2, + "numberOfPages": 1 +} +``` + +| Field | Type | Meaning | +| --- | --- | --- | +| `mediaKind` | string | The kind of the consumed media item. | +| `mediaItemId` | Guid | The Id of the consumed media item. | +| `libraryId` | Guid | The Id of the library recorded with the sessions. | +| `isAvailable` | boolean | Whether the item still exists and its library is accessible to the current user. | +| `title` | string | The title of the item, or an empty string when it is not available. | +| `collectionTitle` | string | The album title of a track, or an empty string when there is none. Books have no collection title. | +| `creatorName` | string | The artist of a track, or the name of one of a book's authors chosen alphabetically, or an empty string when there is none. | +| `coverPath` | string? | The path of the cover art, or `null` when there is none. | +| `lastConsumedOnUtc` | DateTime | The time of the latest recorded activity of the item. | +| `countedSessionCount` | integer | The sessions of the item that count towards the statistics. | +| `completedSessionCount` | integer | The sessions of the item that completed. | +| `consumedDurationInSeconds` | number | The active duration consumed in the item over all of its sessions, in seconds. | + +A deleted item, an item whose library was deleted, and an item in a library the current user can no longer access keep their identity, counts and duration, but are returned with `isAvailable` set to `false`, blank display fields and no cover. This lets the user see the history row and delete it. An item that moved to another library after it was consumed is also reported as unavailable for the recorded library, because the display data of the recorded library cannot be shown for it. + +### Get Most Consumed + +#### Get Most Consumed Request + +```js +GET api/v1/users/me/consumption-history/most-consumed?currentPage=1&perPage=50 +Authorization: Bearer +``` + +An administrator can read the most consumed items of another user: + +```js +GET api/v1/users/2cff0c0f-3a67-4e30-b94f-f4e948a3b64f/consumption-history/most-consumed?currentPage=1&perPage=50 +Authorization: Bearer +``` + +The query parameters are those of [Get Recently Consumed](#get-recently-consumed-request). The records are grouped to one row per media kind, media item and library, then ordered by counted sessions, then by consumed duration, then by the latest activity, all descending, with the media item Id, media kind and library Id as the tiebreakers. + +#### Get Most Consumed Response + +```js +200 Ok +``` + +The response has the same shape as [Get Recently Consumed Response](#get-recently-consumed-response), ordered from the most consumed. + +### Get Consumption Statistics + +#### Get Consumption Statistics Request + +```js +GET api/v1/users/me/consumption-statistics?fromUtc=2026-10-01T00:00:00Z&toUtc=2026-10-31T23:59:59Z +Authorization: Bearer +``` + +An administrator can read the statistics of another user: + +```js +GET api/v1/users/2cff0c0f-3a67-4e30-b94f-f4e948a3b64f/consumption-statistics?fromUtc=2026-10-01T00:00:00Z&toUtc=2026-10-31T23:59:59Z +Authorization: Bearer +``` + +| Query parameter | Meaning | +| --- | --- | +| `libraryId` | Optional. The Id of a library to restrict the statistics to. It must be a non-empty Guid. | +| `mediaKind` | Optional. The name of a media kind to restrict the statistics to, matched case insensitively. Only member names are accepted, so a numeric value is rejected even when it is a defined enumeration value. `None` is rejected. | +| `fromUtc` | Optional. The inclusive start of the date range, in UTC. A trailing zone designator is honored and converted to UTC, while a value without one is interpreted as UTC. | +| `toUtc` | Optional. The inclusive end of the date range, in UTC. A trailing zone designator is honored and converted to UTC, while a value without one is interpreted as UTC. It must not be before `fromUtc`. | + +#### Get Consumption Statistics Response + +```js +200 Ok +``` + +```json +{ + "userId": "2cff0c0f-3a67-4e30-b94f-f4e948a3b64f", + "totalConsumedDurationInSeconds": 12840.5, + "countedSessionCount": 62, + "completedSessionCount": 41, + "stoppedSessionCount": 21, + "completionRate": 0.6612903, + "mediaKindSummaries": [ + { + "mediaKind": "MusicTrack", + "totalConsumedDurationInSeconds": 5520.5, + "countedSessionCount": 60, + "completedSessionCount": 40, + "stoppedSessionCount": 20, + "completionRate": 0.6666667 + }, + { + "mediaKind": "Book", + "totalConsumedDurationInSeconds": 7320, + "countedSessionCount": 2, + "completedSessionCount": 1, + "stoppedSessionCount": 1, + "completionRate": 0.5 + } + ] +} +``` + +| Field | Type | Meaning | +| --- | --- | --- | +| `userId` | Guid | The user the statistics belong to. | +| `totalConsumedDurationInSeconds` | number | The consumed duration over every recorded session, in seconds. Sessions below the counting threshold are included. | +| `countedSessionCount` | integer | The sessions that count towards the statistics. | +| `completedSessionCount` | integer | The recorded sessions that completed. | +| `stoppedSessionCount` | integer | The counted sessions that stopped before completing. | +| `completionRate` | number | The completed sessions divided by the counted sessions, between 0 and 1, or 0 when no session counts. | +| `mediaKindSummaries` | array | The same fields, without `userId`, broken down by media kind, ordered by media kind. | + +The overall totals are the sums of the per-kind summaries, so the completion rate never disagrees with the breakdown. When no record matches, every total is 0 and the breakdown is an empty array. + +### Get All Users Consumption Statistics + +#### Get All Users Consumption Statistics Request + +```js +GET api/v1/users/consumption-statistics?fromUtc=2026-10-01T00:00:00Z&toUtc=2026-10-31T23:59:59Z +Authorization: Bearer +``` + +The same optional `libraryId`, `mediaKind`, `fromUtc` and `toUtc` filters apply. Only an administrator can call this route. It is the only statistics route that loads the records of every user. + +#### Get All Users Consumption Statistics Response + +```js +200 Ok +``` + +```json +{ + "total": { + "totalConsumedDurationInSeconds": 12840.5, + "countedSessionCount": 62, + "completedSessionCount": 41, + "stoppedSessionCount": 21, + "completionRate": 0.6612903, + "mediaKindSummaries": [ + { + "mediaKind": "MusicTrack", + "totalConsumedDurationInSeconds": 5520.5, + "countedSessionCount": 60, + "completedSessionCount": 40, + "stoppedSessionCount": 20, + "completionRate": 0.6666667 + }, + { + "mediaKind": "Book", + "totalConsumedDurationInSeconds": 7320, + "countedSessionCount": 2, + "completedSessionCount": 1, + "stoppedSessionCount": 1, + "completionRate": 0.5 + } + ] + }, + "users": [ + { + "userId": "2cff0c0f-3a67-4e30-b94f-f4e948a3b64f", + "totalConsumedDurationInSeconds": 12840.5, + "countedSessionCount": 62, + "completedSessionCount": 41, + "stoppedSessionCount": 21, + "completionRate": 0.6612903, + "mediaKindSummaries": [ + { + "mediaKind": "MusicTrack", + "totalConsumedDurationInSeconds": 5520.5, + "countedSessionCount": 60, + "completedSessionCount": 40, + "stoppedSessionCount": 20, + "completionRate": 0.6666667 + }, + { + "mediaKind": "Book", + "totalConsumedDurationInSeconds": 7320, + "countedSessionCount": 2, + "completedSessionCount": 1, + "stoppedSessionCount": 1, + "completionRate": 0.5 + } + ] + } + ] +} +``` + +`total` carries the same fields as a user summary without `userId`, including its own `mediaKindSummaries` array, which combines the per-kind summaries of every user. `users` holds one summary per user that has a matching record, ordered by user Id. The all-users route returns no history lists and no tag or genre breakdown, because those are only meaningful per user. + +### Get Tag Consumption + +#### Get Tag Consumption Request + +```js +GET api/v1/users/me/consumption-statistics/tags?mediaKind=MusicTrack +Authorization: Bearer +``` + +An administrator can read the tag breakdown of another user: + +```js +GET api/v1/users/2cff0c0f-3a67-4e30-b94f-f4e948a3b64f/consumption-statistics/tags?mediaKind=MusicTrack +Authorization: Bearer +``` + +The optional `libraryId`, `mediaKind`, `fromUtc` and `toUtc` filters are the same as for [Get Consumption Statistics](#get-consumption-statistics-request). + +#### Get Tag Consumption Response + +```js +200 Ok +``` + +```json +[ + { + "name": "fantasy", + "consumedItemCount": 2, + "consumedDurationInSeconds": 7320 + }, + { + "name": "horror", + "consumedItemCount": 1, + "consumedDurationInSeconds": 1424.5 + } +] +``` + +The records are grouped to one row per media kind, media item and library first, so an item with several sessions contributes its tags once, not once per session. A music track with no tags of its own contributes the tags of its album, and then the tags of its artist when the album has none. Only items in an accessible library with at least one counted session contribute. A name that appears twice on the same item contributes once. Names are normalized to lowercase, so `Horror` and `horror` share one bucket across media kinds. The rows are ordered by consumed item count, then consumed duration, both descending, with the name ascending as the tiebreaker. An item that no longer exists, or that moved to another library after it was consumed, does not contribute to the breakdown, because its terms cannot be resolved for the recorded library. + +`consumedItemCount` is the number of distinct items that carry the tag, not the number of sessions. `consumedDurationInSeconds` is the consumed duration of those items, over all of their sessions. + +### Get Genre Consumption + +#### Get Genre Consumption Request + +```js +GET api/v1/users/me/consumption-statistics/genres?mediaKind=Book +Authorization: Bearer +``` + +An administrator can read the genre breakdown of another user: + +```js +GET api/v1/users/2cff0c0f-3a67-4e30-b94f-f4e948a3b64f/consumption-statistics/genres?mediaKind=Book +Authorization: Bearer +``` + +The optional `libraryId`, `mediaKind`, `fromUtc` and `toUtc` filters are the same as for [Get Consumption Statistics](#get-consumption-statistics-request). + +#### Get Genre Consumption Response + +```js +200 Ok +``` + +```json +[ + { + "name": "fantasy", + "consumedItemCount": 2, + "consumedDurationInSeconds": 7320 + }, + { + "name": "science fiction", + "consumedItemCount": 1, + "consumedDurationInSeconds": 1424.5 + } +] +``` + +The genre breakdown follows the same item level aggregation, lowercase normalization, ordering and availability rules as the tag breakdown. A music track with no genres of its own contributes the genres of its album, and then the genres of its artist when the album has none. + +### Delete Consumption Record + +#### Delete Consumption Record Request + +```js +DELETE api/v1/users/me/consumption-history/2c1b0a9f-8e7d-4c6b-5a4f-3e2d1c0b9a8f +Authorization: Bearer +``` + +An administrator can delete a record of another user: + +```js +DELETE api/v1/users/2cff0c0f-3a67-4e30-b94f-f4e948a3b64f/consumption-history/2c1b0a9f-8e7d-4c6b-5a4f-3e2d1c0b9a8f +Authorization: Bearer +``` + +| Route value | Meaning | +| --- | --- | +| `recordId` | The Id of the consumption record to delete. It must be a non-empty Guid. | +| `userId` | The owner of the record on the per-user route. An administrator can name any user; a regular user can only name themselves. | + +The record is deleted hard. Deleting a record that does not exist, or that belongs to another user, succeeds without changing anything. The resume point of the item is not deleted, because the history and the resume point are separate actions. + +#### Delete Consumption Record Response + +```js +200 Ok +``` + +The response body is an empty JSON object. + +### Delete Consumption Item History + +#### Delete Consumption Item History Request + +```js +DELETE api/v1/users/me/consumption-history/media-items/MusicTrack/9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a +Authorization: Bearer +``` + +An administrator can delete every record of an item of another user: + +```js +DELETE api/v1/users/2cff0c0f-3a67-4e30-b94f-f4e948a3b64f/consumption-history/media-items/Book/7a6b5c4d-3e2f-4a1b-8c9d-0e1f2a3b4c5d/5c6d7e8f-9a0b-4c1d-8e2f-3a4b5c6d7e8f +Authorization: Bearer +``` + +| Route value | Meaning | +| --- | --- | +| `mediaKind` | The kind of the item. `None` is rejected. | +| `mediaItemId` | The Id of the item. It must be a non-empty Guid. | +| `libraryId` | The Id of the library recorded with the item. It must be a non-empty Guid. | +| `userId` | The owner of the history on the per-user route. An administrator can name any user; a regular user can only name themselves. | + +Every recorded session of the item in that library is deleted, not only the sessions inside a date range. The deletion is idempotent and leaves the resume point untouched. + +#### Delete Consumption Item History Response + +```js +200 Ok +``` + +The response body is an empty JSON object. + +### Clear Consumption History + +#### Clear Consumption History Request + +```js +DELETE api/v1/users/me/consumption-history +Authorization: Bearer +``` + +An administrator can clear the whole history of another user: + +```js +DELETE api/v1/users/2cff0c0f-3a67-4e30-b94f-f4e948a3b64f/consumption-history +Authorization: Bearer +``` + +Every consumption record of the target user is deleted. The deletion is idempotent and does not delete any resume point, so the continue watching list survives until the user removes it separately. + +#### Clear Consumption History Response + +```js +200 Ok +``` + +The response body is an empty JSON object. + +### Clear Resume Points + +#### Clear Resume Points Request + +```js +DELETE api/v1/users/me/media-resume-points?libraryId=3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a +Authorization: Bearer +``` + +An administrator can clear the resume points of another user: + +```js +DELETE api/v1/users/2cff0c0f-3a67-4e30-b94f-f4e948a3b64f/media-resume-points +Authorization: Bearer +``` + +| Query parameter | Meaning | +| --- | --- | +| `libraryId` | Optional. The Id of a library to restrict the deletion to. It must be a non-empty Guid. When it is omitted, every resume point of the user is deleted. | + +Clearing resume points deletes no history. The operation is idempotent. + +#### Clear Resume Points Response + +```js +200 Ok +``` + +The response body is an empty JSON object. + +### Pagination + +The recently consumed and most consumed routes accept `currentPage` and `perPage`: + +- When both are omitted, every matching item is returned in one page. `currentPage` is 1, `perPage` is the number of items, which is 0 when none match, and `numberOfPages` is 1. +- When either is supplied, the other defaults to 1 for `currentPage` and 50 for `perPage`. +- A page below 1 is treated as 1. A page size below 1 is treated as 1. +- When at least one item matches, a page beyond the last one is clamped to the last page. +- When a requested page matches no item, `count` is 0, `currentPage` is 1 and `numberOfPages` is 0. +- `count` is the number of distinct items that match the filters, before pagination. + +The statistics, tag and genre routes are not paginated, because their result is already an aggregate bounded by the number of media kinds, tags or genres. + +### Scoping and Authorization + +Every route in this document requires authentication. + +- The `/users/me/...` routes always act on the current user. The identity comes from the authenticated principal, never from the route, query or body. +- The `/users/{userId}/...` routes act on the named user. A regular user may name only themselves. Naming another user returns `403 NotAuthorized`, exactly like a route that names no accessible user, so the response cannot be used to find out whether a user or their history exists. +- The `/users/consumption-statistics` route is only for administrators. A regular user receives `403 NotAuthorized`. +- Administrator access is role based. The per-user routes evaluate the consumption activity access policy, which allows the owner or an administrator. The all-users route checks the administrator role directly. There is no separate permission toggle for consumption activity. + +The statistics and lists never expose the history of another user to a regular user. Display data is resolved per distinct library through the library ownership policy. An item in a library the current user can no longer access keeps its counts but has blank display data, so the history lists reveal no inaccessible title, collection, creator or cover. The service wide totals never include the records of a user that the caller cannot target. + +Deleting a record, every record of an item, the whole history, or the resume points belongs to the same access rule. An administrator can delete any user's consumption activity through the per-user routes, and a regular user can delete only their own. Reading a resume point is not part of this surface; it stays owner only, as documented in [Media Consumption](../../media-consumption/Api.MediaConsumption.md). + +### Private Responses + +Every response produced by these endpoints is private to the authenticated user, and each endpoint sets: + +- `Cache-Control: private, no-store` +- `Vary: Authorization` + +The headers are set before the operation runs, so they are present on the endpoint's problem responses too. A request rejected by the authentication middleware with `401` before the endpoint runs is produced by the framework rather than by the endpoint. + +### 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. | +| `403` | `NotAuthorized` | The authenticated principal carries no user identity, a regular user targets another user, or a regular user calls the all-users route. | +| `409` | `ConcurrencyConflict` | A deletion could not be stored because the database is busy or locked, or because another request changed the same row after this request read it. Repeating the request is safe. | +| `422` | see below | The request failed validation. | + +A request that fails validation is rejected with `422 Unprocessable Entity` and a validation problem whose `errors` object lists the validation error names under the generic `General.Validation` code. + +| Error | Operation | When | +| --- | --- | --- | +| `TargetUserIdIsInvalid` | Per-user routes | The `userId` route value is not a non-empty Guid. | +| `ConsumptionRecordIdCannotBeEmpty` | Delete record | The `recordId` route value is not a non-empty Guid. | +| `MediaItemIdCannotBeEmpty` | Delete item history | The `mediaItemId` route value is the empty Guid. | +| `LibraryIdCannotBeEmpty` | Statistics filters, delete item history, clear resume points | A supplied library Id is not a non-empty Guid. | +| `UnsupportedMediaKind` | Statistics filters, delete item history | The supplied kind is `None` or is not a defined media kind. Omitting `mediaKind` is valid on the statistics filters. | +| `ConsumptionDateRangeIsInvalid` | Statistics filters | A date bound is not a valid date, or `fromUtc` is after `toUtc`. | + +A value that cannot be bound to the request type, such as a malformed route Id on delete item history, is rejected by the framework before these validators run. Media kind query filters are carried as text, so an unknown name reaches the validator and is reported as `UnsupportedMediaKind`. + +### Concurrency + +Deletions use the optimistic concurrency version stored on the consumption record and resume point entities. A deletion that races with another change is reported as `409 ConcurrencyConflict`, and a busy or locked SQLite write is reported the same way. Deleting an already absent record, item history or set of resume points succeeds, so a retried deletion is safe. diff --git a/docs/technical/api/media-consumption/Api.MediaConsumption.md b/docs/technical/api/media-consumption/Api.MediaConsumption.md new file mode 100644 index 00000000..7162d46e --- /dev/null +++ b/docs/technical/api/media-consumption/Api.MediaConsumption.md @@ -0,0 +1,681 @@ +# Lumina API + +- [Lumina API](#lumina-api) + - [Media Consumption](#media-consumption) + - [Start Consumption](#start-consumption) + - [Start Consumption Request](#start-consumption-request) + - [Start Consumption Response](#start-consumption-response) + - [Get Consumption Record](#get-consumption-record) + - [Get Consumption Record Request](#get-consumption-record-request) + - [Get Consumption Record Response](#get-consumption-record-response) + - [Report Consumption Progress](#report-consumption-progress) + - [Report Consumption Progress Request](#report-consumption-progress-request) + - [Report Consumption Progress Response](#report-consumption-progress-response) + - [Complete Consumption](#complete-consumption) + - [Complete Consumption Request](#complete-consumption-request) + - [Complete Consumption Response](#complete-consumption-response) + - [Stop Consumption](#stop-consumption) + - [Stop Consumption Request](#stop-consumption-request) + - [Stop Consumption Response](#stop-consumption-response) + - [Get Resume Point](#get-resume-point) + - [Get Resume Point Request](#get-resume-point-request) + - [Get Resume Point Response](#get-resume-point-response) + - [Media Kinds](#media-kinds) + - [Session Statuses](#session-statuses) + - [Position Kinds](#position-kinds) + - [Reportable Ranges](#reportable-ranges) + - [Session Lifecycle and Resume Points](#session-lifecycle-and-resume-points) + - [Completion Threshold](#completion-threshold) + - [Scoping and Authorization](#scoping-and-authorization) + - [Private Responses](#private-responses) + - [Errors](#errors) + - [Concurrency](#concurrency) + +## Media Consumption + +The media consumption API records what the current user consumed, how far they reached, how long they consumed it, and where they can resume it. It is media neutral: the same routes serve a music track and a book, and every future catalogue uses the same routes without a per-kind endpoint. The statistics read these records; see [Library Statistics](../library/statistics/Api.LibraryStatistics.md) for the counting rules and the aggregated reads. + +A consumption session is stored as a `MediaConsumptionRecord`. It carries the kind of media, the library and the item, the start and end times, the latest position and progress fraction, the active consumed duration, and the number of consecutive pages read for page based media. It is not a playback session: it stores no queue, no current index, no repeat or shuffle state, and it never restores playback. + +A resume point is stored separately as a `MediaResumePoint`, with at most one row per user, media kind and media item. It carries the last known position, the last progress fraction, and when the item was last consumed. Completion deletes it. A session that stops without completing can keep it, depending on the library settings. + +All the routes in this document require authentication and act on the current user. No route or body accepts a user Id. The lifecycle writes are owner only: an admin cannot progress, complete or stop another user's session. + +The supported media kinds are `MusicTrack` and `Book`. The other kinds are planned and are rejected until their catalogues exist, see [Media Kinds](#media-kinds). + +All responses are private to the authenticated user, including the endpoint problem responses, see [Private Responses](#private-responses). + +### Start Consumption + +#### Start Consumption Request + +```js +POST api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/media-items/MusicTrack/9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f/consumption-records +Authorization: Bearer +``` + +The same operation starts a book session: + +```js +POST api/v1/libraries/5c6d7e8f-9a0b-4c1d-8e2f-3a4b5c6d7e8f/media-items/Book/7a6b5c4d-3e2f-4a1b-8c9d-0e1f2a3b4c5d/consumption-records +Authorization: Bearer +``` + +| Route value | Meaning | +| --- | --- | +| `libraryId` | The Id of the media library that contains the item. It must be a Guid and cannot be the empty Guid. | +| `mediaKind` | The kind of media, matched case insensitively. Only the member names are accepted: `MusicTrack` and `Book` for now. Numeric values such as `1`, `6` or `0` are rejected, even when they are defined enumeration values. | +| `mediaItemId` | The Id of the consumed item. It must be a Guid and cannot be the empty Guid. | + +Starts a consumption session for the item named by the route. The request has no body: every identifier is taken from the route, so a client cannot substitute the library, kind or item with a body value. + +The operation validates the request, requires the current user, and evaluates the library ownership policy for the route library. The library is then loaded, and the item is resolved through the catalogue repository of its kind. The item must exist and must belong to the route library. A missing item, an item that belongs to another library, and an item of another kind are reported with the same kind specific not found error, so the route cannot be used to probe another library or another kind. + +When the library tracks progress and the kind can resume, the new session starts from the stored resume point: the record's `lastPosition` and `lastProgressFraction` are initialized from it, and `consecutivePagesRead` starts at zero. The consumed duration always starts at zero, because it measures this session only. When tracking is off, or when there is no stored resume point, the session starts with a null position and a zero progress fraction. + +The start operation records the session immediately and returns its identifier. A new session of a one-shot kind such as a photo would be created completed in the same call, but one-shot kinds are not supported by the current catalogues, so they are rejected before that branch is reached. + +#### Start Consumption Response + +```js +200 Ok +``` + +A music track with no stored resume point: + +```json +{ + "id": "2c1b0a9f-8e7d-4c6b-5a4f-3e2d1c0b9a8f", + "libraryId": "3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a", + "mediaItemId": "9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f", + "mediaKind": "MusicTrack", + "status": "InProgress", + "startedOnUtc": "2026-10-24T12:00:00.0000000Z", + "lastActivityOnUtc": "2026-10-24T12:00:00.0000000Z", + "endedOnUtc": null, + "consumedDurationInSeconds": 0, + "lastPosition": null, + "lastProgressFraction": 0, + "consecutivePagesRead": 0 +} +``` + +A book with a stored resume point: + +```json +{ + "id": "2c1b0a9f-8e7d-4c6b-5a4f-3e2d1c0b9a8f", + "libraryId": "5c6d7e8f-9a0b-4c1d-8e2f-3a4b5c6d7e8f", + "mediaItemId": "7a6b5c4d-3e2f-4a1b-8c9d-0e1f2a3b4c5d", + "mediaKind": "Book", + "status": "InProgress", + "startedOnUtc": "2026-10-24T12:00:00.0000000Z", + "lastActivityOnUtc": "2026-10-24T12:00:00.0000000Z", + "endedOnUtc": null, + "consumedDurationInSeconds": 0, + "lastPosition": { + "kind": "Location", + "timeOffsetSeconds": null, + "location": "epubcfi(/6/4[chapter-3]!/4/2/2)" + }, + "lastProgressFraction": 0.42, + "consecutivePagesRead": 0 +} +``` + +The returned `id` identifies the session in the get, progress, complete and stop routes. + +| Field | Type | Meaning | +| --- | --- | --- | +| `id` | Guid | The Id of the consumption record. | +| `libraryId` | Guid | The Id of the library that contains the consumed item. | +| `mediaItemId` | Guid | The Id of the consumed item. | +| `mediaKind` | string | The kind of media: `MusicTrack` or `Book` today. | +| `status` | string | The state of the session: `InProgress`, `Completed` or `Stopped`. | +| `startedOnUtc` | DateTime | When the session started. | +| `lastActivityOnUtc` | DateTime | When the session last received a progress, complete or stop request. | +| `endedOnUtc` | DateTime? | When the session completed or stopped, or `null` while it is in progress. | +| `consumedDurationInSeconds` | number | The active duration consumed by the session, in seconds. It starts at zero and never decreases. | +| `lastPosition` | object? | The latest known position, or `null` when there is none. See [Position Kinds](#position-kinds). | +| `lastProgressFraction` | number | The latest reported progress fraction, from 0 to 1. It may move backwards. | +| `consecutivePagesRead` | integer | The number of consecutive pages read in this session. It is zero for every kind except page based media such as books. | + +The start response is `200 Ok`. A wrong-library item and a missing item return the same `TrackNotFound` or `BookNotFound` error. A missing library returns `LibraryNotFound`. Starting in a library the current user cannot access returns `NotAuthorized`. + +### Get Consumption Record + +#### Get Consumption Record Request + +```js +GET api/v1/users/me/consumption-records/2c1b0a9f-8e7d-4c6b-5a4f-3e2d1c0b9a8f +Authorization: Bearer +``` + +| Route value | Meaning | +| --- | --- | +| `recordId` | The Id of the consumption record. It must be a Guid and cannot be the empty Guid. | + +Returns the consumption record identified by the route, when it belongs to the current user. A record of another user is reported as not found, exactly like a record that does not exist, so a guessed identifier never reveals the existence of another user's session. + +#### Get Consumption Record Response + +```js +200 Ok +``` + +```json +{ + "id": "2c1b0a9f-8e7d-4c6b-5a4f-3e2d1c0b9a8f", + "libraryId": "5c6d7e8f-9a0b-4c1d-8e2f-3a4b5c6d7e8f", + "mediaItemId": "7a6b5c4d-3e2f-4a1b-8c9d-0e1f2a3b4c5d", + "mediaKind": "Book", + "status": "Stopped", + "startedOnUtc": "2026-10-24T12:00:00.0000000Z", + "lastActivityOnUtc": "2026-10-24T12:12:00.0000000Z", + "endedOnUtc": "2026-10-24T12:12:00.0000000Z", + "consumedDurationInSeconds": 720, + "lastPosition": { + "kind": "Location", + "timeOffsetSeconds": null, + "location": "epubcfi(/6/4[chapter-3]!/4/2/2)" + }, + "lastProgressFraction": 0.42, + "consecutivePagesRead": 6 +} +``` + +The response is a `ConsumptionRecordResponse` with the fields listed in [Start Consumption Response](#start-consumption-response). A record of another user, and a record that does not exist, are both reported with `ConsumptionRecordNotFound`. + +### Report Consumption Progress + +#### Report Consumption Progress Request + +```js +PUT api/v1/users/me/consumption-records/2c1b0a9f-8e7d-4c6b-5a4f-3e2d1c0b9a8f/progress +Authorization: Bearer +Content-Type: application/json +``` + +A music track reports a time offset: + +```json +{ + "position": { + "kind": "TimeOffset", + "timeOffsetSeconds": 92.5, + "location": null + }, + "progressFraction": 0.31, + "consumedDurationInSeconds": 92.5, + "consecutivePagesRead": 0 +} +``` + +A book reports an opaque location and the number of consecutive pages read: + +```json +{ + "position": { + "kind": "Location", + "timeOffsetSeconds": null, + "location": "epubcfi(/6/6[chapter-2]!/4/2/2)" + }, + "progressFraction": 0.18, + "consumedDurationInSeconds": 300, + "consecutivePagesRead": 2 +} +``` + +| Route value | Meaning | +| --- | --- | +| `recordId` | The Id of the consumption record, taken from the route. It must be a Guid and cannot be the empty Guid. | + +| Body field | Type | Required | Meaning | +| --- | --- | --- | --- | +| `position` | object | no | The latest position reported by the client. Send a complete position object to update it; omit it, or send an empty object, to keep the stored position. | +| `progressFraction` | number | yes | The fraction of the item the client reached, from 0 to 1, finite. It may move backwards. | +| `consumedDurationInSeconds` | number | yes | The active duration consumed by this session, in seconds. It must be finite, non-negative, within the maximum reportable range, and never lower than the value already stored for the session. | +| `consecutivePagesRead` | integer | no | The number of consecutive pages read in this session. It must be non-negative and is only accepted for page based media. Defaults to 0. | + +Reports the latest measurements of an in-progress session of the current user. The position and the progress fraction are the latest reported values, not the maximum values reached: a seek backwards is accepted and is stored as the new position. The consumed duration is the only monotonic measurement of the session and can never decrease. The operation never completes a session, even when the reported fraction reaches 1, because completion is explicit or threshold based. + +A session of a non-page-based kind cannot report consecutive pages above zero. A music client that sends `consecutivePagesRead` above zero is rejected with `ConsecutivePagesReadIsOnlySupportedForPageBasedMedia`, even though the request contract has the field for every kind. + +A book page count of 5 does not count as a session for statistics, while 6 does, but that counting rule belongs to the statistics read model and does not change the stored progress. + +The book reader counts a page as one visible reader viewport. A PDF page is a section of its own, while a reflowable section can hold several viewport pages, so the reported page count follows the pages the reader actually scrolled through rather than the printed pages of the source book. + +#### Report Consumption Progress Response + +```js +200 Ok +``` + +```json +{ + "id": "2c1b0a9f-8e7d-4c6b-5a4f-3e2d1c0b9a8f", + "libraryId": "5c6d7e8f-9a0b-4c1d-8e2f-3a4b5c6d7e8f", + "mediaItemId": "7a6b5c4d-3e2f-4a1b-8c9d-0e1f2a3b4c5d", + "mediaKind": "Book", + "status": "InProgress", + "startedOnUtc": "2026-10-24T12:00:00.0000000Z", + "lastActivityOnUtc": "2026-10-24T12:05:00.0000000Z", + "endedOnUtc": null, + "consumedDurationInSeconds": 300, + "lastPosition": { + "kind": "Location", + "timeOffsetSeconds": null, + "location": "epubcfi(/6/6[chapter-2]!/4/2/2)" + }, + "lastProgressFraction": 0.18, + "consecutivePagesRead": 2 +} +``` + +The response is a `ConsumptionRecordResponse` with the fields listed in [Start Consumption Response](#start-consumption-response). A record of another user, and a record that does not exist, are both reported with `ConsumptionRecordNotFound`. A terminal session returns `ConsumptionIsNotInProgress`. + +### Complete Consumption + +#### Complete Consumption Request + +```js +POST api/v1/users/me/consumption-records/2c1b0a9f-8e7d-4c6b-5a4f-3e2d1c0b9a8f/complete +Authorization: Bearer +Content-Type: application/json +``` + +A music track reports its final time offset: + +```json +{ + "position": { + "kind": "TimeOffset", + "timeOffsetSeconds": 300, + "location": null + }, + "progressFraction": 1, + "consumedDurationInSeconds": 300 +} +``` + +A book reports its final opaque location: + +```json +{ + "position": { + "kind": "Location", + "timeOffsetSeconds": null, + "location": "epubcfi(/6/8[chapter-4]!/4/2/2)" + }, + "progressFraction": 1, + "consumedDurationInSeconds": 900 +} +``` + +| Route value | Meaning | +| --- | --- | +| `recordId` | The Id of the consumption record, taken from the route. It must be a Guid and cannot be the empty Guid. | + +| Body field | Type | Required | Meaning | +| --- | --- | --- | --- | +| `position` | object | no | The final position. It is stored when provided; otherwise the stored position is kept. | +| `progressFraction` | number | yes | The final fraction of the item the client reached, from 0 to 1, finite. | +| `consumedDurationInSeconds` | number | yes | The final active duration consumed by the session, in seconds. It must be finite, non-negative, within the maximum reportable range, and never lower than the value already stored. | + +Completes an in-progress session of the current user. Completion is explicit, so it is recorded even when the media was not played to its final second. Completing a session deletes the resume point of the current user for the same media item. The final position, progress fraction, consumed duration and consecutive pages remain on the record. + +#### Complete Consumption Response + +```js +200 Ok +``` + +```json +{ + "id": "2c1b0a9f-8e7d-4c6b-5a4f-3e2d1c0b9a8f", + "libraryId": "3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a", + "mediaItemId": "9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f", + "mediaKind": "MusicTrack", + "status": "Completed", + "startedOnUtc": "2026-10-24T12:00:00.0000000Z", + "lastActivityOnUtc": "2026-10-24T12:05:00.0000000Z", + "endedOnUtc": "2026-10-24T12:05:00.0000000Z", + "consumedDurationInSeconds": 300, + "lastPosition": { + "kind": "TimeOffset", + "timeOffsetSeconds": 300, + "location": null + }, + "lastProgressFraction": 1, + "consecutivePagesRead": 0 +} +``` + +The response is a `ConsumptionRecordResponse` with the fields listed in [Start Consumption Response](#start-consumption-response). A record of another user, and a record that does not exist, are both reported with `ConsumptionRecordNotFound`. A terminal session returns `ConsumptionIsAlreadyTerminal`. + +### Stop Consumption + +#### Stop Consumption Request + +```js +POST api/v1/users/me/consumption-records/2c1b0a9f-8e7d-4c6b-5a4f-3e2d1c0b9a8f/stop +Authorization: Bearer +Content-Type: application/json +``` + +A music track reports where it was stopped: + +```json +{ + "position": { + "kind": "TimeOffset", + "timeOffsetSeconds": 60, + "location": null + }, + "progressFraction": 0.6, + "consumedDurationInSeconds": 60 +} +``` + +A book reports where it was stopped: + +```json +{ + "position": { + "kind": "Location", + "timeOffsetSeconds": null, + "location": "epubcfi(/6/6[chapter-2]!/4/2/2)" + }, + "progressFraction": 0.18, + "consumedDurationInSeconds": 300 +} +``` + +| Route value | Meaning | +| --- | --- | +| `recordId` | The Id of the consumption record, taken from the route. It must be a Guid and cannot be the empty Guid. | + +| Body field | Type | Required | Meaning | +| --- | --- | --- | --- | +| `position` | object | no | The final position. It is stored when provided; otherwise the stored position is kept. | +| `progressFraction` | number | yes | The final fraction of the item the client reached, from 0 to 1, finite. | +| `consumedDurationInSeconds` | number | yes | The final active duration consumed by the session, in seconds. It must be finite, non-negative, within the maximum reportable range, and never lower than the value already stored. | + +Stops an in-progress session of the current user before it completes. The library settings decide the terminal status: + +- When the library tracks progress, has a completion threshold, and the final progress fraction is at or above that threshold, the session is recorded as `Completed` instead of `Stopped`, and its resume point is deleted. Completion does not require the media to reach its final second. +- When the library tracks progress without a completion threshold, the session is recorded as `Stopped`. +- When the library does not track progress, the session is recorded as `Stopped`, without a completion threshold check. + +A stopped session keeps a resume point only when the library tracks progress, the kind can resume, and a final position is known. Without a known position there is nothing to resume from, so no resume point is written. Music libraries default to tracking off, so a normal music stop records history but does not create a resume point. A music library that explicitly enables tracking can create one. + +#### Stop Consumption Response + +```js +200 Ok +``` + +```json +{ + "id": "2c1b0a9f-8e7d-4c6b-5a4f-3e2d1c0b9a8f", + "libraryId": "3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a", + "mediaItemId": "9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f", + "mediaKind": "MusicTrack", + "status": "Stopped", + "startedOnUtc": "2026-10-24T12:00:00.0000000Z", + "lastActivityOnUtc": "2026-10-24T12:01:00.0000000Z", + "endedOnUtc": "2026-10-24T12:01:00.0000000Z", + "consumedDurationInSeconds": 60, + "lastPosition": { + "kind": "TimeOffset", + "timeOffsetSeconds": 60, + "location": null + }, + "lastProgressFraction": 0.6, + "consecutivePagesRead": 0 +} +``` + +The response is a `ConsumptionRecordResponse` with the fields listed in [Start Consumption Response](#start-consumption-response). The `status` is `Completed` when the stop reached the library completion threshold, and `Stopped` otherwise. A record of another user, and a record that does not exist, are both reported with `ConsumptionRecordNotFound`. A terminal session returns `ConsumptionIsAlreadyTerminal`. + +### Get Resume Point + +#### Get Resume Point Request + +```js +GET api/v1/users/me/media-resume-points/Book/7a6b5c4d-3e2f-4a1b-8c9d-0e1f2a3b4c5d +Authorization: Bearer +``` + +The same operation reads a music track resume point, when the music library tracks progress: + +```js +GET api/v1/users/me/media-resume-points/MusicTrack/9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f +Authorization: Bearer +``` + +| Route value | Meaning | +| --- | --- | +| `mediaKind` | The kind of media to resume, matched case insensitively. `MusicTrack` and `Book` can resume today. `Photo` cannot resume. | +| `mediaItemId` | The Id of the media item to resume. It must be a Guid and cannot be the empty Guid. | + +Returns the resume point of the current user for the item named by the route. A book resume point carries an opaque location, while a music track resume point carries a time offset. A resume point of another user is reported as not found, exactly like a missing resume point, so a guessed identifier never reveals another user's position. + +When the media item no longer exists, or no longer belongs to the library recorded in the resume point, the resume point is an orphan. It is deleted before the item is reported as not found. A client that reopens the item must therefore fall back to the beginning instead of assuming the stored point still exists. + +When the library that recorded the resume point no longer tracks consumption progress, the stored resume point is deleted and reported as `MediaResumePointNotFound`, so turning tracking off takes effect for an existing position as well. + +A kind whose catalogue does not exist yet is rejected with `UnsupportedMediaKind`, so a planned kind cannot return a resume point that start would never create. A photo is the exception among the planned kinds: it has no position representation, so it is rejected with `MediaKindCannotResume`. The invalid `None` kind is rejected with `UnsupportedMediaKind`. + +#### Get Resume Point Response + +```js +200 Ok +``` + +```json +{ + "id": "4d5e6f70-8192-4a3b-9c4d-5e6f708192a3", + "libraryId": "5c6d7e8f-9a0b-4c1d-8e2f-3a4b5c6d7e8f", + "mediaItemId": "7a6b5c4d-3e2f-4a1b-8c9d-0e1f2a3b4c5d", + "mediaKind": "Book", + "lastPosition": { + "kind": "Location", + "timeOffsetSeconds": null, + "location": "epubcfi(/6/4[chapter-3]!/4/2/2)" + }, + "lastProgressFraction": 0.42, + "lastConsumedOnUtc": "2026-10-24T12:12:00.0000000Z" +} +``` + +| Field | Type | Meaning | +| --- | --- | --- | +| `id` | Guid | The Id of the resume point. | +| `libraryId` | Guid | The Id of the library that contains the item. | +| `mediaItemId` | Guid | The Id of the item to resume. | +| `mediaKind` | string | The kind of media that is resumed. | +| `lastPosition` | object | The position at which the item can be resumed. See [Position Kinds](#position-kinds). | +| `lastProgressFraction` | number | The progress fraction at which the item can be resumed, from 0 to 1. | +| `lastConsumedOnUtc` | DateTime | When the item was last consumed. | + +A missing resume point returns `MediaResumePointNotFound`. A deleted item, or an item that no longer belongs to the recorded library, returns `TrackNotFound` or `BookNotFound` after the orphan resume point is removed. A kind that cannot resume returns `MediaKindCannotResume`. + +### Media Kinds + +`MediaKind` is shared across media contexts and is stored by its name. + +| Kind | Status | Item | +| --- | --- | --- | +| `None` | Invalid | It is not a media kind and is rejected wherever a kind is required. | +| `MusicTrack` | Supported | A track of a music library. Resumes with a time offset. | +| `PodcastEpisode` | Planned | A podcast episode. Its catalogue does not exist yet. | +| `Audiobook` | Planned | An audiobook. Its catalogue does not exist yet. | +| `Movie` | Planned | A movie. Its catalogue does not exist yet. | +| `TvEpisode` | Planned | A TV episode. Its catalogue does not exist yet. | +| `Book` | Supported | A book of a book library. Resumes with an opaque location. | +| `Photo` | Planned | A photo. Its catalogue does not exist yet, and it has no position, so it cannot resume. | +| `Video` | Planned | A video. Its catalogue does not exist yet. | + +Only the supported kinds can start a consumption session for now. A planned kind is rejected with `UnsupportedMediaKind`, and a `None` kind is rejected by validation. The planned kinds are listed so that clients can map the shared enumeration, not because their routes are available. + +### Session Statuses + +| Status | Meaning | +| --- | --- | +| `InProgress` | The session is running. Progress reports are accepted, and the record has no end time. | +| `Completed` | The session ended because completion was reported, or because a stop reached the library completion threshold. The record has an end time and the status is terminal. | +| `Stopped` | The session ended without completing. The record has an end time and the status is terminal. | + +`Completed` and `Stopped` are terminal. A terminal record rejects further progress with `ConsumptionIsNotInProgress`, and further complete or stop operations with `ConsumptionIsAlreadyTerminal`. No update can move it back to `InProgress`. + +### Position Kinds + +A position is exactly one of two representations. The `kind` names the representation, and the fields of the other representation must be absent or null. + +| Kind | Fields | Used by | +| --- | --- | --- | +| `TimeOffset` | `timeOffsetSeconds`: a non-negative finite number of seconds, within the maximum reportable range. `location` must be null or omitted. | Music tracks and the other time based kinds. | +| `Location` | `location`: a non-empty opaque string of at most 4096 characters. `timeOffsetSeconds` must be null or omitted. | Books and other page or section based kinds. | + +An empty position object means no position and keeps the stored position. When a `kind` is present, exactly one representation must be present: `TimeOffset` requires `timeOffsetSeconds` and no `location`, while `Location` requires `location` and no `timeOffsetSeconds`. A position with a time offset or a location but no `kind`, a position with both representations, a position with a kind but no matching representation, an unknown or numeric kind, a negative or non-finite time offset, or an empty or too long location is rejected with `InvalidMediaPosition`. The position kind must also match the media kind: a time offset on a book, or a location on a music track, is rejected with `InvalidMediaPosition`. + +A photo has no position kind, so it cannot resume. The server does not parse a book location: it stores and returns the opaque locator exactly as reported. + +### Reportable Ranges + +| Value | Rule | +| --- | --- | +| `progressFraction` | Finite and between 0 and 1, inclusive. | +| `consumedDurationInSeconds` | Finite, non-negative, and at most 31 days. It must also be at least the value already stored for the session. | +| `timeOffsetSeconds` | Finite, non-negative, and at most 31 days. | +| `location` | Non-empty and at most 4096 characters. | +| `consecutivePagesRead` | Non-negative. Only page based media may report a value above zero. | + +The 31 day limit keeps accumulated totals representable and rejects durations that cannot describe real media. The consumed duration is the only value that must not decrease; the position and the progress fraction are latest reported values and may move backwards. + +### Session Lifecycle and Resume Points + +A session moves through one lifecycle: + +1. [Start Consumption](#start-consumption) creates an `InProgress` record and returns its identifier. +2. [Report Consumption Progress](#report-consumption-progress) updates the latest position, progress fraction, consumed duration and consecutive page count. It never completes the session. +3. [Complete Consumption](#complete-consumption) or [Stop Consumption](#stop-consumption) ends the session, sets its end time, and makes it terminal. + +A resume point is separate from the history. It is created or updated by progress and stop when the library tracks progress, the kind can resume, and a position is known. It is read by start to initialize a new session. It is deleted by completion and by a stop that reaches the completion threshold. A stopped session that did not reach the threshold keeps it for the next start. Deleting a history record does not delete the resume point, because the two are separate actions in the product. + +The business key of a resume point is the user, the media kind and the media item. There is at most one resume point per key, so a progress report updates the existing row instead of inserting a second one. + +Ending a session is best effort on the client side. A client can disappear between its start request and its first terminal request, for example when a full page unload happens while the start is still in flight. The record created by such a start remains `InProgress`: the API does not expire it, and start is not idempotent, so the next session creates a new record instead of closing or reusing the lost one. A lost session therefore remains in the stored history as a record that was never ended. + +### Completion Threshold + +Completion is explicit or threshold based, and the threshold is a per-library setting. The relevant settings are `shouldTrackConsumptionProgress` and `completionThresholdPercentage` on the library, documented in [Libraries](../library/management/Api.Libraries.md). The per-library value always wins. When a library is created without explicit values, the defaults by library type are: + +| Library category | Track progress | Completion threshold | +| --- | --- | --- | +| Music audio (`Music`, `Remix`, `SoundEffect`, `CoverSongAudio`, `LiveRecordingAudio`, `InterviewAudio`) | no | none | +| Photo | no | none | +| Written content (`Book`, `EBook`, `ComicBook`, `Magazine`, `Newspaper`, `Manga`, `GraphicNovel`, `AcademicPaper`, `SheetMusic`) | yes | 100 | +| Video (`TvShow`, `Movie`, `Documentary`, `Anime`, `ConcertVideo`, `TutorialVideo`, `HomeVideo`, `YouTubeVideo`, `MusicVideo`, `LiveRecordingVideo`, `InterviewVideo`, `CoverSongVideo`) | yes | 90 | +| Audiobook and podcast (`Audiobook`, `PodcastAudio`, `PodcastVideo`) | yes | 95 | +| Other, non-media or unknown (`Playlist`, `Collection`, `Subtitles`, `Lyrics`, `Other`, any type added later) | no | none | + +A stop reaches the threshold when the library tracks progress, a threshold is set, and the final progress fraction is at or above the threshold divided by 100. The comparison is done on the fraction, so a fraction exactly at the threshold completes the session. A library with tracking on and no threshold completes only when completion is reported explicitly. Tracking off never completes a session implicitly. + +### Scoping and Authorization + +Every route acts on the current user, read from the authenticated principal, never from the route, the query or the body. A client cannot read, progress, complete or stop another user's session through these routes. + +Starting a session also applies the library ownership policy for the route library. When the current user cannot access the route library, the operation returns `NotAuthorized` before it looks up the item. When the route library is accessible, an item that does not exist and an item that belongs to another library are reported with the same kind specific not found error, so the response cannot be used to find out whether an item exists in another library. The kind specific errors are: + +| Kind | Not found error | +| --- | --- | +| `MusicTrack` | `TrackNotFound` | +| `Book` | `BookNotFound` | + +A missing library returns `LibraryNotFound`. The current user must have access to the library; otherwise the start returns `NotAuthorized`. + +Reading a single record or a single resume point is owner only. A record or resume point of another user is reported as not found, not as forbidden, so the response shapes are indistinguishable. Admins do not write another user's session. + +### Private Responses + +Every response produced by these endpoints is private to the authenticated user. Each endpoint sets: + +- `Cache-Control: private, no-store` +- `Vary: Authorization` + +The headers are set before the operation runs, so they are present on the endpoint's problem responses too, including `403`, `404`, `409` and `422`. A request rejected by the authentication middleware with `401` before the endpoint runs is produced by the framework rather than by the endpoint. The CORS middleware may also add `Vary: Origin`; the endpoints append `Authorization` instead of replacing the header, so both values are preserved. + +### 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. | +| `403` | `NotAuthorized` | The authenticated principal carries no user identity, or the current user cannot access the route library on start. | +| `403` | `ConsumedDurationCannotDecrease` | A progress, complete or stop request reports a consumed duration lower than the duration already stored for the session. | +| `403` | `ConsecutivePagesReadIsOnlySupportedForPageBasedMedia` | A progress report sends consecutive pages above zero for a kind that is not page based, such as a music track. | +| `403` | `MediaKindCannotResume` | A resume point is requested for a kind that cannot resume, such as a photo. | +| `404` | `LibraryNotFound` | The start route names a library that does not exist. | +| `404` | `TrackNotFound` | The start route names a music track that does not exist, or that does not belong to the route library, or a resume point names a track that no longer exists or no longer belongs to its recorded library. | +| `404` | `BookNotFound` | The start route names a book that does not exist, or that does not belong to the route library, or a resume point names a book that no longer exists or no longer belongs to its recorded library. | +| `404` | `ConsumptionRecordNotFound` | The record does not exist, or it belongs to another user. | +| `404` | `MediaResumePointNotFound` | The resume point does not exist, belongs to another user, or belongs to a library that no longer tracks consumption progress. | +| `409` | `ConsumptionIsNotInProgress` | A progress report targets a session that is already completed or stopped. | +| `409` | `ConsumptionIsAlreadyTerminal` | A complete or stop request targets a session that is already completed or stopped. | +| `409` | `ConcurrencyConflict` | Another request changed the same row after this request read it, or the storage reported a busy or locked database. Repeating the request is safe when it reports the current values. | +| `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": "ConsumptionRecordNotFound", + "instance": "/api/v1/users/me/consumption-records/2c1b0a9f-8e7d-4c6b-5a4f-3e2d1c0b9a8f", + "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/consumption-records/2c1b0a9f-8e7d-4c6b-5a4f-3e2d1c0b9a8f/progress", + "errors": { + "General.Validation": [ + "InvalidProgressFraction", + "InvalidMediaPosition" + ] + }, + "traceId": "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01" +} +``` + +The validation errors of each operation are: + +| Error | Operation | When | +| --- | --- | --- | +| `LibraryIdCannotBeEmpty` | Start | The library Id is missing or is not a non-empty Guid. | +| `MediaItemIdCannotBeEmpty` | Start, Get Resume Point | The item Id is missing or is not a non-empty Guid. | +| `UnsupportedMediaKind` | Start, Get Resume Point | The kind is missing, is not a member name of the media kind enumeration, or is a planned kind whose catalogue does not exist yet. A numeric value is rejected even when it is a defined enumeration value. On Get Resume Point, a photo is rejected with the 403 `MediaKindCannotResume` instead. | +| `ConsumptionRecordIdCannotBeEmpty` | Get Record, Progress, Complete, Stop | The record Id is missing or is not a non-empty Guid. | +| `InvalidMediaPosition` | Progress, Complete, Stop | The position is partially specified, uses both or neither representation for its kind, has an unknown or numeric kind, a negative or non-finite time offset, an empty or too long location, or a position kind that does not match the media kind. | +| `InvalidProgressFraction` | Progress, Complete, Stop | The progress fraction is missing, is not finite, or is outside 0 to 1. | +| `ConsumedDurationMustBeNonNegative` | Progress, Complete, Stop | The consumed duration is missing, is not finite, or is negative. | +| `ConsumedDurationIsOutOfRange` | Progress, Complete, Stop | The consumed duration is above 31 days. | +| `ConsecutivePagesReadMustBeNonNegative` | Progress | The consecutive page count is negative. | + +A value that cannot be bound, such as a non-numeric progress fraction or a non-integer page count, is not reported by these validators. The endpoint does not catch binding failures, so the framework answers the request with its usual binding problem, and the web client never sends such values because its proxy endpoints rebuild the body from typed values. + +### Concurrency + +Every consumption record and resume point carries an optimistic concurrency version. A progress, complete or stop request reads the stored version, and the update is applied only when the stored version still matches. If another request ended or changed the session between the read and the write, the update affects no row and the request is reported as `409 ConcurrencyConflict`. A late progress report therefore never reverts a completed or stopped session, never clears its end time, and never lowers its consumed duration. A busy or locked SQLite write is reported the same way. + +Repeating a progress, complete or stop request after a concurrency conflict is safe only when the client re-reads the record and reports values that are still valid for it. A complete or stop of a terminal session returns `ConsumptionIsAlreadyTerminal`, and a progress report of a terminal session returns `ConsumptionIsNotInProgress`. diff --git a/docs/technical/api/users-management/Api.Settings.md b/docs/technical/api/users-management/Api.Settings.md index 53993dee..6dae4440 100644 --- a/docs/technical/api/users-management/Api.Settings.md +++ b/docs/technical/api/users-management/Api.Settings.md @@ -8,6 +8,12 @@ - [Update User Settings](#update-user-settings) - [Update User Settings Request](#update-user-settings-request) - [Update User Settings Response](#update-user-settings-response) + - [Get Playback State](#get-playback-state) + - [Get Playback State Request](#get-playback-state-request) + - [Get Playback State Response](#get-playback-state-response) + - [Update Playback State](#update-playback-state) + - [Update Playback State Request](#update-playback-state-request) + - [Update Playback State Response](#update-playback-state-response) ## Settings @@ -32,11 +38,25 @@ Returns the settings of the currently authenticated user. "userId": "2cff0c0f-3a67-4e30-b94f-f4e948a3b64f", "isPaginationEnabled": true, "itemsPerPage": 50, - "ignoreThePrefixForAlphaPicker": true, + "shouldIgnoreThePrefixForAlphaPicker": true, "isThemeCachingEnabled": true, "shouldAggregateMetadataWhenMissing": true, "shouldRenderPdfAsImages": false, - "shouldPreserveBookStyles": true + "shouldPreserveBookStyles": true, + "shouldKeepDownloadingWhilePaused": true, + "shouldAutoplay": true, + "isGaplessPlaybackEnabled": true, + "replayGainMode": "Off", + "streamingQuality": "Auto", + "vuMeterOrientation": "Vertical", + "vuMeterSegmentCount": 12, + "vuMeterSegmentGap": 1, + "vuMeterMediumThreshold": 0.6, + "vuMeterHighThreshold": 0.8, + "vuMeterShowPeak": true, + "vuMeterPeakHoldDurationInMilliseconds": 650, + "vuMeterReleasePerSecond": 3, + "vuMeterPeakReleasePerSecond": 0.65 } ``` @@ -50,15 +70,31 @@ PUT api/v1/users/me/settings Updates the settings of the currently authenticated user. +The VU meter settings configure the segmented meter of the player bar: `vuMeterOrientation` is `Vertical` or `Horizontal`, `vuMeterSegmentCount` is between 1 and 128, `vuMeterSegmentGap` is between 0 and 32 pixels, `vuMeterMediumThreshold` and `vuMeterHighThreshold` are between 0 and 1 and the high threshold must not be lower than the medium one, `vuMeterPeakHoldDurationInMilliseconds` is between 0 and 10000, and `vuMeterReleasePerSecond` and `vuMeterPeakReleasePerSecond` are between 0 and 100 level units per second. All of them are required. + ```json { "isPaginationEnabled": true, "itemsPerPage": 50, - "ignoreThePrefixForAlphaPicker": true, + "shouldIgnoreThePrefixForAlphaPicker": true, "isThemeCachingEnabled": true, "shouldAggregateMetadataWhenMissing": true, "shouldRenderPdfAsImages": false, - "shouldPreserveBookStyles": true + "shouldPreserveBookStyles": true, + "shouldKeepDownloadingWhilePaused": true, + "shouldAutoplay": true, + "isGaplessPlaybackEnabled": true, + "replayGainMode": "Off", + "streamingQuality": "Auto", + "vuMeterOrientation": "Vertical", + "vuMeterSegmentCount": 12, + "vuMeterSegmentGap": 1, + "vuMeterMediumThreshold": 0.6, + "vuMeterHighThreshold": 0.8, + "vuMeterShowPeak": true, + "vuMeterPeakHoldDurationInMilliseconds": 650, + "vuMeterReleasePerSecond": 3, + "vuMeterPeakReleasePerSecond": 0.65 } ``` @@ -67,3 +103,49 @@ Updates the settings of the currently authenticated user. ```js 200 Ok ``` + +### Get Playback State + +#### Get Playback State Request + +```js +GET api/v1/users/me/settings/playback-state +``` + +Returns the playback state (the last volume and mute state) the player reported for the currently authenticated user. The values are written automatically by the player and are never surfaced as settings fields. + +#### Get Playback State Response + +```js +200 Ok +``` + +```json +{ + "volume": 0.75, + "isMuted": false +} +``` + +### Update Playback State + +#### Update Playback State Request + +```js +PUT api/v1/users/me/settings/playback-state +``` + +Updates the playback state the player reported for the currently authenticated user. Both fields are required: the volume is a value between 0 and 1, and the mute state is a boolean. A request that omits either field, or sends a volume outside that range, is rejected with a `422 Unprocessable Entity`. + +```json +{ + "volume": 0.75, + "isMuted": false +} +``` + +#### Update Playback State Response + +```js +200 Ok +``` diff --git a/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0006.md b/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0006.md index 2018e742..bc32e032 100644 --- a/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0006.md +++ b/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0006.md @@ -33,7 +33,7 @@ SQLite Write-Ahead Logging (`PRAGMA journal_mode=WAL`) and a busy timeout are en ### Risks and Tradeoffs | Risk | Mitigation Strategy | |-------------------------------|-------------------------------------------------------------------| -| Raw SQL duplication | All raw SQL is confined to the two bulk repositories, behind the repository and unit of work abstractions | +| Raw SQL duplication | All raw SQL is confined to the bulk repositories (the scan jobs and the documented playlist append), behind the repository and unit of work abstractions | | Concurrency errors | WAL and a busy timeout are enabled at startup, and the bulk operations run on dedicated connections | | Layer integrity | Dapper is referenced only by the DataAccess layer | @@ -47,4 +47,26 @@ Bulk statements would run on the same connection as the tracked queries of the j ### 2. Third party bulk library (for example EF Core bulk extensions) A dedicated bulk extension library would abstract the raw SQL. -**Rejected**: Dapper is a small, widely adopted and dependency free mapper, and the amount of raw SQL is small and confined to two repositories. See the ADRs of the scan subsystem for the exact statements. +**Rejected**: Dapper is a small, widely adopted and dependency free mapper, and the amount of raw SQL is small and confined to the bulk repositories. See the ADRs of the scan subsystem for the exact statements, and the amendment below for the playlist append. + +## Amendment: Playlist Whole-Library Appends (2026-10-20) + +The playlist feature needs to append a whole library, which can contain hundreds of thousands of tracks, to a playlist in one request. The Entity Framework change tracker cannot materialize that graph, so `PlaylistRepository.AddEntriesAsync` performs the append with parameterized multi-row `INSERT` statements in bounded batches. + +Unlike the scan jobs, this bulk operation deliberately uses the connection and the transaction of the request's unit of work, not a dedicated connection. The request middleware already holds the SQLite write transaction, and a dedicated connection would wait on that lock while the request waits on the append. Sharing the request transaction keeps the append atomic with the ownership check and the activity update, and the busy timeout plus the unique `(PlaylistId, Position)` index turn a concurrent append into a mapped conflict instead of a duplicate position. + +The exception is confined to the append and the rare sparse-key rebalance in `PlaylistRepository` and is documented in the class remarks. Moves and removals use Entity Framework `ExecuteUpdateAsync` and `ExecuteDeleteAsync` on their normal path, so they keep the model, the transaction and the error mapping. The rebalance uses raw SQL only when repeated midpoint moves exhaust the numeric gap between two neighbors; it respaces the order keys through a temporary table inside the request transaction. + +## Amendment: Playlist Scope Ordering and Rollback (2026-10-21) + +A whole library, artist or album scope is now appended with one `INSERT ... SELECT` statement in `PlaylistRepository.AddScopeEntriesAsync`. The statement joins the catalogue tables, orders the tracks with `ROW_NUMBER()` in SQLite and computes the sparse positions as part of the insert, so the scope is never materialized, sorted in memory or sent to the data access layer as a list of Ids. Explicit track lists still use the batched `AddEntriesAsync` path, because that list is already in memory. + +An append that fails or is cancelled rolls the request transaction back explicitly. The context records that rollback, and the eventual consistency middleware skips the commit and logs it when the response still reports success, instead of committing a partially written operation. + +## Amendment: Request Transaction Ownership and Aborted Requests (2026-10-21) + +The eventual consistency middleware now begins, commits and rolls back the request transaction through `IUnitOfWork`, so the transaction boundary follows the unit of work instead of the `DbContext` being used directly. The commit-before-publish sequence of ADR-0002 is unchanged. + +An aborted request is no longer left at its default success status: the exception handling middleware reports it as `499 Client Closed Request` and rethrows. The eventual consistency middleware therefore decides from the response status alone. It commits a 2xx response and rolls back every other response, including an abort, and it deliberately does not consult the request abort token, because that token can already be cancelled after a successful operation whose response was already sent. + +This replaces the in-context rollback marker and the repository's rollback of the ambient request transaction described in the previous amendment. A repository now only commits or rolls back a transaction it opened itself, which happens when it runs without an ambient request transaction. A partially written append is therefore discarded by the middleware's rollback, not by a signal from the repository. diff --git a/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0014.md b/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0014.md index 46b8df6e..32fd843b 100644 --- a/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0014.md +++ b/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0014.md @@ -82,3 +82,17 @@ Introduce a generic persistence engine driven by a per-aggregate profile describ Stop modeling shared references as a shared table keyed by name, and store them per aggregate, removing the duplicate-key-in-graph class of bug at the source. **Rejected**: it requires a database schema change and changes query behavior for shared references, which is out of scope. The shared tables are kept, and the concern is handled where it belongs, in the persistence toolkit. + +## Amendment: Set-Based Playlist Entry Operations (2026-10-20) + +The playlist entries are mutated by set-based storage operations because a playlist can hold a whole library. The batched raw append and the `ExecuteUpdateAsync` and `ExecuteDeleteAsync` move and removal statements bypass the change tracker and therefore also bypass the auditing interceptor. + +Those operations stamp `UpdatedOnUtc` and `UpdatedBy` on the playlist row themselves, stamp the creation or update audit columns of the entry rows they write, and increment the playlist concurrency token, in the same transaction. This is the only exception to the rule that the auditing interceptor is the only writer of the audit columns. Details edits still go through `EditableValuesCopier` and leave the audit columns to the interceptor. The exception is confined to `PlaylistRepository` and is documented in the class remarks. + +Ordering is storage owned as well. The unique index on `(PlaylistId, Position)` is the enforced invariant, and the positions are sparse order keys rather than dense indices. A move normally changes one key to the midpoint between its new neighbors, and a removal deletes one row, so neither rewrites the following range. If repeated midpoint moves exhaust the numeric gap between two neighbors, a rare rebalance respaces the keys with a temporary table and two passes so the unique index is never violated. The domain only rejects duplicate positions on reconstitution, so a storage gap is readable instead of making the playlist impossible to load. + +## Amendment: Playlist Entry Count and Change Detection (2026-10-21) + +The playlist row now carries a denormalized `EntryCount`, maintained by the set-based append and removal operations in the same statement that updates the playlist activity time and concurrency token. Window reads, moves and the single-add read-back use that column instead of counting the entries of the playlist, so none of them scan an index proportional to the playlist size. + +Details edits still go through `EditableValuesCopier`, but the copier now compares the incoming value with the tracked value before assigning it and marks only an actual change as modified. `PlaylistRepository.UpdateAsync` also compares the tracked original values explicitly before it decides to increment the concurrency token, so a no-op save neither restamps the row nor bumps its version. diff --git a/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0016.md b/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0016.md new file mode 100644 index 00000000..f438f466 --- /dev/null +++ b/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0016.md @@ -0,0 +1,97 @@ +# Architecture Decision Record (ADR): 0016 - Playback Delivery Decision and Player Capability Negotiation + +## Status + +**Accepted** (2026-10-14) + +## Context + +Lumina's music player is implemented from scratch, on WebCodecs for decoding and the Web Audio API for output, with no `HTMLMediaElement` and no Media Source Extensions. That player can only demux a curated set of containers and decode a curated set of codecs, so the server has to tell it, before it fetches any audio, whether a track can be played as stored or whether the server has to change the container or the codec first. + +The server already has each track's stored probe result (the container and the codec, plus the sample rate, the channels, the bit depth, the duration and the ReplayGain values) and a stream endpoint with HTTP range support that serves the original file. What is missing is the decision itself and a way for the player to state what it can play. + +## Decision + +Introduce a playback format service (`IPlaybackFormatService`, `PlaybackFormatService`) that, given the container and the codec of a track as read from its stored probe result and the capabilities a player advertises, decides one of three delivery modes: direct play, remux, or transcode. It stays in the Application layer (interface) and the Infrastructure layer (implementation), as a service: the byte and codec pipeline is not part of the playback domain aggregate. + +### Delivery modes + +| Mode | Condition | Delivery format | Delivery shape | +|---|---|---|---| +| Direct play | The player can demux the stored container and decode the stored codec | The stored container and codec, unchanged | Byte range seekable | +| Remux | The player can decode the stored codec but has no demuxer for the stored container | The stored codec, repackaged into a server container the player can demux | Time addressed segments | +| Transcode | The player cannot decode the stored codec | The most preferred codec the server can produce that the player advertises | Time addressed segments | + +- The stored codec is the free form description reported by the probe (for example `MPEG-1 Layer 3`), so it is canonicalized to the codec name players advertise (for example `MP3`) before it is compared. The MPEG layer is matched by its layer number only (`LAYER 3`/`LAYER III`), so `MPEG-1 Layer 1` and `MPEG-1 Layer 2` are not mistaken for `MP3`, and a description that names no recognizable codec is left as it is, which keeps it from matching any advertised codec and forces a transcode. Containers are canonicalized by casing. +- The container a normalized delivery is produced in is always chosen from the containers the server can produce for the codec, never from the container the player names: the player only selects among the server's known containers, so a container supplied by a client never reaches the transcoder or a cache name. The containers the server produces each codec in are, in order of preference: `PCM` in `WAV`, `MP3` in `MP3`, `FLAC` in `FLAC`, `Opus` and `Vorbis` in `OGG`, `AAC` in `MP4` then `AAC`. +- The server can produce, in order of preference, `AAC`, `OPUS`, `MP3`, `VORBIS`, `FLAC` and `PCM` (the efficient lossy codecs before the lossless ones, and uncompressed last), so a transcode re-encodes to the first of these the player advertises in one of its containers. When the player advertises no producible codec, the decision fails with `NoSupportedPlaybackFormat`, which is a forbidden outcome (HTTP 403) rather than a malformed request, and no delivery is attempted. + +### Capability input convention + +The capabilities a player can demux and decode directly are carried on the playback manifest request as a query parameter named `capabilities`, whose value is a comma separated list of `container/codec` pairs: + +``` +GET /api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}/playback-manifest?capabilities=mp3/mp3,flac/flac,ogg/opus,ogg/vorbis,wav/pcm,mp4/aac +``` + +- The container and the codec of a pair are matched case insensitively, and surrounding whitespace is ignored. +- A pair must name both a container and a codec, with neither empty (for example `flac`, `a/b/c` and `a//b` are ignored). +- At most 32 pairs are read from one request, so the parsing work stays bounded regardless of the input length. +- When the parameter is absent, empty, or lists no valid pair, the server applies the default capabilities of the bundled player, so a request that advertises nothing still gets a playable decision: + `mp3/mp3`, `flac/flac`, `ogg/opus`, `ogg/vorbis`, `wav/pcm`, `aac/aac`. The default set is the bundled player's demuxer set (MP3, AAC/ADTS, FLAC, OGG and WAV), so it deliberately contains no `mp4/aac` pair: a track stored in MP4 is remuxed to raw AAC for a request that advertises nothing, rather than being marked direct play for a container the bundled player cannot demux. +- The convention is a query parameter rather than a request header, so that it is part of the request's own contract, is trivially testable, and is forwarded by the web app's manifest proxy without depending on header forwarding. + +### Delivery shape + +The `TimeAddressedSegments` delivery shape is a sequence of approximately fixed duration segments addressed and seeked by time, so that finding a time never requires mapping a byte range to it. The nominal segment duration is 6 seconds, and it is carried in the delivery decision so that the producer of the segments and the player agree on it. A segment is cut at the first packet at or after its nominal boundary, so its real start is not always an exact multiple of the nominal duration; the producer records the real start in its index, and the segment route reports it in a response header. Direct play is `ByteRangeSeekable`, because the original file is served by the existing range-capable stream endpoint. + +### Segment addressing + +The segments are exposed through a dedicated segment route, `.../stream/deliveries/{deliveryId}/segments/{segmentIndex}`, which extends the track stream endpoint's contract. The playback manifest carries its relative path in `segmentStreamPathTemplate`, with `{deliveryId}` and `{segmentIndex}` placeholders, and the web application rewrites that path to its own segment proxy so that the browser never reaches the API server. The manifest also reports the opaque `deliveryId` the placeholders are expanded with. + +- An index addresses a whole segment, so no byte range is ever sent for a normalized delivery. +- The delivery handle the manifest issued is the only authority on the delivery of the segments. It is a random, opaque value bound to the user and the track, and it captures the delivery decision, the quality cap and the source file version the manifest declared. The segment route resolves it instead of recomputing the decision from a capability list, rereading the user's quality setting, or restating a file that may have changed. A changed file is rejected as a conflict rather than starting a second production whose segments would be mixed with the declared one. +- Library ownership is still evaluated on every segment request, so revoked access stops playback immediately. The track membership and the library content locations are the ones captured when the manifest was issued, so deleting a track row while its file remains, or removing a content location, can keep that media streamable until the handle expires. That is the deliberate trade-off for not reloading the track and library graph for every six second segment; the handle lifetime is bounded to 12 hours. +- The handles are process local, like the normalized audio cache they address. They expire after a bounded lifetime, are bounded globally and per user, and a repeated manifest for the same delivery inputs reuses the existing handle, so the registry cannot grow without bound. Expired handles are removed in issue order from a queue, so the sweep is amortized constant time rather than a scan of every handle. +- A production is atomic: the first segment request may wait for the whole normalized track to be produced and cached, and the following segment requests are served from that cache. +- The player keeps a bounded lookahead of one segment ahead of the segment the demuxer consumed, so the link is not idle between segments and the streamed indicator can run ahead. The lookahead stops while playback is paused unless the user enabled the keep-downloading-while-paused preference, and it never advances itself, so it cannot turn into a full download of the track. +- Gapless prefetch starts only near the end of the current track, not at load time. A normalized next track therefore transitions without a gap only when its production is already cached or finishes within that lead; otherwise it starts normally at the boundary. The lead is deliberately shorter than a long production, because holding a normalization slot for a track the user may never reach is worse than a small gap. +- The player keeps every segment it has fetched for the lifetime of the track, so seeking back into a fetched segment does not fetch it again. A seek reads the target segment from its first packet and drops the packets that end before the target, instead of seeking inside the segment: a container that numbers its frames across the whole track would otherwise add that number to the segment offset twice. A segment is short, so reading it from its start is exact for every delivered container. + +## Consequences + +### Positive Outcomes + +| Aspect | Benefit | +|---|---| +| Decoupling | The player states what it can play and never has to know the server's codecs; the server states the delivery and never has to know the player's implementation | +| Efficiency | A container a player cannot demux but a codec it can decode is repackaged instead of re-encoded, and only a genuinely unsupported codec is re-encoded | +| Determinism | The containers the server produces each codec in and the transcode preference order are fixed, so the same input always yields the same delivery | +| Seekability | Time addressed segments make a normalized delivery seekable without a byte to time index | +| Testability | The decision is a pure function of the stored container and codec and the advertised capabilities | + +### Risks and Mitigations + +| Risk | Mitigation Strategy | +|---|---| +| The probe reports a codec as a free form description that does not name the codec the player advertises | The stored description is canonicalized to the advertised codec names before comparison, and the MPEG layer is matched by its layer number, so a description that names no decodable codec is left unmatched and forces a transcode | +| A player advertises a container the server cannot produce | The delivered container is always chosen from the containers the server produces the codec in, never from the container the player names, so a client supplied container never reaches the transcoder or a cache name; a codec the player cannot be served in any server container is not used | +| The real segment start drifts from the nominal grid | The nominal duration is carried by the manifest, and the exact indexed start of each segment is reported in `X-Segment-Start-Seconds` and used by the player, so neither side assumes an exact grid | + +## Alternatives Considered + +### 1. Decide the delivery from the container only + +**Rejected**: a container can carry several codecs (for example `OGG` carries both Vorbis and Opus), so the container alone cannot tell whether the player can decode the audio, and the difference between a remux and a transcode would be lost. + +### 2. Let the player decide, by sending its full codec support to the server and reading the probe result itself + +**Rejected**: it leaks the server's storage and probe details to the client and duplicates the decision on both sides. The server owns the probe result and the producible formats. + +### 3. Carry the capabilities in a request header + +**Rejected**: a header has to be explicitly forwarded by the web app's manifest proxy and is harder to exercise from a browser or a request file than a query parameter, with no benefit that a query parameter does not already provide. + +### 4. Deliver a remuxed track as a single byte range seekable file instead of segments + +**Rejected**: it makes remuxed and transcoded tracks two different delivery shapes for the player to consume, and it reintroduces the byte to time mapping the time addressed shape exists to avoid. Both normalized deliveries use the same shape. diff --git a/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0017.md b/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0017.md new file mode 100644 index 00000000..1a1e6f43 --- /dev/null +++ b/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0017.md @@ -0,0 +1,108 @@ +# 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`, 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. + +## Amendment: Explicit Default Media Kind (2026-10-29) + +`FavoriteMediaKind` now declares `None = 0` as its first member and default value, so an unset kind is never mistaken for `MusicArtist`. The other members keep their order and now occupy values 1 to 6. `None` is not a favoritable kind: the application validators reject it with `FavoriteMediaKindIsInvalid`, `Favorite.IsSupported` reports it as unsupported, and no operation creates a favorite of it. A stored favorite whose kind was recorded as `None` is still rehydrated without failure, so the read paths remain tolerant of legacy or malformed rows. Because the kind is stored by name, no data migration is required. + diff --git a/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0018.md b/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0018.md new file mode 100644 index 00000000..b30cfb39 --- /dev/null +++ b/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0018.md @@ -0,0 +1,125 @@ +# Architecture Decision Record (ADR): 0018 - Media Neutral Consumption History, Resume Points, and Derived Statistics + +## Status + +**Accepted** (2026-10-26) + +## Context + +Consumption is one concept across media kinds. A music track and a book already produce sessions today, and video, photo, podcast and audiobook catalogues are planned. The same facts apply to each kind: who consumed an item, when the session started and ended, how long it was actively consumed, how far it reached, and where it can be resumed. A separate model per kind would repeat the aggregate, table, endpoints and contracts for every catalogue. + +The feature raises questions: + +1. **One concept, many media kinds**: consuming a track, a book or a video is the same fact for statistics, deletion and visibility, so a history per kind would repeat the model, the endpoints and the contracts. +2. **Two lifecycles**: history is a session with a start, progress and a terminal state, while resuming is the latest position of an item. History can be deleted without losing the position, and completion deletes the position but keeps the history. +3. **Reference integrity across catalogues**: one table cannot declare a foreign key to the tables of several media kinds, and a history row must survive the deletion of the item it references. +4. **Derived statistics**: a stored counter would disagree with the history after every deletion and would have to be rebuilt whenever a counting rule changes. +5. **Library policy**: whether a position is remembered and when a session is complete are per-library settings, not fixed properties of a media kind. +6. **Privacy**: a regular user must never read or delete another user's history, while an administrator must be able to do both without a separate permission toggle. + +## Decision + +Use one `MediaConsumptionBoundedContext` that owns two independent write aggregates and one read model: + +- `MediaConsumptionRecord` is the history of one consumption session. +- `MediaResumePoint` is the latest position of one user and item. +- `ConsumptionStatistics` is a read model computed from the records on every request. + +The decision includes these rules: + +- **History and resume are separate aggregates.** A record has its own identifier, status, start, activity and end times, consumed duration, latest position, latest progress fraction and consecutive page count. A resume point has its own identifier and the business key `(UserId, MediaKind, MediaItemId)`. The storage layer owns the unique index of that key. A record is never the source of a resume point, and a resume point is never part of the record. +- **The latest reported position wins.** `LastPosition` is replaced by every report that carries a position, and `LastProgressFraction` by every report. Both may move backwards. Seeking from 75 percent back to the beginning and continuing from there leaves the resume point at the new position, not at the highest position ever reached. No monotonic rule is applied to either field. +- **Consumed duration is monotonic within one record.** It measures active listening, watching or reading time, it never decreases, and a report below the stored value is rejected. It is the only measurement with that rule. +- **Completion is explicit or threshold based.** A session stopped at or after the library completion threshold is recorded as `Completed` and its resume point is deleted. Completion never requires playback to the final second of a media file. A library that tracks progress without a completion threshold completes only when completion is reported explicitly. +- **Progress tracking and completion thresholds are per-library settings.** `ShouldTrackConsumptionProgress` and `CompletionThresholdPercentage` live in `LibraryConsumptionSettings` on the library aggregate. Defaults are applied by library type when a library is created, and when progress tracking is enabled later without a threshold. The per-library value always wins once it is set. +- **Statistics are derived, never stored.** `ConsumptionStatistics` aggregates the records in the application layer on every request. There is no rollup table, no projection table and no counter aggregate, so deleting a record changes the statistics immediately. The `MediaConsumptionRule` value objects own the counting rules per media kind. +- **Tags and genres are lowercase and shared across kinds.** `Tag` and `Genre` normalize names with `Trim().ToLowerInvariant()`, and the statistics group them by that normalized name across media kinds. The application resolves the terms of each consumed record through the catalogue repository of its media kind, in a per-kind branch, and the photo branch is added when the photo catalogue exists. For a music track, the terms fall back from the track to its album and then to its artist. +- **Access is based on the user and the administrator role.** A regular user reads and deletes only their own history, statistics and resume points. An administrator reads any user's history and statistics, and deletes any user's history and resume points. A resume point is readable only by its owner. There is no per-user permission toggle. Lifecycle writes (`start`, `progress`, `complete`, `stop`) are owner only, so an administrator does not write another user's session. + +### Model + +| Element | Decision | +|---|---| +| Bounded context | `MediaConsumptionBoundedContext` in the Domain layer. User, library and media item references are identifier copies under its `ExternalIdentifiers` directories, so the context depends on no other bounded context. | +| `MediaConsumptionRecord` | The write aggregate of a session. It holds a `MediaConsumptionRecordId`, the owner, the library, the media kind, the media item identifier, the status, the start, last activity and end times, the consumed duration, the latest position and progress fraction, and the consecutive page count. No album, artist, series or catalogue hierarchy is stored on the record. | +| `MediaResumePoint` | The write aggregate of the latest position. It holds a `MediaResumePointId`, the owner, the library, the media kind, the media item identifier, the latest position, the latest progress fraction and the last consumption time. It is created only for a resumable kind whose library tracks progress. | +| `ConsumptionStatistics` | A read model, not an aggregate and not a table. It is built from `MediaConsumptionRecordEntity` collections in the application handlers and mapped to the summary, recent, most consumed, tag and genre responses. | +| `MediaKind` | The shared enumeration in `Lumina.Domain.SharedKernel`. `MusicTrack` and `Book` are supported by the current catalogues. `PodcastEpisode`, `Audiobook`, `Movie`, `TvEpisode`, `Photo` and `Video` have rules and are listed for clients, but are rejected by the lifecycle endpoints until their catalogues exist. `None` is invalid. | +| `MediaConsumptionRule` | The shared value object hierarchy that owns resumability (`PositionKind`, `CanResume`), one-shot behavior and counting (`Counts`). It is reused by both aggregates and the statistics read model, so callers never switch on `MediaKind` for these rules. | +| Completion settings | `LibraryConsumptionSettings` on the `Library` aggregate. It stores `ShouldTrackConsumptionProgress` and an optional `CompletionThresholdPercentage`. The validator rejects a threshold when tracking is off, and a threshold outside 0 to 100 when it is supplied. | +| Storage | `MediaConsumptionRecords` and `MediaResumePoints`. The owner is a cascading foreign key to `Users`; the media item is a plain identifier with no foreign key to a media catalogue. Both tables carry an optimistic concurrency version and the audit columns. | +| Invariants | The resume points have a unique index on `(UserId, MediaKind, MediaItemId)`. Records are indexed by `(UserId, MediaKind, MediaItemId, LastActivityOnUtc)` for the history lists and by `(UserId, MediaKind, StartedOnUtc)` for date filtered statistics. | +| Domain events | `MediaConsumptionStartedDomainEvent`, `MediaConsumptionProgressedDomainEvent`, `MediaConsumptionCompletedDomainEvent` and `MediaConsumptionStoppedDomainEvent`. Resume point changes raise no event; the history events are the published seam. | + +### Counting rules + +The statistics count a session when the rule of its media kind says so. Duration totals every record, including the records that do not count, because the time was consumed regardless. + +| Media kind | A session counts when | +|---|---| +| `MusicTrack` | The session completed, or the consumed duration reached 30 seconds | +| `PodcastEpisode` | The session completed, or the consumed duration reached 30 seconds | +| `Audiobook` | The session completed, or the consumed duration reached 60 seconds | +| `Movie` | The session completed, or the consumed duration reached 3 minutes | +| `TvEpisode` | The session completed, or the consumed duration reached 3 minutes | +| `Book` | The session completed, or more than 5 consecutive pages were read | +| `Photo` | Every session counts | +| `Video` | The session completed, or the consumed duration reached 3 minutes | + +### Operations + +- **Start**: validates the request, requires the current user, evaluates the library ownership policy, rejects an unsupported kind, resolves the item through the catalogue repository of its kind within the route library, and loads the library settings. When tracking is on and the kind can resume, the new record is initialized from the stored resume point; the consumed duration always starts at zero. A one-shot kind such as a photo is created completed in the same call. +- **Progress**: loads the record of the current user, applies the latest position, fraction, duration and consecutive page count, and upserts the resume point when tracking is on and the kind can resume. Progress never completes a session. +- **Complete**: loads the record of the current user, makes it terminal as `Completed`, and deletes the resume point for the same user, kind and item. +- **Stop**: loads the record and the library settings. It stops the record without a threshold check when tracking is off or no threshold is set. When tracking is on and a threshold is set, a final fraction at or above it completes the record and deletes the resume point; otherwise the record is stopped and the resume point is upserted. +- **Statistics**: the statistics repository binds the target user and every optional filter and returns read-only record entities. The application handlers aggregate the records, resolve display data and tags or genres through the catalogue repositories, paginate, and map the DTOs. +- **Deletion**: deleting a record, every record of an item, or the whole history is idempotent and never deletes resume points. Clearing resume points never deletes history. An administrator may delete any user's history or resume points through the per-user routes; reading a resume point stays owner only. + +## Consequences + +### Positive Outcomes + +| Aspect | Benefit | +|---|---| +| One model | Music, books and every planned kind share one history, one resume representation, one set of lifecycle endpoints and one statistics read model | +| Context isolation | Both aggregates hold identifiers only, so the context depends on no media catalogue and could move to its own service | +| Independent lifecycles | History and resume can be deleted, completed and queried independently without one becoming the source of truth for the other | +| Correct statistics | Statistics always agree with the stored history, and a deleted record or a changed counting rule takes effect on the next request | +| Per-library policy | Progress tracking and completion thresholds are chosen per library instead of being hardcoded for a media kind | +| Privacy by default | A regular user cannot read or delete another user's data, and a wrong user id is reported as not authorized rather than revealing existence | + +### Risks and Mitigations + +| Risk | Mitigation Strategy | +|---|---| +| Without a foreign key, a record can point at an item that no longer exists | This is intended: the history keeps its counts and duration, and the list returns the item as unavailable with blank display data so the user can delete it | +| A client can report a lower position after a higher one | This is the required behavior: the latest position wins, and only the consumed duration is monotonic | +| Statistics recompute from all matching records on every request | The repository filters by user, library, kind and date range in the query. A rollup can be added later as an optimization without changing the write model | +| A resume point can become orphaned when an item or library is deleted | Reading a resume point resolves the item through its catalogue first; a missing item or a library mismatch deletes the orphan and reports the item as not found | +| A forgotten `InProgress` record stays in history | The client ends a session on stop, skip, track change, reaching the end, a playback failure or unload. Pause and seek only report progress and leave the session in progress. A lost start is not expired by the server, so its record remains in history until the user deletes it. The limitation is accepted instead of adding expiry or cleanup of abandoned records | + +## Alternatives Considered + +### 1. Add a history and resume model per media kind + +A `BookReadingHistory`, a `VideoWatchHistory` and a `PhotoViewHistory`, each with its own aggregate, table, endpoints and contracts. + +**Rejected**: it repeats the same aggregate, table, endpoints and contracts for every kind, and it makes cross-kind statistics, deletion and admin visibility a union of several models. It also reintroduces the same extension cost for every planned catalogue. + +### 2. Store the resume position inside the record + +Keep the latest position only on `MediaConsumptionRecord` and find the last record when a client resumes. + +**Rejected**: the history is a session log, while resuming is one current value per item. Finding it would mean reading the latest record and keeping abandoned records alive, and deleting history would silently remove the ability to resume. The two values have different lifetimes, business keys and deletion rules, so they are separate aggregates. + +### 3. Store statistics as counter columns or a rollup table + +Maintain total duration, counted sessions and completed sessions as counters, or project them into a table. + +**Rejected**: a counter is a second source of truth. Deleting history, changing a counting rule or fixing a bad session would leave it wrong until a rebuild, while deriving the statistics from the records is always correct and needs no rebuild. + +### 4. Hardcode resumability and completion thresholds per media kind + +Decide in the aggregate that music can never resume, that books always complete at 100 percent, and that video always completes at 90 percent. + +**Rejected**: users want to resume a movie without watching the credits to the last second, some music libraries want to resume, and a book library may want an explicit completion only. The library owns these choices, and the media kind only supplies the default and the shape of a position. diff --git a/docs/technical/domain/Aggregates.AudioLibrary.md b/docs/technical/domain/Aggregates.AudioLibrary.md index f4df0db0..7c334620 100644 --- a/docs/technical/domain/Aggregates.AudioLibrary.md +++ b/docs/technical/domain/Aggregates.AudioLibrary.md @@ -286,6 +286,7 @@ class Track "channels": 2, "bitDepth": 16, "audioCodec": "FLAC", + "container": "FLAC", "bitrate": 980, "acoustId": "f0e1d2c3-b4a5-4c6d-8e7f-9a0b1c2d3e4f", "replayGainTrackGain": -7.5, diff --git a/docs/technical/domain/UbiquitousLanguage.md b/docs/technical/domain/UbiquitousLanguage.md index 9bae25bd..f3f249c4 100644 --- a/docs/technical/domain/UbiquitousLanguage.md +++ b/docs/technical/domain/UbiquitousLanguage.md @@ -5,12 +5,26 @@ - _**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 - _**Stream**_: A media item accessed via streaming rather than local storage - _**Language Track**_: An audio or text track in a specific language - _**Media Contributor**_: A person, group, or organization that contributed to a media item, together with the role they played +- _**Direct Play**_: Delivery of a track's audio as stored, because the player can demux its container and decode its codec +- _**Remux**_: Delivery of a track's audio with its codec repackaged into a container the player can demux, without re-encoding it +- _**Transcode**_: Delivery of a track's audio re-encoded into a codec the player can decode +- _**Playback Capabilities**_: The container and codec combinations a player advertises it can demux and decode directly +- _**Delivery Shape**_: The way delivered audio is addressed and seeked, by byte range or as fixed duration, time addressed segments +- _**Media Consumption**_: The recording of what a user consumed, how far they reached and how long they consumed it, across every media kind +- _**Media Consumption Record**_: The record of one consumption session of a media item by a user, from its start to its progress, completion or stop, private to that user. It stores no queue, current index, repeat or shuffle state +- _**Media Resume Point**_: The latest position of one media item for one user, stored separately from the consumption history so the user can resume the item. There is at most one per user, media kind and media item +- _**Consumption Statistics**_: The read model derived from the consumption records on every request. It is not an aggregate, it is not stored, and it has no counter or rollup table +- _**Counted Session**_: A consumption record that counts towards the statistics, because it completed or because its media kind's counting rule was reached +- _**ShouldTrackConsumptionProgress**_: The per-library setting that decides whether the latest position of an item is remembered, so the user can resume it +- _**CompletionThresholdPercentage**_: The optional per-library percentage of an item that must be consumed for a session to count as completed when it stops. When it is absent and tracking is on, completion is recorded only when it is reported explicitly ## Video Content - _**TV Show**_: A series of episodes typically organized into seasons @@ -88,8 +102,11 @@ - SheetMusic - Photo - PhotoAlbum +- MediaConsumptionRecord +- MediaResumePoint - User - Playlist +- Favorite - Collection - SubtitleFile - Lyrics @@ -107,7 +124,10 @@ - PodcastLibrary (root: PodcastLibrary, entities: Podcast, PodcastEpisode) - WrittenContentLibrary (root: WrittenContentLibrary, entities: Book, EBook, BookSeries, ComicBook, ComicSeries, Magazine, MagazineIssue, Newspaper, Manga, GraphicNovel, AcademicPaper, SheetMusic, Screenplay) - PhotoLibrary (root: PhotoLibrary, entities: Photo, PhotoAlbum, AlbumArtwork, MoviePoster) -- UserProfile (root: User, entities: Playlist, Collection) +- UserProfile (root: User, entities: Collection) +- PlaylistManagement (root: Playlist, entities: PlaylistEntry) +- Favorites (root: Favorite, no entities) +- MediaConsumption (roots: MediaConsumptionRecord, MediaResumePoint, no entities) - SupplementaryContentLibrary (root: SupplementaryContentLibrary, entities: SubtitleFile, Lyrics, LanguageTrack) - FileSystemManagement (root: File, entities: Stream) @@ -160,6 +180,14 @@ - StreamInfo - StreamingQuality - UserPreferences +- LibraryConsumptionSettings +- MediaConsumptionRecordId +- MediaResumePointId +- MediaPosition +- MediaConsumptionRule (abstract) +- DurationThresholdConsumptionRule (abstract) +- PageThresholdConsumptionRule (abstract) +- EverySessionConsumptionRule (abstract) - Rating (abstract) - AudioRating - Genre @@ -203,6 +231,16 @@ - MediaItemRemoved - PlaylistCreated - PlaylistUpdated +- PlaylistEntryAdded +- PlaylistEntryRemoved +- PlaylistEntriesReordered +- PlaylistDeleted +- FavoriteAdded +- FavoriteRemoved +- MediaConsumptionStarted +- MediaConsumptionProgressed +- MediaConsumptionCompleted +- MediaConsumptionStopped - UserPreferencesChanged - MetadataUpdated - FileTranscoded @@ -217,6 +255,13 @@ - UserExperience - Aggregates: UserProfile - Services: RecommendationEngine, ContentCurationService, UserActivityTrackingService +- PlaylistManagement + - Aggregates: Playlist +- Favorites + - Aggregates: Favorite +- MediaConsumption + - Aggregates: MediaConsumptionRecord, MediaResumePoint + - Read models: ConsumptionStatistics - ContentDelivery - Aggregates: FileSystemManagement - Services: StreamingService, ContentSynchronizationService @@ -232,6 +277,10 @@ - PhotoRepository - UserRepository - PlaylistRepository +- FavoriteRepository +- MediaConsumptionRecordRepository +- MediaResumePointRepository +- ConsumptionStatisticsRepository - CollectionRepository - FileRepository - StreamRepository diff --git a/docs/technical/requests/favorites/AddFavorite.http b/docs/technical/requests/favorites/AddFavorite.http new file mode 100644 index 00000000..fe753ce0 --- /dev/null +++ b/docs/technical/requests/favorites/AddFavorite.http @@ -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" +} diff --git a/docs/technical/requests/favorites/GetFavoriteStatus.http b/docs/technical/requests/favorites/GetFavoriteStatus.http new file mode 100644 index 00000000..1499123b --- /dev/null +++ b/docs/technical/requests/favorites/GetFavoriteStatus.http @@ -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}} diff --git a/docs/technical/requests/favorites/GetFavorites.http b/docs/technical/requests/favorites/GetFavorites.http new file mode 100644 index 00000000..8ec7556b --- /dev/null +++ b/docs/technical/requests/favorites/GetFavorites.http @@ -0,0 +1,2 @@ +GET {{host}}/api/v1/users/me/favorites?mediaKind=MusicTrack¤tPage=1&perPage=200 +Authorization: Bearer {{ACCESS_TOKEN}} diff --git a/docs/technical/requests/favorites/RemoveFavorite.http b/docs/technical/requests/favorites/RemoveFavorite.http new file mode 100644 index 00000000..3406d216 --- /dev/null +++ b/docs/technical/requests/favorites/RemoveFavorite.http @@ -0,0 +1,2 @@ +DELETE {{host}}/api/v1/users/me/favorites/MusicTrack/9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f +Authorization: Bearer {{ACCESS_TOKEN}} diff --git a/docs/technical/requests/library/audio-library/music-library/tracks/GetPlaybackManifest.http b/docs/technical/requests/library/audio-library/music-library/tracks/GetPlaybackManifest.http new file mode 100644 index 00000000..b6afd735 --- /dev/null +++ b/docs/technical/requests/library/audio-library/music-library/tracks/GetPlaybackManifest.http @@ -0,0 +1,2 @@ +GET {{host}}/api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/albums/e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f/tracks/{{$guid}}/playback-manifest?capabilities=mp3/mp3,flac/flac,ogg/opus,ogg/vorbis,wav/pcm,mp4/aac +Authorization: Bearer {{ACCESS_TOKEN}} diff --git a/docs/technical/requests/library/audio-library/music-library/tracks/ShuffleTracks.http b/docs/technical/requests/library/audio-library/music-library/tracks/ShuffleTracks.http new file mode 100644 index 00000000..4cdb383c --- /dev/null +++ b/docs/technical/requests/library/audio-library/music-library/tracks/ShuffleTracks.http @@ -0,0 +1,10 @@ +POST {{host}}/api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/tracks/shuffle +Authorization: Bearer {{ACCESS_TOKEN}} +Content-Type: application/json + +{ + "count": 100, + "artistId": null, + "albumId": null, + "excludedTrackIds": [] +} diff --git a/docs/technical/requests/library/audio-library/music-library/tracks/StreamTrack.http b/docs/technical/requests/library/audio-library/music-library/tracks/StreamTrack.http new file mode 100644 index 00000000..bd5cf3df --- /dev/null +++ b/docs/technical/requests/library/audio-library/music-library/tracks/StreamTrack.http @@ -0,0 +1,3 @@ +GET {{host}}/api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/albums/e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f/tracks/{{$guid}}/stream +Authorization: Bearer {{ACCESS_TOKEN}} +Range: bytes=0-1048575 diff --git a/docs/technical/requests/library/audio-library/music-library/tracks/StreamTrackSegment.http b/docs/technical/requests/library/audio-library/music-library/tracks/StreamTrackSegment.http new file mode 100644 index 00000000..2bd235ae --- /dev/null +++ b/docs/technical/requests/library/audio-library/music-library/tracks/StreamTrackSegment.http @@ -0,0 +1,2 @@ +GET {{host}}/api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/albums/e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f/tracks/{{$guid}}/stream/deliveries/8f14e45fceea167a5a36dedd4bea2543/segments/0 +Authorization: Bearer {{ACCESS_TOKEN}} diff --git a/docs/technical/requests/library/audio-library/music-library/tracks/UpdateTrack.http b/docs/technical/requests/library/audio-library/music-library/tracks/UpdateTrack.http index e8bd3ec3..8553d97a 100644 --- a/docs/technical/requests/library/audio-library/music-library/tracks/UpdateTrack.http +++ b/docs/technical/requests/library/audio-library/music-library/tracks/UpdateTrack.http @@ -3,7 +3,6 @@ Authorization: Bearer {{ACCESS_TOKEN}} Content-Type: application/json { - "path": "/music/queen/a-night-at-the-opera/01-bohemian-rhapsody.flac", "metadata": { "title": "Bohemian Rhapsody", "originalTitle": "Bohemian Rhapsody", diff --git a/docs/technical/requests/library/management/AddLibrary.http b/docs/technical/requests/library/management/AddLibrary.http index 0a20c31f..5b09ae1c 100644 --- a/docs/technical/requests/library/management/AddLibrary.http +++ b/docs/technical/requests/library/management/AddLibrary.http @@ -14,6 +14,8 @@ Content-Type: application/json "canDownloadMetadataFromWeb": true, "shouldSaveMetadataInMediaDirectories": true, "shouldSkipUnchangedDirectoriesDuringScan": true, + "shouldTrackConsumptionProgress": true, + "completionThresholdPercentage": 100, "pathTemplateParts": [ { "kind": "Artist", "representation": "{0}", "isOptional": false }, { "kind": "Separator", "representation": "", "isOptional": false } diff --git a/docs/technical/requests/library/management/UpdateLibrary.http b/docs/technical/requests/library/management/UpdateLibrary.http index aa82d623..2733e7d1 100644 --- a/docs/technical/requests/library/management/UpdateLibrary.http +++ b/docs/technical/requests/library/management/UpdateLibrary.http @@ -16,6 +16,8 @@ Content-Type: application/json "canDownloadMetadataFromWeb": true, "shouldSaveMetadataInMediaDirectories": true, "shouldSkipUnchangedDirectoriesDuringScan": true, + "shouldTrackConsumptionProgress": true, + "completionThresholdPercentage": 100, "pathTemplateParts": [ { "kind": "Artist", "representation": "{0}", "isOptional": false }, { "kind": "Separator", "representation": "", "isOptional": false } diff --git a/docs/technical/requests/library/statistics/ClearConsumptionHistory.http b/docs/technical/requests/library/statistics/ClearConsumptionHistory.http new file mode 100644 index 00000000..ed3a4477 --- /dev/null +++ b/docs/technical/requests/library/statistics/ClearConsumptionHistory.http @@ -0,0 +1,7 @@ +### Current user +DELETE {{host}}/api/v1/users/me/consumption-history +Authorization: Bearer {{ACCESS_TOKEN}} + +### Another user (admin) +DELETE {{host}}/api/v1/users/2cff0c0f-3a67-4e30-b94f-f4e948a3b64f/consumption-history +Authorization: Bearer {{ACCESS_TOKEN}} diff --git a/docs/technical/requests/library/statistics/ClearResumePoints.http b/docs/technical/requests/library/statistics/ClearResumePoints.http new file mode 100644 index 00000000..3358f73a --- /dev/null +++ b/docs/technical/requests/library/statistics/ClearResumePoints.http @@ -0,0 +1,11 @@ +### Current user, every library +DELETE {{host}}/api/v1/users/me/media-resume-points +Authorization: Bearer {{ACCESS_TOKEN}} + +### Current user, one library +DELETE {{host}}/api/v1/users/me/media-resume-points?libraryId=3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a +Authorization: Bearer {{ACCESS_TOKEN}} + +### Another user (admin) +DELETE {{host}}/api/v1/users/2cff0c0f-3a67-4e30-b94f-f4e948a3b64f/media-resume-points +Authorization: Bearer {{ACCESS_TOKEN}} diff --git a/docs/technical/requests/library/statistics/DeleteConsumptionItemHistory.http b/docs/technical/requests/library/statistics/DeleteConsumptionItemHistory.http new file mode 100644 index 00000000..719b562b --- /dev/null +++ b/docs/technical/requests/library/statistics/DeleteConsumptionItemHistory.http @@ -0,0 +1,7 @@ +### Current user +DELETE {{host}}/api/v1/users/me/consumption-history/media-items/MusicTrack/9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a +Authorization: Bearer {{ACCESS_TOKEN}} + +### Another user (admin) +DELETE {{host}}/api/v1/users/2cff0c0f-3a67-4e30-b94f-f4e948a3b64f/consumption-history/media-items/Book/7a6b5c4d-3e2f-4a1b-8c9d-0e1f2a3b4c5d/5c6d7e8f-9a0b-4c1d-8e2f-3a4b5c6d7e8f +Authorization: Bearer {{ACCESS_TOKEN}} diff --git a/docs/technical/requests/library/statistics/DeleteConsumptionRecord.http b/docs/technical/requests/library/statistics/DeleteConsumptionRecord.http new file mode 100644 index 00000000..e4060af9 --- /dev/null +++ b/docs/technical/requests/library/statistics/DeleteConsumptionRecord.http @@ -0,0 +1,7 @@ +### Current user +DELETE {{host}}/api/v1/users/me/consumption-history/2c1b0a9f-8e7d-4c6b-5a4f-3e2d1c0b9a8f +Authorization: Bearer {{ACCESS_TOKEN}} + +### Another user (admin) +DELETE {{host}}/api/v1/users/2cff0c0f-3a67-4e30-b94f-f4e948a3b64f/consumption-history/2c1b0a9f-8e7d-4c6b-5a4f-3e2d1c0b9a8f +Authorization: Bearer {{ACCESS_TOKEN}} diff --git a/docs/technical/requests/library/statistics/GetAllUsersConsumptionStatistics.http b/docs/technical/requests/library/statistics/GetAllUsersConsumptionStatistics.http new file mode 100644 index 00000000..1747e0d5 --- /dev/null +++ b/docs/technical/requests/library/statistics/GetAllUsersConsumptionStatistics.http @@ -0,0 +1,3 @@ +### All users (admin) +GET {{host}}/api/v1/users/consumption-statistics?fromUtc=2026-10-01T00:00:00Z&toUtc=2026-10-31T23:59:59Z +Authorization: Bearer {{ACCESS_TOKEN}} diff --git a/docs/technical/requests/library/statistics/GetConsumptionStatistics.http b/docs/technical/requests/library/statistics/GetConsumptionStatistics.http new file mode 100644 index 00000000..bf4e0b85 --- /dev/null +++ b/docs/technical/requests/library/statistics/GetConsumptionStatistics.http @@ -0,0 +1,7 @@ +### Current user +GET {{host}}/api/v1/users/me/consumption-statistics?fromUtc=2026-10-01T00:00:00Z&toUtc=2026-10-31T23:59:59Z +Authorization: Bearer {{ACCESS_TOKEN}} + +### Another user (admin) +GET {{host}}/api/v1/users/2cff0c0f-3a67-4e30-b94f-f4e948a3b64f/consumption-statistics?libraryId=3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a&mediaKind=Book +Authorization: Bearer {{ACCESS_TOKEN}} diff --git a/docs/technical/requests/library/statistics/GetGenreConsumption.http b/docs/technical/requests/library/statistics/GetGenreConsumption.http new file mode 100644 index 00000000..d611c3e9 --- /dev/null +++ b/docs/technical/requests/library/statistics/GetGenreConsumption.http @@ -0,0 +1,7 @@ +### Current user +GET {{host}}/api/v1/users/me/consumption-statistics/genres?mediaKind=Book +Authorization: Bearer {{ACCESS_TOKEN}} + +### Another user (admin) +GET {{host}}/api/v1/users/2cff0c0f-3a67-4e30-b94f-f4e948a3b64f/consumption-statistics/genres +Authorization: Bearer {{ACCESS_TOKEN}} diff --git a/docs/technical/requests/library/statistics/GetMostConsumed.http b/docs/technical/requests/library/statistics/GetMostConsumed.http new file mode 100644 index 00000000..b3cad1fc --- /dev/null +++ b/docs/technical/requests/library/statistics/GetMostConsumed.http @@ -0,0 +1,7 @@ +### Current user +GET {{host}}/api/v1/users/me/consumption-history/most-consumed?currentPage=1&perPage=50 +Authorization: Bearer {{ACCESS_TOKEN}} + +### Another user (admin) +GET {{host}}/api/v1/users/2cff0c0f-3a67-4e30-b94f-f4e948a3b64f/consumption-history/most-consumed?currentPage=1&perPage=50 +Authorization: Bearer {{ACCESS_TOKEN}} diff --git a/docs/technical/requests/library/statistics/GetRecentlyConsumed.http b/docs/technical/requests/library/statistics/GetRecentlyConsumed.http new file mode 100644 index 00000000..69f09c0b --- /dev/null +++ b/docs/technical/requests/library/statistics/GetRecentlyConsumed.http @@ -0,0 +1,7 @@ +### Current user +GET {{host}}/api/v1/users/me/consumption-history/recently-consumed?currentPage=1&perPage=50 +Authorization: Bearer {{ACCESS_TOKEN}} + +### Another user (admin) +GET {{host}}/api/v1/users/2cff0c0f-3a67-4e30-b94f-f4e948a3b64f/consumption-history/recently-consumed?libraryId=3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a&mediaKind=MusicTrack¤tPage=1&perPage=50&fromUtc=2026-10-01T00:00:00Z&toUtc=2026-10-31T23:59:59Z +Authorization: Bearer {{ACCESS_TOKEN}} diff --git a/docs/technical/requests/library/statistics/GetTagConsumption.http b/docs/technical/requests/library/statistics/GetTagConsumption.http new file mode 100644 index 00000000..ed88b1f4 --- /dev/null +++ b/docs/technical/requests/library/statistics/GetTagConsumption.http @@ -0,0 +1,7 @@ +### Current user +GET {{host}}/api/v1/users/me/consumption-statistics/tags?mediaKind=MusicTrack +Authorization: Bearer {{ACCESS_TOKEN}} + +### Another user (admin) +GET {{host}}/api/v1/users/2cff0c0f-3a67-4e30-b94f-f4e948a3b64f/consumption-statistics/tags +Authorization: Bearer {{ACCESS_TOKEN}} diff --git a/docs/technical/requests/media-consumption/CompleteConsumption.http b/docs/technical/requests/media-consumption/CompleteConsumption.http new file mode 100644 index 00000000..30b4f909 --- /dev/null +++ b/docs/technical/requests/media-consumption/CompleteConsumption.http @@ -0,0 +1,29 @@ +### Music track +POST {{host}}/api/v1/users/me/consumption-records/2c1b0a9f-8e7d-4c6b-5a4f-3e2d1c0b9a8f/complete +Authorization: Bearer {{ACCESS_TOKEN}} +Content-Type: application/json + +{ + "position": { + "kind": "TimeOffset", + "timeOffsetSeconds": 300, + "location": null + }, + "progressFraction": 1, + "consumedDurationInSeconds": 300 +} + +### Book +POST {{host}}/api/v1/users/me/consumption-records/8f7e6d5c-4b3a-4928-8170-6f5e4d3c2b1a/complete +Authorization: Bearer {{ACCESS_TOKEN}} +Content-Type: application/json + +{ + "position": { + "kind": "Location", + "timeOffsetSeconds": null, + "location": "epubcfi(/6/8[chapter-4]!/4/2/2)" + }, + "progressFraction": 1, + "consumedDurationInSeconds": 900 +} diff --git a/docs/technical/requests/media-consumption/GetConsumptionRecord.http b/docs/technical/requests/media-consumption/GetConsumptionRecord.http new file mode 100644 index 00000000..8f48213b --- /dev/null +++ b/docs/technical/requests/media-consumption/GetConsumptionRecord.http @@ -0,0 +1,7 @@ +### Music track session +GET {{host}}/api/v1/users/me/consumption-records/2c1b0a9f-8e7d-4c6b-5a4f-3e2d1c0b9a8f +Authorization: Bearer {{ACCESS_TOKEN}} + +### Book session +GET {{host}}/api/v1/users/me/consumption-records/8f7e6d5c-4b3a-4928-8170-6f5e4d3c2b1a +Authorization: Bearer {{ACCESS_TOKEN}} diff --git a/docs/technical/requests/media-consumption/GetResumePoint.http b/docs/technical/requests/media-consumption/GetResumePoint.http new file mode 100644 index 00000000..24324e1d --- /dev/null +++ b/docs/technical/requests/media-consumption/GetResumePoint.http @@ -0,0 +1,7 @@ +### Music track +GET {{host}}/api/v1/users/me/media-resume-points/MusicTrack/9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f +Authorization: Bearer {{ACCESS_TOKEN}} + +### Book +GET {{host}}/api/v1/users/me/media-resume-points/Book/7a6b5c4d-3e2f-4a1b-8c9d-0e1f2a3b4c5d +Authorization: Bearer {{ACCESS_TOKEN}} diff --git a/docs/technical/requests/media-consumption/ReportConsumptionProgress.http b/docs/technical/requests/media-consumption/ReportConsumptionProgress.http new file mode 100644 index 00000000..60215107 --- /dev/null +++ b/docs/technical/requests/media-consumption/ReportConsumptionProgress.http @@ -0,0 +1,31 @@ +### Music track +PUT {{host}}/api/v1/users/me/consumption-records/2c1b0a9f-8e7d-4c6b-5a4f-3e2d1c0b9a8f/progress +Authorization: Bearer {{ACCESS_TOKEN}} +Content-Type: application/json + +{ + "position": { + "kind": "TimeOffset", + "timeOffsetSeconds": 92.5, + "location": null + }, + "progressFraction": 0.31, + "consumedDurationInSeconds": 92.5, + "consecutivePagesRead": 0 +} + +### Book +PUT {{host}}/api/v1/users/me/consumption-records/8f7e6d5c-4b3a-4928-8170-6f5e4d3c2b1a/progress +Authorization: Bearer {{ACCESS_TOKEN}} +Content-Type: application/json + +{ + "position": { + "kind": "Location", + "timeOffsetSeconds": null, + "location": "epubcfi(/6/6[chapter-2]!/4/2/2)" + }, + "progressFraction": 0.18, + "consumedDurationInSeconds": 300, + "consecutivePagesRead": 2 +} diff --git a/docs/technical/requests/media-consumption/StartConsumption.http b/docs/technical/requests/media-consumption/StartConsumption.http new file mode 100644 index 00000000..96ed5972 --- /dev/null +++ b/docs/technical/requests/media-consumption/StartConsumption.http @@ -0,0 +1,7 @@ +### Music track +POST {{host}}/api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/media-items/MusicTrack/9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f/consumption-records +Authorization: Bearer {{ACCESS_TOKEN}} + +### Book +POST {{host}}/api/v1/libraries/5c6d7e8f-9a0b-4c1d-8e2f-3a4b5c6d7e8f/media-items/Book/7a6b5c4d-3e2f-4a1b-8c9d-0e1f2a3b4c5d/consumption-records +Authorization: Bearer {{ACCESS_TOKEN}} diff --git a/docs/technical/requests/media-consumption/StopConsumption.http b/docs/technical/requests/media-consumption/StopConsumption.http new file mode 100644 index 00000000..722a35c6 --- /dev/null +++ b/docs/technical/requests/media-consumption/StopConsumption.http @@ -0,0 +1,29 @@ +### Music track +POST {{host}}/api/v1/users/me/consumption-records/2c1b0a9f-8e7d-4c6b-5a4f-3e2d1c0b9a8f/stop +Authorization: Bearer {{ACCESS_TOKEN}} +Content-Type: application/json + +{ + "position": { + "kind": "TimeOffset", + "timeOffsetSeconds": 60, + "location": null + }, + "progressFraction": 0.6, + "consumedDurationInSeconds": 60 +} + +### Book +POST {{host}}/api/v1/users/me/consumption-records/8f7e6d5c-4b3a-4928-8170-6f5e4d3c2b1a/stop +Authorization: Bearer {{ACCESS_TOKEN}} +Content-Type: application/json + +{ + "position": { + "kind": "Location", + "timeOffsetSeconds": null, + "location": "epubcfi(/6/6[chapter-2]!/4/2/2)" + }, + "progressFraction": 0.18, + "consumedDurationInSeconds": 300 +} diff --git a/docs/technical/requests/users-management/settings/GetPlaybackState.http b/docs/technical/requests/users-management/settings/GetPlaybackState.http new file mode 100644 index 00000000..12b6f7cb --- /dev/null +++ b/docs/technical/requests/users-management/settings/GetPlaybackState.http @@ -0,0 +1,2 @@ +GET {{host}}/api/v1/users/me/settings/playback-state +Authorization: Bearer {{ACCESS_TOKEN}} diff --git a/docs/technical/requests/users-management/settings/UpdatePlaybackState.http b/docs/technical/requests/users-management/settings/UpdatePlaybackState.http new file mode 100644 index 00000000..0b712520 --- /dev/null +++ b/docs/technical/requests/users-management/settings/UpdatePlaybackState.http @@ -0,0 +1,8 @@ +PUT {{host}}/api/v1/users/me/settings/playback-state +Authorization: Bearer {{ACCESS_TOKEN}} +Content-Type: application/json + +{ + "volume": 0.75, + "isMuted": false +} diff --git a/docs/technical/requests/users-management/settings/UpdateUserSettings.http b/docs/technical/requests/users-management/settings/UpdateUserSettings.http index 58cb8c67..22804ce0 100644 --- a/docs/technical/requests/users-management/settings/UpdateUserSettings.http +++ b/docs/technical/requests/users-management/settings/UpdateUserSettings.http @@ -5,9 +5,23 @@ Content-Type: application/json { "isPaginationEnabled": true, "itemsPerPage": 50, - "ignoreThePrefixForAlphaPicker": true, + "shouldIgnoreThePrefixForAlphaPicker": true, "isThemeCachingEnabled": true, "shouldAggregateMetadataWhenMissing": true, "shouldRenderPdfAsImages": false, - "shouldPreserveBookStyles": true + "shouldPreserveBookStyles": true, + "shouldKeepDownloadingWhilePaused": true, + "shouldAutoplay": true, + "isGaplessPlaybackEnabled": true, + "replayGainMode": "Off", + "streamingQuality": "Auto", + "vuMeterOrientation": "Vertical", + "vuMeterSegmentCount": 12, + "vuMeterSegmentGap": 1, + "vuMeterMediumThreshold": 0.6, + "vuMeterHighThreshold": 0.8, + "vuMeterShowPeak": true, + "vuMeterPeakHoldDurationInMilliseconds": 650, + "vuMeterReleasePerSecond": 3, + "vuMeterPeakReleasePerSecond": 0.65 } diff --git a/docs/technical/theming/Theming.md b/docs/technical/theming/Theming.md index 3712232a..1401a625 100644 --- a/docs/technical/theming/Theming.md +++ b/docs/technical/theming/Theming.md @@ -13,8 +13,18 @@ The web client of Lumina is a themed shell: every page is rendered inside the te - [Safety Limits](#safety-limits) - [Template Resolution](#template-resolution) - [The Layout Template (shared/layout)](#the-layout-template-sharedlayout) + - [The Audio Player Bar](#the-audio-player-bar) + - [The VU Meter](#the-vu-meter) + - [Play Affordances on the Music Pages](#play-affordances-on-the-music-pages) + - [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) + - [The Statistics Page](#the-statistics-page) + - [Favorite Toggles](#favorite-toggles) - [The Scripts Section](#the-scripts-section) - [Assets](#assets) - [Configuration Options](#configuration-options) @@ -161,7 +171,14 @@ Known page keys: | `shared/layout` | The layout that wraps the shell of every page. | | `shared/nav-menu` | The navigation menu of the theme. | | `shared/not-found` | The 404 page. | +| `shared/audio-player` | The audio player bar shell. | +| `shared/audio-player/queue-item` | The queue item of the audio player bar. | +| `shared/audio-player/playlist-item` | The playlist item of the audio player bar. | | `library/written-content-library/book-library/books/index` | The books browsing page. | +| `playlists/index` | The page that lists and deletes the playlists of the current user. | +| `playlists/item` | The page that creates a playlist, or edits, reorders, plays and deletes an existing playlist of the current user. The `isNew` page data field tells the two modes apart. | +| `favorites/index` | The page that lists, filters and removes the favorites of the current user across media kinds. | +| `library/statistics/index` | The page that shows the consumption statistics of the current user or, for an administrator, of another user or every user, across every media kind. | | `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. | @@ -222,6 +239,185 @@ The layout template of the bundled theme shows the intended shape: The rendered page content, navigation and scripts are inserted unescaped with `{{&...}}`, because they are trusted application HTML. The layout is best effort: when the theme cannot be loaded or rendered, the application falls back to its built-in layout, so a broken theme never takes the whole site down. +### The Audio Player Bar + +Every authenticated page renders the audio player bar through the `audioPlayer` field of the layout model. The bar starts hidden, and the global audio player script shows it when playback starts, expands it and hides it again. The markup comes from the `shared/audio-player` template of the active theme; when the theme does not provide that template, the application renders its own fallback markup, so the player always has a bar to bind to. + +The theme owns the position, orientation and size of the bar, and it owns the room reserved for it on the main content element. The application fallback happens to fix the bar to the bottom, but that is only the fallback layout: a theme can make it a vertical bar on a side, a horizontal bar at the bottom, or any other placement, and can expand its queue in any direction. A layout must keep these element hooks, which the audio player drives (the id control is bound by the global site script, which routes it to the audio player): + +| Element | Hook | Meaning | +| --- | --- | --- | +| The bar container, with the `audio-player-container` class | `not-shown` class | The bar is hidden. The theme decides how that state is presented and which space it releases. | +| The bar container | `expanded` class | The bar is expanded. This is the layout-neutral state a theme styles for its own layout. | +| The bar container | `inert` attribute | Set while the bar is hidden and removed when it is shown, so a collapsed bar keeps none of its focusable controls in the tab order. | +| The expanded area, with the `audio-player-expanded` class | Layout child of the bar container | The cover art, now playing details and queue of the expanded bar. Its position is theme-owned. The fallback stylesheet places it above the bar in a flex column, but the player does not require that layout. A theme that animates the area should keep it in the DOM while the transition runs. | +| The condensed bar, with the `audio-player-bar` class | Layout child of the bar container | The row of controls. Its position is theme-owned; the fallback stylesheet places it at the bottom edge of the container. | +| The main content element | `audio-player-not-shown` class | The bar is hidden, so the content area releases the room the theme reserved for the bar. | +| The main content element | `audio-player-bar-expanded` class | The bar is expanded. This is the layout-neutral state for the main content element's own adjustment. | +| The expand and collapse control | `id="audio-player-expand-toggle"` | A focusable control, such as a `button`, that expands or collapses the bar. Its label may describe the action in the theme's own layout. | +| The queue-to-playlist combo box | `data-audio-player-playlist-combobox` | A standard application combo box (`enlightenment-combobox`) in the expanded area that lists the playlists of the current user. Its root carries the hook; its selected text carries the chosen playlist Id in `data-value`. When the theme does not render the hook, the player builds a built-in combo box of the same markup and places it in a `audio-player-queue-area` wrapper above the queue, so the action never becomes a new column of the expanded layout. | +| The queue-to-playlist button | `data-audio-player-add-queue-to-playlist` | A focusable control in the expanded area that appends the current queue, in order, to the playlist selected in the combo box. When the theme does not render it, the player builds a built-in button next to the combo box. The player disables it while the queue is empty, while no playlist exists, and while an add is in flight. | + +The `shared/audio-player` template receives the following model: + +| Field | Content | +| --- | --- | +| `appBase` | The absolute base URL of the Web application, used to reference the application scripts. | +| `assetBase` | The base URL of the theme assets, used by the theme template to reference its own assets. | +| `queueItemTemplate` | The raw source of the `shared/audio-player/queue-item` sub template, inlined by the application into a plain text script element. | +| `playlistItemTemplate` | The raw source of the `shared/audio-player/playlist-item` sub template, inlined by the application into a plain text script element. | +| `strings` | The localized strings of the bar, keyed by their resource names. A shell template uses `toggleExpanded`, `previous`, `next`, `stop`, `repeat`, `repeatOff`, `repeatAll`, `repeatOne`, `queue`, `albumArtwork`, `addQueueToPlaylist`, `addToPlaylist`, `selectPlaylist` and `add` for its controls; the player reads the play, pause, mute, unmute, volume, seek, buffering, success and failure labels from the global scripts configuration instead, so a themed shell does not need to render them. | + +The bundled themes reserve the room for their bottom bar like this. It is an example of a bottom layout, not a required layout: + +```css +main { + bottom: 50px; + transition: bottom 1s ease, height 1s ease; +} + +main.audio-player-not-shown { + bottom: 0; +} + +main.audio-player-bar-expanded { + bottom: calc(100% - 22px); /* expanded height, less the menu height */ +} +``` + +A theme with a vertical bar instead reserves a side column, a theme with a bar on top reserves top space, and a theme whose expanded bar overlays the content reserves no space at all. The application fallback layout reserves the room itself, because the application stylesheet does not position the content area of a theme. A theme that omits its own space reservation leaves its bar overlapping its content. + +The flex column used by the application fallback is also only a default. The player toggles the state classes and never reads the geometry of the bar, so a theme can lay the container out in any direction, place the expanded area to the left, right, above or below the condensed bar, and make the queue scroll vertically or horizontally. The player's only layout-dependent behavior is scrolling the `data-audio-player-queue` element so the current entry aligns to its start on both axes. + +A theme that restyles the fallback transition can set `--audio-player-expanded-duration` on `.audio-player-container` to keep its height, fade and padding transitions on the same duration. The bundled themes set it to `1s`, matching their own height transition; the application fallback uses `0.4s`. A theme that uses a different transition can ignore the property. + +The markup inside the bar exposes the hook attributes the audio player script binds. A theme that replaces the bar markup must keep all of them; the part of the bar whose hook is missing stays inert. The deprecated `queuechange` event keeps its ordered descriptor array payload for older theme scripts; new code must use `queuestatechange`, whose payload is the compact queue summary. + +| Hook attribute | Meaning | +| --- | --- | +| `data-audio-player-play-pause` | The play and pause control. The player adds the `is-playing` class to it while a track plays. | +| `data-audio-player-stop` | The stop control. Clicking it stops playback; a condensed bar then slides out of view, while an expanded bar stays on screen. | +| `data-audio-player-previous` | The previous control. It either returns to the previous queue entry or restarts the current track, following the navigation history. | +| `data-audio-player-next` | The next control. It starts the next queue entry and loads another shuffle or autoplay batch when the queue is at its end. The player sets `disabled` and the `is-disabled` class when there is no next entry. | +| `data-audio-player-repeat` | The repeat toggle. The player writes `data-audio-player-repeat-mode` (`off`, `all` or `one`), toggles `aria-pressed`, the `is-active` class and, for one, the `is-one` class. | +| `data-audio-player-progress` | The progress bar, a `role="slider"` element with `tabindex="0"` that the player scrubs and whose ARIA value attributes it writes. It carries `data-audio-player-progress-state` (`idle`, `ready` or `buffering`) and the `is-buffering` class while it loads. | +| `data-audio-player-progress-played` | The played layer of the bar. The player publishes its start and width as the custom properties `--audio-player-progress-played-start` and `--audio-player-progress-played-width`. | +| `data-audio-player-progress-downloaded` | The downloaded but not played layer. `--audio-player-progress-downloaded-start` and `--audio-player-progress-downloaded-width`. | +| `data-audio-player-progress-undownloaded` | The not yet downloaded layer. `--audio-player-progress-undownloaded-start` and `--audio-player-progress-undownloaded-width`. | +| `data-audio-player-current-time` | The current position, written as `m:ss`. | +| `data-audio-player-total-time` | The duration, written as `m:ss`, or `--:--` while it is unknown. | +| `data-audio-player-track-name` | The track name. | +| `data-audio-player-album-name` | The album name, shown underneath the track name. The player leaves it empty when the descriptor has no album title, including when the title is the stored `Unknown Album` placeholder, so a track without an album shows only its name. | +| `data-audio-player-now-playing-title` | The current track name of the expanded player, under its cover. | +| `data-audio-player-now-playing-release-type` | The release type of the current track's album, such as Album, Live or EP. Multiple types are joined with commas. It is left empty when the album has no release type. | +| `data-audio-player-now-playing-release` | The release name of the current track's album in the expanded player. It is left empty when the album has no displayable title. | +| `data-audio-player-now-playing-year` | The release year of the current track's album in the expanded player. It is left empty when the year is not known. | +| `data-audio-player-now-playing-artist` | The artist name of the current track's album in the expanded player. It is left empty until the album details are available. | +| `data-audio-player-favorite` | The favorite toggle of the current track, in the condensed bar between repeat and mute. The player sets its media kind and track Id, and hides it while no track is loaded. A missing hook gets the built-in toggle in that place. | +| `data-audio-player-artwork-carousel` | The carousel of the stored artwork of the current track's album. The player appends one `button.artwork-carousel-item` per stored image, carrying `data-artwork-path`, and toggles the `selected` class and `aria-pressed` on the chosen item. The element is hidden with the `hidden` attribute while the album has no stored artwork. | +| `data-audio-player-cover-thumbnail`, `data-audio-player-cover-image` | The cover art of the condensed bar and of the expanded bar. Choosing an album artwork in the carousel replaces both images until the next track. | +| `data-audio-player-vu-meter` | The root of the VU meter of the condensed bar, between the album art and the current time label. The player fills it with its channels, segments and peak markers, exactly as described in [The VU Meter](#the-vu-meter). A theme that does not render the hook gets the built-in meter inserted in that place. | +| `data-audio-player-volume` | The volume slider, a `role="slider"` element with `tabindex="0"` that the player scrubs and whose ARIA value attributes it writes. The fill is published as `--audio-player-volume-start` and `--audio-player-volume-width`. | +| `data-audio-player-volume-level` | The volume fill. It carries no geometry of its own: the stylesheet drives it from the custom properties above. | +| `data-audio-player-mute` | The mute toggle. The player toggles the `is-muted` class and the `aria-pressed` state on it. | +| `data-audio-player-queue` | The queue list of the expanded bar. The player writes `data-audio-player-queue-entry-id` on every rendered item root, whether it comes from the theme sub template or from the built-in markup, and makes the root focusable, so clicking an item or pressing Enter or Space on it starts that entry. The element must stay the scroll container of the list, because the player scrolls the current entry to the start of whichever axis the theme makes scrollable when playback advances or the bar expands. | + +Each progress layer also carries `data-audio-player-progress-layer` (`played`, `downloaded` or `undownloaded`) in the markup, so a theme can select a layer by its state as well as by its class. The player writes no inline geometry on any of the bar elements: it publishes the geometry of each state as the custom properties above, which the application stylesheet consumes, so a theme restyles or reorients either bar by consuming the same properties. + +#### The VU Meter + +The condensed bar shows a segmented VU meter that follows the level of the track itself. The renderer taps it after the track's ReplayGain normalization and before the output volume and mute stage, so lowering the volume or muting the player never changes the height of the meter for the same moment of audio. The meter is a spectrum meter with one channel per frequency band, with 24 logarithmically spaced bands between 40 Hz and 16 kHz, each drawn as a stack of segments. The number of segments, the gap between them, the two threshold zones, the peak marker and its hold and falloff times, and the orientation are per-user settings, so the meter reflects the values the user saved on the settings page. + +The meter is built from elements rather than a canvas, exactly like the three state progress bar, so a theme restyles every part of it. The root carries the `audio-player-vu-meter` class and the `data-audio-player-vu-meter` hook, and the player fills it with: + +| Element | Class and hook | State the player writes | +| --- | --- | --- | +| A channel, one per band | `audio-player-vu-channel`, `data-audio-player-vu-channel` (the zero based band index) | None. The channel is a layout container. | +| A segment, one per configured segment of a channel | `audio-player-vu-segment`, `data-audio-player-vu-segment` | `data-audio-player-vu-segment-state` (`active` or `inactive`) and `data-audio-player-vu-segment-zone` (`normal`, `medium` or `high`). The zone is derived from the position of the segment and the two thresholds of the settings. | +| A peak marker, one per channel | `audio-player-vu-peak`, `data-audio-player-vu-peak` | `data-audio-player-vu-peak-state` (`active` or `inactive`). The marker is removed with the `hidden` attribute while the show peak setting is off. | + +The segments are rendered in ascending level order, so the first segment of a channel is the quietest one. The root also carries `data-audio-player-vu-meter-orientation` (`vertical` or `horizontal`), `data-audio-player-vu-meter-segments` (the configured segment count) and `data-audio-player-vu-meter-show-peak` (`true` or `false`), so a theme can select a state or a layout from the root as well. + +The player publishes no geometry other than two custom properties, which a theme maps to whichever axis its own layout uses: + +| Custom property | Published on | Meaning | +| --- | --- | --- | +| `--audio-player-vu-segment-gap` | The meter root | The configured gap between segments and between channels, as a CSS length in pixels. | +| `--audio-player-vu-segment-count` | The meter root | The configured number of segments per channel, as a plain number, so a stylesheet can size the meter from it. | +| `--audio-player-vu-peak-position` | Each peak marker | The held peak of its channel, as a percentage of the channel axis, from `0%` at the quiet end to `100%` at the loud end. | + +The fallback stylesheet sizes the vertical meter from whole pixel square cells rather than stretching it over a box, because a box divided into rows gives fractional heights that browsers snap unevenly. The cell is the largest whole pixel size that fits the configured segments in `--audio-player-vu-extent` (48px by default), capped by `--audio-player-vu-max-cell` (4px), and a theme can override either property. With the default 12 segments and a 1px gap the cells are 3px squares. + +The application fallback stylesheet gives the meter its own default look: 24 columns of segments whose active state uses one of three colors, with the inactive segments transparent, and a peak line that spans the short axis of the channel. A theme can replace all of it. The colors are custom properties declared on the bar container (`--audio-player-vu-normal-color`, `--audio-player-vu-medium-color`, `--audio-player-vu-high-color`, `--audio-player-vu-inactive-color`, `--audio-player-vu-peak-color` and `--audio-player-vu-background-color`), so a theme recolors the meter without touching the markup, and it can give each zone, each state and each orientation its own shape, image or animation. + +The meter is decorative for assistive technology and carries `aria-hidden="true"`, because the same information is available through the now playing labels and the progress bar. It reads the analyzer that the player renderer taps after the track's ReplayGain normalization and before the output volume, so it needs no extra request and no extra decode, it is unaffected by the volume and mute controls, and it never affects playback. When the player is paused, stopped, ended or failed, the displayed levels fall to zero instead of freezing. + +#### Play Affordances on the Music Pages + +The artist page, the album page and the track page render play triggers, and the card actions menus render play and shuffle triggers, all handled by the global audio player script through event delegation. The music library cards on the home page, the artist cards and the album cards offer both actions, so the whole library, an artist or a release can be started in order or shuffled. A theme template that replaces one of those pages or menus opts in by rendering the same trigger attributes: the player binds one listener on the document, so a trigger works anywhere in the swapped page content and the page needs no script of its own. + +The trigger attributes are: + +| Attribute | Meaning | +| --- | --- | +| `data-audio-player-play` | Marks the element as a play trigger. Clicking it replaces the queue with the described context and starts playback. | +| `data-audio-player-play-next` | Marks the element as a play next trigger. While something is current, clicking it inserts the described track or context after the current entry without starting playback and discards the pending autoplay continuation. When nothing is current, the player starts the described context instead, because there is no entry to queue after. | +| `data-audio-player-play-shuffled` | Marks the element as a shuffled play trigger. Clicking it starts the described context and turns shuffle on for the scope in `data-audio-player-shuffle-scope`. | +| `data-audio-player-play-library` | Marks the element as a library play trigger. Clicking it starts the whole library named by `data-library-id` in artist page order, without needing a track, album or artist context. | +| `data-audio-player-play-library-shuffled` | Marks the element as a library shuffle trigger. Clicking it starts a shuffled playback of the whole library named by `data-library-id`, without needing a track, album or artist context. | +| `data-audio-player-shuffle-scope` | The scope of a shuffled play trigger: `release`, `artist` or `library`. A shuffled play trigger without this attribute shuffles the release it started. | + +All triggers read the play descriptor from the same `data-*` attributes: + +| Attribute | Meaning | +| --- | --- | +| `data-library-id` | The Id of the media library the context belongs to. Required by every trigger. | +| `data-track-id` | The Id of the track. Required by a track trigger. | +| `data-album-id` | The Id of the album. Required by a track trigger and by an album context trigger. | +| `data-artist-id` | The Id of the artist. Required by a track trigger, an album context trigger and an artist context trigger. | +| `data-title` | The display title of the track or context, shown in the bar while the context loads. Optional. | +| `data-album-title` | The display title of the album the track belongs to, shown under the track name in the bar. Optional, and meaningful on a track trigger. An album context already uses its `data-title` as the album title while the context loads, so it does not need this attribute. | +| `data-duration` | The duration of the track in seconds. Optional, and meaningful on a track trigger. | +| `data-cover-art-path` | The artwork path of the cover, relative to the API server base, exactly like the artwork path the album page uses. Optional. | +| `data-cover-art-url` | An absolute cover art URL, or a relative artwork path. Optional, and used in preference to `data-cover-art-path` when both are present. | + +The context a trigger describes decides the required parameters and the queue it builds: + +| Trigger | Required attributes | Queue | +| --- | --- | --- | +| Track | `data-library-id`, `data-track-id`, `data-album-id`, `data-artist-id` | The single track. | +| Album | `data-library-id`, `data-album-id`, `data-artist-id` | The tracks of the release, in disc and then track number order. | +| Artist | `data-library-id`, `data-artist-id` | Every release of the artist in the order the artist page presents them, each in disc and track number order. | +| Library | `data-library-id` | Every track of the first artist of the library that has tracks, in artist page order, followed by the remaining artists in the same order. | + +The album queue is read through `api-get-tracks`, the artist queue through `api-get-albums` and then `api-get-tracks`, and a track trigger uses the descriptor alone. A library trigger reads `api-get-artists` to find the first artist that has tracks and then builds that artist's queue; when playback reaches the end, the continuation walks the remaining artists in library order. The queue script documents these endpoints and their order in full. + +An album or artist trigger carries its effective cover into the entries it queues. A `data-cover-art-url` is kept as the resolved cover URL of the context, so a theme that supplies only that attribute does not lose the cover when the queue is built. An album trigger falls back to the context cover for a release without one. An artist trigger falls back to the artist cover, and a library trigger falls back to the cover of the artist the release belongs to, so a release with its own cover always keeps that cover. The `data-cover-art-path` is kept on every entry for artwork matching, even when the trigger supplies a cover URL. + +Each page exposes the values its own triggers need. The album page provides `artistId`, `albumId`, `libraryId`, `albumTitle`, `albumCoverPath` and `albumHasTracks` for the album trigger. Its per-track triggers are rendered from the track rows the page loads from `tracksUrl`, which returns the `id`, `title`, `trackNumber`, `discNumber` and `durationInSeconds` of each track; `albumJson` carries the album model the template script starts from, and `trackUrl` is the template of a track page route. The artist page provides `artistId`, `libraryId`, `artistName`, `artistCoverPath` and `artistHasReleases` for the play all trigger, and `albumsUrl` and `albumUrl` for the release list and its cards. The release rows returned by `albumsUrl` carry the `id`, `title` and `coverPath` used by the album card Play and Shuffle actions. The track page provides `artistId`, `albumId`, `trackId`, `libraryId`, `trackTitle`, `trackDurationInSeconds`, `albumTitle` and `albumCoverPath` for its trigger. The artist index page provides `libraryId` and `itemsUrl` for its artist cards, and each row of `itemsUrl` carries the `id`, `name` and `coverPath` used by the artist card Play and Shuffle actions. The home page library cards are application markup, and each music library card uses the library `id` for its Play and Shuffle actions. A theme template that changes these pages uses the same values and endpoints to render equivalent triggers. + +The application fallback templates render the triggers on the existing `confirm-button` controls: the page-level controls carry their localized label, and the per-track control carries a text play glyph with an accessible label. The card actions menus of music libraries, artists and albums render Play and Shuffle; the album card menu also keeps Remove beside them. A theme may use any markup and classes; only the trigger and descriptor attributes are required, and a trigger must be a focusable element, such as a `button`. The bundled themes render these triggers on the pages and card menus they provide, so a custom theme that replaces one of those templates must render them again to keep playback and shuffle reachable from that page. + +#### The audio player sub templates + +Like the file system browser, the audio player is split into a shell template and the sub templates of its dynamic content, all provided as mirrored files under `templates/shared/audio-player/`. The shell template inlines the raw source of each sub template into a plain text script element, so that the browser never parses the theme markup into live elements and requests their resources before the player renders them: + +```html + + +``` + +The sub templates are rendered client side by the audio player script with the same Mustache syntax as the server side engine. They receive the following fields: + +| Template | Fields | +| --- | --- | +| `queue-item` | `entryId` (the identity of this occurrence in the queue), `index` (the one based position in the queue), `trackId`, `albumId`, `artistId`, `libraryId`, `title`, `duration` (the formatted `m:ss` duration), `durationSeconds`, `coverArtUrl` (the resolved cover art URL, which is the music placeholder when the entry has no artwork), `isCurrent`, `isPlayed`, `isLast`, `isContinuation` (the entry was added by the autoplay continuation) and `isShuffled` (the entry was added by a shuffle batch). The item root must keep the `audio-player-queue-item` class, the stylesheet hook of a queue item: the player appends the rendered element as-is, so the class is what lets the theme style it. The player writes `is-current`, `is-played`, `is-continuation` and `is-shuffled` on the root itself, so a theme item does not need to render those state classes, and it writes `data-audio-player-queue-entry-id`, so a theme item does not need to render the identity either. A theme item should render the favorite toggle with the `data-favorite-toggle`, `data-favorite-media-kind` and `data-favorite-media-item-id` attributes. The player appends the built-in toggle when it is missing. | +| `playlist-item` | `index`, `trackId`, `albumId`, `artistId`, `libraryId`, `title`, `duration`, `durationSeconds`, `coverArtUrl` and `isCurrent`. The item root must keep the `audio-player-playlist-item` class, the stylesheet hook of a playlist item. The shell inlines this sub template for theme authors, but the player does not render a saved playlist list with it yet; the saved playlist page renders its own rows from the page data described below. | + +A theme can omit any sub template: the player then renders that part with its own built-in markup. When a theme replaces the shell, it must keep the two plain text script element ids above, the element hooks of the bar, and the `audio-player-container`, `not-shown` and `expanded` classes the player toggles. + +Every field of the `queue-item` and `playlist-item` models is untrusted: titles and identifiers come from file metadata and the music endpoints. Render these fields with the escaped form, `{{field}}`. The template engine also supports the unescaped form `{{{field}}}`, but these models contain no trusted HTML, so unescaped tags must not be used for them. Escaping does not neutralise whitespace in an unquoted attribute, so every model value placed in an attribute must sit inside quoted attribute marks, for example `data-track-id="{{trackId}}"` and never `data-track-id={{trackId}}`. + ### The Navigation Template (shared/nav-menu) The navigation template renders the menu of the active theme. Its model contains the site name and two menu structures, one for the mobile menu and one for the desktop menu bar: @@ -317,6 +513,192 @@ Page templates are rendered into a content section that the layout wraps. A page {{/scripts}} ``` +#### The Playlist Pages + +`playlists/index` receives a model with the following fields: + +| Field | Content | +| --- | --- | +| `getPlaylistsUrl` | The route that returns the playlists of the current user. | +| `addUrl` | The route of the dedicated page that creates a playlist. | +| `itemUrl` | The route template of a playlist page. The trailing `00000000-0000-0000-0000-000000000000` is replaced by the Id of the playlist. | +| `deleteUrl` | The route template that deletes a playlist. The trailing `00000000-0000-0000-0000-000000000000` is replaced by the Id of the playlist. | +| `antiforgeryToken` | The anti-forgery token the page submits with its mutating requests. | +| `strings` | The localized strings of the page, keyed by their resource names. | + +`playlists/item` receives a model with the following fields: + +| Field | Content | +| --- | --- | +| `isNew` | `true` on the create page, `false` on the page of an existing playlist. The same page key serves both modes. | +| `playlistId` | The Id of the playlist the page shows, or the empty Id on the create page. | +| `playlistJson` | The playlist metadata and only the first 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 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. | +| `removeEntryUrl` | The route template that removes an entry. The trailing `00000000-0000-0000-0000-000000000000` is replaced by the Id of the entry. | +| `moveEntryUrl` | The route that moves one entry of the playlist to a new position. The empty `00000000-0000-0000-0000-000000000000` entry segment is replaced by the entry Id; the body carries `targetPosition`. | +| `getEnabledLibrariesUrl` | The route that lists the media libraries the current user can browse. | +| `getArtistsUrl` | The route that lists the artists of a music library. It takes `libraryId` as a query parameter. | +| `getArtistAlbumsUrl` | The route template that lists the releases of an artist. The trailing `00000000-0000-0000-0000-000000000000` is replaced by the Id of the artist, and the library Id is passed as a query parameter. | +| `getAlbumTracksUrl` | The route template that lists the tracks of an album. The two `00000000-0000-0000-0000-000000000000` segments are replaced by the Ids of the artist and the album, and the library Id is passed as a query parameter. | +| `indexUrl` | The route of the playlists page. | +| `antiforgeryToken` | The anti-forgery token the page submits with its mutating requests. | +| `strings` | The localized strings of the page, keyed by their resource names. | + +The fallback views keep these element hooks, which the application script drives: on the list page, `playlists-container`, `no-playlists` and `playlist-count`; on the item page, `playlist-details-form`, `playlist-title`, `playlist-name-input`, `playlist-description-input`, `save-playlist-button`, `cancel-playlist-button`, `play-playlist-button`, `delete-playlist-button`, `playlist-entries`, `no-tracks`, `load-more-entries-button`, `playlist-library-combobox`, `playlist-artist-combobox`, `playlist-album-combobox`, `playlist-track-combobox`, `add-track-button` and `no-music-libraries`. The four track picker controls are standard application combo boxes, not native `select` elements. A theme that restructures a page must keep the hooks the page script needs for that page. + +The playlist rows use the same play affordance contract as the music pages: an element with `data-audio-player-play` and the `data-track-id`, `data-library-id`, `data-album-id`, `data-artist-id`, `data-title`, `data-album-title`, `data-duration` and `data-cover-art-path` attributes is handed to the global player by event delegation. The page fills `data-track-id` from the entry `mediaItemId`, because a music entry references a track. The Play playlist control fetches every 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. A playable row also renders the heart of the global favorites script (`data-favorite-toggle`, with the kind `MusicTrack`) and the declarative add-to-playlist action (`data-playlist-add` with the track, library, album, artist and title attributes), so the row can be favorited and saved without leaving the playlist. A theme template that replaces the row must keep both controls to keep those actions reachable. + +#### The Shared Add to Playlist Action + +The music library card on the home page, the artist cards, the album cards and the actions menu of an album track row share one add-to-playlist action. The action is a menu item with the `card-action-add-to-playlist` class in both cases. Their click handler calls `window.LuminaPlaylists.showAddScopeDialogAsync(scope)`, where `scope` carries `libraryId`, the optional `artistId`, `albumId` and `trackId`, the `title` shown in the dialog, the page-local `addToPlaylistLabel`, and the optional `returnFocus` element that gets the focus back when the dialog closes. The helper is provided by `wwwroot/js/playlists.js`, which every layout loads. The page passes its own localized label from its page resource as `addToPlaylistLabel`. + +The dialog is rendered by the application, not by the theme: it is a standard application dialog surface with a standard `enlightenment-combobox` of the playlists of the current user. When the scope carries a `trackId`, the dialog appends that single track through the single entry route. Otherwise, the server resolves the ordered track Ids of the scope and appends them to the selected playlist in one batch request. In both cases it shows the result notification and dispatches the `lumina:playlist-updated` event so an open playlist page refreshes. A theme that renders the dialog itself does not get this behavior; it must keep the action wired to the shared helper or reimplement the whole flow. + +A page or a theme template can also render a declarative action that needs no script of its own. The global playlist script binds one click listener on the document, so the action works anywhere in the swapped page content, inside the player bar, and on controls that a page renders later. The action is any focusable element, normally a `button`, that carries these attributes: + +| Attribute | Meaning | +| --- | --- | +| `data-playlist-add` | Required. Marks the element as an add-to-playlist action. | +| `data-playlist-library-id` | Required. The Id of the media library the scope belongs to. An action without it is inert, because a scope is always resolved inside one library. | +| `data-playlist-track-id` | Optional. The Id of a single track. When present, the action appends that track through the single entry route and the album and artist attributes are only descriptive. | +| `data-playlist-album-id` | Optional. The Id of the album of a scope that is not a single track. | +| `data-playlist-artist-id` | Optional. The Id of the artist of a scope that is not a single track. | +| `data-playlist-title` | Optional. The title shown in the dialog, so the user sees what the action will add. | + +The default action is prevented and the event stops propagating at the document listener, so link navigation is suppressed. An ancestor handler that already ran is not undone. A disabled action stays inert. Playlist rows and theme markup use these attributes; the player queue action uses its own combobox and button instead. + +The layout provides the shared configuration as `window.playlistConfiguration`: + +| Field | Content | +| --- | --- | +| `getPlaylistsUrl` | The route that returns the playlists of the current user. | +| `addPlaylistEntryUrl` | The route that appends one track to a playlist. The empty `00000000-0000-0000-0000-000000000000` segment is replaced by the playlist Id; the body carries `trackId`. | +| `addScopeEntriesUrl` | The route that appends a whole library, artist or album scope to a playlist. The empty `00000000-0000-0000-0000-000000000000` segment is replaced by the playlist Id; the body carries `libraryId` and the optional `artistId` and `albumId`, and the server resolves and appends the tracks in catalogue order in the database. | +| `createPlaylistUrl` | The route of the dedicated create playlist page, linked from the empty state of the dialog. | +| `strings` | The localized dialog labels, including `selectPlaylist`, `noPlaylists`, `createPlaylist`, `tracksAdded`, `tracksAddFailed` and `noTracksToAdd`. | + +The player queue action does not use the declarative attributes. Its label comes from the `PlaylistAddToPlaylist` layout resource, exposed to the player as `strings.addToPlaylist` in the audio player configuration. + +#### The Album Track Actions Menu + +Every rendered track row of the album details page carries the same `card-actions-trigger` button with the vertical dots as the card menus, plus the `track-actions-trigger` class that places it inline in the row. The page script creates the same `card-actions-menu` markup on demand. The menu has three application actions: `card-action-add-to-playlist` opens the shared add-to-playlist dialog for that track, `card-action-add-to-queue` calls `window.LuminaAudioPlayer.instance.appendToQueueAsync(descriptor)`, and `card-action-play-all-from-here` calls `playAsync` with an explicit queue built from the clicked track and every track that follows it in the album order. The player starts the clicked track for the last action, and replaces the queue. A theme that renders the album page must keep the track row markup and the script behavior, or provide its own equivalent. + +#### The 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. + +#### The Statistics Page + +`library/statistics/index` receives a model with the following fields: + +The five URLs that return the data of a selected user accept an optional `userId` query parameter. The page script appends it when an administrator selected a user, including `Me`, and omits it for a regular user. The Web proxy calls the `/users/{userId}/...` API route when `userId` is present and the `/users/me/...` route when it is absent. + +| Field | Content | +| --- | --- | +| `getStatisticsUrl` | The route that returns the statistics of the selected user. It takes the optional `userId`, `libraryId`, `mediaKind`, `fromUtc` and `toUtc` query parameters, and returns the summary of that user. | +| `getAllUsersStatisticsUrl` | The route that returns the statistics of every user. It takes the optional `libraryId`, `mediaKind`, `fromUtc` and `toUtc` filters, and returns the combined totals and one summary per user. | +| `getRecentlyConsumedUrl` | The route that returns a page of the recently consumed items of the selected user. It takes the optional `userId`, the same filters, and the optional `currentPage` and `perPage` query parameters, and returns `data`, `currentPage`, `perPage`, `count` and `numberOfPages`. | +| `getMostConsumedUrl` | The route that returns a page of the most consumed items of the selected user, with the same query parameters and response shape. | +| `getTagConsumptionUrl` | The route that returns the tag breakdown of the selected user. It takes the optional `userId`, `libraryId`, `mediaKind`, `fromUtc` and `toUtc` query parameters. | +| `getGenreConsumptionUrl` | The route that returns the genre breakdown of the selected user, with the same query parameters as the tag route. | +| `getLibrariesUrl` | The route that returns the libraries available for the library filter. | +| `getUsersUrl` | The route that returns the users available for the administrator user selector, or an empty string for a regular user. | +| `deleteConsumptionItemHistoryUrl` | The route that deletes every consumption record of one media item. It is extended with `mediaKind`, `mediaItemId` and `libraryId`, and with `userId` when a user is named. | +| `clearConsumptionHistoryUrl` | The route that deletes the consumption history of the selected user. It is extended with `userId` when the administrator selected a user. | +| `clearResumePointsUrl` | The route that deletes the resume points of the selected user. It is extended with `userId` when the administrator selected a user. | +| `culture` | The culture of the page, for example `en-US`, used to format dates and percentages in the browser. | +| `isAdmin` | Whether the current user is an administrator and can select another user or all users. | +| `currentUserId` | The Id of the current user, or `null` when it cannot be determined. | +| `strings` | The localized strings of the page, keyed by their resource names. | + +A summary carries `userId` on a per-user result, plus `totalConsumedDurationInSeconds`, `countedSessionCount`, `completedSessionCount`, `stoppedSessionCount`, `completionRate` and `mediaKindSummaries`. The all-users result carries a `total` summary without `userId` and a `users` list of per-user summaries. A media kind summary carries `mediaKind` and the same totals without `userId`. + +A row of the recently consumed or most consumed list carries `mediaKind`, `mediaItemId`, `libraryId`, `isAvailable`, `title`, `collectionTitle`, `creatorName`, `coverPath`, `lastConsumedOnUtc`, `countedSessionCount`, `completedSessionCount` and `consumedDurationInSeconds`. A tag or genre row carries `name`, `consumedItemCount` and `consumedDurationInSeconds`. Names are lowercase and grouped across media kinds. An item that is no longer available keeps its counts and duration but has blank display fields, so the page shows it as unavailable without a link. + +The page script loads the libraries for the filter, and the users only when the current user is an administrator. The user selector offers the current user, every other user, and `All users`. The all-users selection loads the combined totals and the per-user table, and hides the tag breakdown and the history lists, which are only meaningful per user. Any other selection loads the summary, the media kind breakdown, the tag and genre bars, and the two history lists. Applying the filters reloads every section with the selected library, media kind and date range. Clearing the history or the resume points asks for confirmation first, and refreshing after a deletion reloads every section. + +The fallback view keeps these element hooks, which the application script drives: `statistics-user-filter`, `statistics-user-filter-toggle`, `statistics-user-filter-dropdown`, `statistics-library-filter`, `statistics-library-filter-toggle`, `statistics-library-filter-dropdown`, `statistics-kind-filter`, `statistics-kind-filter-toggle`, `statistics-from-date`, `statistics-to-date`, `statistics-apply-filters`, `statistics-reset-filters`, `statistics-loading`, `statistics-load-failed`, `retry-statistics-button`, `statistics-content`, `statistics-total-duration`, `statistics-counted-sessions`, `statistics-completed-sessions`, `statistics-completion-rate`, `statistics-media-kind-breakdown`, `statistics-no-media-kind`, `statistics-users-section`, `statistics-users-table`, `statistics-no-users`, `statistics-terms`, `statistics-genres`, `statistics-tags`, `statistics-no-genres`, `statistics-no-tags`, `statistics-history-section`, `statistics-clear-history`, `statistics-clear-resume-points`, `statistics-recently-consumed`, `statistics-no-recently-consumed`, `statistics-most-consumed`, `statistics-no-most-consumed`, `statistics-all-users-note` and `statistics-empty-state`. A theme template that renders the page itself gets the same behavior by keeping these hooks and rendering the localized strings from the page model. + +#### Favorite Toggles + +A favorite toggle is the heart of a media card, of a track row, or of the condensed audio player bar. 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, on the rows of the track table of the album page (the kind `MusicTrack`, after the duration), on the rows of a saved playlist, on the favorite toggle of the condensed audio player bar for the current track, and on every queue item of the player (the kind `MusicTrack`). The detail pages of an artist, an album, a track and a book render no toggle. A theme that replaces a list must render the hearts again to keep favoriting reachable from it, and a theme queue item uses the same `data-favorite-toggle` contract. + +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. diff --git a/plugins/Lumina.Plugins.ID3/Common/Models/DTO/Tags/Id3TagDto.cs b/plugins/Lumina.Plugins.ID3/Common/Models/DTO/Tags/Id3TagDto.cs index 02897507..7c8103b5 100644 --- a/plugins/Lumina.Plugins.ID3/Common/Models/DTO/Tags/Id3TagDto.cs +++ b/plugins/Lumina.Plugins.ID3/Common/Models/DTO/Tags/Id3TagDto.cs @@ -216,6 +216,11 @@ internal sealed class Id3TagDto /// public string? AudioCodec { get; init; } + /// + /// Gets or initializes the container of the audio file of the track, for example MP3, FLAC, OGG, AAC, MP4 or WAV. + /// + public string? Container { get; init; } + /// /// Gets or initializes the official website associated with the artist. /// diff --git a/plugins/Lumina.Plugins.ID3/Core/Mapping/Id3TagMapper.cs b/plugins/Lumina.Plugins.ID3/Core/Mapping/Id3TagMapper.cs index df197b9a..6986686f 100644 --- a/plugins/Lumina.Plugins.ID3/Core/Mapping/Id3TagMapper.cs +++ b/plugins/Lumina.Plugins.ID3/Core/Mapping/Id3TagMapper.cs @@ -164,6 +164,7 @@ internal static class Id3TagMapper Channels: data.Channels, BitDepth: data.BitDepth, AudioCodec: NullIfWhiteSpace(data.AudioCodec), + Container: NullIfWhiteSpace(data.Container), Bitrate: data.Bitrate, MusicBrainzRecordingId: ParseGuid(data.MusicBrainzRecordingId), MusicBrainzTrackId: ParseGuid(data.MusicBrainzReleaseTrackId), diff --git a/plugins/Lumina.Plugins.ID3/Core/Tags/AudioContainerResolver.cs b/plugins/Lumina.Plugins.ID3/Core/Tags/AudioContainerResolver.cs new file mode 100644 index 00000000..3c2b4e1e --- /dev/null +++ b/plugins/Lumina.Plugins.ID3/Core/Tags/AudioContainerResolver.cs @@ -0,0 +1,57 @@ +#region ========================================================================= USING ===================================================================================== +using System; +#endregion + +namespace Lumina.Plugins.ID3.Core.Tags; + +/// +/// Resolves the canonical name of the container of an audio file from the concrete type the tagging library parsed it as. +/// +internal static class AudioContainerResolver +{ + /// + /// Resolves the container of the audio file parsed by . + /// + /// The parsed audio file whose container is resolved. + /// The canonical name of the container, for example MP3, FLAC, OGG, AAC, MP4 or WAV, or when the container cannot be recognized. + public static string? Resolve(TagLib.File tagFile) + { + // The concrete type of the parsed file is the most reliable description of its container, because it is chosen by the parser from the + // actual bytes of the file, while the mime type only describes the extension. The scanning pipeline resolves the container the same way, + // so that the container captured during a scan and the one captured during metadata enrichment always agree. + return tagFile switch + { + TagLib.Mpeg.File => "MP3", + TagLib.Flac.File => "FLAC", + TagLib.Mpeg4.File => "MP4", + TagLib.Aac.File => "AAC", + TagLib.Ogg.File => "OGG", + TagLib.Riff.File => "WAV", + TagLib.Aiff.File => "AIFF", + TagLib.Ape.File => "APE", + TagLib.WavPack.File => "WAVPACK", + TagLib.Asf.File => "WMA", + TagLib.Dsf.File => "DSF", + TagLib.Matroska.File => "MATROSKA", + TagLib.MusePack.File => "MPC", + TagLib.Audible.File => "AA", + _ => ResolveFromMimeType(tagFile.MimeType) + }; + } + + /// + /// Resolves the container from the mime type reported by the tagging library, for the containers that have no dedicated parser. + /// + /// The mime type reported by the tagging library. + /// The name of the container, or when it cannot be derived. + public static string? ResolveFromMimeType(string? mimeType) + { + if (string.IsNullOrWhiteSpace(mimeType)) + return null; + + // The library reports its mime types with the "taglib/" prefix, so only the last segment names the container. + string[] segments = mimeType.Split('/', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); + string? container = segments.Length > 0 ? segments[^1] : null; + return string.IsNullOrWhiteSpace(container) ? null : container.ToUpperInvariant(); + } +} diff --git a/plugins/Lumina.Plugins.ID3/Core/Tags/Id3TagReader.cs b/plugins/Lumina.Plugins.ID3/Core/Tags/Id3TagReader.cs index 4f86de83..d2f80301 100644 --- a/plugins/Lumina.Plugins.ID3/Core/Tags/Id3TagReader.cs +++ b/plugins/Lumina.Plugins.ID3/Core/Tags/Id3TagReader.cs @@ -166,6 +166,7 @@ internal sealed class Id3TagReader BitDepth = audioProperties.BitsPerSample > 0 ? audioProperties.BitsPerSample : null, Bitrate = audioProperties.AudioBitrate > 0 ? audioProperties.AudioBitrate : null, AudioCodec = NullIfWhiteSpace(audioProperties.Description), + Container = AudioContainerResolver.Resolve(tagFile), Website = NullIfWhiteSpace(GetExtendedField(extendedFields, "WOAR", "website")), MusicBrainzArtistId = NullIfWhiteSpace(tag.MusicBrainzArtistId), MusicBrainzReleaseArtistId = NullIfWhiteSpace(tag.MusicBrainzReleaseArtistId), diff --git a/plugins/Lumina.Plugins.MusicBrainz/Core/Mapping/MusicBrainzMapper.cs b/plugins/Lumina.Plugins.MusicBrainz/Core/Mapping/MusicBrainzMapper.cs index 5b6a363a..81b40249 100644 --- a/plugins/Lumina.Plugins.MusicBrainz/Core/Mapping/MusicBrainzMapper.cs +++ b/plugins/Lumina.Plugins.MusicBrainz/Core/Mapping/MusicBrainzMapper.cs @@ -183,6 +183,7 @@ internal static partial class MusicBrainzMapper Channels: null, BitDepth: null, AudioCodec: null, + Container: null, Bitrate: null, MusicBrainzRecordingId: ParseGuid(recording.Id), MusicBrainzTrackId: null, diff --git a/src/Lumina.Application/Common/CQRS/ICommandHandler.cs b/src/Lumina.Application/Common/CQRS/ICommandHandler.cs index 19e0018d..04842335 100644 --- a/src/Lumina.Application/Common/CQRS/ICommandHandler.cs +++ b/src/Lumina.Application/Common/CQRS/ICommandHandler.cs @@ -17,7 +17,7 @@ public interface ICommandHandler where TCommand : ICommand /// Handles the specified command and returns a result. /// /// The command to handle. - /// Token to monitor for cancellation requests. + /// Cancellation token that can be used to stop the execution. /// A task that represents the asynchronous operation, containing the result of the command execution. Task HandleAsync(TCommand command, CancellationToken cancellationToken = default); } diff --git a/src/Lumina.Application/Common/CQRS/IQueryHandler.cs b/src/Lumina.Application/Common/CQRS/IQueryHandler.cs index 8b5fadde..9f33322e 100644 --- a/src/Lumina.Application/Common/CQRS/IQueryHandler.cs +++ b/src/Lumina.Application/Common/CQRS/IQueryHandler.cs @@ -17,7 +17,7 @@ public interface IQueryHandler where TQuery : IQuery /// Handles the specified query and returns a result. /// /// The query to handle. - /// Token to monitor for cancellation requests. + /// Cancellation token that can be used to stop the execution. /// A task that represents the asynchronous operation, containing the result of the query execution. Task HandleAsync(TQuery query, CancellationToken cancellationToken = default); } diff --git a/src/Lumina.Application/Common/DTO/Favorites/FavoriteItemDisplayDto.cs b/src/Lumina.Application/Common/DTO/Favorites/FavoriteItemDisplayDto.cs new file mode 100644 index 00000000..09519a0a --- /dev/null +++ b/src/Lumina.Application/Common/DTO/Favorites/FavoriteItemDisplayDto.cs @@ -0,0 +1,33 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Common.DTO.Favorites; + +/// +/// Data transfer object for the generic display data of a favorited media item. +/// +/// +/// 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. +/// +/// The Id of the media library that contains the media item. +/// The title of the media item. +/// The Id of the collection that contains the media item, or an empty Guid when there is none. +/// The title of the collection that contains the media item, or an empty string when there is none. +/// The Id of the creator of the media item, or an empty Guid when there is none. +/// The name of the creator of the media item, or an empty string when there is none. +/// The path of the cover art of the media item, if available. +[DebuggerDisplay("LibraryId: {LibraryId}; Title: {Title}")] +public sealed record FavoriteItemDisplayDto( + Guid LibraryId, + string Title, + Guid CollectionId, + string CollectionTitle, + Guid CreatorId, + string CreatorName, + string? CoverPath +); diff --git a/src/Lumina.Application/Common/DTO/Favorites/FavoriteItemDto.cs b/src/Lumina.Application/Common/DTO/Favorites/FavoriteItemDto.cs new file mode 100644 index 00000000..d34c46db --- /dev/null +++ b/src/Lumina.Application/Common/DTO/Favorites/FavoriteItemDto.cs @@ -0,0 +1,17 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Favorites; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Common.DTO.Favorites; + +/// +/// Data transfer object for a stored favorite together with the display data of the media item it references. +/// +/// The stored favorite. +/// The display data of the referenced media item, or when it no longer exists. +[DebuggerDisplay("Id: {Favorite.Id}; MediaKind: {Favorite.MediaKind}")] +public sealed record FavoriteItemDto( + FavoriteEntity Favorite, + FavoriteItemDisplayDto? Display +); diff --git a/src/Lumina.Application/Common/DTO/MediaConsumption/AllUsersConsumptionStatisticsDto.cs b/src/Lumina.Application/Common/DTO/MediaConsumption/AllUsersConsumptionStatisticsDto.cs new file mode 100644 index 00000000..92804c6a --- /dev/null +++ b/src/Lumina.Application/Common/DTO/MediaConsumption/AllUsersConsumptionStatisticsDto.cs @@ -0,0 +1,17 @@ +#region ========================================================================= USING ===================================================================================== +using System.Collections.Generic; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Common.DTO.MediaConsumption; + +/// +/// Data transfer object for the consumption statistics of every user, together with their combined totals. +/// +/// The combined consumption statistics of every user. +/// The consumption statistics of each user. +[DebuggerDisplay("UserCount: {Users.Count}; CountedSessionCount: {Total.CountedSessionCount}")] +public sealed record AllUsersConsumptionStatisticsDto( + ConsumptionTotalsDto Total, + IReadOnlyList Users +); diff --git a/src/Lumina.Application/Common/DTO/MediaConsumption/ConsumedItemDto.cs b/src/Lumina.Application/Common/DTO/MediaConsumption/ConsumedItemDto.cs new file mode 100644 index 00000000..45a116a2 --- /dev/null +++ b/src/Lumina.Application/Common/DTO/MediaConsumption/ConsumedItemDto.cs @@ -0,0 +1,38 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Common.DTO.MediaConsumption; + +/// +/// Data transfer object for a media item of the consumption history, together with its aggregated consumption counts and display details. +/// +/// The kind of the consumed media item. +/// The Id of the consumed media item. +/// The Id of the media library that contains the media item. +/// Whether the media item still exists and can be accessed by the user. When , the title, collection title, creator name, and cover path are blank, while the identity and aggregation fields remain. +/// The title of the media item, or an empty string when the item is not available. +/// The title of the collection that contains the media item, or an empty string when there is none. +/// The name of the creator of the media item, or an empty string when there is none. +/// The path of the cover art of the media item, if available. +/// The date and time when the media item was last consumed. +/// The number of consumption sessions of the media item that count towards statistics. +/// The number of consumption sessions of the media item that completed. +/// The active duration consumed in the media item, over all of its sessions, in milliseconds. +[DebuggerDisplay("MediaKind: {MediaKind}; MediaItemId: {MediaItemId}; CountedSessionCount: {CountedSessionCount}")] +public sealed record ConsumedItemDto( + MediaKind MediaKind, + Guid MediaItemId, + Guid LibraryId, + bool IsAvailable, + string Title, + string CollectionTitle, + string CreatorName, + string? CoverPath, + DateTime LastConsumedOnUtc, + int CountedSessionCount, + int CompletedSessionCount, + long ConsumedDurationMilliseconds +); diff --git a/src/Lumina.Application/Common/DTO/MediaConsumption/ConsumptionRecordDto.cs b/src/Lumina.Application/Common/DTO/MediaConsumption/ConsumptionRecordDto.cs new file mode 100644 index 00000000..d488430e --- /dev/null +++ b/src/Lumina.Application/Common/DTO/MediaConsumption/ConsumptionRecordDto.cs @@ -0,0 +1,39 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Common.DTO.MediaConsumption; + +/// +/// Data transfer object for a media consumption session. +/// +/// The Id of the consumption record. +/// The Id of the media library that contains the consumed media item. +/// The Id of the consumed media item. +/// The kind of media that was consumed. +/// The state of the consumption session. +/// The date and time when the session started. +/// The date and time when the session last received activity. +/// The date and time when the session completed or stopped, if it has ended. +/// The active duration consumed by the session, in milliseconds. +/// The last known position for the media item, if any. +/// The latest reported progress fraction of the media item. +/// The number of consecutive pages read in the session. +[DebuggerDisplay("Id: {Id}; MediaKind: {MediaKind}; Status: {Status}")] +public sealed record ConsumptionRecordDto( + Guid Id, + Guid LibraryId, + Guid MediaItemId, + MediaKind MediaKind, + ConsumptionStatus Status, + DateTime StartedOnUtc, + DateTime LastActivityOnUtc, + DateTime? EndedOnUtc, + long ConsumedDurationMilliseconds, + MediaPositionDto? LastPosition, + double LastProgressFraction, + int ConsecutivePagesRead +); diff --git a/src/Lumina.Application/Common/DTO/MediaConsumption/ConsumptionStatisticsDto.cs b/src/Lumina.Application/Common/DTO/MediaConsumption/ConsumptionStatisticsDto.cs new file mode 100644 index 00000000..b4b1b950 --- /dev/null +++ b/src/Lumina.Application/Common/DTO/MediaConsumption/ConsumptionStatisticsDto.cs @@ -0,0 +1,28 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Collections.Generic; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Common.DTO.MediaConsumption; + +/// +/// Data transfer object for the consumption statistics of a user. +/// +/// The Id of the user the statistics belong to. +/// The total duration consumed over every recorded session, in milliseconds. +/// The number of recorded sessions that count towards statistics. +/// The number of recorded sessions that completed. +/// The number of recorded sessions that stopped before they completed and count towards statistics. +/// The fraction of the counted sessions that completed, between 0 and 1, or 0 when there is no counted session. +/// The consumption statistics broken down by media kind. +[DebuggerDisplay("UserId: {UserId}; CountedSessionCount: {CountedSessionCount}")] +public sealed record ConsumptionStatisticsDto( + Guid UserId, + long TotalConsumedDurationMilliseconds, + int CountedSessionCount, + int CompletedSessionCount, + int StoppedSessionCount, + double CompletionRate, + IReadOnlyList MediaKindSummaries +); diff --git a/src/Lumina.Application/Common/DTO/MediaConsumption/ConsumptionTotalsDto.cs b/src/Lumina.Application/Common/DTO/MediaConsumption/ConsumptionTotalsDto.cs new file mode 100644 index 00000000..151f5cc5 --- /dev/null +++ b/src/Lumina.Application/Common/DTO/MediaConsumption/ConsumptionTotalsDto.cs @@ -0,0 +1,25 @@ +#region ========================================================================= USING ===================================================================================== +using System.Collections.Generic; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Common.DTO.MediaConsumption; + +/// +/// Data transfer object for the combined consumption statistics of every user. +/// +/// The total duration consumed over every recorded session of every user, in milliseconds. +/// The number of recorded sessions of every user that count towards statistics. +/// The number of recorded sessions of every user that completed. +/// The number of recorded sessions of every user that stopped before they completed and count towards statistics. +/// The fraction of the counted sessions of every user that completed, between 0 and 1, or 0 when there is no counted session. +/// The combined consumption statistics broken down by media kind. +[DebuggerDisplay("CountedSessionCount: {CountedSessionCount}; CompletedSessionCount: {CompletedSessionCount}")] +public sealed record ConsumptionTotalsDto( + long TotalConsumedDurationMilliseconds, + int CountedSessionCount, + int CompletedSessionCount, + int StoppedSessionCount, + double CompletionRate, + IReadOnlyList MediaKindSummaries +); diff --git a/src/Lumina.Application/Common/DTO/MediaConsumption/GenreConsumptionDto.cs b/src/Lumina.Application/Common/DTO/MediaConsumption/GenreConsumptionDto.cs new file mode 100644 index 00000000..4d5b0e57 --- /dev/null +++ b/src/Lumina.Application/Common/DTO/MediaConsumption/GenreConsumptionDto.cs @@ -0,0 +1,18 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Common.DTO.MediaConsumption; + +/// +/// Data transfer object for the consumption statistics of a genre, grouped across media kinds. +/// +/// The lowercase name of the genre. +/// The number of distinct media items that carry the genre and were consumed. +/// The active duration consumed in the media items that carry the genre, in milliseconds. +[DebuggerDisplay("Name: {Name}; ConsumedItemCount: {ConsumedItemCount}")] +public sealed record GenreConsumptionDto( + string Name, + int ConsumedItemCount, + long ConsumedDurationMilliseconds +); diff --git a/src/Lumina.Application/Common/DTO/MediaConsumption/MediaKindConsumptionStatisticsDto.cs b/src/Lumina.Application/Common/DTO/MediaConsumption/MediaKindConsumptionStatisticsDto.cs new file mode 100644 index 00000000..cec9ecf0 --- /dev/null +++ b/src/Lumina.Application/Common/DTO/MediaConsumption/MediaKindConsumptionStatisticsDto.cs @@ -0,0 +1,25 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Common.DTO.MediaConsumption; + +/// +/// Data transfer object for the consumption statistics of a user for one kind of media. +/// +/// The kind of media the statistics belong to. +/// The total duration consumed over every recorded session of the media kind, in milliseconds. +/// The number of recorded sessions of the media kind that count towards statistics. +/// The number of recorded sessions of the media kind that completed. +/// The number of recorded sessions of the media kind that stopped before they completed and count towards statistics. +/// The fraction of the counted sessions of the media kind that completed, between 0 and 1, or 0 when there is no counted session. +[DebuggerDisplay("MediaKind: {MediaKind}; CountedSessionCount: {CountedSessionCount}")] +public sealed record MediaKindConsumptionStatisticsDto( + MediaKind MediaKind, + long TotalConsumedDurationMilliseconds, + int CountedSessionCount, + int CompletedSessionCount, + int StoppedSessionCount, + double CompletionRate +); diff --git a/src/Lumina.Application/Common/DTO/MediaConsumption/MediaPositionDto.cs b/src/Lumina.Application/Common/DTO/MediaConsumption/MediaPositionDto.cs new file mode 100644 index 00000000..16c6214a --- /dev/null +++ b/src/Lumina.Application/Common/DTO/MediaConsumption/MediaPositionDto.cs @@ -0,0 +1,19 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Common.DTO.MediaConsumption; + +/// +/// Data transfer object for a position reached in a media item during a consumption session. +/// +/// The kind of representation used by the position. +/// The position within the media item, in milliseconds, when the position is a time offset. +/// The opaque locator within the media item, when the position is not a time offset. +[DebuggerDisplay("Kind: {Kind}; TimeOffsetMilliseconds: {TimeOffsetMilliseconds}")] +public sealed record MediaPositionDto( + MediaPositionKind Kind, + long? TimeOffsetMilliseconds, + string? Location +); diff --git a/src/Lumina.Application/Common/DTO/MediaConsumption/ResumePointDto.cs b/src/Lumina.Application/Common/DTO/MediaConsumption/ResumePointDto.cs new file mode 100644 index 00000000..08ae9047 --- /dev/null +++ b/src/Lumina.Application/Common/DTO/MediaConsumption/ResumePointDto.cs @@ -0,0 +1,28 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Common.DTO.MediaConsumption; + +/// +/// Data transfer object for the point at which a user can resume consuming a media item. +/// +/// The Id of the resume point. +/// The Id of the media library that contains the media item. +/// The Id of the media item to resume. +/// The kind of media that is resumed. +/// The position at which the media item can be resumed. +/// The progress fraction at which the media item can be resumed. +/// The date and time when the media item was last consumed. +[DebuggerDisplay("Id: {Id}; MediaKind: {MediaKind}; MediaItemId: {MediaItemId}")] +public sealed record ResumePointDto( + Guid Id, + Guid LibraryId, + Guid MediaItemId, + MediaKind MediaKind, + MediaPositionDto LastPosition, + double LastProgressFraction, + DateTime LastConsumedOnUtc +); diff --git a/src/Lumina.Application/Common/DTO/MediaConsumption/TagConsumptionDto.cs b/src/Lumina.Application/Common/DTO/MediaConsumption/TagConsumptionDto.cs new file mode 100644 index 00000000..e836165d --- /dev/null +++ b/src/Lumina.Application/Common/DTO/MediaConsumption/TagConsumptionDto.cs @@ -0,0 +1,18 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Common.DTO.MediaConsumption; + +/// +/// Data transfer object for the consumption statistics of a tag, grouped across media kinds. +/// +/// The lowercase name of the tag. +/// The number of distinct media items that carry the tag and were consumed. +/// The active duration consumed in the media items that carry the tag, in milliseconds. +[DebuggerDisplay("Name: {Name}; ConsumedItemCount: {ConsumedItemCount}")] +public sealed record TagConsumptionDto( + string Name, + int ConsumedItemCount, + long ConsumedDurationMilliseconds +); diff --git a/src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Albums/AlbumLiteRow.cs b/src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Albums/AlbumLiteRow.cs index 9a74fa8a..45540f8c 100644 --- a/src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Albums/AlbumLiteRow.cs +++ b/src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Albums/AlbumLiteRow.cs @@ -9,35 +9,17 @@ namespace Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.A /// /// Lightweight read model of an album, containing only the fields needed to display the album in a card-based grid or a list. /// -public sealed record AlbumLiteRow -{ - /// - /// Gets the Id of the album. - /// - public required Guid Id { get; init; } - - /// - /// Gets the title of the album. - /// - public required string Title { get; init; } - - /// - /// Gets the number of tracks of the release. - /// - public int TotalTracks { get; init; } - - /// - /// Gets the path of the image representing the album, if available. - /// - public string? CoverPath { get; init; } - - /// - /// Gets the release year of the album (the re-release year, if available, or the original release year), if known. - /// - public int? ReleaseYear { get; init; } - - /// - /// Gets the set of types of the release. - /// - public List? ReleaseTypes { get; init; } -} +/// The Id of the album. +/// The title of the album. +/// The number of tracks of the release. +/// The path of the image representing the album, if available. +/// The release year of the album (the re-release year, if available, or the original release year), if known. +/// The set of types of the release. +public sealed record AlbumLiteRow( + Guid Id, + string Title, + int TotalTracks, + string? CoverPath, + int? ReleaseYear, + List? ReleaseTypes +); diff --git a/src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Artists/ArtistLiteRow.cs b/src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Artists/ArtistLiteRow.cs index 31970314..a9a58483 100644 --- a/src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Artists/ArtistLiteRow.cs +++ b/src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Artists/ArtistLiteRow.cs @@ -7,20 +7,11 @@ namespace Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.A /// /// Lightweight read model of an artist, containing only the fields needed to display the artist in a card-based grid or a list. /// -public sealed record ArtistLiteRow -{ - /// - /// Gets the Id of the artist. - /// - public required Guid Id { get; init; } - - /// - /// Gets the name of the artist. - /// - public required string Name { get; init; } - - /// - /// Gets the path of the image representing the artist, if available. - /// - public string? CoverPath { get; init; } -} +/// The Id of the artist. +/// The name of the artist. +/// The path of the image representing the artist, if available. +public sealed record ArtistLiteRow( + Guid Id, + string Name, + string? CoverPath +); diff --git a/src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/NormalizedTrackDto.cs b/src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/NormalizedTrackDto.cs new file mode 100644 index 00000000..16efa3e8 --- /dev/null +++ b/src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/NormalizedTrackDto.cs @@ -0,0 +1,34 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.SharedKernel.Common.Enums.Playback; +using System; +using System.Collections.Generic; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback; + +/// +/// Data transfer object for the normalized audio of a track, produced and cached as a sequence of fixed duration segments. +/// +/// The Id of the track whose audio the cached entry holds, so the caller can verify that the entry is the one it authorized. +/// The opaque identifier of the cached entry that holds the normalized audio. +/// The way the audio is delivered, which is a remux or a transcode. +/// The container of the delivered audio. +/// The codec of the delivered audio. +/// The duration of each segment of the delivered audio, in seconds. +/// +/// The duration of the produced and cached audio, in seconds, rounded up to the next second. It is the produced end rather than the probed duration, so +/// it always covers every produced segment. +/// +/// The segments that make up the delivered audio, in playback order. +[DebuggerDisplay("TrackId: {TrackId} CacheId: {CacheId} Container: {Container} Codec: {Codec}")] +public sealed record NormalizedTrackDto( + Guid TrackId, + string CacheId, + PlaybackDeliveryMode Mode, + string Container, + string Codec, + int SegmentDurationSeconds, + int DurationInSeconds, + IReadOnlyList Segments +); diff --git a/src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/NormalizedTrackRequestDto.cs b/src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/NormalizedTrackRequestDto.cs new file mode 100644 index 00000000..358f52de --- /dev/null +++ b/src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/NormalizedTrackRequestDto.cs @@ -0,0 +1,52 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.SharedKernel.Common.Enums.Playback; +using System; +using System.Collections.Generic; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback; + +/// +/// Data transfer object for the request to produce the normalized audio of a track, as the delivery decision of a playback manifest describes it. +/// +/// The Id of the track whose audio is normalized. It binds the produced cache entry to the track the caller authorized. +/// The Id of the user whose request starts the production. It is used for the per-user admission limit, and never for the cache identity. +/// The file system path of the stored audio file of the track. +/// +/// The content locations the source path is allowed to be inside. The service validates the path against them and re-checks it after opening, so a +/// caller that forgets to enforce containment cannot hand an arbitrary path to the transcoder. +/// +/// The container of the stored audio file, as captured by the probe, used to pin the ffmpeg demuxer. +/// The way the audio is delivered, which is a remux or a transcode. +/// The container of the delivered audio, as chosen by the delivery decision. +/// The codec of the delivered audio, as chosen by the delivery decision. +/// The duration of each segment of the delivered audio, in seconds. +/// The duration of the audio of the track, in seconds. +/// The stored audio bitrate of the track, in kbps, used to estimate a remux of a lossy codec. +/// The sample rate of the stored audio of the track, in Hz, used to estimate the size of a lossless delivery. +/// The number of audio channels of the track, used to estimate the size of a lossless delivery. +/// The bit depth of the stored audio of the track, if applicable, used to estimate the size of a lossless delivery. +/// The quality cap applied to the delivered audio when it has to be re-encoded. +/// The length the source file had when the delivery was declared, in bytes. The production is rejected when the file no longer matches. +/// The last modification time the source file had when the delivery was declared. The production is rejected when the file no longer matches. +[DebuggerDisplay("TrackId: {TrackId} Mode: {Mode} Container: {Container} Codec: {Codec}")] +public sealed record NormalizedTrackRequestDto( + Guid TrackId, + Guid UserId, + string SourcePath, + IReadOnlyList AllowedRoots, + string? SourceContainer, + PlaybackDeliveryMode Mode, + string Container, + string Codec, + int SegmentDurationSeconds, + int DurationInSeconds, + int? Bitrate, + int SampleRate, + int Channels, + int? BitDepth, + PlaybackStreamingQuality Quality, + long SourceLength, + DateTime SourceLastModifiedUtc +); diff --git a/src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/NormalizedTrackSegmentDataDto.cs b/src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/NormalizedTrackSegmentDataDto.cs new file mode 100644 index 00000000..1b767175 --- /dev/null +++ b/src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/NormalizedTrackSegmentDataDto.cs @@ -0,0 +1,29 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +using System.IO; +#endregion + +namespace Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback; + +/// +/// Data transfer object for a single produced segment of the normalized audio of a track, ready to be written to the response. +/// +/// +/// The segment owns a live stream over a leased cache entry, so it is an internal delivery object of the API rather than a serializable +/// contract. The caller must dispose the stream once the response is written, which releases the cache reader lease. +/// +/// The read stream over the segment, which the caller owns and must release once the response is written. +/// The length of the segment, in bytes, taken from the index of the normalized audio. +/// The exact start of the segment on the track timeline, in seconds, taken from the index of the normalized audio. +/// The container of the delivered audio, used to resolve the media type of the segment. +/// The number of segments the production holds, so the caller can tell the end of the audio from a missing segment. +/// The duration of the produced normalized audio, in seconds, which can differ from the probed duration. +[DebuggerDisplay("Length: {Length} StartSeconds: {StartSeconds} Container: {Container} SegmentCount: {SegmentCount}")] +public sealed record NormalizedTrackSegmentDataDto( + Stream Content, + long Length, + decimal StartSeconds, + string Container, + int SegmentCount, + int DurationInSeconds +); diff --git a/src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/NormalizedTrackSegmentDto.cs b/src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/NormalizedTrackSegmentDto.cs new file mode 100644 index 00000000..00c3cb1a --- /dev/null +++ b/src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/NormalizedTrackSegmentDto.cs @@ -0,0 +1,20 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback; + +/// +/// Data transfer object for a single fixed duration segment of the normalized audio of a track. +/// +/// The zero based position of the segment in the delivered audio. +/// The time, in seconds from the start of the track, at which the segment starts. +/// The duration of the segment, in seconds. +/// The length of the segment, in bytes. +[DebuggerDisplay("Index: {Index} StartSeconds: {StartSeconds} DurationSeconds: {DurationSeconds}")] +public sealed record NormalizedTrackSegmentDto( + int Index, + decimal StartSeconds, + decimal DurationSeconds, + long Length +); diff --git a/src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackCapabilityDto.cs b/src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackCapabilityDto.cs new file mode 100644 index 00000000..49bffeb5 --- /dev/null +++ b/src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackCapabilityDto.cs @@ -0,0 +1,16 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback; + +/// +/// Data transfer object for a single container and codec combination that a player advertises it can demux and decode directly. +/// +/// The container the player can demux, for example MP3, FLAC, OGG, WAV or MP4. +/// The codec the player can decode, for example MP3, FLAC, Opus, Vorbis, PCM or AAC. +[DebuggerDisplay("Container: {Container} Codec: {Codec}")] +public sealed record PlaybackCapabilityDto( + string Container, + string Codec +); diff --git a/src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackDeliveryDecisionDto.cs b/src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackDeliveryDecisionDto.cs new file mode 100644 index 00000000..72fb25db --- /dev/null +++ b/src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackDeliveryDecisionDto.cs @@ -0,0 +1,23 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.SharedKernel.Common.Enums.Playback; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback; + +/// +/// Data transfer object for the decision of how the audio of a track is delivered to a player: as the original file, as the same codec repackaged, or re-encoded. +/// +/// The way the audio is delivered. +/// The container of the delivered audio, which is the stored container of the track for a direct play. +/// The codec of the delivered audio, which is the stored codec of the track for a direct play. +/// The shape the delivered audio is addressed and seeked by. +/// The duration of each segment of the delivered audio, in seconds, or zero when the shape is not time addressed. +[DebuggerDisplay("Mode: {Mode} Container: {Container} Codec: {Codec} Shape: {Shape}")] +public sealed record PlaybackDeliveryDecisionDto( + PlaybackDeliveryMode Mode, + string Container, + string Codec, + PlaybackDeliveryShape Shape, + int SegmentDurationSeconds +); diff --git a/src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackDeliveryHandleDto.cs b/src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackDeliveryHandleDto.cs new file mode 100644 index 00000000..5ba7674d --- /dev/null +++ b/src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackDeliveryHandleDto.cs @@ -0,0 +1,25 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.SharedKernel.Common.Enums.Playback; +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback; + +/// +/// Data transfer object for the delivery a playback manifest issued to a user. It composes the exact normalization request the delivery declares, +/// so a new production input is added in one place and can never drift between the cache identity and the handle. +/// +/// The complete normalization request the delivery declares, including its user, track, decision, quality and source identity. +/// The shape the delivered audio is addressed by, which must be time addressed segments for a segment route. +/// The Id of the library the track belongs to, so the segment route can scope the delivery without querying it again. +/// The Id of the album the track belongs to, so the segment route can scope the delivery without querying it again. +/// The Id of the artist that owns the album, so the segment route can scope the delivery without querying it again. +[DebuggerDisplay("TrackId: {Request.TrackId} Mode: {Request.Mode} Container: {Request.Container} Codec: {Request.Codec}")] +public sealed record PlaybackDeliveryHandleDto( + NormalizedTrackRequestDto Request, + PlaybackDeliveryShape Shape, + Guid LibraryId, + Guid AlbumId, + Guid ArtistId +); diff --git a/src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackSourceFormatDto.cs b/src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackSourceFormatDto.cs new file mode 100644 index 00000000..2c3810ec --- /dev/null +++ b/src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackSourceFormatDto.cs @@ -0,0 +1,16 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback; + +/// +/// Data transfer object for the stored format of a track's audio, that a playback delivery decision is made on. +/// +/// The container of the audio file of the track, for example MP3, FLAC, OGG, MP4 or WAV. +/// The codec of the audio of the track, as reported by the probe, for example AAC, FLAC, Opus or PCM. +[DebuggerDisplay("Container: {Container} Codec: {Codec}")] +public sealed record PlaybackSourceFormatDto( + string? Container, + string? Codec +); diff --git a/src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/ShuffleTrackRowDto.cs b/src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/ShuffleTrackRowDto.cs new file mode 100644 index 00000000..941e5ec0 --- /dev/null +++ b/src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/ShuffleTrackRowDto.cs @@ -0,0 +1,25 @@ +#region ========================================================================= USING ===================================================================================== +using System; +#endregion + +namespace Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; + +/// +/// Read model of a track returned by a randomized shuffle query, carrying everything the client needs to queue and play it. +/// +/// The Id of the track. +/// The title of the track. +/// The duration of the track in seconds. +/// The Id of the album the track belongs to. +/// The title of the album the track belongs to. +/// The Id of the artist the album belongs to. +/// The path of the cover of the album, if available. +public sealed record ShuffleTrackRowDto( + Guid TrackId, + string Title, + int DurationInSeconds, + Guid AlbumId, + string AlbumTitle, + Guid ArtistId, + string? CoverPath +); diff --git a/src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackAccessSummaryDto.cs b/src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackAccessSummaryDto.cs new file mode 100644 index 00000000..50968d0c --- /dev/null +++ b/src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackAccessSummaryDto.cs @@ -0,0 +1,18 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Collections.Generic; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; + +/// +/// Data transfer object for the access information of a set of existing tracks. +/// +/// The number of distinct requested tracks that exist. +/// The distinct Ids of the media libraries that contain those tracks. +[DebuggerDisplay("TrackCount: {TrackCount}; Libraries: {LibraryIds.Count}")] +public sealed record TrackAccessSummaryDto( + int TrackCount, + IReadOnlyList LibraryIds +); diff --git a/src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackLiteRow.cs b/src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackLiteRow.cs index 33275f1a..6107f315 100644 --- a/src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackLiteRow.cs +++ b/src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackLiteRow.cs @@ -7,30 +7,15 @@ namespace Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.T /// /// Lightweight read model of a track, containing only the fields needed to display the track in a list. /// -public sealed record TrackLiteRow -{ - /// - /// Gets the Id of the track. - /// - public required Guid Id { get; init; } - - /// - /// Gets the title of the track. - /// - public required string Title { get; init; } - - /// - /// Gets the number of the track on its disc. - /// - public int TrackNumber { get; init; } - - /// - /// Gets the number of the disc the track belongs to, if applicable. - /// - public int? DiscNumber { get; init; } - - /// - /// Gets the duration of the track in seconds. - /// - public int DurationInSeconds { get; init; } -} +/// The Id of the track. +/// The title of the track. +/// The number of the track on its disc. +/// The number of the disc the track belongs to, if applicable. +/// The duration of the track in seconds. +public sealed record TrackLiteRow( + Guid Id, + string Title, + int TrackNumber, + int? DiscNumber, + int DurationInSeconds +); diff --git a/src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackPlaybackManifestDto.cs b/src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackPlaybackManifestDto.cs new file mode 100644 index 00000000..c9059377 --- /dev/null +++ b/src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackPlaybackManifestDto.cs @@ -0,0 +1,36 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; + +/// +/// Data transfer object for the stored probe result of a track, containing only the fields a playback manifest is built from. +/// +/// The file system path of the stored audio file of the track, used to bind a normalized delivery to the file version it was declared for. +/// The container of the audio file of the track, for example MP3, FLAC, OGG, AAC, MP4 or WAV, if applicable. +/// The audio codec used by the audio file of the track, if applicable. +/// The duration of the audio of the track in seconds. +/// The sample rate of the audio of the track in Hz. +/// The number of audio channels of the track. +/// The bit depth of the audio of the track, if applicable. +/// The bitrate of the audio of the track, in kbps, if applicable. +/// The ReplayGain track gain of the track, in decibels, if applicable. +/// The ReplayGain track peak of the track, if applicable. +/// The ReplayGain album gain of the track, in decibels, if applicable. +/// The ReplayGain album peak of the track, if applicable. +[DebuggerDisplay("Container: {Container} Codec: {AudioCodec}")] +public sealed record TrackPlaybackManifestDto( + string Path, + string? Container, + string? AudioCodec, + int DurationInSeconds, + int SampleRate, + int Channels, + int? BitDepth, + int? Bitrate, + decimal? ReplayGainTrackGain, + decimal? ReplayGainTrackPeak, + decimal? ReplayGainAlbumGain, + decimal? ReplayGainAlbumPeak +); diff --git a/src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackStreamDto.cs b/src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackStreamDto.cs new file mode 100644 index 00000000..bef2ea79 --- /dev/null +++ b/src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackStreamDto.cs @@ -0,0 +1,33 @@ +#region ========================================================================= USING ===================================================================================== +using System; +#endregion + +namespace Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; + +/// +/// Data transfer object for a track, containing the data needed to stream, or to describe the streaming of, its audio file. +/// +/// The file system path of the track. +/// The Id of the media library the track belongs to. +/// The Id of the album the track belongs to. +/// The Id of the artist that owns the album the track belongs to. +/// The container of the audio file of the track, for example MP3, FLAC, OGG, AAC, MP4 or WAV, if applicable. +/// The audio codec used by the audio file of the track, if applicable. +/// The duration of the audio of the track in seconds. +/// The sample rate of the audio of the track in Hz. +/// The number of audio channels of the track. +/// The bit depth of the audio of the track, if applicable. +/// The bitrate of the audio of the track, in kbps, if applicable. +public sealed record TrackStreamDto( + string Path, + Guid LibraryId, + Guid AlbumId, + Guid ArtistId, + string? Container, + string? AudioCodec, + int DurationInSeconds, + int SampleRate, + int Channels, + int? BitDepth, + int? Bitrate +); diff --git a/src/Lumina.Application/Common/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/BookLiteRow.cs b/src/Lumina.Application/Common/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/BookLiteRow.cs index 9a2e1b96..8e0966da 100644 --- a/src/Lumina.Application/Common/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/BookLiteRow.cs +++ b/src/Lumina.Application/Common/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/BookLiteRow.cs @@ -7,25 +7,13 @@ namespace Lumina.Application.Common.DTO.MediaLibrary.WrittenContentLibrary.BookL /// /// Lightweight read model of a book, containing only the fields needed to display the book in a card-based grid or a list. /// -public sealed record BookLiteRow -{ - /// - /// Gets the Id of the book. - /// - public required Guid Id { get; init; } - - /// - /// Gets the title of the book. - /// - public required string Title { get; init; } - - /// - /// Gets the release year of the book (re-release year, if available, or original release year), if known. - /// - public int? ReleaseYear { get; init; } - - /// - /// Gets the path of the image representing the cover of the book, if available. - /// - public string? CoverPath { get; init; } -} +/// The Id of the book. +/// The title of the book. +/// The release year of the book (re-release year, if available, or original release year), if known. +/// The path of the image representing the cover of the book, if available. +public sealed record BookLiteRow( + Guid Id, + string Title, + int? ReleaseYear, + string? CoverPath +); diff --git a/src/Lumina.Application/Common/DTO/Playlists/PlaylistBulkAddResultDto.cs b/src/Lumina.Application/Common/DTO/Playlists/PlaylistBulkAddResultDto.cs new file mode 100644 index 00000000..e2c5893f --- /dev/null +++ b/src/Lumina.Application/Common/DTO/Playlists/PlaylistBulkAddResultDto.cs @@ -0,0 +1,16 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Common.DTO.Playlists; + +/// +/// Data transfer object for the result of appending entries to a playlist in one bulk operation. +/// +/// The sparse order key of the first appended entry. +/// The number of entries appended. +[DebuggerDisplay("FirstPosition: {FirstPosition}; AddedCount: {AddedCount}")] +public sealed record PlaylistBulkAddResultDto( + long FirstPosition, + int AddedCount +); diff --git a/src/Lumina.Application/Common/DTO/Playlists/PlaylistDetailsDto.cs b/src/Lumina.Application/Common/DTO/Playlists/PlaylistDetailsDto.cs new file mode 100644 index 00000000..5661bbdc --- /dev/null +++ b/src/Lumina.Application/Common/DTO/Playlists/PlaylistDetailsDto.cs @@ -0,0 +1,18 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Playlists; +using Lumina.Application.Common.DTO.Pagination; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Common.DTO.Playlists; + +/// +/// Data transfer object for a stored playlist together with a page of its entries and their display data. +/// +/// The stored playlist. +/// The requested page of entries. +[DebuggerDisplay("PlaylistId: {Playlist.Id}; Name: {Playlist.Name}; Entries: {Entries.Count}")] +public sealed record PlaylistDetailsDto( + PlaylistEntity Playlist, + PaginatedResultDto Entries +); diff --git a/src/Lumina.Application/Common/DTO/Playlists/PlaylistEntryDisplayDto.cs b/src/Lumina.Application/Common/DTO/Playlists/PlaylistEntryDisplayDto.cs new file mode 100644 index 00000000..b9cea7a7 --- /dev/null +++ b/src/Lumina.Application/Common/DTO/Playlists/PlaylistEntryDisplayDto.cs @@ -0,0 +1,31 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Common.DTO.Playlists; + +/// +/// Data transfer object for the display data of the media item referenced by a playlist entry, together with its collection and creator. +/// +/// The Id of the track. +/// The title of the track. +/// The duration of the track in seconds. +/// The Id of the media library that contains the track. +/// The Id of the album that contains the track. +/// The title of the album that contains the track. +/// The Id of the artist that produced the track. +/// The name of the artist that produced the track. +/// The path of the cover art of the album, if available. +[DebuggerDisplay("TrackId: {TrackId}; TrackTitle: {TrackTitle}")] +public sealed record PlaylistEntryDisplayDto( + Guid TrackId, + string TrackTitle, + int DurationInSeconds, + Guid LibraryId, + Guid AlbumId, + string AlbumTitle, + Guid ArtistId, + string ArtistName, + string? CoverPath +); diff --git a/src/Lumina.Application/Common/DTO/Playlists/PlaylistEntryDto.cs b/src/Lumina.Application/Common/DTO/Playlists/PlaylistEntryDto.cs new file mode 100644 index 00000000..4ebc9410 --- /dev/null +++ b/src/Lumina.Application/Common/DTO/Playlists/PlaylistEntryDto.cs @@ -0,0 +1,19 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Playlists; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Common.DTO.Playlists; + +/// +/// Data transfer object for a stored playlist entry together with the display data of the media item it references and its dense display position. +/// +/// The stored entry. +/// The display data of the referenced media item, or when it no longer exists. +/// The dense zero based position shown to the client. +[DebuggerDisplay("EntryId: {Entry.Id}; MediaItemId: {Entry.MediaItemId}; Position: {DisplayPosition}")] +public sealed record PlaylistEntryDto( + PlaylistEntryEntity Entry, + PlaylistEntryDisplayDto? Display, + int DisplayPosition +); diff --git a/src/Lumina.Application/Common/DTO/Playlists/PlaylistSummaryDto.cs b/src/Lumina.Application/Common/DTO/Playlists/PlaylistSummaryDto.cs new file mode 100644 index 00000000..f5eaa70c --- /dev/null +++ b/src/Lumina.Application/Common/DTO/Playlists/PlaylistSummaryDto.cs @@ -0,0 +1,28 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.SharedKernel.Common.Enums.Playlists; +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Common.DTO.Playlists; + +/// +/// Data transfer object for a playlist in a list, without its entries. +/// +/// The Id of the playlist. +/// The name of the playlist. +/// The description of the playlist, if applicable. +/// The kind of media the playlist holds. +/// The number of entries of the playlist. +/// The date and time when the playlist was created. +/// The date and time when the playlist was last updated, if applicable. +[DebuggerDisplay("Id: {Id}; Name: {Name}; EntryCount: {EntryCount}")] +public sealed record PlaylistSummaryDto( + Guid Id, + string Name, + string? Description, + PlaylistType Type, + int EntryCount, + DateTime CreatedOnUtc, + DateTime? UpdatedOnUtc +); diff --git a/src/Lumina.Application/Common/DataAccess/Entities/Common/ISharedReferenceEntity.cs b/src/Lumina.Application/Common/DataAccess/Entities/Common/ISharedReferenceEntity.cs index 99d3b4b3..847c1beb 100644 --- a/src/Lumina.Application/Common/DataAccess/Entities/Common/ISharedReferenceEntity.cs +++ b/src/Lumina.Application/Common/DataAccess/Entities/Common/ISharedReferenceEntity.cs @@ -1,12 +1,12 @@ namespace Lumina.Application.Common.DataAccess.Entities.Common; /// -/// Interface for a shared reference entity, whose identity is its name and whose rows are shared across the whole storage medium instead of being owned by a single parent. +/// Interface for a shared reference entity, whose identity is its normalized name and whose rows are shared across the whole storage medium instead of being owned by a single parent. /// public interface ISharedReferenceEntity { /// - /// Gets the name that identifies the shared reference. + /// Gets the name that identifies the shared reference, stored in lowercase and culture-invariant form. /// string? Name { get; } } diff --git a/src/Lumina.Application/Common/DataAccess/Entities/Favorites/FavoriteEntity.cs b/src/Lumina.Application/Common/DataAccess/Entities/Favorites/FavoriteEntity.cs new file mode 100644 index 00000000..a529eff0 --- /dev/null +++ b/src/Lumina.Application/Common/DataAccess/Entities/Favorites/FavoriteEntity.cs @@ -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; + +/// +/// Repository entity for a favorite - the marker of a user on a media item of any media kind. +/// +/// +/// 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. +/// +[DebuggerDisplay("Id: {Id}; MediaKind: {MediaKind}; MediaItemId: {MediaItemId}")] +public class FavoriteEntity : IStorageEntity, IAuditableEntity +{ + /// + /// Gets the Id of the favorite. + /// + public required Guid Id { get; init; } + + /// + /// Gets or sets the Id of the user that owns the favorite. + /// + public required Guid UserId { get; set; } + + /// + /// Gets or sets the kind of the favorited media item. + /// + public required FavoriteMediaKind MediaKind { get; set; } + + /// + /// Gets or sets the Id of the favorited media item. + /// + public required Guid MediaItemId { get; set; } + + /// + /// Gets or sets the time and date when the entity was added. + /// + public required DateTime CreatedOnUtc { get; set; } + + /// + /// Gets or sets the Id of the user that created the entity. + /// + public required Guid CreatedBy { get; set; } + + /// + /// Gets or sets the optional time and date when the entity was updated. + /// + public DateTime? UpdatedOnUtc { get; set; } + + /// + /// Gets or sets the optional Id of the user that updated the entity. + /// + public required Guid? UpdatedBy { get; set; } +} diff --git a/src/Lumina.Application/Common/DataAccess/Entities/MediaConsumption/MediaConsumptionRecordEntity.cs b/src/Lumina.Application/Common/DataAccess/Entities/MediaConsumption/MediaConsumptionRecordEntity.cs new file mode 100644 index 00000000..a1ab167b --- /dev/null +++ b/src/Lumina.Application/Common/DataAccess/Entities/MediaConsumption/MediaConsumptionRecordEntity.cs @@ -0,0 +1,118 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Common; +using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Common.DataAccess.Entities.MediaConsumption; + +/// +/// Repository entity for a media consumption session. +/// +[DebuggerDisplay("Id: {Id}; MediaKind: {MediaKind}; Status: {Status}")] +public class MediaConsumptionRecordEntity : IStorageEntity, IAuditableEntity +{ + /// + /// Gets the Id of the consumption record. + /// + public required Guid Id { get; init; } + + /// + /// Gets or sets the Id of the user that started the consumption session. + /// + public required Guid UserId { get; set; } + + /// + /// Gets or sets the Id of the media library that contains the consumed media item. + /// + public required Guid LibraryId { get; set; } + + /// + /// Gets or sets the kind of media that was consumed. + /// + public required MediaKind MediaKind { get; set; } + + /// + /// Gets or sets the Id of the consumed media item. + /// + public required Guid MediaItemId { get; set; } + + /// + /// Gets or sets the state of the consumption session. + /// + public ConsumptionStatus Status { get; set; } + + /// + /// Gets or sets the date and time when the consumption session started. + /// + public required DateTime StartedOnUtc { get; set; } + + /// + /// Gets or sets the date and time when the consumption session last received activity. + /// + public DateTime LastActivityOnUtc { get; set; } + + /// + /// Gets or sets the date and time when the consumption session completed or stopped, if it has ended. + /// + public DateTime? EndedOnUtc { get; set; } + + /// + /// Gets or sets the active duration consumed by the session, in milliseconds. It is stored as a whole number of milliseconds so that the + /// stored value is independent of the persistence medium's support for time values. + /// + public long ConsumedDurationMilliseconds { get; set; } + + /// + /// Gets or sets the kind of representation used by the last known position, if the session has a known position. + /// + public MediaPositionKind? LastPositionKind { get; set; } + + /// + /// Gets or sets the last known position within the media item, in milliseconds, when the position is a time offset. + /// + public long? LastPositionTimeOffsetMilliseconds { get; set; } + + /// + /// Gets or sets the last known opaque locator within the media item, when the position is not a time offset. + /// + public string? LastPositionLocation { get; set; } + + /// + /// Gets or sets the latest reported progress fraction of the media item. + /// + public double LastProgressFraction { get; set; } + + /// + /// Gets or sets the number of consecutive pages read in the consumption session. + /// + public int ConsecutivePagesRead { get; set; } + + /// + /// Gets or sets the version of the stored row. It is used as an optimistic concurrency token, so that a report that read the record before + /// another report changed it can never overwrite the newer state. + /// + public long Version { get; set; } + + /// + /// Gets or sets the time and date when the entity was added. + /// + public required DateTime CreatedOnUtc { get; set; } + + /// + /// Gets or sets the Id of the user that created the entity. + /// + public required Guid CreatedBy { get; set; } + + /// + /// Gets or sets the optional time and date when the entity was updated. + /// + public DateTime? UpdatedOnUtc { get; set; } + + /// + /// Gets or sets the optional Id of the user that updated the entity. + /// + public required Guid? UpdatedBy { get; set; } +} diff --git a/src/Lumina.Application/Common/DataAccess/Entities/MediaConsumption/MediaResumePointEntity.cs b/src/Lumina.Application/Common/DataAccess/Entities/MediaConsumption/MediaResumePointEntity.cs new file mode 100644 index 00000000..b0f03f25 --- /dev/null +++ b/src/Lumina.Application/Common/DataAccess/Entities/MediaConsumption/MediaResumePointEntity.cs @@ -0,0 +1,92 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Common; +using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Common.DataAccess.Entities.MediaConsumption; + +/// +/// Repository entity for the point at which a user can resume consuming a media item. +/// +[DebuggerDisplay("Id: {Id}; MediaKind: {MediaKind}; MediaItemId: {MediaItemId}")] +public class MediaResumePointEntity : IStorageEntity, IAuditableEntity +{ + /// + /// Gets the Id of the resume point. + /// + public required Guid Id { get; init; } + + /// + /// Gets or sets the Id of the user that owns the resume point. + /// + public required Guid UserId { get; set; } + + /// + /// Gets or sets the Id of the media library that contains the media item. + /// + public required Guid LibraryId { get; set; } + + /// + /// Gets or sets the kind of media that is resumed. + /// + public required MediaKind MediaKind { get; set; } + + /// + /// Gets or sets the Id of the media item to resume. + /// + public required Guid MediaItemId { get; set; } + + /// + /// Gets the kind of representation used by the position at which the media item can be resumed. + /// + public required MediaPositionKind LastPositionKind { get; init; } + + /// + /// Gets or sets the position within the media item, in milliseconds, when the position is a time offset. + /// + public long? LastPositionTimeOffsetMilliseconds { get; set; } + + /// + /// Gets or sets the opaque locator within the media item, when the position is not a time offset. + /// + public string? LastPositionLocation { get; set; } + + /// + /// Gets or sets the progress fraction at which the media item can be resumed. + /// + public double LastProgressFraction { get; set; } + + /// + /// Gets or sets the date and time when the media item was last consumed. + /// + public DateTime LastConsumedOnUtc { get; set; } + + /// + /// Gets or sets the version of the stored row. It is used as an optimistic concurrency token, so that a report that read the resume point before + /// another report changed it can never overwrite the newer state. + /// + public long Version { get; set; } + + /// + /// Gets or sets the time and date when the entity was added. + /// + public required DateTime CreatedOnUtc { get; set; } + + /// + /// Gets or sets the Id of the user that created the entity. + /// + public required Guid CreatedBy { get; set; } + + /// + /// Gets or sets the optional time and date when the entity was updated. + /// + public DateTime? UpdatedOnUtc { get; set; } + + /// + /// Gets or sets the optional Id of the user that updated the entity. + /// + public required Guid? UpdatedBy { get; set; } +} diff --git a/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/MusicLibraryScanItemMetadataEntity.cs b/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/MusicLibraryScanItemMetadataEntity.cs index 8b943070..02661eae 100644 --- a/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/MusicLibraryScanItemMetadataEntity.cs +++ b/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/MusicLibraryScanItemMetadataEntity.cs @@ -94,6 +94,11 @@ public class MusicLibraryScanItemMetadataEntity : IStorageEntity /// public string? AudioCodec { get; set; } + /// + /// Gets or sets the container of the audio file, for example MP3, FLAC, OGG, AAC, MP4 or WAV, if applicable. + /// + public string? Container { get; set; } + /// /// Gets or sets the bitrate of the audio in kbps, if applicable. /// diff --git a/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/TrackEntity.cs b/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/TrackEntity.cs index 23a2794e..246685ca 100644 --- a/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/TrackEntity.cs +++ b/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/TrackEntity.cs @@ -141,6 +141,11 @@ public class TrackEntity : IStorageEntity, IAuditableEntity /// public string? AudioCodec { get; set; } + /// + /// Gets or sets the container of the audio file, for example MP3, FLAC, OGG, AAC, MP4 or WAV, if applicable. + /// + public string? Container { get; set; } + /// /// Gets or sets the bitrate of the audio in kbps, if applicable. /// diff --git a/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/Management/LibraryEntity.cs b/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/Management/LibraryEntity.cs index 993b48a4..1abed50d 100644 --- a/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/Management/LibraryEntity.cs +++ b/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/Management/LibraryEntity.cs @@ -80,6 +80,16 @@ public class LibraryEntity : IStorageEntity, IAuditableEntity /// public bool ShouldSkipUnchangedDirectoriesDuringScan { get; init; } + /// + /// Gets a value indicating whether the consumption progress of the media library items is tracked. + /// + public bool ShouldTrackConsumptionProgress { get; init; } + + /// + /// Gets the percentage of a media library item that must be consumed for its session to be considered completed, when progress tracking is enabled. + /// + public int? CompletionThresholdPercentage { get; init; } + /// /// Gets or sets the fingerprint of the metadata provider configuration of the media library, used to detect /// whether the configuration changed since the last scan, and thus whether the books need re-enrichment. diff --git a/src/Lumina.Application/Common/DataAccess/Entities/Playlists/PlaylistEntity.cs b/src/Lumina.Application/Common/DataAccess/Entities/Playlists/PlaylistEntity.cs new file mode 100644 index 00000000..7b9bcd53 --- /dev/null +++ b/src/Lumina.Application/Common/DataAccess/Entities/Playlists/PlaylistEntity.cs @@ -0,0 +1,80 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Common; +using Lumina.Domain.SharedKernel.Common.Enums.Playlists; +using System; +using System.Collections.Generic; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Common.DataAccess.Entities.Playlists; + +/// +/// Repository entity for a playlist. +/// +[DebuggerDisplay("Id: {Id}; Name: {Name}; Type: {Type}")] +public class PlaylistEntity : IStorageEntity, IAuditableEntity +{ + /// + /// Gets the Id of the playlist. + /// + public required Guid Id { get; init; } + + /// + /// Gets or sets the Id of the user that owns the playlist. + /// + public required Guid UserId { get; set; } + + /// + /// Gets or sets the name of the playlist. + /// + public required string Name { get; set; } + + /// + /// Gets or sets the description of the playlist, if applicable. + /// + public string? Description { get; set; } + + /// + /// Gets or sets the kind of media the playlist holds. + /// + public required PlaylistType Type { get; set; } + + /// + /// Gets or sets the ordered entries of the playlist. + /// + public List Entries { get; set; } = []; + + /// + /// Gets or sets the number of entries the playlist holds. + /// + /// + /// The count is maintained by the set-based entry operations in the same statement that appends or removes entries and updates the + /// playlist, so reading a window of a very large playlist never has to count its entries. + /// + public int EntryCount { get; set; } + + /// + /// Gets or sets the concurrency token of the playlist. + /// + public long Version { get; set; } + + /// + /// Gets or sets the time and date when the entity was added. + /// + public required DateTime CreatedOnUtc { get; set; } + + /// + /// Gets or sets the Id of the user that created the entity. + /// + public required Guid CreatedBy { get; set; } + + /// + /// Gets or sets the optional time and date when the entity was updated. + /// + public DateTime? UpdatedOnUtc { get; set; } + + /// + /// Gets or sets the optional Id of the user that updated the entity. + /// + public required Guid? UpdatedBy { get; set; } +} diff --git a/src/Lumina.Application/Common/DataAccess/Entities/Playlists/PlaylistEntryEntity.cs b/src/Lumina.Application/Common/DataAccess/Entities/Playlists/PlaylistEntryEntity.cs new file mode 100644 index 00000000..787c4375 --- /dev/null +++ b/src/Lumina.Application/Common/DataAccess/Entities/Playlists/PlaylistEntryEntity.cs @@ -0,0 +1,64 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Common; +using Lumina.Domain.SharedKernel.Common.Enums.Playlists; +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Common.DataAccess.Entities.Playlists; + +/// +/// Repository entity for an ordered entry of a playlist. +/// +/// +/// The entry references a media item by its Id and by the kind of media item, without a foreign key, so a playlist survives the deletion +/// of the item it references and the entry can be shown to its owner so that it can be removed. +/// +[DebuggerDisplay("Id: {Id}; MediaItemId: {MediaItemId}; MediaItemType: {MediaItemType}; Position: {Position}")] +public class PlaylistEntryEntity : IStorageEntity, IAuditableEntity +{ + /// + /// Gets the Id of the entry. + /// + public required Guid Id { get; init; } + + /// + /// Gets or sets the Id of the playlist the entry belongs to. + /// + public required Guid PlaylistId { get; set; } + + /// + /// Gets or sets the Id of the media item referenced by the entry. + /// + public required Guid MediaItemId { get; set; } + + /// + /// Gets or sets the kind of media item referenced by the entry. + /// + public PlaylistMediaItemType MediaItemType { get; set; } + + /// + /// Gets or sets the sparse order key of the entry in the ordered entries of the playlist. + /// + public long Position { get; set; } + + /// + /// Gets or sets the time and date when the entry was added. + /// + public DateTime CreatedOnUtc { get; set; } + + /// + /// Gets or sets the Id of the user that created the entry. + /// + public Guid CreatedBy { get; set; } + + /// + /// Gets or sets the optional time and date when the entry was updated. + /// + public DateTime? UpdatedOnUtc { get; set; } + + /// + /// Gets or sets the optional Id of the user that updated the entry. + /// + public Guid? UpdatedBy { get; set; } +} diff --git a/src/Lumina.Application/Common/DataAccess/Entities/UsersManagement/UserSettingsEntity.cs b/src/Lumina.Application/Common/DataAccess/Entities/UsersManagement/UserSettingsEntity.cs index 877e541b..b472e933 100644 --- a/src/Lumina.Application/Common/DataAccess/Entities/UsersManagement/UserSettingsEntity.cs +++ b/src/Lumina.Application/Common/DataAccess/Entities/UsersManagement/UserSettingsEntity.cs @@ -1,5 +1,6 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.DataAccess.Entities.Common; +using Lumina.Domain.SharedKernel.Common.Enums.Playback; using System; using System.Diagnostics; #endregion @@ -65,6 +66,86 @@ public class UserSettingsEntity : IStorageEntity, IAuditableEntity /// public bool ShouldPreserveBookStyles { get; set; } + /// + /// Gets or sets whether the player keeps downloading a track while playback is paused, or not, up to the entire file. + /// + public bool ShouldKeepDownloadingWhilePaused { get; set; } = true; + + /// + /// Gets or sets whether the player continues playback at the end of an album or artist, or not. + /// + public bool ShouldAutoplay { get; set; } = true; + + /// + /// Gets or sets whether the player transitions between consecutive tracks without a gap, or not. + /// + public bool IsGaplessPlaybackEnabled { get; set; } = true; + + /// + /// Gets or sets the way ReplayGain normalization is applied to the tracks the user plays. + /// + public ReplayGainMode ReplayGainMode { get; set; } + + /// + /// Gets or sets the quality cap applied to the audio the server normalizes for the user. + /// + public PlaybackStreamingQuality StreamingQuality { get; set; } + + /// + /// Gets or sets the direction in which each channel of the VU meter of the audio player grows. + /// + public VuMeterOrientation VuMeterOrientation { get; set; } + + /// + /// Gets or sets the number of segments each channel of the VU meter is divided into. + /// + public int VuMeterSegmentCount { get; set; } = 12; + + /// + /// Gets or sets the gap, in pixels, between the segments and the channels of the VU meter. + /// + public int VuMeterSegmentGap { get; set; } = 1; + + /// + /// Gets or sets the level, between 0 and 1, above which a segment of the VU meter is drawn with its medium state. + /// + public double VuMeterMediumThreshold { get; set; } = 0.6; + + /// + /// Gets or sets the level, between 0 and 1, above which a segment of the VU meter is drawn with its high state. + /// + public double VuMeterHighThreshold { get; set; } = 0.8; + + /// + /// Gets or sets whether the VU meter holds the peak level of each channel after it falls, or not. + /// + public bool VuMeterShowPeak { get; set; } = true; + + /// + /// Gets or sets the time, in milliseconds, a peak of the VU meter is held before it starts falling. + /// + public int VuMeterPeakHoldDurationInMilliseconds { get; set; } = 650; + + /// + /// Gets or sets the number of level units the display of the VU meter falls per second when the input level drops. + /// + public double VuMeterReleasePerSecond { get; set; } = 3.0; + + /// + /// Gets or sets the number of level units the peak of the VU meter falls per second after its hold time elapsed. + /// + public double VuMeterPeakReleasePerSecond { get; set; } = 0.65; + + /// + /// Gets or sets the last volume the player reported for the user. Written automatically by the player, and not part of the settings the user edits. + /// + public double Volume { get; set; } = 1.0; + + /// + /// Gets or sets the last mute state the player reported for the user. Written automatically by the player, and not part of the settings the user edits. + /// + public bool IsMuted { get; set; } + /// /// Gets or sets the time and date when the entity was added. /// diff --git a/src/Lumina.Application/Common/DataAccess/Repositories/BookLibrary/IBookRepository.cs b/src/Lumina.Application/Common/DataAccess/Repositories/BookLibrary/IBookRepository.cs index d9516d0b..48192b99 100644 --- a/src/Lumina.Application/Common/DataAccess/Repositories/BookLibrary/IBookRepository.cs +++ b/src/Lumina.Application/Common/DataAccess/Repositories/BookLibrary/IBookRepository.cs @@ -124,6 +124,15 @@ public interface IBookRepository : IRepository, /// An containing either the display names of the authors of the books, keyed by book Id, or an error. Task>> GetAuthorsDisplayNamesByBookIdsAsync(IReadOnlyCollection bookIds, CancellationToken cancellationToken); + /// + /// Gets the books identified by , optionally together with their navigation properties. + /// + /// The Ids of the books to get. + /// Whether the navigation properties of the books should be loaded together with the books themselves. + /// Cancellation token that can be used to stop the execution. + /// An containing either the existing books, or an error. + Task>> GetByIdsAsync(IReadOnlyCollection bookIds, bool shouldIncludeNavigationProperties, CancellationToken cancellationToken); + /// /// Deletes all the books of the media library identified by , together with their artwork and their related data. /// diff --git a/src/Lumina.Application/Common/DataAccess/Repositories/Favorites/IFavoriteRepository.cs b/src/Lumina.Application/Common/DataAccess/Repositories/Favorites/IFavoriteRepository.cs new file mode 100644 index 00000000..966cf241 --- /dev/null +++ b/src/Lumina.Application/Common/DataAccess/Repositories/Favorites/IFavoriteRepository.cs @@ -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; + +/// +/// Interface for the repository for favorites. +/// +public interface IFavoriteRepository : IRepository, + IInsertRepositoryAction, + IDeleteByIdRepositoryAction +{ + /// + /// Gets the favorite of the user identified by on the media item identified by and , if it exists. + /// + /// The Id of the user the favorite must belong to. + /// The kind of the favorited media item. + /// The Id of the favorited media item. + /// Whether the retrieved entity should be tracked by the persistence medium, so that changes to it can be saved. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either the favorite, when the user has not favorited the media item, or an error. + /// + Task> GetByMediaItemIdForUserAsync(Guid userId, FavoriteMediaKind mediaKind, Guid mediaItemId, bool shouldTrackEntities = true, CancellationToken cancellationToken = default); + + /// + /// Gets the Id of the media library that contains the media item identified by and , if the media item exists. + /// + /// The kind of the media item. + /// The Id of the media item. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either the Id of the library that contains the media item, when the + /// media item does not exist or its kind has no catalogued library yet, or an error. + /// + Task> GetMediaItemLibraryIdAsync(FavoriteMediaKind mediaKind, Guid mediaItemId, CancellationToken cancellationToken); + + /// + /// Gets the paginated favorites of the user identified by , together with the display data of the media items they reference, + /// or all the matching favorites when the pagination data is . + /// + /// The Id of the user whose favorites are retrieved. + /// The kind of media item to restrict the favorites to, or for every kind. + /// The pagination data that includes the current page and the number of items per page to retrieve. If , all matching favorites are returned. + /// Whether the retrieved entities should be tracked by the persistence medium, so that changes to them can be saved. Pass for read-only scenarios, to avoid the tracking overhead. + /// Cancellation token that can be used to stop the execution. + /// An containing either a , or an error. + Task>> GetAllForUserAsync(Guid userId, FavoriteMediaKind? mediaKind, PaginationDataDto? paginationData = null, bool shouldTrackEntities = false, CancellationToken cancellationToken = default); + + /// + /// Gets the Ids, among , of the media items of kind that the user identified by has favorited. + /// + /// The Id of the user whose favorites are checked. + /// The kind of the media items. + /// The Ids of the media items to check. + /// Cancellation token that can be used to stop the execution. + /// An containing either the subset of the Ids that are favorites of the user, or an error. + Task>> GetFavoritedMediaItemIdsForUserAsync(Guid userId, FavoriteMediaKind mediaKind, IReadOnlyCollection mediaItemIds, CancellationToken cancellationToken); +} diff --git a/src/Lumina.Application/Common/DataAccess/Repositories/MediaConsumption/IConsumptionStatisticsRepository.cs b/src/Lumina.Application/Common/DataAccess/Repositories/MediaConsumption/IConsumptionStatisticsRepository.cs new file mode 100644 index 00000000..5f84730b --- /dev/null +++ b/src/Lumina.Application/Common/DataAccess/Repositories/MediaConsumption/IConsumptionStatisticsRepository.cs @@ -0,0 +1,42 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaConsumption; +using Lumina.Application.Common.DataAccess.Repositories.Common.Base; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Application.Common.DataAccess.Repositories.MediaConsumption; + +/// +/// Interface for the repository for the consumption records used to build consumption statistics. +/// +public interface IConsumptionStatisticsRepository : IRepository +{ + /// + /// Gets the consumption records of the user identified by , optionally limited to a media library, a media kind, and a date + /// range. + /// + /// The Id of the user whose consumption records are retrieved. + /// The Id of the media library to restrict the records to, or for every library. + /// The kind of media to restrict the records to, or for every kind. + /// The start of the date range, or when the range has no start. + /// The end of the date range, or when the range has no end. + /// Cancellation token that can be used to stop the execution. + /// An containing either the consumption records of the user, or an error. + Task>> GetForUserAsync(Guid userId, Guid? libraryId, MediaKind? mediaKind, DateTime? fromUtc, DateTime? toUtc, CancellationToken cancellationToken); + + /// + /// Gets the consumption records of every user, optionally limited to a media library, a media kind, and a date range. + /// + /// The Id of the media library to restrict the records to, or for every library. + /// The kind of media to restrict the records to, or for every kind. + /// The start of the date range, or when the range has no start. + /// The end of the date range, or when the range has no end. + /// Cancellation token that can be used to stop the execution. + /// An containing either the consumption records of every user, or an error. + Task>> GetForAllUsersAsync(Guid? libraryId, MediaKind? mediaKind, DateTime? fromUtc, DateTime? toUtc, CancellationToken cancellationToken); +} diff --git a/src/Lumina.Application/Common/DataAccess/Repositories/MediaConsumption/IMediaConsumptionRecordRepository.cs b/src/Lumina.Application/Common/DataAccess/Repositories/MediaConsumption/IMediaConsumptionRecordRepository.cs new file mode 100644 index 00000000..ddbcad74 --- /dev/null +++ b/src/Lumina.Application/Common/DataAccess/Repositories/MediaConsumption/IMediaConsumptionRecordRepository.cs @@ -0,0 +1,71 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaConsumption; +using Lumina.Application.Common.DataAccess.Repositories.Common.Actions; +using Lumina.Application.Common.DataAccess.Repositories.Common.Base; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using System; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Application.Common.DataAccess.Repositories.MediaConsumption; + +/// +/// Interface for the repository for media consumption records. +/// +public interface IMediaConsumptionRecordRepository : IRepository, + IInsertRepositoryAction +{ + /// + /// Gets the consumption record identified by when it belongs to the user identified by , if it exists. + /// + /// The Id of the consumption record to get. + /// The Id of the user the consumption record must belong to. + /// Whether the retrieved record should be tracked by the persistence medium, so that changes to it can be saved. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either the consumption record identified by and owned by + /// , when no such record exists, or an error. + /// + Task> GetByIdForUserAsync(Guid id, Guid userId, bool shouldTrackEntities = true, CancellationToken cancellationToken = default); + + /// + /// Updates the consumption record of the user identified by , when the record belongs to that user and still holds the + /// version it was read with. + /// + /// The consumption record whose editable values are applied to the stored record. Its owner must match . + /// The Id of the user the consumption record must belong to. It is authoritative for locating the stored record; the owner carried by is not used to select it. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful update, or an error. + Task> UpdateForUserAsync(MediaConsumptionRecordEntity data, Guid userId, CancellationToken cancellationToken); + + /// + /// Deletes the consumption record identified by when it belongs to the user identified by . A record + /// that does not exist is not an error. + /// + /// The Id of the consumption record to delete. + /// The Id of the user the consumption record must belong to. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful deletion, or an error. + Task> DeleteForUserAsync(Guid id, Guid userId, CancellationToken cancellationToken); + + /// + /// Deletes every consumption record of a media item of the user identified by . + /// + /// The Id of the user whose consumption records are deleted. + /// The kind of the consumed media item. + /// The Id of the consumed media item. + /// The Id of the media library that contains the media item. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful deletion, or an error. + Task> DeleteAllByMediaItemIdForUserAsync(Guid userId, MediaKind mediaKind, Guid mediaItemId, Guid libraryId, CancellationToken cancellationToken); + + /// + /// Deletes every consumption record of the user identified by . + /// + /// The Id of the user whose consumption records are deleted. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful deletion, or an error. + Task> DeleteAllForUserAsync(Guid userId, CancellationToken cancellationToken); +} diff --git a/src/Lumina.Application/Common/DataAccess/Repositories/MediaConsumption/IMediaResumePointRepository.cs b/src/Lumina.Application/Common/DataAccess/Repositories/MediaConsumption/IMediaResumePointRepository.cs new file mode 100644 index 00000000..2c25faf4 --- /dev/null +++ b/src/Lumina.Application/Common/DataAccess/Repositories/MediaConsumption/IMediaResumePointRepository.cs @@ -0,0 +1,70 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaConsumption; +using Lumina.Application.Common.DataAccess.Repositories.Common.Base; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using System; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Application.Common.DataAccess.Repositories.MediaConsumption; + +/// +/// Interface for the repository for media resume points. +/// +public interface IMediaResumePointRepository : IRepository +{ + /// + /// Gets the resume point of the user identified by for the media item identified by and + /// , if it exists. + /// + /// The Id of the user the resume point must belong to. + /// The kind of the media item to resume. + /// The Id of the media item to resume. + /// Whether the retrieved resume point should be tracked by the persistence medium, so that changes to it can be saved. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either the resume point of the user for the media item, when no such resume + /// point exists, or an error. + /// + Task> GetForUserAndMediaItemAsync(Guid userId, MediaKind mediaKind, Guid mediaItemId, bool shouldTrackEntities = true, CancellationToken cancellationToken = default); + + /// + /// Saves the resume point of the user identified by , inserting it when it does not exist and updating it otherwise. The + /// business key of the resume point, made of the user, the media kind, and the media item, is preserved. + /// + /// The resume point whose values are saved. Its owner must match . + /// The Id of the user the resume point must belong to. It is authoritative for locating the stored resume point and for the owner of a new one; the owner carried by is not used to select it. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful save, or an error. + Task> UpsertForUserAsync(MediaResumePointEntity data, Guid userId, CancellationToken cancellationToken); + + /// + /// Deletes the resume point of the user identified by for the media item identified by and + /// . A resume point that does not exist is not an error. + /// + /// The Id of the user the resume point must belong to. + /// The kind of the media item to resume. + /// The Id of the media item to resume. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful deletion, or an error. + Task> DeleteForUserAndMediaItemAsync(Guid userId, MediaKind mediaKind, Guid mediaItemId, CancellationToken cancellationToken); + + /// + /// Deletes every resume point of the user identified by . + /// + /// The Id of the user whose resume points are deleted. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful deletion, or an error. + Task> DeleteAllForUserAsync(Guid userId, CancellationToken cancellationToken); + + /// + /// Deletes every resume point of the user identified by in the media library identified by . + /// + /// The Id of the user whose resume points are deleted. + /// The Id of the media library whose resume points are deleted. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful deletion, or an error. + Task> DeleteAllForUserInLibraryAsync(Guid userId, Guid libraryId, CancellationToken cancellationToken); +} diff --git a/src/Lumina.Application/Common/DataAccess/Repositories/MusicLibrary/IMusicArtworkRepository.cs b/src/Lumina.Application/Common/DataAccess/Repositories/MusicLibrary/IMusicArtworkRepository.cs index dd5898c4..7e6b6e0b 100644 --- a/src/Lumina.Application/Common/DataAccess/Repositories/MusicLibrary/IMusicArtworkRepository.cs +++ b/src/Lumina.Application/Common/DataAccess/Repositories/MusicLibrary/IMusicArtworkRepository.cs @@ -27,6 +27,15 @@ public interface IMusicArtworkRepository : IRepository, /// An containing either a collection of , or an error. Task>> GetByOwnerAsync(MusicArtworkOwnerType ownerType, Guid ownerId, CancellationToken cancellationToken); + /// + /// Gets the pieces of artwork owned by the music library items of the provided identified by any of . + /// + /// The type of the music library items that own the artwork. + /// The Ids of the music library items that own the artwork. + /// Cancellation token that can be used to stop the execution. + /// An containing either the artwork of the existing owners, or an error. + Task>> GetByOwnersAsync(MusicArtworkOwnerType ownerType, IReadOnlyCollection ownerIds, CancellationToken cancellationToken); + /// /// Deletes all the pieces of artwork owned by the music library item of the provided identified by . /// diff --git a/src/Lumina.Application/Common/DataAccess/Repositories/MusicLibrary/ITrackRepository.cs b/src/Lumina.Application/Common/DataAccess/Repositories/MusicLibrary/ITrackRepository.cs index 72f1b185..ce7ebd7d 100644 --- a/src/Lumina.Application/Common/DataAccess/Repositories/MusicLibrary/ITrackRepository.cs +++ b/src/Lumina.Application/Common/DataAccess/Repositories/MusicLibrary/ITrackRepository.cs @@ -49,6 +49,19 @@ public interface ITrackRepository : IRepository, /// An containing either a paginated result of , or an error. Task>> GetTracksLiteByAlbumIdAsync(Guid albumId, PaginationDataDto? paginationData, CancellationToken cancellationToken); + /// + /// Gets a uniformly random selection of tracks of the library identified by , optionally scoped to + /// an artist or an album, excluding the tracks in . + /// + /// The Id of the library whose tracks are sampled. + /// The Id of the artist whose tracks are sampled, or for every artist of the library. + /// The Id of the album whose tracks are sampled, or for every album of the scope. + /// The tracks that must not be returned. + /// The maximum number of tracks to return. + /// Cancellation token that can be used to stop the execution. + /// An containing either a collection of , or an error. + Task>> GetShuffleTracksLiteAsync(Guid libraryId, Guid? artistId, Guid? albumId, IReadOnlyCollection excludedTrackIds, int count, CancellationToken cancellationToken); + /// /// Gets the track of the library identified by that is stored at the provided . /// @@ -58,6 +71,38 @@ public interface ITrackRepository : IRepository, /// An containing either the stored at the provided path, or an error. Task> GetByPathAsync(Guid libraryId, string path, CancellationToken cancellationToken); + /// + /// Gets the data needed to stream the audio file of the track identified by , when it belongs to the album identified by + /// and to the media library identified by , and that album belongs to the artist identified by + /// . + /// + /// The Id of the media library the track must belong to. + /// The Id of the album the track must belong to. + /// The Id of the artist that must own the album the track belongs to. + /// The Id of the track whose streaming data is retrieved. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either the of the track, when no track matches the + /// provided identifiers, or an error. + /// + Task> GetTrackStreamInfoAsync(Guid libraryId, Guid albumId, Guid artistId, Guid trackId, CancellationToken cancellationToken); + + /// + /// Gets the stored probe result needed to build the playback manifest of the track identified by , when it belongs to + /// the album identified by and to the media library identified by , and that album belongs + /// to the artist identified by . + /// + /// The Id of the media library the track must belong to. + /// The Id of the album the track must belong to. + /// The Id of the artist that must own the album the track belongs to. + /// The Id of the track whose playback manifest data is retrieved. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either the of the track, when no track + /// matches the provided identifiers, or an error. + /// + Task> GetPlaybackManifestInfoAsync(Guid libraryId, Guid albumId, Guid artistId, Guid trackId, CancellationToken cancellationToken); + /// /// Resets the enrichment state of the tracks stored at the provided in the media library identified by /// , together with their albums and artists, so that they are re-enriched, because their content changed since the last scan. @@ -84,4 +129,21 @@ public interface ITrackRepository : IRepository, /// Cancellation token that can be used to stop the execution. /// An representing either a successful operation, or an error. Task> ResetMetadataStatusForLibraryAsync(Guid libraryId, CancellationToken cancellationToken); + + /// + /// Gets the number of tracks in that exist, together with the distinct Ids of the libraries that contain them. + /// + /// The Ids of the tracks whose access information is retrieved. + /// Cancellation token that can be used to stop the execution. + /// An containing either the access summary of the existing tracks, or an error. + Task> GetAccessInfoByIdsAsync(IReadOnlyCollection trackIds, CancellationToken cancellationToken); + + /// + /// Gets the tracks identified by , optionally together with their navigation properties. + /// + /// The Ids of the tracks to get. + /// Whether the navigation properties of the tracks should be loaded together with the tracks themselves. + /// Cancellation token that can be used to stop the execution. + /// An containing either the existing tracks, or an error. + Task>> GetByIdsAsync(IReadOnlyCollection trackIds, bool shouldIncludeNavigationProperties, CancellationToken cancellationToken); } diff --git a/src/Lumina.Application/Common/DataAccess/Repositories/Playlists/IPlaylistRepository.cs b/src/Lumina.Application/Common/DataAccess/Repositories/Playlists/IPlaylistRepository.cs new file mode 100644 index 00000000..20e2401d --- /dev/null +++ b/src/Lumina.Application/Common/DataAccess/Repositories/Playlists/IPlaylistRepository.cs @@ -0,0 +1,131 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Playlists; +using Lumina.Application.Common.DataAccess.Repositories.Common.Actions; +using Lumina.Application.Common.DataAccess.Repositories.Common.Base; +using Lumina.Application.Common.DTO.Pagination; +using Lumina.Application.Common.DTO.Playlists; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.SharedKernel.Common.Enums.Playlists; +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Application.Common.DataAccess.Repositories.Playlists; + +/// +/// Interface for the repository for playlists. +/// +public interface IPlaylistRepository : IRepository, + IInsertRepositoryAction, + IUpdateRepositoryAction, + IDeleteByIdRepositoryAction +{ + /// + /// Gets the playlist identified by when it belongs to the user identified by , if it exists. + /// + /// The Id of the playlist to get. + /// The Id of the user the playlist must belong to. + /// Whether the entries of the playlist should be loaded together with the playlist itself. + /// Whether the retrieved entities should be tracked by the persistence medium, so that changes to them can be saved. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either the playlist identified by and owned by , + /// when no such playlist exists, or an error. + /// + Task> GetByIdForUserAsync(Guid id, Guid userId, bool shouldIncludeNavigationProperties = true, bool shouldTrackEntities = true, CancellationToken cancellationToken = default); + + /// + /// Gets the playlists of the user identified by , ordered by their most recent activity. + /// + /// The Id of the user whose playlists are retrieved. + /// Cancellation token that can be used to stop the execution. + /// An containing either the playlists of the user, or an error. + Task>> GetAllForUserAsync(Guid userId, CancellationToken cancellationToken); + + /// + /// Gets the playlist identified by together with a page of the display details of the media items its entries reference, + /// when the playlist belongs to the user identified by , or all the entries when the pagination data is . + /// + /// The Id of the playlist to get. + /// The Id of the user the playlist must belong to. + /// The pagination data that includes the current page and the number of items per page to retrieve. If , all matching entries are returned. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either the playlist details, when no such playlist exists, or an error. + /// + Task> GetDetailsForUserAsync(Guid id, Guid userId, PaginationDataDto? paginationData = null, CancellationToken cancellationToken = default); + + /// + /// Appends a batch of media items of one kind to the end of the ordered entries of a playlist of the user identified by + /// , using batched bulk inserts, and updates the activity time of the playlist in the same transaction. + /// + /// The Id of the playlist to append to. + /// The Id of the user the playlist must belong to. + /// The Ids of the media items to append, in order. Duplicates are kept. + /// The kind of media item referenced by every appended entry. + /// The Ids to assign to the appended entries, in the same order as , or to generate them. + /// The activity time to store on the playlist. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either the sparse order key of the first appended entry and the added count, or an error. + /// + Task> AddEntriesAsync(Guid playlistId, Guid userId, IReadOnlyList mediaItemIds, PlaylistMediaItemType mediaItemType, IReadOnlyList? entryIds, DateTime updatedOnUtc, CancellationToken cancellationToken); + + /// + /// Appends every media item of a library, an artist or an album to the end of the ordered entries of a playlist of the user identified by + /// , in catalogue order, without materializing the scope. + /// + /// The Id of the playlist to append to. + /// The Id of the user the playlist must belong to. + /// The Id of the library whose media items are appended. + /// The Id of the artist the scope is limited to, or for every artist of the library. + /// The Id of the album the scope is limited to, or for every album of the scope. + /// The kind of media item referenced by every appended entry. + /// The activity time to store on the playlist. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either the sparse order key of the first appended entry and the added count, or an error. + /// + Task> AddScopeEntriesAsync(Guid playlistId, Guid userId, Guid libraryId, Guid? artistId, Guid? albumId, PlaylistMediaItemType mediaItemType, DateTime updatedOnUtc, CancellationToken cancellationToken); + + /// + /// Moves one entry of a playlist of the user identified by to a new dense position by changing only its + /// sparse order key, and updates the activity time of the playlist in the same transaction. + /// + /// The Id of the playlist whose entry is moved. + /// The Id of the user the playlist must belong to. + /// The Id of the entry to move. + /// The new zero based position of the entry. + /// The activity time to store on the playlist. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful move, or an error. + Task> MoveEntryAsync(Guid playlistId, Guid userId, Guid entryId, int targetPosition, DateTime updatedOnUtc, CancellationToken cancellationToken); + + /// + /// Removes one entry of a playlist of the user identified by by deleting only that row, and updates the + /// activity time of the playlist in the same transaction. + /// + /// The Id of the playlist whose entry is removed. + /// The Id of the user the playlist must belong to. + /// The Id of the entry to remove. + /// The activity time to store on the playlist. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either zero, because sparse positions need no repositioning, or an error. + /// + Task> RemoveEntryAsync(Guid playlistId, Guid userId, Guid entryId, DateTime updatedOnUtc, CancellationToken cancellationToken); + + /// + /// Gets the entry that was just appended to a playlist of the user identified by , together with the display details of the track it references. + /// + /// The Id of the playlist the entry must belong to. + /// The Id of the user the playlist must belong to. + /// The Id of the appended entry to get. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either the entry details, when the entry does not exist in that playlist of the user, or an error. + /// + Task> GetAppendedEntryDetailsForUserAsync(Guid playlistId, Guid userId, Guid entryId, CancellationToken cancellationToken); +} diff --git a/src/Lumina.Application/Common/DataAccess/UoW/IUnitOfWork.cs b/src/Lumina.Application/Common/DataAccess/UoW/IUnitOfWork.cs index 0290d2a0..dd1cb2c6 100644 --- a/src/Lumina.Application/Common/DataAccess/UoW/IUnitOfWork.cs +++ b/src/Lumina.Application/Common/DataAccess/UoW/IUnitOfWork.cs @@ -1,9 +1,12 @@ #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.MediaConsumption; using Lumina.Application.Common.DataAccess.Repositories.MediaContributors; using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary; using Lumina.Application.Common.DataAccess.Repositories.MusicLibrary; +using Lumina.Application.Common.DataAccess.Repositories.Playlists; using Lumina.Application.Common.DataAccess.Repositories.Plugins; using Lumina.Application.Common.DataAccess.Repositories.Scheduling; using Lumina.Application.Common.DataAccess.Repositories.Themes; @@ -150,6 +153,31 @@ public interface IUnitOfWork /// IUserSettingsRepository UserSettingsRepository { get; } + /// + /// Gets the playlist repository. + /// + IPlaylistRepository PlaylistRepository { get; } + + /// + /// Gets the favorite repository. + /// + IFavoriteRepository FavoriteRepository { get; } + + /// + /// Gets the media consumption record repository. + /// + IMediaConsumptionRecordRepository MediaConsumptionRecordRepository { get; } + + /// + /// Gets the media resume point repository. + /// + IMediaResumePointRepository MediaResumePointRepository { get; } + + /// + /// Gets the repository for the consumption records used to build consumption statistics. + /// + IConsumptionStatisticsRepository ConsumptionStatisticsRepository { get; } + /// /// Saves the changes made to the database. /// diff --git a/src/Lumina.Application/Common/Errors/Errors.Persistence.cs b/src/Lumina.Application/Common/Errors/Errors.Persistence.cs index df0b3197..6d58d1cd 100644 --- a/src/Lumina.Application/Common/Errors/Errors.Persistence.cs +++ b/src/Lumina.Application/Common/Errors/Errors.Persistence.cs @@ -14,5 +14,6 @@ public static partial class Errors public static Error ErrorPersistingMediaLibrary => Error.Failure(description: nameof(ErrorPersistingMediaLibrary)); public static Error ErrorPersistingAuthorizationRole => Error.Failure(description: nameof(ErrorPersistingAuthorizationRole)); public static Error UniqueConstraintViolation => Error.Conflict(description: nameof(UniqueConstraintViolation)); + public static Error ConcurrencyConflict => Error.Conflict(description: nameof(ConcurrencyConflict)); } } diff --git a/src/Lumina.Application/Common/Infrastructure/Authorization/AuthorizationRoles.cs b/src/Lumina.Application/Common/Infrastructure/Authorization/AuthorizationRoles.cs new file mode 100644 index 00000000..497db7d6 --- /dev/null +++ b/src/Lumina.Application/Common/Infrastructure/Authorization/AuthorizationRoles.cs @@ -0,0 +1,12 @@ +namespace Lumina.Application.Common.Infrastructure.Authorization; + +/// +/// Class for the names of the authorization roles. +/// +public static class AuthorizationRoles +{ + /// + /// The role that grants administrative access. + /// + public const string ADMIN = "Admin"; +} diff --git a/src/Lumina.Application/Common/Infrastructure/Authorization/Policies/ConsumptionActivity/ConsumptionActivityAccessPolicyContext.cs b/src/Lumina.Application/Common/Infrastructure/Authorization/Policies/ConsumptionActivity/ConsumptionActivityAccessPolicyContext.cs new file mode 100644 index 00000000..a5d740e6 --- /dev/null +++ b/src/Lumina.Application/Common/Infrastructure/Authorization/Policies/ConsumptionActivity/ConsumptionActivityAccessPolicyContext.cs @@ -0,0 +1,14 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Infrastructure.Authorization.Policies.Common.Base; +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Common.Infrastructure.Authorization.Policies.ConsumptionActivity; + +/// +/// Represents the context required to evaluate the consumption activity authorization policy. +/// +/// The Id of the user whose consumption activity is being accessed. +[DebuggerDisplay("TargetUserId: {TargetUserId}")] +public sealed record ConsumptionActivityAccessPolicyContext(Guid TargetUserId) : PolicyContext; diff --git a/src/Lumina.Application/Common/Infrastructure/Authorization/Policies/ConsumptionActivity/IConsumptionActivityAccessPolicy.cs b/src/Lumina.Application/Common/Infrastructure/Authorization/Policies/ConsumptionActivity/IConsumptionActivityAccessPolicy.cs new file mode 100644 index 00000000..aadaf37c --- /dev/null +++ b/src/Lumina.Application/Common/Infrastructure/Authorization/Policies/ConsumptionActivity/IConsumptionActivityAccessPolicy.cs @@ -0,0 +1,12 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Infrastructure.Authorization.Policies.Common.Base; +#endregion + +namespace Lumina.Application.Common.Infrastructure.Authorization.Policies.ConsumptionActivity; + +/// +/// Interface for the consumption activity authorization policy. +/// +public interface IConsumptionActivityAccessPolicy : IAuthorizationPolicy +{ +} diff --git a/src/Lumina.Application/Common/Mapping/Favorites/AddFavoriteRequestMapping.cs b/src/Lumina.Application/Common/Mapping/Favorites/AddFavoriteRequestMapping.cs new file mode 100644 index 00000000..50a47702 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/Favorites/AddFavoriteRequestMapping.cs @@ -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; + +/// +/// Extension methods for converting . +/// +public static class AddFavoriteRequestMapping +{ + /// + /// Converts to . + /// + /// The request to be converted. + /// The converted command. + public static AddFavoriteCommand ToCommand(this AddFavoriteRequest request) + { + return new AddFavoriteCommand(request.MediaKind, request.MediaItemId); + } +} diff --git a/src/Lumina.Application/Common/Mapping/Favorites/FavoriteEntityMapping.cs b/src/Lumina.Application/Common/Mapping/Favorites/FavoriteEntityMapping.cs new file mode 100644 index 00000000..a368a0fe --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/Favorites/FavoriteEntityMapping.cs @@ -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; + +/// +/// Extension methods for converting . +/// +public static class FavoriteEntityMapping +{ + /// + /// Converts to . + /// + /// The repository entity to be converted. + /// + /// An containing either a successfully converted , or an error message. + /// + public static Result ToDomainEntity(this FavoriteEntity repositoryEntity) + { + return Favorite.Create( + FavoriteId.Create(repositoryEntity.Id), + UserId.Create(repositoryEntity.UserId), + MediaItemId.Create(repositoryEntity.MediaItemId), + repositoryEntity.MediaKind, + repositoryEntity.CreatedOnUtc, + Optional.FromNullable(repositoryEntity.UpdatedOnUtc)); + } + + /// + /// Converts to . + /// + /// The repository entity to be converted. + /// The converted response. + public static FavoriteResponse ToResponse(this FavoriteEntity repositoryEntity) + { + return new FavoriteResponse( + repositoryEntity.Id, + repositoryEntity.MediaKind, + repositoryEntity.MediaItemId, + repositoryEntity.CreatedOnUtc); + } +} diff --git a/src/Lumina.Application/Common/Mapping/Favorites/FavoriteItemDtoMapping.cs b/src/Lumina.Application/Common/Mapping/Favorites/FavoriteItemDtoMapping.cs new file mode 100644 index 00000000..829110ba --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/Favorites/FavoriteItemDtoMapping.cs @@ -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; + +/// +/// Extension methods for converting . +/// +public static class FavoriteItemDtoMapping +{ + /// + /// Converts to . + /// + /// The favorite data to be converted. + /// The converted response, flagged as not available with empty display fields when the display data is missing. + 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); + } + + /// + /// Converts to a paginated collection of . + /// + /// The paginated favorite data to be converted. + /// The converted paginated responses. + public static PaginatedResponse ToResponses(this PaginatedResultDto data) + { + return new PaginatedResponse + { + Data = [.. data.Data.Select(item => item.ToResponse())], + CurrentPage = data.CurrentPage, + PerPage = data.PerPage, + Count = data.Count, + NumberOfPages = data.NumberOfPages + }; + } +} diff --git a/src/Lumina.Application/Common/Mapping/Favorites/FavoriteMapping.cs b/src/Lumina.Application/Common/Mapping/Favorites/FavoriteMapping.cs new file mode 100644 index 00000000..66500db4 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/Favorites/FavoriteMapping.cs @@ -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; + +/// +/// Extension methods for converting . +/// +public static class FavoriteMapping +{ + /// + /// Converts to . + /// + /// The domain entity to be converted. + /// The converted repository entity. + 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 + }; + } +} diff --git a/src/Lumina.Application/Common/Mapping/Favorites/GetFavoriteStatusRequestMapping.cs b/src/Lumina.Application/Common/Mapping/Favorites/GetFavoriteStatusRequestMapping.cs new file mode 100644 index 00000000..c855c6d6 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/Favorites/GetFavoriteStatusRequestMapping.cs @@ -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; + +/// +/// Extension methods for converting . +/// +public static class GetFavoriteStatusRequestMapping +{ + /// + /// Converts to . + /// + /// The request to be converted. + /// The converted query. + public static GetFavoriteStatusQuery ToQuery(this GetFavoriteStatusRequest request) + { + return new GetFavoriteStatusQuery(request.MediaKind, request.MediaItemIds); + } +} diff --git a/src/Lumina.Application/Common/Mapping/Favorites/GetFavoritesRequestMapping.cs b/src/Lumina.Application/Common/Mapping/Favorites/GetFavoritesRequestMapping.cs new file mode 100644 index 00000000..7e3c89cd --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/Favorites/GetFavoritesRequestMapping.cs @@ -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; + +/// +/// Extension methods for converting . +/// +public static class GetFavoritesRequestMapping +{ + /// + /// Converts to . + /// + /// The request to be converted. + /// The converted query. + 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); + } +} diff --git a/src/Lumina.Application/Common/Mapping/MediaConsumption/AllUsersConsumptionStatisticsDtoMapping.cs b/src/Lumina.Application/Common/Mapping/MediaConsumption/AllUsersConsumptionStatisticsDtoMapping.cs new file mode 100644 index 00000000..e8f205ee --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/MediaConsumption/AllUsersConsumptionStatisticsDtoMapping.cs @@ -0,0 +1,26 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DTO.MediaConsumption; +using Lumina.Contracts.Responses.MediaConsumption; +using System.Linq; +#endregion + +namespace Lumina.Application.Common.Mapping.MediaConsumption; + +/// +/// Extension methods for converting . +/// +public static class AllUsersConsumptionStatisticsDtoMapping +{ + /// + /// Converts to . + /// + /// The data transfer object to be converted. + /// The converted response. + public static AllUsersConsumptionStatisticsResponse ToResponse(this AllUsersConsumptionStatisticsDto data) + { + return new AllUsersConsumptionStatisticsResponse( + data.Total.ToResponse(), + [.. data.Users.Select(user => user.ToResponse())] + ); + } +} diff --git a/src/Lumina.Application/Common/Mapping/MediaConsumption/ClearResumePointsRequestMapping.cs b/src/Lumina.Application/Common/Mapping/MediaConsumption/ClearResumePointsRequestMapping.cs new file mode 100644 index 00000000..fc4788e3 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/MediaConsumption/ClearResumePointsRequestMapping.cs @@ -0,0 +1,26 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.MediaConsumption.Commands.ClearResumePoints; +using Lumina.Contracts.Requests.MediaConsumption; +#endregion + +namespace Lumina.Application.Common.Mapping.MediaConsumption; + +/// +/// Extension methods for converting . +/// +public static class ClearResumePointsRequestMapping +{ + /// + /// Converts to . + /// + /// The request to be converted. + /// The Id of the user whose resume points are deleted, taken from the route, or for the current user. + /// The converted command. + public static ClearResumePointsCommand ToCommand(this ClearResumePointsRequest request, string? targetUserId) + { + return new ClearResumePointsCommand( + targetUserId, + request.LibraryId + ); + } +} diff --git a/src/Lumina.Application/Common/Mapping/MediaConsumption/CompleteConsumptionRequestMapping.cs b/src/Lumina.Application/Common/Mapping/MediaConsumption/CompleteConsumptionRequestMapping.cs new file mode 100644 index 00000000..3a5f4bab --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/MediaConsumption/CompleteConsumptionRequestMapping.cs @@ -0,0 +1,31 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.MediaConsumption.Commands.CompleteConsumption; +using Lumina.Contracts.Requests.MediaConsumption; +#endregion + +namespace Lumina.Application.Common.Mapping.MediaConsumption; + +/// +/// Extension methods for converting . +/// +public static class CompleteConsumptionRequestMapping +{ + /// + /// Converts to . + /// + /// The request to be converted. + /// The Id of the consumption record, taken from the route. + /// The converted command. + public static CompleteConsumptionCommand ToCommand(this CompleteConsumptionRequest request, string? consumptionRecordId) + { + return new CompleteConsumptionCommand( + consumptionRecordId, + request.Position?.Kind, + request.Position?.TimeOffsetSeconds, + request.Position?.Location, + request.ProgressFraction, + request.ConsumedDurationInSeconds, + request.ConsecutivePagesRead + ); + } +} diff --git a/src/Lumina.Application/Common/Mapping/MediaConsumption/ConsumedItemDtoMapping.cs b/src/Lumina.Application/Common/Mapping/MediaConsumption/ConsumedItemDtoMapping.cs new file mode 100644 index 00000000..997b21e0 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/MediaConsumption/ConsumedItemDtoMapping.cs @@ -0,0 +1,57 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DTO.MediaConsumption; +using Lumina.Application.Common.DTO.Pagination; +using Lumina.Application.Common.Utilities; +using Lumina.Contracts.Responses.Common; +using Lumina.Contracts.Responses.MediaConsumption; +using System; +using System.Linq; +#endregion + +namespace Lumina.Application.Common.Mapping.MediaConsumption; + +/// +/// Extension methods for converting . +/// +public static class ConsumedItemDtoMapping +{ + /// + /// Converts to . + /// + /// The data transfer object to be converted. + /// The converted response. + public static ConsumedItemResponse ToResponse(this ConsumedItemDto data) + { + return new ConsumedItemResponse( + data.MediaKind, + data.MediaItemId, + data.LibraryId, + data.IsAvailable, + data.Title, + data.CollectionTitle, + data.CreatorName, + data.CoverPath, + DateTime.SpecifyKind(data.LastConsumedOnUtc, DateTimeKind.Utc), + data.CountedSessionCount, + data.CompletedSessionCount, + data.ConsumedDurationMilliseconds.ToClampedTimeSpan().TotalSeconds + ); + } + + /// + /// Converts to a paginated collection of . + /// + /// The paginated data transfer objects to be converted. + /// The converted paginated responses. + public static PaginatedResponse ToResponses(this PaginatedResultDto data) + { + return new PaginatedResponse + { + Data = [.. data.Data.Select(item => item.ToResponse())], + CurrentPage = data.CurrentPage, + PerPage = data.PerPage, + Count = data.Count, + NumberOfPages = data.NumberOfPages + }; + } +} diff --git a/src/Lumina.Application/Common/Mapping/MediaConsumption/ConsumptionRecordDtoMapping.cs b/src/Lumina.Application/Common/Mapping/MediaConsumption/ConsumptionRecordDtoMapping.cs new file mode 100644 index 00000000..c2122019 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/MediaConsumption/ConsumptionRecordDtoMapping.cs @@ -0,0 +1,38 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DTO.MediaConsumption; +using Lumina.Application.Common.Utilities; +using Lumina.Contracts.Responses.MediaConsumption; +using System; +#endregion + +namespace Lumina.Application.Common.Mapping.MediaConsumption; + +/// +/// Extension methods for converting . This mapping is the record response builder for repository-driven +/// single-record reads. +/// +public static class ConsumptionRecordDtoMapping +{ + /// + /// Converts to . + /// + /// The data transfer object to be converted. + /// The converted response. + public static ConsumptionRecordResponse ToResponse(this ConsumptionRecordDto data) + { + return new ConsumptionRecordResponse( + data.Id, + data.LibraryId, + data.MediaItemId, + data.MediaKind, + data.Status, + DateTime.SpecifyKind(data.StartedOnUtc, DateTimeKind.Utc), + DateTime.SpecifyKind(data.LastActivityOnUtc, DateTimeKind.Utc), + data.EndedOnUtc.HasValue ? DateTime.SpecifyKind(data.EndedOnUtc.Value, DateTimeKind.Utc) : null, + data.ConsumedDurationMilliseconds.ToClampedTimeSpan().TotalSeconds, + data.LastPosition?.ToResponse(), + data.LastProgressFraction, + data.ConsecutivePagesRead + ); + } +} diff --git a/src/Lumina.Application/Common/Mapping/MediaConsumption/ConsumptionStatisticsDtoMapping.cs b/src/Lumina.Application/Common/Mapping/MediaConsumption/ConsumptionStatisticsDtoMapping.cs new file mode 100644 index 00000000..6005fa07 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/MediaConsumption/ConsumptionStatisticsDtoMapping.cs @@ -0,0 +1,32 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DTO.MediaConsumption; +using Lumina.Application.Common.Utilities; +using Lumina.Contracts.Responses.MediaConsumption; +using System.Linq; +#endregion + +namespace Lumina.Application.Common.Mapping.MediaConsumption; + +/// +/// Extension methods for converting . +/// +public static class ConsumptionStatisticsDtoMapping +{ + /// + /// Converts to . + /// + /// The data transfer object to be converted. + /// The converted response. + public static ConsumptionSummaryResponse ToResponse(this ConsumptionStatisticsDto data) + { + return new ConsumptionSummaryResponse( + data.UserId, + data.TotalConsumedDurationMilliseconds.ToClampedTimeSpan().TotalSeconds, + data.CountedSessionCount, + data.CompletedSessionCount, + data.StoppedSessionCount, + data.CompletionRate, + [.. data.MediaKindSummaries.Select(mediaKindSummary => mediaKindSummary.ToResponse())] + ); + } +} diff --git a/src/Lumina.Application/Common/Mapping/MediaConsumption/ConsumptionTotalsDtoMapping.cs b/src/Lumina.Application/Common/Mapping/MediaConsumption/ConsumptionTotalsDtoMapping.cs new file mode 100644 index 00000000..322097ed --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/MediaConsumption/ConsumptionTotalsDtoMapping.cs @@ -0,0 +1,31 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DTO.MediaConsumption; +using Lumina.Application.Common.Utilities; +using Lumina.Contracts.Responses.MediaConsumption; +using System.Linq; +#endregion + +namespace Lumina.Application.Common.Mapping.MediaConsumption; + +/// +/// Extension methods for converting . +/// +public static class ConsumptionTotalsDtoMapping +{ + /// + /// Converts to . + /// + /// The data transfer object to be converted. + /// The converted response. + public static ConsumptionTotalsResponse ToResponse(this ConsumptionTotalsDto data) + { + return new ConsumptionTotalsResponse( + data.TotalConsumedDurationMilliseconds.ToClampedTimeSpan().TotalSeconds, + data.CountedSessionCount, + data.CompletedSessionCount, + data.StoppedSessionCount, + data.CompletionRate, + [.. data.MediaKindSummaries.Select(mediaKindSummary => mediaKindSummary.ToResponse())] + ); + } +} diff --git a/src/Lumina.Application/Common/Mapping/MediaConsumption/GenreConsumptionDtoMapping.cs b/src/Lumina.Application/Common/Mapping/MediaConsumption/GenreConsumptionDtoMapping.cs new file mode 100644 index 00000000..b8e9c761 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/MediaConsumption/GenreConsumptionDtoMapping.cs @@ -0,0 +1,39 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DTO.MediaConsumption; +using Lumina.Application.Common.Utilities; +using Lumina.Contracts.Responses.MediaConsumption; +using System.Collections.Generic; +using System.Linq; +#endregion + +namespace Lumina.Application.Common.Mapping.MediaConsumption; + +/// +/// Extension methods for converting . +/// +public static class GenreConsumptionDtoMapping +{ + /// + /// Converts to . + /// + /// The data transfer object to be converted. + /// The converted response. + public static GenreConsumptionResponse ToResponse(this GenreConsumptionDto data) + { + return new GenreConsumptionResponse( + data.Name, + data.ConsumedItemCount, + data.ConsumedDurationMilliseconds.ToClampedTimeSpan().TotalSeconds + ); + } + + /// + /// Converts to a collection of . + /// + /// The data transfer objects to be converted. + /// The converted responses. + public static IReadOnlyList ToResponses(this IReadOnlyList data) + { + return [.. data.Select(item => item.ToResponse())]; + } +} diff --git a/src/Lumina.Application/Common/Mapping/MediaConsumption/GetAllUsersConsumptionStatisticsRequestMapping.cs b/src/Lumina.Application/Common/Mapping/MediaConsumption/GetAllUsersConsumptionStatisticsRequestMapping.cs new file mode 100644 index 00000000..5b3dbec6 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/MediaConsumption/GetAllUsersConsumptionStatisticsRequestMapping.cs @@ -0,0 +1,27 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.MediaConsumption.Queries.GetAllUsersConsumptionStatistics; +using Lumina.Contracts.Requests.MediaConsumption; +#endregion + +namespace Lumina.Application.Common.Mapping.MediaConsumption; + +/// +/// Extension methods for converting . +/// +public static class GetAllUsersConsumptionStatisticsRequestMapping +{ + /// + /// Converts to . + /// + /// The request to be converted. + /// The converted query. + public static GetAllUsersConsumptionStatisticsQuery ToQuery(this GetAllUsersConsumptionStatisticsRequest request) + { + return new GetAllUsersConsumptionStatisticsQuery( + request.LibraryId, + request.MediaKind, + request.FromUtc, + request.ToUtc + ); + } +} diff --git a/src/Lumina.Application/Common/Mapping/MediaConsumption/GetConsumptionStatisticsRequestMapping.cs b/src/Lumina.Application/Common/Mapping/MediaConsumption/GetConsumptionStatisticsRequestMapping.cs new file mode 100644 index 00000000..8413faa3 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/MediaConsumption/GetConsumptionStatisticsRequestMapping.cs @@ -0,0 +1,29 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.MediaConsumption.Queries.GetConsumptionStatistics; +using Lumina.Contracts.Requests.MediaConsumption; +#endregion + +namespace Lumina.Application.Common.Mapping.MediaConsumption; + +/// +/// Extension methods for converting . +/// +public static class GetConsumptionStatisticsRequestMapping +{ + /// + /// Converts to . + /// + /// The request to be converted. + /// The Id of the user whose statistics are retrieved, taken from the route, or for the current user. + /// The converted query. + public static GetConsumptionStatisticsQuery ToQuery(this GetConsumptionStatisticsRequest request, string? targetUserId) + { + return new GetConsumptionStatisticsQuery( + targetUserId, + request.LibraryId, + request.MediaKind, + request.FromUtc, + request.ToUtc + ); + } +} diff --git a/src/Lumina.Application/Common/Mapping/MediaConsumption/GetGenreConsumptionRequestMapping.cs b/src/Lumina.Application/Common/Mapping/MediaConsumption/GetGenreConsumptionRequestMapping.cs new file mode 100644 index 00000000..6a88e5a0 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/MediaConsumption/GetGenreConsumptionRequestMapping.cs @@ -0,0 +1,29 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.MediaConsumption.Queries.GetGenreConsumption; +using Lumina.Contracts.Requests.MediaConsumption; +#endregion + +namespace Lumina.Application.Common.Mapping.MediaConsumption; + +/// +/// Extension methods for converting . +/// +public static class GetGenreConsumptionRequestMapping +{ + /// + /// Converts to . + /// + /// The request to be converted. + /// The Id of the user whose statistics are retrieved, taken from the route, or for the current user. + /// The converted query. + public static GetGenreConsumptionQuery ToQuery(this GetGenreConsumptionRequest request, string? targetUserId) + { + return new GetGenreConsumptionQuery( + targetUserId, + request.LibraryId, + request.MediaKind, + request.FromUtc, + request.ToUtc + ); + } +} diff --git a/src/Lumina.Application/Common/Mapping/MediaConsumption/GetMostConsumedRequestMapping.cs b/src/Lumina.Application/Common/Mapping/MediaConsumption/GetMostConsumedRequestMapping.cs new file mode 100644 index 00000000..68119459 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/MediaConsumption/GetMostConsumedRequestMapping.cs @@ -0,0 +1,39 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DTO.Pagination; +using Lumina.Application.Core.MediaConsumption.Queries.GetMostConsumed; +using Lumina.Contracts.Requests.MediaConsumption; +#endregion + +namespace Lumina.Application.Common.Mapping.MediaConsumption; + +/// +/// Extension methods for converting . +/// +public static class GetMostConsumedRequestMapping +{ + /// + /// Converts to . + /// + /// The request to be converted. + /// The Id of the user whose history is retrieved, taken from the route, or for the current user. + /// The converted query. + public static GetMostConsumedQuery ToQuery(this GetMostConsumedRequest request, string? targetUserId) + { + PaginationDataDto? paginationData = null; + if (request.CurrentPage is not null || request.PerPage is not null) + paginationData = new PaginationDataDto + { + CurrentPage = request.CurrentPage ?? 1, + PerPage = request.PerPage ?? 50 + }; + + return new GetMostConsumedQuery( + targetUserId, + request.LibraryId, + request.MediaKind, + request.FromUtc, + request.ToUtc, + paginationData + ); + } +} diff --git a/src/Lumina.Application/Common/Mapping/MediaConsumption/GetRecentlyConsumedRequestMapping.cs b/src/Lumina.Application/Common/Mapping/MediaConsumption/GetRecentlyConsumedRequestMapping.cs new file mode 100644 index 00000000..5b92c9ee --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/MediaConsumption/GetRecentlyConsumedRequestMapping.cs @@ -0,0 +1,39 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DTO.Pagination; +using Lumina.Application.Core.MediaConsumption.Queries.GetRecentlyConsumed; +using Lumina.Contracts.Requests.MediaConsumption; +#endregion + +namespace Lumina.Application.Common.Mapping.MediaConsumption; + +/// +/// Extension methods for converting . +/// +public static class GetRecentlyConsumedRequestMapping +{ + /// + /// Converts to . + /// + /// The request to be converted. + /// The Id of the user whose history is retrieved, taken from the route, or for the current user. + /// The converted query. + public static GetRecentlyConsumedQuery ToQuery(this GetRecentlyConsumedRequest request, string? targetUserId) + { + PaginationDataDto? paginationData = null; + if (request.CurrentPage is not null || request.PerPage is not null) + paginationData = new PaginationDataDto + { + CurrentPage = request.CurrentPage ?? 1, + PerPage = request.PerPage ?? 50 + }; + + return new GetRecentlyConsumedQuery( + targetUserId, + request.LibraryId, + request.MediaKind, + request.FromUtc, + request.ToUtc, + paginationData + ); + } +} diff --git a/src/Lumina.Application/Common/Mapping/MediaConsumption/GetTagConsumptionRequestMapping.cs b/src/Lumina.Application/Common/Mapping/MediaConsumption/GetTagConsumptionRequestMapping.cs new file mode 100644 index 00000000..526df04b --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/MediaConsumption/GetTagConsumptionRequestMapping.cs @@ -0,0 +1,29 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.MediaConsumption.Queries.GetTagConsumption; +using Lumina.Contracts.Requests.MediaConsumption; +#endregion + +namespace Lumina.Application.Common.Mapping.MediaConsumption; + +/// +/// Extension methods for converting . +/// +public static class GetTagConsumptionRequestMapping +{ + /// + /// Converts to . + /// + /// The request to be converted. + /// The Id of the user whose statistics are retrieved, taken from the route, or for the current user. + /// The converted query. + public static GetTagConsumptionQuery ToQuery(this GetTagConsumptionRequest request, string? targetUserId) + { + return new GetTagConsumptionQuery( + targetUserId, + request.LibraryId, + request.MediaKind, + request.FromUtc, + request.ToUtc + ); + } +} diff --git a/src/Lumina.Application/Common/Mapping/MediaConsumption/MediaConsumptionRecordEntityMapping.cs b/src/Lumina.Application/Common/Mapping/MediaConsumption/MediaConsumptionRecordEntityMapping.cs new file mode 100644 index 00000000..73e6190a --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/MediaConsumption/MediaConsumptionRecordEntityMapping.cs @@ -0,0 +1,112 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaConsumption; +using Lumina.Application.Common.DTO.MediaConsumption; +using Lumina.Application.Common.Utilities; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.Common.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.ExternalIdentifiers.LibraryManagementBoundedContext.LibraryAggregate; +using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.ExternalIdentifiers.MediaLibraryBoundedContext.MediaItemAggregate; +using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.ExternalIdentifiers.UserManagementBoundedContext.UserAggregate; +using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.MediaConsumptionRecordAggregate; +using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.MediaConsumptionRecordAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption; +using System; +using DomainErrors = Lumina.Domain.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.Common.Mapping.MediaConsumption; + +/// +/// Extension methods for converting . +/// +public static class MediaConsumptionRecordEntityMapping +{ + /// + /// Converts to . + /// + /// The repository entity to be converted. + /// + /// An containing either a successfully converted , or an error message. + /// + public static Result ToDomainEntity(this MediaConsumptionRecordEntity repositoryEntity) + { + Optional endedOnUtc = repositoryEntity.EndedOnUtc.HasValue + ? Optional.Some(DateTime.SpecifyKind(repositoryEntity.EndedOnUtc.Value, DateTimeKind.Utc)) + : Optional.None(); + + Optional lastPosition = Optional.None(); + if (repositoryEntity.LastPositionKind.HasValue) + { + MediaPositionKind positionKind = repositoryEntity.LastPositionKind.Value; + if (positionKind == MediaPositionKind.TimeOffset) + { + // A stored position outside the representable range is rejected like a negative one, instead of being silently clamped to a position that no client ever reported. + long maximumTimeOffsetMilliseconds = TimeSpan.MaxValue.Ticks / TimeSpan.TicksPerMillisecond; + if (!repositoryEntity.LastPositionTimeOffsetMilliseconds.HasValue || + repositoryEntity.LastPositionTimeOffsetMilliseconds.Value < 0 || + repositoryEntity.LastPositionTimeOffsetMilliseconds.Value > maximumTimeOffsetMilliseconds || + repositoryEntity.LastPositionLocation is not null) + return DomainErrors.MediaConsumption.InvalidMediaPosition; + lastPosition = Optional.Some( + MediaPosition.CreateTimeOffset(TimeSpan.FromMilliseconds(repositoryEntity.LastPositionTimeOffsetMilliseconds.Value))); + } + else if (positionKind == MediaPositionKind.Location) + { + if (string.IsNullOrWhiteSpace(repositoryEntity.LastPositionLocation) || + repositoryEntity.LastPositionTimeOffsetMilliseconds.HasValue) + return DomainErrors.MediaConsumption.InvalidMediaPosition; + lastPosition = Optional.Some(MediaPosition.CreateLocation(repositoryEntity.LastPositionLocation)); + } + else + return DomainErrors.MediaConsumption.InvalidMediaPosition; + } + + return MediaConsumptionRecord.Reconstitute( + MediaConsumptionRecordId.Create(repositoryEntity.Id), + UserId.Create(repositoryEntity.UserId), + LibraryId.Create(repositoryEntity.LibraryId), + MediaItemId.Create(repositoryEntity.MediaItemId), + repositoryEntity.MediaKind, + repositoryEntity.Status, + DateTime.SpecifyKind(repositoryEntity.StartedOnUtc, DateTimeKind.Utc), + DateTime.SpecifyKind(repositoryEntity.LastActivityOnUtc, DateTimeKind.Utc), + endedOnUtc, + repositoryEntity.ConsumedDurationMilliseconds.ToClampedTimeSpan(), + lastPosition, + repositoryEntity.LastProgressFraction, + repositoryEntity.ConsecutivePagesRead + ); + } + + /// + /// Converts to . + /// + /// The repository entity to be converted. + /// The converted data transfer object. + public static ConsumptionRecordDto ToDto(this MediaConsumptionRecordEntity repositoryEntity) + { + MediaPositionDto? lastPosition = null; + if (repositoryEntity.LastPositionKind.HasValue) + { + lastPosition = new MediaPositionDto( + repositoryEntity.LastPositionKind.Value, + repositoryEntity.LastPositionTimeOffsetMilliseconds, + repositoryEntity.LastPositionLocation); + } + + return new ConsumptionRecordDto( + repositoryEntity.Id, + repositoryEntity.LibraryId, + repositoryEntity.MediaItemId, + repositoryEntity.MediaKind, + repositoryEntity.Status, + DateTime.SpecifyKind(repositoryEntity.StartedOnUtc, DateTimeKind.Utc), + DateTime.SpecifyKind(repositoryEntity.LastActivityOnUtc, DateTimeKind.Utc), + repositoryEntity.EndedOnUtc.HasValue ? DateTime.SpecifyKind(repositoryEntity.EndedOnUtc.Value, DateTimeKind.Utc) : null, + repositoryEntity.ConsumedDurationMilliseconds, + lastPosition, + repositoryEntity.LastProgressFraction, + repositoryEntity.ConsecutivePagesRead + ); + } +} diff --git a/src/Lumina.Application/Common/Mapping/MediaConsumption/MediaConsumptionRecordMapping.cs b/src/Lumina.Application/Common/Mapping/MediaConsumption/MediaConsumptionRecordMapping.cs new file mode 100644 index 00000000..0dd3e24e --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/MediaConsumption/MediaConsumptionRecordMapping.cs @@ -0,0 +1,101 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaConsumption; +using Lumina.Application.Common.DTO.MediaConsumption; +using Lumina.Contracts.Responses.MediaConsumption; +using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.MediaConsumptionRecordAggregate; +using System; +#endregion + +namespace Lumina.Application.Common.Mapping.MediaConsumption; + +/// +/// Extension methods for converting . The record is mapped directly to its repository entity and to its response. +/// Repository-driven single-record reads map the entity to its DTO and then to the response. +/// +public static class MediaConsumptionRecordMapping +{ + /// + /// Converts to . + /// + /// The domain entity to be converted. + /// The converted repository entity. + public static MediaConsumptionRecordEntity ToRepositoryEntity(this MediaConsumptionRecord domainEntity) + { + return new MediaConsumptionRecordEntity + { + Id = domainEntity.Id.Value, + UserId = domainEntity.UserId.Value, + LibraryId = domainEntity.LibraryId.Value, + MediaKind = domainEntity.MediaKind, + MediaItemId = domainEntity.MediaItemId.Value, + Status = domainEntity.Status, + StartedOnUtc = domainEntity.StartedOnUtc, + LastActivityOnUtc = domainEntity.LastActivityOnUtc, + EndedOnUtc = domainEntity.EndedOnUtc.HasValue ? domainEntity.EndedOnUtc.Value : null, + // Stored time is truncated to whole milliseconds instead of rounded, so a retried report of the same fractional second maps to + // the same stored value and is not rejected as a decrease by the domain. + ConsumedDurationMilliseconds = (long)domainEntity.ConsumedDuration.TotalMilliseconds, + LastPositionKind = domainEntity.LastPosition.HasValue ? domainEntity.LastPosition.Value.Kind : null, + LastPositionTimeOffsetMilliseconds = domainEntity.LastPosition.HasValue && domainEntity.LastPosition.Value.TimeOffset.HasValue + ? (long)domainEntity.LastPosition.Value.TimeOffset.Value.TotalMilliseconds + : null, + LastPositionLocation = domainEntity.LastPosition.HasValue && domainEntity.LastPosition.Value.Location.HasValue + ? domainEntity.LastPosition.Value.Location.Value + : null, + LastProgressFraction = domainEntity.LastProgressFraction, + ConsecutivePagesRead = domainEntity.ConsecutivePagesRead, + Version = 1, + CreatedOnUtc = domainEntity.CreatedOnUtc, + CreatedBy = Guid.Empty, + // The audit columns are owned by the auditing interceptor, so they are never mapped here. + UpdatedOnUtc = null, + UpdatedBy = null + }; + } + + /// + /// Converts to . + /// + /// The domain entity to be converted. + /// The converted data transfer object. + public static ConsumptionRecordDto ToDto(this MediaConsumptionRecord domainEntity) + { + return new ConsumptionRecordDto( + domainEntity.Id.Value, + domainEntity.LibraryId.Value, + domainEntity.MediaItemId.Value, + domainEntity.MediaKind, + domainEntity.Status, + DateTime.SpecifyKind(domainEntity.StartedOnUtc, DateTimeKind.Utc), + DateTime.SpecifyKind(domainEntity.LastActivityOnUtc, DateTimeKind.Utc), + domainEntity.EndedOnUtc.HasValue ? DateTime.SpecifyKind(domainEntity.EndedOnUtc.Value, DateTimeKind.Utc) : null, + (long)domainEntity.ConsumedDuration.TotalMilliseconds, + domainEntity.LastPosition.HasValue ? domainEntity.LastPosition.Value.ToDto() : null, + domainEntity.LastProgressFraction, + domainEntity.ConsecutivePagesRead + ); + } + + /// + /// Converts to . + /// + /// The domain entity to be converted. + /// The converted response. + public static ConsumptionRecordResponse ToResponse(this MediaConsumptionRecord domainEntity) + { + return new ConsumptionRecordResponse( + domainEntity.Id.Value, + domainEntity.LibraryId.Value, + domainEntity.MediaItemId.Value, + domainEntity.MediaKind, + domainEntity.Status, + DateTime.SpecifyKind(domainEntity.StartedOnUtc, DateTimeKind.Utc), + DateTime.SpecifyKind(domainEntity.LastActivityOnUtc, DateTimeKind.Utc), + domainEntity.EndedOnUtc.HasValue ? DateTime.SpecifyKind(domainEntity.EndedOnUtc.Value, DateTimeKind.Utc) : null, + domainEntity.ConsumedDuration.TotalSeconds, + domainEntity.LastPosition.HasValue ? domainEntity.LastPosition.Value.ToResponse() : null, + domainEntity.LastProgressFraction, + domainEntity.ConsecutivePagesRead + ); + } +} diff --git a/src/Lumina.Application/Common/Mapping/MediaConsumption/MediaKindConsumptionStatisticsDtoMapping.cs b/src/Lumina.Application/Common/Mapping/MediaConsumption/MediaKindConsumptionStatisticsDtoMapping.cs new file mode 100644 index 00000000..cfed82e2 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/MediaConsumption/MediaKindConsumptionStatisticsDtoMapping.cs @@ -0,0 +1,30 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DTO.MediaConsumption; +using Lumina.Application.Common.Utilities; +using Lumina.Contracts.Responses.MediaConsumption; +#endregion + +namespace Lumina.Application.Common.Mapping.MediaConsumption; + +/// +/// Extension methods for converting . +/// +public static class MediaKindConsumptionStatisticsDtoMapping +{ + /// + /// Converts to . + /// + /// The data transfer object to be converted. + /// The converted response. + public static MediaKindConsumptionSummaryResponse ToResponse(this MediaKindConsumptionStatisticsDto data) + { + return new MediaKindConsumptionSummaryResponse( + data.MediaKind, + data.TotalConsumedDurationMilliseconds.ToClampedTimeSpan().TotalSeconds, + data.CountedSessionCount, + data.CompletedSessionCount, + data.StoppedSessionCount, + data.CompletionRate + ); + } +} diff --git a/src/Lumina.Application/Common/Mapping/MediaConsumption/MediaPositionDtoMapping.cs b/src/Lumina.Application/Common/Mapping/MediaConsumption/MediaPositionDtoMapping.cs new file mode 100644 index 00000000..a05179c4 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/MediaConsumption/MediaPositionDtoMapping.cs @@ -0,0 +1,27 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DTO.MediaConsumption; +using Lumina.Application.Common.Utilities; +using Lumina.Contracts.Responses.MediaConsumption; +#endregion + +namespace Lumina.Application.Common.Mapping.MediaConsumption; + +/// +/// Extension methods for converting . This mapping is the position response builder for repository-driven reads. +/// +public static class MediaPositionDtoMapping +{ + /// + /// Converts to . + /// + /// The data transfer object to be converted. + /// The converted response. + public static MediaPositionResponse ToResponse(this MediaPositionDto data) + { + return new MediaPositionResponse( + data.Kind, + data.TimeOffsetMilliseconds.HasValue ? data.TimeOffsetMilliseconds.Value.ToClampedTimeSpan().TotalSeconds : null, + data.Location + ); + } +} diff --git a/src/Lumina.Application/Common/Mapping/MediaConsumption/MediaPositionMapping.cs b/src/Lumina.Application/Common/Mapping/MediaConsumption/MediaPositionMapping.cs new file mode 100644 index 00000000..7ced73f5 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/MediaConsumption/MediaPositionMapping.cs @@ -0,0 +1,41 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DTO.MediaConsumption; +using Lumina.Contracts.Responses.MediaConsumption; +using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.Common.ValueObjects; +#endregion + +namespace Lumina.Application.Common.Mapping.MediaConsumption; + +/// +/// Extension methods for converting . The position is mapped directly to its DTO and to its response. +/// +public static class MediaPositionMapping +{ + /// + /// Converts to . + /// + /// The domain value object to be converted. + /// The converted data transfer object. + public static MediaPositionDto ToDto(this MediaPosition domainValueObject) + { + return new MediaPositionDto( + domainValueObject.Kind, + domainValueObject.TimeOffset.HasValue ? (long)domainValueObject.TimeOffset.Value.TotalMilliseconds : null, + domainValueObject.Location.HasValue ? domainValueObject.Location.Value : null + ); + } + + /// + /// Converts to . + /// + /// The domain value object to be converted. + /// The converted response. + public static MediaPositionResponse ToResponse(this MediaPosition domainValueObject) + { + return new MediaPositionResponse( + domainValueObject.Kind, + domainValueObject.TimeOffset.HasValue ? domainValueObject.TimeOffset.Value.TotalSeconds : null, + domainValueObject.Location.HasValue ? domainValueObject.Location.Value : null + ); + } +} diff --git a/src/Lumina.Application/Common/Mapping/MediaConsumption/MediaResumePointEntityMapping.cs b/src/Lumina.Application/Common/Mapping/MediaConsumption/MediaResumePointEntityMapping.cs new file mode 100644 index 00000000..072f4b79 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/MediaConsumption/MediaResumePointEntityMapping.cs @@ -0,0 +1,90 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaConsumption; +using Lumina.Application.Common.DTO.MediaConsumption; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.Common.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.ExternalIdentifiers.LibraryManagementBoundedContext.LibraryAggregate; +using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.ExternalIdentifiers.MediaLibraryBoundedContext.MediaItemAggregate; +using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.ExternalIdentifiers.UserManagementBoundedContext.UserAggregate; +using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.MediaResumePointAggregate; +using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.MediaResumePointAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption; +using System; +using DomainErrors = Lumina.Domain.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.Common.Mapping.MediaConsumption; + +/// +/// Extension methods for converting . +/// +public static class MediaResumePointEntityMapping +{ + /// + /// Converts to . + /// + /// The repository entity to be converted. + /// + /// An containing either a successfully converted , or an error message. + /// + public static Result ToDomainEntity(this MediaResumePointEntity repositoryEntity) + { + MediaPosition lastPosition; + if (repositoryEntity.LastPositionKind == MediaPositionKind.TimeOffset) + { + // A stored position outside the representable range is rejected like a negative one, instead of being silently clamped to a position that no client ever reported. + long maximumTimeOffsetMilliseconds = TimeSpan.MaxValue.Ticks / TimeSpan.TicksPerMillisecond; + if (!repositoryEntity.LastPositionTimeOffsetMilliseconds.HasValue || + repositoryEntity.LastPositionTimeOffsetMilliseconds.Value < 0 || + repositoryEntity.LastPositionTimeOffsetMilliseconds.Value > maximumTimeOffsetMilliseconds || + repositoryEntity.LastPositionLocation is not null) + return DomainErrors.MediaConsumption.InvalidMediaPosition; + lastPosition = MediaPosition.CreateTimeOffset(TimeSpan.FromMilliseconds(repositoryEntity.LastPositionTimeOffsetMilliseconds.Value)); + } + else if (repositoryEntity.LastPositionKind == MediaPositionKind.Location) + { + if (string.IsNullOrWhiteSpace(repositoryEntity.LastPositionLocation) || + repositoryEntity.LastPositionTimeOffsetMilliseconds.HasValue) + return DomainErrors.MediaConsumption.InvalidMediaPosition; + lastPosition = MediaPosition.CreateLocation(repositoryEntity.LastPositionLocation); + } + else + return DomainErrors.MediaConsumption.InvalidMediaPosition; + + return MediaResumePoint.Reconstitute( + MediaResumePointId.Create(repositoryEntity.Id), + UserId.Create(repositoryEntity.UserId), + LibraryId.Create(repositoryEntity.LibraryId), + MediaItemId.Create(repositoryEntity.MediaItemId), + repositoryEntity.MediaKind, + lastPosition, + repositoryEntity.LastProgressFraction, + DateTime.SpecifyKind(repositoryEntity.LastConsumedOnUtc, DateTimeKind.Utc), + DateTime.SpecifyKind(repositoryEntity.CreatedOnUtc, DateTimeKind.Utc), + repositoryEntity.UpdatedOnUtc.HasValue + ? Optional.Some(DateTime.SpecifyKind(repositoryEntity.UpdatedOnUtc.Value, DateTimeKind.Utc)) + : Optional.None() + ); + } + + /// + /// Converts to . + /// + /// The repository entity to be converted. + /// The converted data transfer object. + public static ResumePointDto ToDto(this MediaResumePointEntity repositoryEntity) + { + return new ResumePointDto( + repositoryEntity.Id, + repositoryEntity.LibraryId, + repositoryEntity.MediaItemId, + repositoryEntity.MediaKind, + new MediaPositionDto( + repositoryEntity.LastPositionKind, + repositoryEntity.LastPositionTimeOffsetMilliseconds, + repositoryEntity.LastPositionLocation), + repositoryEntity.LastProgressFraction, + DateTime.SpecifyKind(repositoryEntity.LastConsumedOnUtc, DateTimeKind.Utc) + ); + } +} diff --git a/src/Lumina.Application/Common/Mapping/MediaConsumption/MediaResumePointMapping.cs b/src/Lumina.Application/Common/Mapping/MediaConsumption/MediaResumePointMapping.cs new file mode 100644 index 00000000..7ce6aefd --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/MediaConsumption/MediaResumePointMapping.cs @@ -0,0 +1,84 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaConsumption; +using Lumina.Application.Common.DTO.MediaConsumption; +using Lumina.Contracts.Responses.MediaConsumption; +using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.MediaResumePointAggregate; +using System; +#endregion + +namespace Lumina.Application.Common.Mapping.MediaConsumption; + +/// +/// Extension methods for converting . The resume point is mapped directly to its repository entity and to its response. +/// Repository-driven single-record reads map the entity to its DTO and then to the response. +/// +public static class MediaResumePointMapping +{ + /// + /// Converts to . + /// + /// The domain entity to be converted. + /// The converted repository entity. + public static MediaResumePointEntity ToRepositoryEntity(this MediaResumePoint domainEntity) + { + return new MediaResumePointEntity + { + Id = domainEntity.Id.Value, + UserId = domainEntity.UserId.Value, + LibraryId = domainEntity.LibraryId.Value, + MediaKind = domainEntity.MediaKind, + MediaItemId = domainEntity.MediaItemId.Value, + LastPositionKind = domainEntity.LastPosition.Kind, + LastPositionTimeOffsetMilliseconds = domainEntity.LastPosition.TimeOffset.HasValue + ? (long)domainEntity.LastPosition.TimeOffset.Value.TotalMilliseconds + : null, + LastPositionLocation = domainEntity.LastPosition.Location.HasValue + ? domainEntity.LastPosition.Location.Value + : null, + LastProgressFraction = domainEntity.LastProgressFraction, + LastConsumedOnUtc = domainEntity.LastConsumedOnUtc, + Version = 1, + CreatedOnUtc = domainEntity.CreatedOnUtc, + CreatedBy = Guid.Empty, + // The audit columns are owned by the auditing interceptor, so they are never mapped here. + UpdatedOnUtc = null, + UpdatedBy = null + }; + } + + /// + /// Converts to . + /// + /// The domain entity to be converted. + /// The converted data transfer object. + public static ResumePointDto ToDto(this MediaResumePoint domainEntity) + { + return new ResumePointDto( + domainEntity.Id.Value, + domainEntity.LibraryId.Value, + domainEntity.MediaItemId.Value, + domainEntity.MediaKind, + domainEntity.LastPosition.ToDto(), + domainEntity.LastProgressFraction, + DateTime.SpecifyKind(domainEntity.LastConsumedOnUtc, DateTimeKind.Utc) + ); + } + + /// + /// Converts to . + /// + /// The domain entity to be converted. + /// The converted response. + public static ResumePointResponse ToResponse(this MediaResumePoint domainEntity) + { + return new ResumePointResponse( + domainEntity.Id.Value, + domainEntity.LibraryId.Value, + domainEntity.MediaItemId.Value, + domainEntity.MediaKind, + domainEntity.LastPosition.ToResponse(), + domainEntity.LastProgressFraction, + DateTime.SpecifyKind(domainEntity.LastConsumedOnUtc, DateTimeKind.Utc) + ); + } +} diff --git a/src/Lumina.Application/Common/Mapping/MediaConsumption/ReportConsumptionProgressRequestMapping.cs b/src/Lumina.Application/Common/Mapping/MediaConsumption/ReportConsumptionProgressRequestMapping.cs new file mode 100644 index 00000000..698173a9 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/MediaConsumption/ReportConsumptionProgressRequestMapping.cs @@ -0,0 +1,31 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.MediaConsumption.Commands.ReportConsumptionProgress; +using Lumina.Contracts.Requests.MediaConsumption; +#endregion + +namespace Lumina.Application.Common.Mapping.MediaConsumption; + +/// +/// Extension methods for converting . +/// +public static class ReportConsumptionProgressRequestMapping +{ + /// + /// Converts to . + /// + /// The request to be converted. + /// The Id of the consumption record, taken from the route. + /// The converted command. + public static ReportConsumptionProgressCommand ToCommand(this ReportConsumptionProgressRequest request, string? consumptionRecordId) + { + return new ReportConsumptionProgressCommand( + consumptionRecordId, + request.Position?.Kind, + request.Position?.TimeOffsetSeconds, + request.Position?.Location, + request.ProgressFraction, + request.ConsumedDurationInSeconds, + request.ConsecutivePagesRead + ); + } +} diff --git a/src/Lumina.Application/Common/Mapping/MediaConsumption/ResumePointDtoMapping.cs b/src/Lumina.Application/Common/Mapping/MediaConsumption/ResumePointDtoMapping.cs new file mode 100644 index 00000000..52fb7b08 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/MediaConsumption/ResumePointDtoMapping.cs @@ -0,0 +1,32 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DTO.MediaConsumption; +using Lumina.Contracts.Responses.MediaConsumption; +using System; +#endregion + +namespace Lumina.Application.Common.Mapping.MediaConsumption; + +/// +/// Extension methods for converting . This mapping is the resume point response builder for repository-driven +/// single-record reads. +/// +public static class ResumePointDtoMapping +{ + /// + /// Converts to . + /// + /// The data transfer object to be converted. + /// The converted response. + public static ResumePointResponse ToResponse(this ResumePointDto data) + { + return new ResumePointResponse( + data.Id, + data.LibraryId, + data.MediaItemId, + data.MediaKind, + data.LastPosition.ToResponse(), + data.LastProgressFraction, + DateTime.SpecifyKind(data.LastConsumedOnUtc, DateTimeKind.Utc) + ); + } +} diff --git a/src/Lumina.Application/Common/Mapping/MediaConsumption/StopConsumptionRequestMapping.cs b/src/Lumina.Application/Common/Mapping/MediaConsumption/StopConsumptionRequestMapping.cs new file mode 100644 index 00000000..d354756a --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/MediaConsumption/StopConsumptionRequestMapping.cs @@ -0,0 +1,31 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.MediaConsumption.Commands.StopConsumption; +using Lumina.Contracts.Requests.MediaConsumption; +#endregion + +namespace Lumina.Application.Common.Mapping.MediaConsumption; + +/// +/// Extension methods for converting . +/// +public static class StopConsumptionRequestMapping +{ + /// + /// Converts to . + /// + /// The request to be converted. + /// The Id of the consumption record, taken from the route. + /// The converted command. + public static StopConsumptionCommand ToCommand(this StopConsumptionRequest request, string? consumptionRecordId) + { + return new StopConsumptionCommand( + consumptionRecordId, + request.Position?.Kind, + request.Position?.TimeOffsetSeconds, + request.Position?.Location, + request.ProgressFraction, + request.ConsumedDurationInSeconds, + request.ConsecutivePagesRead + ); + } +} diff --git a/src/Lumina.Application/Common/Mapping/MediaConsumption/TagConsumptionDtoMapping.cs b/src/Lumina.Application/Common/Mapping/MediaConsumption/TagConsumptionDtoMapping.cs new file mode 100644 index 00000000..4db6a9f6 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/MediaConsumption/TagConsumptionDtoMapping.cs @@ -0,0 +1,39 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DTO.MediaConsumption; +using Lumina.Application.Common.Utilities; +using Lumina.Contracts.Responses.MediaConsumption; +using System.Collections.Generic; +using System.Linq; +#endregion + +namespace Lumina.Application.Common.Mapping.MediaConsumption; + +/// +/// Extension methods for converting . +/// +public static class TagConsumptionDtoMapping +{ + /// + /// Converts to . + /// + /// The data transfer object to be converted. + /// The converted response. + public static TagConsumptionResponse ToResponse(this TagConsumptionDto data) + { + return new TagConsumptionResponse( + data.Name, + data.ConsumedItemCount, + data.ConsumedDurationMilliseconds.ToClampedTimeSpan().TotalSeconds + ); + } + + /// + /// Converts to a collection of . + /// + /// The data transfer objects to be converted. + /// The converted responses. + public static IReadOnlyList ToResponses(this IReadOnlyList data) + { + return [.. data.Select(item => item.ToResponse())]; + } +} diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Albums/AlbumEntityMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Albums/AlbumEntityMapping.cs index 887dcb2c..105cc548 100644 --- a/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Albums/AlbumEntityMapping.cs +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Albums/AlbumEntityMapping.cs @@ -170,7 +170,7 @@ public static class AlbumEntityMapping repositoryEntity.ReleaseCountry, repositoryEntity.ReleaseVersion ); - // language and original language make sense only if their subproperties have values + // Language and original language make sense only if their subproperties have values. LanguageInfoDto? languageInfo = !string.IsNullOrWhiteSpace(repositoryEntity.LanguageCode) || !string.IsNullOrWhiteSpace(repositoryEntity.LanguageName) || !string.IsNullOrWhiteSpace(repositoryEntity.LanguageNativeName) @@ -207,6 +207,7 @@ public static class AlbumEntityMapping return new AlbumResponse( repositoryEntity.Id, repositoryEntity.ArtistId, + repositoryEntity.Artist?.Name ?? string.Empty, repositoryEntity.LibraryId, metadata, repositoryEntity.MediaFormat, diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/UpdateArtistCommandMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/UpdateArtistCommandMapping.cs index 076e5672..ebcc9b38 100644 --- a/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/UpdateArtistCommandMapping.cs +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/UpdateArtistCommandMapping.cs @@ -158,7 +158,6 @@ public static class UpdateArtistCommandMapping Result updateTrackResult = artist.UpdateTrackInAlbum( existingAlbum, existingTrack, - domainTrack.Path, domainTrack.Metadata, domainTrack.Disambiguation, domainTrack.TrackNumber, diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/AudioMetadataDtoMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/AudioMetadataDtoMapping.cs index 76393ef8..379acd51 100644 --- a/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/AudioMetadataDtoMapping.cs +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/AudioMetadataDtoMapping.cs @@ -111,7 +111,6 @@ public static class AudioMetadataDtoMapping return artist.UpdateTrackInAlbum( album, track, - track.Path, metadataResult.Value, disambiguation, track.TrackNumber, @@ -203,6 +202,9 @@ public static class AudioMetadataDtoMapping Optional audioCodec = Optional.FromNullable(dto.AudioCodec); if (!audioCodec.HasValue) audioCodec = track.Metadata.AudioCodec; + // The container is captured from the file itself: a provider that re-reads the file supplies it, and when it is absent the track keeps the stored + // container, which the domain enforces when the metadata is applied. The preserve rule therefore lives in one place, the domain update. + Optional container = Optional.FromNullable(dto.Container); Optional bitrate = Optional.FromNullable(dto.Bitrate); if (!bitrate.HasValue) bitrate = track.Metadata.Bitrate; @@ -221,6 +223,7 @@ public static class AudioMetadataDtoMapping originalLanguage, bitDepth, audioCodec, + container, bitrate, track.Metadata.AcoustId, track.Metadata.ReplayGainTrackGain, diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/MusicTrackMetadataDtoMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/MusicTrackMetadataDtoMapping.cs index 4d05db8a..721998ed 100644 --- a/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/MusicTrackMetadataDtoMapping.cs +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/MusicTrackMetadataDtoMapping.cs @@ -63,6 +63,7 @@ public static class MusicTrackMetadataDtoMapping if (dto.OriginalLanguage is not null && dto.OriginalLanguage.LanguageCode is not null && dto.OriginalLanguage.LanguageName is not null) originalLanguage = LanguageInfo.Create(dto.OriginalLanguage.LanguageCode, dto.OriginalLanguage.LanguageName, Optional.FromNullable(dto.OriginalLanguage.NativeName)); + // The container is captured from the file itself and is never settable through a request; on an edit the track keeps the container it already has. return AudioMetadata.Create( dto.Title!, Optional.FromNullable(dto.OriginalTitle), @@ -77,6 +78,7 @@ public static class MusicTrackMetadataDtoMapping originalLanguage, Optional.FromNullable(dto.BitDepth), Optional.FromNullable(dto.AudioCodec), + Optional.None(), Optional.FromNullable(dto.Bitrate), Optional.FromNullable(dto.AcoustId), Optional.FromNullable(dto.ReplayGainTrackGain), diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/ShuffleTrackRowDtoMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/ShuffleTrackRowDtoMapping.cs new file mode 100644 index 00000000..1850f39f --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/ShuffleTrackRowDtoMapping.cs @@ -0,0 +1,41 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; +using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; +using System.Collections.Generic; +using System.Linq; +#endregion + +namespace Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; + +/// +/// Extension methods for converting . +/// +public static class ShuffleTrackRowDtoMapping +{ + /// + /// Converts to . + /// + /// The read model to be converted. + /// The converted response. + public static ShuffleTrackResponse ToResponse(this ShuffleTrackRowDto readModel) + { + return new ShuffleTrackResponse( + readModel.TrackId, + readModel.Title, + readModel.DurationInSeconds, + readModel.AlbumId, + readModel.AlbumTitle, + readModel.ArtistId, + readModel.CoverPath); + } + + /// + /// Converts to a collection of . + /// + /// The read models to be converted. + /// The converted responses. + public static IReadOnlyList ToResponses(this IEnumerable readModels) + { + return [.. readModels.Select(readModel => readModel.ToResponse())]; + } +} diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/ShuffleTracksRequestMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/ShuffleTracksRequestMapping.cs new file mode 100644 index 00000000..83e1fd5d --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/ShuffleTracksRequestMapping.cs @@ -0,0 +1,28 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Queries.ShuffleTracks; +using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; +#endregion + +namespace Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; + +/// +/// Extension methods for converting . +/// +public static class ShuffleTracksRequestMapping +{ + /// + /// Converts to . + /// + /// The request to be converted. + /// The Id of the library the tracks are sampled from, taken from the route. + /// The converted query. + public static ShuffleTracksQuery ToQuery(this ShuffleTracksRequest request, string? libraryId) + { + return new ShuffleTracksQuery( + libraryId, + request.Count, + request.ArtistId, + request.AlbumId, + request.ExcludedTrackIds); + } +} diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackEntityMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackEntityMapping.cs index 82a08ab2..c4f755f4 100644 --- a/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackEntityMapping.cs +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackEntityMapping.cs @@ -1,4 +1,5 @@ #region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DTO.MediaConsumption; using Lumina.Application.Common.Mapping.Common.Metadata; using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; using Lumina.Contracts.DTO.Common; @@ -13,6 +14,7 @@ using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibrary using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects; using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; using Lumina.Domain.SharedKernel.Common.Enums.Common; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using System; using System.Collections.Generic; using System.Linq; @@ -27,6 +29,33 @@ namespace Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibra /// public static class TrackEntityMapping { + /// + /// Converts to the consumption history row of a music track. + /// + /// The repository entity to be converted. + /// The date and time when the track was last consumed. + /// The number of sessions of the track that count towards statistics. + /// The number of sessions of the track that completed. + /// The active duration consumed in the track, over all of its sessions, in milliseconds. + /// The path of the cover art of the album that contains the track, if available. + /// The converted consumption history row. + public static ConsumedItemDto ToDto(this TrackEntity repositoryEntity, DateTime lastConsumedOnUtc, int countedSessionCount, int completedSessionCount, long consumedDurationMilliseconds, string? coverPath) + { + return new ConsumedItemDto( + MediaKind.MusicTrack, + repositoryEntity.Id, + repositoryEntity.LibraryId, + true, + repositoryEntity.Title, + repositoryEntity.Album?.Title ?? string.Empty, + repositoryEntity.Album?.Artist?.Name ?? string.Empty, + coverPath, + lastConsumedOnUtc, + countedSessionCount, + completedSessionCount, + consumedDurationMilliseconds); + } + /// /// Converts to . /// @@ -84,6 +113,7 @@ public static class TrackEntityMapping originalLanguage, Optional.FromNullable(repositoryEntity.BitDepth), Optional.FromNullable(repositoryEntity.AudioCodec), + Optional.FromNullable(repositoryEntity.Container), Optional.FromNullable(repositoryEntity.Bitrate), Optional.FromNullable(repositoryEntity.AcoustId), Optional.FromNullable(repositoryEntity.ReplayGainTrackGain), @@ -259,7 +289,8 @@ public static class TrackEntityMapping [.. repositoryEntity.Moods.ToResponses()], [.. repositoryEntity.Isrcs.ToResponses()], [.. repositoryEntity.Contributors.Select(contributor => new MediaContributorReferenceDto(contributor.MediaContributorId, contributor.Role))], - [.. repositoryEntity.Ratings.ToResponses()]); + [.. repositoryEntity.Ratings.ToResponses()], + repositoryEntity.Container); } /// diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackMapping.cs index c666917c..60efeef1 100644 --- a/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackMapping.cs +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackMapping.cs @@ -52,6 +52,7 @@ public static class TrackMapping Channels = domainEntity.Metadata.Channels, BitDepth = domainEntity.Metadata.BitDepth.HasValue ? domainEntity.Metadata.BitDepth.Value : null, AudioCodec = domainEntity.Metadata.AudioCodec.HasValue ? domainEntity.Metadata.AudioCodec.Value : null, + Container = domainEntity.Metadata.Container.HasValue ? domainEntity.Metadata.Container.Value : null, Bitrate = domainEntity.Metadata.Bitrate.HasValue ? domainEntity.Metadata.Bitrate.Value : null, AcoustId = domainEntity.Metadata.AcoustId.HasValue ? domainEntity.Metadata.AcoustId.Value : null, ReplayGainTrackGain = domainEntity.Metadata.ReplayGainTrackGain.HasValue ? domainEntity.Metadata.ReplayGainTrackGain.Value : null, diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/UpdateTrackCommandMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/UpdateTrackCommandMapping.cs index c7ff1519..ee882104 100644 --- a/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/UpdateTrackCommandMapping.cs +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/UpdateTrackCommandMapping.cs @@ -85,7 +85,6 @@ public static class UpdateTrackCommandMapping Result updateResult = artist.UpdateTrackInAlbum( album, track, - command.Path!, metadataResult.Value, Optional.FromNullable(metadata.Disambiguation), command.TrackNumber!.Value, diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/UpdateTrackRequestMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/UpdateTrackRequestMapping.cs index 257e2bf1..62d1d6da 100644 --- a/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/UpdateTrackRequestMapping.cs +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/UpdateTrackRequestMapping.cs @@ -26,7 +26,6 @@ public static class UpdateTrackRequestMapping artistId, albumId, trackId, - request.Path, request.Metadata, request.TrackNumber, request.DiscNumber, diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/AddMediaLibraryRequestMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/AddMediaLibraryRequestMapping.cs index e02402e7..0005fa63 100644 --- a/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/AddMediaLibraryRequestMapping.cs +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/AddMediaLibraryRequestMapping.cs @@ -29,6 +29,8 @@ public static class AddMediaLibraryRequestMapping request.CanDownloadMetadataFromWeb, request.ShouldSaveMetadataInMediaDirectories, request.ShouldSkipUnchangedDirectoriesDuringScan, + request.ShouldTrackConsumptionProgress, + request.CompletionThresholdPercentage, request.PathTemplateParts?.Select(part => new LibraryPathTemplatePartDto(part.Kind, part.Representation, part.IsOptional)).ToArray() ); } diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/LibraryEntityMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/LibraryEntityMapping.cs index 70060f17..52e3d970 100644 --- a/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/LibraryEntityMapping.cs +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/LibraryEntityMapping.cs @@ -36,6 +36,8 @@ public static class LibraryEntityMapping repositoryEntity.CanDownloadMetadataFromWeb, repositoryEntity.ShouldSaveMetadataInMediaDirectories, repositoryEntity.ShouldSkipUnchangedDirectoriesDuringScan, + repositoryEntity.ShouldTrackConsumptionProgress, + repositoryEntity.CompletionThresholdPercentage, [.. repositoryEntity.PathTemplateParts .OrderBy(part => part.Position) .Select(part => new LibraryPathTemplatePartResponse(part.Kind.ToString(), part.Representation, part.IsOptional))], @@ -57,6 +59,8 @@ public static class LibraryEntityMapping if (pathTemplateResult.IsFailure) return pathTemplateResult.Errors; + LibraryConsumptionSettings consumptionSettings = repositoryEntity.ToDomainValueObject(); + return Library.Create( LibraryId.Create(repositoryEntity.Id), UserId.Create(repositoryEntity.UserId), @@ -69,11 +73,24 @@ public static class LibraryEntityMapping repositoryEntity.CanDownloadMetadataFromWeb, repositoryEntity.ShouldSaveMetadataInMediaDirectories, repositoryEntity.ShouldSkipUnchangedDirectoriesDuringScan, + consumptionSettings, pathTemplateResult.Value, [.. repositoryEntity.LibraryScans.Select(libraryScan => ScanId.Create(libraryScan.Id))] ); } + /// + /// Converts the consumption settings stored on to . + /// + /// The repository entity whose consumption settings are converted. + /// The converted consumption settings. + public static LibraryConsumptionSettings ToDomainValueObject(this LibraryEntity repositoryEntity) + { + return LibraryConsumptionSettings.Create( + repositoryEntity.ShouldTrackConsumptionProgress, + Optional.FromNullable(repositoryEntity.CompletionThresholdPercentage)); + } + /// /// Builds the path template of a media library from its ordered stored parts. /// diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/LibraryMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/LibraryMapping.cs index 3d90a2a8..deeb00d9 100644 --- a/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/LibraryMapping.cs +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/LibraryMapping.cs @@ -39,6 +39,10 @@ public static class LibraryMapping CanDownloadMetadataFromWeb = domainEntity.CanDownloadMetadataFromWeb, ShouldSaveMetadataInMediaDirectories = domainEntity.ShouldSaveMetadataInMediaDirectories, ShouldSkipUnchangedDirectoriesDuringScan = domainEntity.ShouldSkipUnchangedDirectoriesDuringScan, + ShouldTrackConsumptionProgress = domainEntity.ConsumptionSettings.ShouldTrackConsumptionProgress, + CompletionThresholdPercentage = domainEntity.ConsumptionSettings.CompletionThresholdPercentage.HasValue + ? domainEntity.ConsumptionSettings.CompletionThresholdPercentage.Value + : null, LibraryScans = [.. domainEntity.ScanIds.Select(scanId => new LibraryScanEntity() { Id = scanId.Value, diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/UpdateLibraryRequestMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/UpdateLibraryRequestMapping.cs index 529bbc32..dcc62c28 100644 --- a/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/UpdateLibraryRequestMapping.cs +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/UpdateLibraryRequestMapping.cs @@ -31,6 +31,8 @@ public static class UpdateLibraryRequestMapping request.CanDownloadMetadataFromWeb, request.ShouldSaveMetadataInMediaDirectories, request.ShouldSkipUnchangedDirectoriesDuringScan, + request.ShouldTrackConsumptionProgress, + request.CompletionThresholdPercentage, request.PathTemplateParts?.Select(part => new LibraryPathTemplatePartDto(part.Kind, part.Representation, part.IsOptional)).ToArray() ); } diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookEntityMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookEntityMapping.cs index f5475a89..b3b5c3ad 100644 --- a/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookEntityMapping.cs +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookEntityMapping.cs @@ -1,5 +1,6 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Application.Common.DTO.MediaConsumption; using Lumina.Application.Common.DTO.Pagination; using Lumina.Application.Common.Mapping.Common.Metadata; using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; @@ -31,6 +32,33 @@ namespace Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.B /// public static class BookEntityMapping { + /// + /// Converts to the consumption history row of a book. + /// + /// The repository entity to be converted. + /// The date and time when the book was last consumed. + /// The number of sessions of the book that count towards statistics. + /// The number of sessions of the book that completed. + /// The active duration consumed in the book, over all of its sessions, in milliseconds. + /// The name of the author of the book, or an empty string when there is none. + /// The converted consumption history row. + public static ConsumedItemDto ToDto(this BookEntity repositoryEntity, DateTime lastConsumedOnUtc, int countedSessionCount, int completedSessionCount, long consumedDurationMilliseconds, string creatorName) + { + return new ConsumedItemDto( + MediaKind.Book, + repositoryEntity.Id, + repositoryEntity.LibraryId, + true, + repositoryEntity.Title, + string.Empty, + creatorName, + repositoryEntity.Artwork.FirstOrDefault(artwork => artwork.ArtworkType == ArtworkType.Cover)?.FileName, + lastConsumedOnUtc, + countedSessionCount, + completedSessionCount, + consumedDurationMilliseconds); + } + /// /// Converts to . /// diff --git a/src/Lumina.Application/Common/Mapping/Playlists/AddPlaylistEntriesRequestMapping.cs b/src/Lumina.Application/Common/Mapping/Playlists/AddPlaylistEntriesRequestMapping.cs new file mode 100644 index 00000000..c5df9221 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/Playlists/AddPlaylistEntriesRequestMapping.cs @@ -0,0 +1,23 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.Playlists.Commands.AddPlaylistEntries; +using Lumina.Contracts.Requests.Playlists; +#endregion + +namespace Lumina.Application.Common.Mapping.Playlists; + +/// +/// Extension methods for converting . +/// +public static class AddPlaylistEntriesRequestMapping +{ + /// + /// Converts to . + /// + /// The request to be converted. + /// The Id of the playlist, taken from the route. + /// The converted command. + public static AddPlaylistEntriesCommand ToCommand(this AddPlaylistEntriesRequest request, string? playlistId) + { + return new AddPlaylistEntriesCommand(playlistId, request.TrackIds); + } +} diff --git a/src/Lumina.Application/Common/Mapping/Playlists/AddPlaylistEntryRequestMapping.cs b/src/Lumina.Application/Common/Mapping/Playlists/AddPlaylistEntryRequestMapping.cs new file mode 100644 index 00000000..7ffcd8c2 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/Playlists/AddPlaylistEntryRequestMapping.cs @@ -0,0 +1,23 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.Playlists.Commands.AddPlaylistEntry; +using Lumina.Contracts.Requests.Playlists; +#endregion + +namespace Lumina.Application.Common.Mapping.Playlists; + +/// +/// Extension methods for converting . +/// +public static class AddPlaylistEntryRequestMapping +{ + /// + /// Converts to . + /// + /// The request to be converted. + /// The Id of the playlist, taken from the route. + /// The converted command. + public static AddPlaylistEntryCommand ToCommand(this AddPlaylistEntryRequest request, string? playlistId) + { + return new AddPlaylistEntryCommand(playlistId, request.TrackId); + } +} diff --git a/src/Lumina.Application/Common/Mapping/Playlists/AddPlaylistScopeEntriesRequestMapping.cs b/src/Lumina.Application/Common/Mapping/Playlists/AddPlaylistScopeEntriesRequestMapping.cs new file mode 100644 index 00000000..10b678db --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/Playlists/AddPlaylistScopeEntriesRequestMapping.cs @@ -0,0 +1,23 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.Playlists.Commands.AddPlaylistScopeEntries; +using Lumina.Contracts.Requests.Playlists; +#endregion + +namespace Lumina.Application.Common.Mapping.Playlists; + +/// +/// Extension methods for converting . +/// +public static class AddPlaylistScopeEntriesRequestMapping +{ + /// + /// Converts to . + /// + /// The request to be converted. + /// The Id of the playlist, taken from the route. + /// The converted command. + public static AddPlaylistScopeEntriesCommand ToCommand(this AddPlaylistScopeEntriesRequest request, string? playlistId) + { + return new AddPlaylistScopeEntriesCommand(playlistId, request.LibraryId, request.ArtistId, request.AlbumId); + } +} diff --git a/src/Lumina.Application/Common/Mapping/Playlists/CreatePlaylistRequestMapping.cs b/src/Lumina.Application/Common/Mapping/Playlists/CreatePlaylistRequestMapping.cs new file mode 100644 index 00000000..83d07c2d --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/Playlists/CreatePlaylistRequestMapping.cs @@ -0,0 +1,22 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.Playlists.Commands.CreatePlaylist; +using Lumina.Contracts.Requests.Playlists; +#endregion + +namespace Lumina.Application.Common.Mapping.Playlists; + +/// +/// Extension methods for converting . +/// +public static class CreatePlaylistRequestMapping +{ + /// + /// Converts to . + /// + /// The request to be converted. + /// The converted command. + public static CreatePlaylistCommand ToCommand(this CreatePlaylistRequest request) + { + return new CreatePlaylistCommand(request.Name, request.Description, request.Type); + } +} diff --git a/src/Lumina.Application/Common/Mapping/Playlists/GetPlaylistRequestMapping.cs b/src/Lumina.Application/Common/Mapping/Playlists/GetPlaylistRequestMapping.cs new file mode 100644 index 00000000..a2c0ac60 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/Playlists/GetPlaylistRequestMapping.cs @@ -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; + +/// +/// Extension methods for converting . +/// +public static class GetPlaylistRequestMapping +{ + /// + /// Converts to . + /// + /// The request to be converted. + /// The Id of the playlist whose entries are retrieved, taken from the route. + /// The converted query. + 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); + } +} diff --git a/src/Lumina.Application/Common/Mapping/Playlists/MovePlaylistEntryRequestMapping.cs b/src/Lumina.Application/Common/Mapping/Playlists/MovePlaylistEntryRequestMapping.cs new file mode 100644 index 00000000..79f0ff93 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/Playlists/MovePlaylistEntryRequestMapping.cs @@ -0,0 +1,24 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.Playlists.Commands.MovePlaylistEntry; +using Lumina.Contracts.Requests.Playlists; +#endregion + +namespace Lumina.Application.Common.Mapping.Playlists; + +/// +/// Extension methods for converting . +/// +public static class MovePlaylistEntryRequestMapping +{ + /// + /// Converts to . + /// + /// The request to be converted. + /// The Id of the playlist, taken from the route. + /// The Id of the entry to move, taken from the route. + /// The converted command. + public static MovePlaylistEntryCommand ToCommand(this MovePlaylistEntryRequest request, string? playlistId, string? playlistEntryId) + { + return new MovePlaylistEntryCommand(playlistId, playlistEntryId, request.TargetPosition); + } +} diff --git a/src/Lumina.Application/Common/Mapping/Playlists/PlaylistDetailsDtoMapping.cs b/src/Lumina.Application/Common/Mapping/Playlists/PlaylistDetailsDtoMapping.cs new file mode 100644 index 00000000..b22d8a57 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/Playlists/PlaylistDetailsDtoMapping.cs @@ -0,0 +1,29 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DTO.Playlists; +using Lumina.Contracts.Responses.Playlists; +#endregion + +namespace Lumina.Application.Common.Mapping.Playlists; + +/// +/// Extension methods for converting . +/// +public static class PlaylistDetailsDtoMapping +{ + /// + /// Converts to . + /// + /// The playlist details data to be converted. + /// The converted response. + public static PlaylistResponse ToResponse(this PlaylistDetailsDto data) + { + return new PlaylistResponse( + data.Playlist.Id, + data.Playlist.Name, + data.Playlist.Description, + data.Playlist.Type, + data.Entries.ToResponses(), + data.Playlist.CreatedOnUtc, + data.Playlist.UpdatedOnUtc); + } +} diff --git a/src/Lumina.Application/Common/Mapping/Playlists/PlaylistEntityMapping.cs b/src/Lumina.Application/Common/Mapping/Playlists/PlaylistEntityMapping.cs new file mode 100644 index 00000000..5a34e182 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/Playlists/PlaylistEntityMapping.cs @@ -0,0 +1,49 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Playlists; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.ExternalIdentifiers.UserManagementBoundedContext.UserAggregate; +using Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate; +using Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate.Entities; +using Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate.ValueObjects; +using System; +using System.Collections.Generic; +using System.Linq; +#endregion + +namespace Lumina.Application.Common.Mapping.Playlists; + +/// +/// Extension methods for converting . +/// +public static class PlaylistEntityMapping +{ + /// + /// Converts to . + /// + /// The repository entity to be converted. + /// + /// An containing either a successfully converted , or an error message. + /// + public static Result ToDomainEntity(this PlaylistEntity repositoryEntity) + { + List entries = []; + // The entries are ordered by their position, because the order of a navigation collection is not guaranteed by the storage medium. + foreach (PlaylistEntryEntity entryEntity in repositoryEntity.Entries.OrderBy(entry => entry.Position)) + { + Result convertEntryResult = entryEntity.ToDomainEntity(); + if (convertEntryResult.IsFailure) + return convertEntryResult.Errors; + entries.Add(convertEntryResult.Value); + } + + return Playlist.Create( + PlaylistId.Create(repositoryEntity.Id), + UserId.Create(repositoryEntity.UserId), + repositoryEntity.Name, + Optional.FromNullable(repositoryEntity.Description), + repositoryEntity.Type, + entries, + repositoryEntity.CreatedOnUtc, + Optional.FromNullable(repositoryEntity.UpdatedOnUtc)); + } +} diff --git a/src/Lumina.Application/Common/Mapping/Playlists/PlaylistEntryDtoMapping.cs b/src/Lumina.Application/Common/Mapping/Playlists/PlaylistEntryDtoMapping.cs new file mode 100644 index 00000000..77a33dbc --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/Playlists/PlaylistEntryDtoMapping.cs @@ -0,0 +1,71 @@ +#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; + +/// +/// Extension methods for converting . +/// +public static class PlaylistEntryDtoMapping +{ + /// + /// Converts to . + /// + /// The playlist entry data to be converted. + /// The converted response. + public static PlaylistEntryResponse ToResponse(this PlaylistEntryDto data) + { + if (data.Display is null) + return new PlaylistEntryResponse( + data.Entry.Id, + data.Entry.MediaItemId, + data.Entry.MediaItemType, + data.DisplayPosition, + Guid.Empty, + Guid.Empty, + Guid.Empty, + string.Empty, + string.Empty, + string.Empty, + 0, + null); + + PlaylistEntryDisplayDto display = data.Display; + return new PlaylistEntryResponse( + data.Entry.Id, + data.Entry.MediaItemId, + data.Entry.MediaItemType, + data.DisplayPosition, + display.LibraryId, + display.AlbumId, + display.ArtistId, + display.TrackTitle, + display.AlbumTitle, + display.ArtistName, + display.DurationInSeconds, + display.CoverPath); + } + + /// + /// Converts to a paginated collection of . + /// + /// The paginated playlist entry data to be converted. + /// The converted paginated responses. + public static PaginatedResponse ToResponses(this PaginatedResultDto data) + { + return new PaginatedResponse + { + Data = [.. data.Data.Select(entry => entry.ToResponse())], + CurrentPage = data.CurrentPage, + PerPage = data.PerPage, + Count = data.Count, + NumberOfPages = data.NumberOfPages + }; + } +} diff --git a/src/Lumina.Application/Common/Mapping/Playlists/PlaylistEntryEntityMapping.cs b/src/Lumina.Application/Common/Mapping/Playlists/PlaylistEntryEntityMapping.cs new file mode 100644 index 00000000..ca1c256c --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/Playlists/PlaylistEntryEntityMapping.cs @@ -0,0 +1,31 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Playlists; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.ExternalIdentifiers.MediaLibraryBoundedContext.MediaItemAggregate; +using Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate.Entities; +using Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate.ValueObjects; +#endregion + +namespace Lumina.Application.Common.Mapping.Playlists; + +/// +/// Extension methods for converting . +/// +public static class PlaylistEntryEntityMapping +{ + /// + /// Converts to . + /// + /// The repository entity to be converted. + /// + /// An containing either a successfully converted , or an error message. + /// + public static Result ToDomainEntity(this PlaylistEntryEntity repositoryEntity) + { + return PlaylistEntry.Create( + PlaylistEntryId.Create(repositoryEntity.Id), + MediaItemId.Create(repositoryEntity.MediaItemId), + repositoryEntity.MediaItemType, + repositoryEntity.Position); + } +} diff --git a/src/Lumina.Application/Common/Mapping/Playlists/PlaylistEntryMapping.cs b/src/Lumina.Application/Common/Mapping/Playlists/PlaylistEntryMapping.cs new file mode 100644 index 00000000..81a82715 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/Playlists/PlaylistEntryMapping.cs @@ -0,0 +1,31 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Playlists; +using Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate.Entities; +using System; +#endregion + +namespace Lumina.Application.Common.Mapping.Playlists; + +/// +/// Extension methods for converting . +/// +public static class PlaylistEntryMapping +{ + /// + /// Converts to . + /// + /// The domain entity to be converted. + /// The Id of the playlist that owns the entry. + /// The converted repository entity. + public static PlaylistEntryEntity ToRepositoryEntity(this PlaylistEntry domainEntity, Guid playlistId) + { + return new PlaylistEntryEntity + { + Id = domainEntity.Id.Value, + PlaylistId = playlistId, + MediaItemId = domainEntity.MediaItemId.Value, + MediaItemType = domainEntity.MediaItemType, + Position = domainEntity.Position + }; + } +} diff --git a/src/Lumina.Application/Common/Mapping/Playlists/PlaylistMapping.cs b/src/Lumina.Application/Common/Mapping/Playlists/PlaylistMapping.cs new file mode 100644 index 00000000..19c4c591 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/Playlists/PlaylistMapping.cs @@ -0,0 +1,40 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Playlists; +using Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate; +using System; +using System.Linq; +#endregion + +namespace Lumina.Application.Common.Mapping.Playlists; + +/// +/// Extension methods for converting . +/// +public static class PlaylistMapping +{ + /// + /// Converts to . + /// + /// The domain entity to be converted. + /// The converted repository entity. + public static PlaylistEntity ToRepositoryEntity(this Playlist domainEntity) + { + return new PlaylistEntity + { + Id = domainEntity.Id.Value, + UserId = domainEntity.UserId.Value, + Name = domainEntity.Name, + Description = domainEntity.Description.HasValue ? domainEntity.Description.Value : null, + Type = domainEntity.Type, + Entries = [.. domainEntity.Entries + .OrderBy(entry => entry.Position) + .Select(entry => entry.ToRepositoryEntity(domainEntity.Id.Value))], + // This is the correct count for an insert. The update path deliberately keeps the stored count, because details edits never load the entries and must not overwrite it. + EntryCount = domainEntity.Entries.Count, + CreatedOnUtc = domainEntity.CreatedOnUtc, + CreatedBy = Guid.Empty, + UpdatedOnUtc = domainEntity.UpdatedOnUtc.HasValue ? domainEntity.UpdatedOnUtc.Value : null, + UpdatedBy = null + }; + } +} diff --git a/src/Lumina.Application/Common/Mapping/Playlists/PlaylistSummaryDtoMapping.cs b/src/Lumina.Application/Common/Mapping/Playlists/PlaylistSummaryDtoMapping.cs new file mode 100644 index 00000000..d141ca57 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/Playlists/PlaylistSummaryDtoMapping.cs @@ -0,0 +1,29 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DTO.Playlists; +using Lumina.Contracts.Responses.Playlists; +#endregion + +namespace Lumina.Application.Common.Mapping.Playlists; + +/// +/// Extension methods for converting . +/// +public static class PlaylistSummaryDtoMapping +{ + /// + /// Converts to . + /// + /// The data transfer object to be converted. + /// The converted response. + public static PlaylistSummaryResponse ToResponse(this PlaylistSummaryDto dto) + { + return new PlaylistSummaryResponse( + dto.Id, + dto.Name, + dto.Description, + dto.Type, + dto.EntryCount, + dto.CreatedOnUtc, + dto.UpdatedOnUtc); + } +} diff --git a/src/Lumina.Application/Common/Mapping/Playlists/UpdatePlaylistRequestMapping.cs b/src/Lumina.Application/Common/Mapping/Playlists/UpdatePlaylistRequestMapping.cs new file mode 100644 index 00000000..5d36d529 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/Playlists/UpdatePlaylistRequestMapping.cs @@ -0,0 +1,23 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.Playlists.Commands.UpdatePlaylist; +using Lumina.Contracts.Requests.Playlists; +#endregion + +namespace Lumina.Application.Common.Mapping.Playlists; + +/// +/// Extension methods for converting . +/// +public static class UpdatePlaylistRequestMapping +{ + /// + /// Converts to . + /// + /// The request to be converted. + /// The Id of the playlist, taken from the route. + /// The converted command. + public static UpdatePlaylistCommand ToCommand(this UpdatePlaylistRequest request, string? playlistId) + { + return new UpdatePlaylistCommand(playlistId, request.Name, request.Description); + } +} diff --git a/src/Lumina.Application/Common/Mapping/UsersManagement/Users/UpdatePlaybackStateRequestMapping.cs b/src/Lumina.Application/Common/Mapping/UsersManagement/Users/UpdatePlaybackStateRequestMapping.cs new file mode 100644 index 00000000..31e45f8a --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/UsersManagement/Users/UpdatePlaybackStateRequestMapping.cs @@ -0,0 +1,25 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.UsersManagement.Settings.Commands.UpdatePlaybackState; +using Lumina.Contracts.Requests.UsersManagement.Settings; +#endregion + +namespace Lumina.Application.Common.Mapping.UsersManagement.Users; + +/// +/// Extension methods for converting . +/// +public static class UpdatePlaybackStateRequestMapping +{ + /// + /// Converts to . + /// + /// The request to be converted. + /// The converted command. + public static UpdatePlaybackStateCommand ToCommand(this UpdatePlaybackStateRequest request) + { + return new UpdatePlaybackStateCommand( + request.Volume, + request.IsMuted + ); + } +} diff --git a/src/Lumina.Application/Common/Mapping/UsersManagement/Users/UpdateUserSettingsRequestMapping.cs b/src/Lumina.Application/Common/Mapping/UsersManagement/Users/UpdateUserSettingsRequestMapping.cs index a936d1b2..098767b0 100644 --- a/src/Lumina.Application/Common/Mapping/UsersManagement/Users/UpdateUserSettingsRequestMapping.cs +++ b/src/Lumina.Application/Common/Mapping/UsersManagement/Users/UpdateUserSettingsRequestMapping.cs @@ -25,7 +25,21 @@ public static class UpdateUserSettingsRequestMapping request.ShouldAggregateMetadataWhenMissing, request.ShouldAggregateArtworkWhenMissing, request.ShouldRenderPdfAsImages, - request.ShouldPreserveBookStyles + request.ShouldPreserveBookStyles, + request.ShouldKeepDownloadingWhilePaused, + request.ShouldAutoplay, + request.IsGaplessPlaybackEnabled, + request.ReplayGainMode, + request.StreamingQuality, + request.VuMeterOrientation, + request.VuMeterSegmentCount, + request.VuMeterSegmentGap, + request.VuMeterMediumThreshold, + request.VuMeterHighThreshold, + request.VuMeterShowPeak, + request.VuMeterPeakHoldDurationInMilliseconds, + request.VuMeterReleasePerSecond, + request.VuMeterPeakReleasePerSecond ); } } diff --git a/src/Lumina.Application/Common/Mapping/UsersManagement/Users/UserSettingsEntityMapping.cs b/src/Lumina.Application/Common/Mapping/UsersManagement/Users/UserSettingsEntityMapping.cs index 4da52a6f..ab434cdd 100644 --- a/src/Lumina.Application/Common/Mapping/UsersManagement/Users/UserSettingsEntityMapping.cs +++ b/src/Lumina.Application/Common/Mapping/UsersManagement/Users/UserSettingsEntityMapping.cs @@ -33,7 +33,23 @@ public static class UserSettingsEntityMapping repositoryEntity.ShouldAggregateMetadataWhenMissing, repositoryEntity.ShouldAggregateArtworkWhenMissing, repositoryEntity.ShouldRenderPdfAsImages, - repositoryEntity.ShouldPreserveBookStyles + repositoryEntity.ShouldPreserveBookStyles, + repositoryEntity.ShouldKeepDownloadingWhilePaused, + repositoryEntity.ShouldAutoplay, + repositoryEntity.IsGaplessPlaybackEnabled, + repositoryEntity.ReplayGainMode, + repositoryEntity.StreamingQuality, + repositoryEntity.VuMeterOrientation, + repositoryEntity.VuMeterSegmentCount, + repositoryEntity.VuMeterSegmentGap, + repositoryEntity.VuMeterMediumThreshold, + repositoryEntity.VuMeterHighThreshold, + repositoryEntity.VuMeterShowPeak, + repositoryEntity.VuMeterPeakHoldDurationInMilliseconds, + repositoryEntity.VuMeterReleasePerSecond, + repositoryEntity.VuMeterPeakReleasePerSecond, + repositoryEntity.Volume, + repositoryEntity.IsMuted ); } @@ -53,7 +69,21 @@ public static class UserSettingsEntityMapping repositoryEntity.ShouldAggregateMetadataWhenMissing, repositoryEntity.ShouldAggregateArtworkWhenMissing, repositoryEntity.ShouldRenderPdfAsImages, - repositoryEntity.ShouldPreserveBookStyles + repositoryEntity.ShouldPreserveBookStyles, + repositoryEntity.ShouldKeepDownloadingWhilePaused, + repositoryEntity.ShouldAutoplay, + repositoryEntity.IsGaplessPlaybackEnabled, + repositoryEntity.ReplayGainMode, + repositoryEntity.StreamingQuality, + repositoryEntity.VuMeterOrientation, + repositoryEntity.VuMeterSegmentCount, + repositoryEntity.VuMeterSegmentGap, + repositoryEntity.VuMeterMediumThreshold, + repositoryEntity.VuMeterHighThreshold, + repositoryEntity.VuMeterShowPeak, + repositoryEntity.VuMeterPeakHoldDurationInMilliseconds, + repositoryEntity.VuMeterReleasePerSecond, + repositoryEntity.VuMeterPeakReleasePerSecond ); } } diff --git a/src/Lumina.Application/Common/Mapping/UsersManagement/Users/UserSettingsMapping.cs b/src/Lumina.Application/Common/Mapping/UsersManagement/Users/UserSettingsMapping.cs index aabba107..5ad4a7d5 100644 --- a/src/Lumina.Application/Common/Mapping/UsersManagement/Users/UserSettingsMapping.cs +++ b/src/Lumina.Application/Common/Mapping/UsersManagement/Users/UserSettingsMapping.cs @@ -29,7 +29,23 @@ public static class UserSettingsMapping ShouldAggregateMetadataWhenMissing = domainEntity.ShouldAggregateMetadataWhenMissing, ShouldAggregateArtworkWhenMissing = domainEntity.ShouldAggregateArtworkWhenMissing, ShouldRenderPdfAsImages = domainEntity.ShouldRenderPdfAsImages, - ShouldPreserveBookStyles = domainEntity.ShouldPreserveBookStyles + ShouldPreserveBookStyles = domainEntity.ShouldPreserveBookStyles, + ShouldKeepDownloadingWhilePaused = domainEntity.ShouldKeepDownloadingWhilePaused, + ShouldAutoplay = domainEntity.ShouldAutoplay, + IsGaplessPlaybackEnabled = domainEntity.IsGaplessPlaybackEnabled, + ReplayGainMode = domainEntity.ReplayGainMode, + StreamingQuality = domainEntity.StreamingQuality, + VuMeterOrientation = domainEntity.VuMeterOrientation, + VuMeterSegmentCount = domainEntity.VuMeterSegmentCount, + VuMeterSegmentGap = domainEntity.VuMeterSegmentGap, + VuMeterMediumThreshold = domainEntity.VuMeterMediumThreshold, + VuMeterHighThreshold = domainEntity.VuMeterHighThreshold, + VuMeterShowPeak = domainEntity.VuMeterShowPeak, + VuMeterPeakHoldDurationInMilliseconds = domainEntity.VuMeterPeakHoldDurationInMilliseconds, + VuMeterReleasePerSecond = domainEntity.VuMeterReleasePerSecond, + VuMeterPeakReleasePerSecond = domainEntity.VuMeterPeakReleasePerSecond, + Volume = domainEntity.Volume, + IsMuted = domainEntity.IsMuted }; } @@ -49,7 +65,21 @@ public static class UserSettingsMapping domainEntity.ShouldAggregateMetadataWhenMissing, domainEntity.ShouldAggregateArtworkWhenMissing, domainEntity.ShouldRenderPdfAsImages, - domainEntity.ShouldPreserveBookStyles + domainEntity.ShouldPreserveBookStyles, + domainEntity.ShouldKeepDownloadingWhilePaused, + domainEntity.ShouldAutoplay, + domainEntity.IsGaplessPlaybackEnabled, + domainEntity.ReplayGainMode, + domainEntity.StreamingQuality, + domainEntity.VuMeterOrientation, + domainEntity.VuMeterSegmentCount, + domainEntity.VuMeterSegmentGap, + domainEntity.VuMeterMediumThreshold, + domainEntity.VuMeterHighThreshold, + domainEntity.VuMeterShowPeak, + domainEntity.VuMeterPeakHoldDurationInMilliseconds, + domainEntity.VuMeterReleasePerSecond, + domainEntity.VuMeterPeakReleasePerSecond ); } } diff --git a/src/Lumina.Application/Common/Telemetry/TelemetryCommandHandlerDecorator.cs b/src/Lumina.Application/Common/Telemetry/TelemetryCommandHandlerDecorator.cs index 29123465..d71c82a1 100644 --- a/src/Lumina.Application/Common/Telemetry/TelemetryCommandHandlerDecorator.cs +++ b/src/Lumina.Application/Common/Telemetry/TelemetryCommandHandlerDecorator.cs @@ -36,7 +36,7 @@ public class TelemetryCommandHandlerDecorator : ICommandHandl /// Handles the specified command, emitting telemetry around the execution of the wrapped handler. /// /// The command to handle. - /// Token to monitor for cancellation requests. + /// Cancellation token that can be used to stop the execution. /// A task that represents the asynchronous operation, containing the result of the command execution. public async Task HandleAsync(TCommand command, CancellationToken cancellationToken) { diff --git a/src/Lumina.Application/Common/Telemetry/TelemetryDomainEventHandlerDecorator.cs b/src/Lumina.Application/Common/Telemetry/TelemetryDomainEventHandlerDecorator.cs index 02e96c1f..99171558 100644 --- a/src/Lumina.Application/Common/Telemetry/TelemetryDomainEventHandlerDecorator.cs +++ b/src/Lumina.Application/Common/Telemetry/TelemetryDomainEventHandlerDecorator.cs @@ -35,7 +35,7 @@ public class TelemetryDomainEventHandlerDecorator : IDomainEventHa /// Handles the specified domain event, emitting telemetry around the execution of the wrapped handler. /// /// The domain event to handle. - /// Token to monitor for cancellation requests. + /// Cancellation token that can be used to stop the execution. /// A task that represents the asynchronous operation. public async ValueTask HandleAsync(TDomainEvent domainEvent, CancellationToken cancellationToken) { diff --git a/src/Lumina.Application/Common/Telemetry/TelemetryQueryHandlerDecorator.cs b/src/Lumina.Application/Common/Telemetry/TelemetryQueryHandlerDecorator.cs index f5529bb6..5712d6f2 100644 --- a/src/Lumina.Application/Common/Telemetry/TelemetryQueryHandlerDecorator.cs +++ b/src/Lumina.Application/Common/Telemetry/TelemetryQueryHandlerDecorator.cs @@ -36,7 +36,7 @@ public class TelemetryQueryHandlerDecorator : IQueryHandler /// The query to handle. - /// Token to monitor for cancellation requests. + /// Cancellation token that can be used to stop the execution. /// A task that represents the asynchronous operation, containing the result of the query execution. public async Task HandleAsync(TQuery query, CancellationToken cancellationToken) { diff --git a/src/Lumina.Application/Common/Utilities/AudioFileFormatUtilities.cs b/src/Lumina.Application/Common/Utilities/AudioFileFormatUtilities.cs new file mode 100644 index 00000000..242edcf5 --- /dev/null +++ b/src/Lumina.Application/Common/Utilities/AudioFileFormatUtilities.cs @@ -0,0 +1,40 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; +using System; +using System.IO; +#endregion + +namespace Lumina.Application.Common.Utilities; + +/// +/// Provides helpers for the enumeration. +/// +public static class AudioFileFormatUtilities +{ + /// + /// Gets the audio file format of the file stored at the provided , derived from its file extension. + /// + /// The path of the audio file whose file format is resolved. + /// The audio file format of the file, or when the extension is not a recognized audio extension. + public static AudioFileFormat ToAudioFileFormat(this string filePath) + { + return Path.GetExtension(filePath).ToLowerInvariant() switch + { + ".mp3" => AudioFileFormat.MP3, + ".flac" => AudioFileFormat.FLAC, + ".m4a" => AudioFileFormat.M4A, + ".aac" => AudioFileFormat.AAC, + ".ogg" => AudioFileFormat.OGG, + ".opus" => AudioFileFormat.OPUS, + ".wav" => AudioFileFormat.WAV, + ".wma" => AudioFileFormat.WMA, + ".aiff" or ".aif" => AudioFileFormat.AIFF, + ".ape" => AudioFileFormat.APE, + ".wv" => AudioFileFormat.WAVPACK, + ".dsf" => AudioFileFormat.DSF, + ".dff" => AudioFileFormat.DFF, + ".mka" => AudioFileFormat.MATROSKA, + _ => AudioFileFormat.None + }; + } +} diff --git a/src/Lumina.Application/Common/Utilities/DurationUtilities.cs b/src/Lumina.Application/Common/Utilities/DurationUtilities.cs new file mode 100644 index 00000000..c6702238 --- /dev/null +++ b/src/Lumina.Application/Common/Utilities/DurationUtilities.cs @@ -0,0 +1,23 @@ +#region ========================================================================= USING ===================================================================================== +using System; +#endregion + +namespace Lumina.Application.Common.Utilities; + +/// +/// Extension methods for converting stored duration values to . +/// +public static class DurationUtilities +{ + /// + /// Converts a duration stored as whole milliseconds to a , clamped to the largest value a can + /// represent so that an accumulated total above that limit does not throw. + /// + /// The duration, in milliseconds. + /// The duration, clamped to when it exceeds the representable range. + public static TimeSpan ToClampedTimeSpan(this long milliseconds) + { + long maximumMilliseconds = TimeSpan.MaxValue.Ticks / TimeSpan.TicksPerMillisecond; + return TimeSpan.FromMilliseconds(Math.Min(milliseconds, maximumMilliseconds)); + } +} diff --git a/src/Lumina.Application/Common/Utilities/FavoriteMediaKindExtensions.cs b/src/Lumina.Application/Common/Utilities/FavoriteMediaKindExtensions.cs new file mode 100644 index 00000000..cc424d97 --- /dev/null +++ b/src/Lumina.Application/Common/Utilities/FavoriteMediaKindExtensions.cs @@ -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; + +/// +/// Extension methods for the enumeration. +/// +public static class FavoriteMediaKindExtensions +{ + /// + /// Gets the error that reports that a media item of does not exist. + /// + /// The kind of the media item that was not found. + /// The not found error specific to the media kind, or the not supported error when the media kind cannot be favorited yet. + 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 + }; + } +} diff --git a/src/Lumina.Application/Common/Utilities/ValidatorUtilities.cs b/src/Lumina.Application/Common/Utilities/ValidatorUtilities.cs index c0c5d385..27bc9a0e 100644 --- a/src/Lumina.Application/Common/Utilities/ValidatorUtilities.cs +++ b/src/Lumina.Application/Common/Utilities/ValidatorUtilities.cs @@ -2,6 +2,7 @@ using Lumina.Application.Common.Infrastructure.Validation; using System; using System.Collections; +using System.Linq; using System.Text.RegularExpressions; #endregion @@ -174,6 +175,26 @@ public static class ValidatorUtilities return ruleBuilder.Must(value => !value.HasValue || value.Value >= valueToCompare); } + /// + /// Defines a validation rule that ensures the nullable double property is greater than or equal to the value another property of the request selects. + /// + /// + /// If either the property or the selected comparison value is , this rule passes (use + /// to check for missing values). + /// + /// The type of the request being validated. + /// The rule builder instance. + /// A function that selects the value the property must be greater than or equal to. + /// The current instance for method chaining. + public static IRuleBuilder GreaterThanOrEqualTo(this IRuleBuilder ruleBuilder, Func comparisonSelector) + { + return ruleBuilder.Must((request, value) => + { + double? comparisonValue = comparisonSelector(request); + return !value.HasValue || !comparisonValue.HasValue || value.Value >= comparisonValue.Value; + }); + } + /// /// Defines a validation rule that ensures the property is not . /// @@ -238,6 +259,23 @@ public static class ValidatorUtilities return ruleBuilder.Must(value => value.HasValue && Enum.IsDefined(value.Value)); } + /// + /// Defines a validation rule that ensures a textual enum value is either or the name of a defined member of the specified + /// enumeration type. + /// + /// + /// Only the member names of the enumeration are accepted, so a numeric value is rejected even when it is a defined member. A + /// value represents an omitted optional filter and passes. + /// + /// The type of the request being validated. + /// The type of the enumeration. + /// The rule builder instance. + /// The current instance for method chaining. + public static IRuleBuilder IsInEnum(this IRuleBuilder ruleBuilder) where TEnum : struct, Enum + { + return ruleBuilder.Must(value => value is null || Enum.GetNames().Contains(value, StringComparer.OrdinalIgnoreCase)); + } + /// /// Defines a validation rule that ensures the string property does not exceed the specified maximum length. /// @@ -365,6 +403,22 @@ public static class ValidatorUtilities return ruleBuilder.Must(value => !value.HasValue || (value.Value >= minimumValue && value.Value <= maximumValue)); } + /// + /// Defines a validation rule that ensures the nullable double property is within the specified inclusive range. + /// + /// + /// If the property is , this rule passes (use to check for missing values). + /// + /// The type of the request being validated. + /// The rule builder instance. + /// The minimum allowed value of the property. + /// The maximum allowed value of the property. + /// The current instance for method chaining. + public static IRuleBuilder InclusiveBetween(this IRuleBuilder ruleBuilder, double minimumValue, double maximumValue) + { + return ruleBuilder.Must(value => !value.HasValue || (value.Value >= minimumValue && value.Value <= maximumValue)); + } + /// /// Defines a validation rule that ensures the property is equal to another property of the request. /// diff --git a/src/Lumina.Application/Core/Admin/Authorization/Permissions/Queries/GetPermissions/GetPermissionsQueryHandler.cs b/src/Lumina.Application/Core/Admin/Authorization/Permissions/Queries/GetPermissions/GetPermissionsQueryHandler.cs index 3ea703dc..bbc0974b 100644 --- a/src/Lumina.Application/Core/Admin/Authorization/Permissions/Queries/GetPermissions/GetPermissionsQueryHandler.cs +++ b/src/Lumina.Application/Core/Admin/Authorization/Permissions/Queries/GetPermissions/GetPermissionsQueryHandler.cs @@ -57,7 +57,7 @@ public class GetPermissionsQueryHandler : IQueryHandler> getPermissionsResult = await _unitOfWork.PermissionRepository.GetAllAsync(cancellationToken: cancellationToken).ConfigureAwait(false); diff --git a/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/AddRole/AddRoleCommandHandler.cs b/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/AddRole/AddRoleCommandHandler.cs index aeeaf41e..69183552 100644 --- a/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/AddRole/AddRoleCommandHandler.cs +++ b/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/AddRole/AddRoleCommandHandler.cs @@ -1,8 +1,6 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.CQRS; using Lumina.Application.Common.DataAccess.Entities.Authorization; -using Lumina.Application.Common.DataAccess.Repositories.Authorization; using Lumina.Application.Common.DataAccess.UoW; using Lumina.Application.Common.Errors; using Lumina.Application.Common.Infrastructure.Authentication; @@ -10,6 +8,7 @@ using Lumina.Application.Common.Infrastructure.Authorization; using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Common.Mapping.Authorization; using Lumina.Contracts.Responses.Authorization; +using Lumina.Domain.Common.Primitives; using System; using System.Collections.Generic; using System.Linq; @@ -65,7 +64,7 @@ public class AddRoleCommandHandler : ICommandHandler +/// Command for marking a media item as a favorite of the current user. +/// +/// The kind of the media item to favorite. +/// The unique identifier of the media item to favorite. +[DebuggerDisplay("MediaKind: {MediaKind}; MediaItemId: {MediaItemId}")] +public record AddFavoriteCommand( + FavoriteMediaKind? MediaKind, + Guid? MediaItemId +) : ICommand; diff --git a/src/Lumina.Application/Core/Favorites/Commands/AddFavorite/AddFavoriteCommandHandler.cs b/src/Lumina.Application/Core/Favorites/Commands/AddFavorite/AddFavoriteCommandHandler.cs new file mode 100644 index 00000000..e5258a51 --- /dev/null +++ b/src/Lumina.Application/Core/Favorites/Commands/AddFavorite/AddFavoriteCommandHandler.cs @@ -0,0 +1,154 @@ +#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; + +/// +/// Handler for the command to mark a media item as a favorite of the current user. +/// +public class AddFavoriteCommandHandler : ICommandHandler> +{ + private readonly IUnitOfWork _unitOfWork; + private readonly ICurrentUserService _currentUserService; + private readonly IAuthorizationService _authorizationService; + private readonly IDomainEventsQueue _domainEventsQueue; + private readonly IValidator _validator; + + /// + /// Initializes a new instance of the class. + /// + /// Injected unit of work for interacting with the data access layer repositories. + /// Injected service to retrieve the current user information. + /// Injected service for authorization related functionality. + /// Injected service for the queue of domain events. + /// Injected validator for application validation rules. + public AddFavoriteCommandHandler( + IUnitOfWork unitOfWork, + ICurrentUserService currentUserService, + IAuthorizationService authorizationService, + IDomainEventsQueue domainEventsQueue, + IValidator validator) + { + _unitOfWork = unitOfWork; + _currentUserService = currentUserService; + _authorizationService = authorizationService; + _domainEventsQueue = domainEventsQueue; + _validator = validator; + } + + /// + /// Handles the command to mark a media item as a favorite of the current user. + /// + /// The command to be handled. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either the favorite of the current user on the media item, or an error message. + /// + public async Task> HandleAsync(AddFavoriteCommand command, CancellationToken cancellationToken) + { + List validationResult = _validator.Validate(command); + if (validationResult.Count > 0) + return validationResult; + + // An authenticated request must always carry a user identity. + Guid? currentUserId = _currentUserService.UserId; + if (currentUserId is null) + return ApplicationErrors.Authorization.NotAuthorized; + Guid userId = currentUserId.Value; + + // The validator guarantees that the 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 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( + 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 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 createFavoriteResult = Favorite.Create(UserId.Create(userId), MediaItemId.Create(mediaItemId), mediaKind); + if (createFavoriteResult.IsFailure) + return createFavoriteResult.Errors; + Favorite favorite = createFavoriteResult.Value; + + Result insertResult = await _unitOfWork.FavoriteRepository.InsertAsync(favorite.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false); + if (insertResult.IsFailure) + return insertResult.Errors; + + Result 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 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(); + } + + // The persisted row is read back, so the response carries the timestamps the auditing interceptor actually stored. + Result 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; + + // Queue any domain events, to be published after the request has completed successfully. The events are queued only after the persisted + // row has been read back, so a failed read cannot announce a favorite that the request reports as failed. + foreach (IDomainEvent domainEvent in favorite.GetDomainEvents()) + _domainEventsQueue.Enqueue(domainEvent); + + return getFavoriteResult.Value.ToResponse(); + } +} diff --git a/src/Lumina.Application/Core/Favorites/Commands/AddFavorite/AddFavoriteCommandValidator.cs b/src/Lumina.Application/Core/Favorites/Commands/AddFavorite/AddFavoriteCommandValidator.cs new file mode 100644 index 00000000..9b03a0b1 --- /dev/null +++ b/src/Lumina.Application/Core/Favorites/Commands/AddFavorite/AddFavoriteCommandValidator.cs @@ -0,0 +1,44 @@ +#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; +#endregion + +namespace Lumina.Application.Core.Favorites.Commands.AddFavorite; + +/// +/// Validates the needed validation rules for . +/// +public class AddFavoriteCommandValidator : AbstractValidator +{ + /// + /// Initializes a new instance of the class. + /// + 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.MediaKind) + .Must(mediaKind => mediaKind != FavoriteMediaKind.None) + .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); + } +} diff --git a/src/Lumina.Application/Core/Favorites/Commands/RemoveFavorite/RemoveFavoriteCommand.cs b/src/Lumina.Application/Core/Favorites/Commands/RemoveFavorite/RemoveFavoriteCommand.cs new file mode 100644 index 00000000..c3cee0c3 --- /dev/null +++ b/src/Lumina.Application/Core/Favorites/Commands/RemoveFavorite/RemoveFavoriteCommand.cs @@ -0,0 +1,17 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Core.Favorites.Commands.RemoveFavorite; + +/// +/// Command for removing a media item from the favorites of the current user. +/// +/// The name of the kind of the favorited media item, taken from the route. +/// The unique identifier of the favorited media item, taken from the route. +[DebuggerDisplay("MediaKind: {MediaKind}; MediaItemId: {MediaItemId}")] +public record RemoveFavoriteCommand( + string? MediaKind, + string? MediaItemId +) : ICommand; diff --git a/src/Lumina.Application/Core/Favorites/Commands/RemoveFavorite/RemoveFavoriteCommandHandler.cs b/src/Lumina.Application/Core/Favorites/Commands/RemoveFavorite/RemoveFavoriteCommandHandler.cs new file mode 100644 index 00000000..e91e0687 --- /dev/null +++ b/src/Lumina.Application/Core/Favorites/Commands/RemoveFavorite/RemoveFavoriteCommandHandler.cs @@ -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; + +/// +/// Handler for the command to remove a media item from the favorites of the current user. +/// +public class RemoveFavoriteCommandHandler : ICommandHandler> +{ + private readonly IUnitOfWork _unitOfWork; + private readonly ICurrentUserService _currentUserService; + private readonly IDomainEventsQueue _domainEventsQueue; + private readonly IValidator _validator; + + /// + /// Initializes a new instance of the class. + /// + /// Injected unit of work for interacting with the data access layer repositories. + /// Injected service to retrieve the current user information. + /// Injected service for the queue of domain events. + /// Injected validator for application validation rules. + public RemoveFavoriteCommandHandler( + IUnitOfWork unitOfWork, + ICurrentUserService currentUserService, + IDomainEventsQueue domainEventsQueue, + IValidator validator) + { + _unitOfWork = unitOfWork; + _currentUserService = currentUserService; + _domainEventsQueue = domainEventsQueue; + _validator = validator; + } + + /// + /// Handles the command to remove a media item from the favorites of the current user. + /// + /// The command to be handled. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + public async Task> HandleAsync(RemoveFavoriteCommand command, CancellationToken cancellationToken) + { + List validationResult = _validator.Validate(command); + if (validationResult.Count > 0) + return validationResult; + + // An authenticated request must always carry a user identity. + Guid? currentUserId = _currentUserService.UserId; + if (currentUserId is null) + return ApplicationErrors.Authorization.NotAuthorized; + Guid userId = currentUserId.Value; + + // The validator guarantees that the route values are a defined media kind name and a non-empty Guid before this point. + FavoriteMediaKind mediaKind = Enum.Parse(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 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 toDomainEntityResult = getFavoriteResult.Value.ToDomainEntity(); + if (toDomainEntityResult.IsFailure) + return toDomainEntityResult.Errors; + Favorite favorite = toDomainEntityResult.Value; + + Result removeResult = favorite.Remove(); + if (removeResult.IsFailure) + return removeResult.Errors; + + Result deleteFavoriteResult = await _unitOfWork.FavoriteRepository.DeleteByIdAsync(favorite.Id.Value, cancellationToken).ConfigureAwait(false); + if (deleteFavoriteResult.IsFailure) + return deleteFavoriteResult.Errors; + + Result 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 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; + } +} diff --git a/src/Lumina.Application/Core/Favorites/Commands/RemoveFavorite/RemoveFavoriteCommandValidator.cs b/src/Lumina.Application/Core/Favorites/Commands/RemoveFavorite/RemoveFavoriteCommandValidator.cs new file mode 100644 index 00000000..b6a46775 --- /dev/null +++ b/src/Lumina.Application/Core/Favorites/Commands/RemoveFavorite/RemoveFavoriteCommandValidator.cs @@ -0,0 +1,44 @@ +#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; + +/// +/// Validates the needed validation rules for . +/// +public class RemoveFavoriteCommandValidator : AbstractValidator +{ + /// + /// Initializes a new instance of the class. + /// + public RemoveFavoriteCommandValidator() + { + RuleFor(command => command.MediaKind) + .NotEmpty() + .WithError(Errors.Favorites.FavoriteMediaKindIsInvalid); + + // Only the member names other than the default None are accepted, so a numeric route value that happens to parse as an + // enumeration value, or the explicit default value, is rejected. + RuleFor(command => command.MediaKind) + .Must(mediaKind => Enum.GetNames() + .Where(mediaKindName => !string.Equals(mediaKindName, nameof(FavoriteMediaKind.None), StringComparison.Ordinal)) + .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); + } +} diff --git a/src/Lumina.Application/Core/Favorites/Queries/GetFavoriteStatus/GetFavoriteStatusQuery.cs b/src/Lumina.Application/Core/Favorites/Queries/GetFavoriteStatus/GetFavoriteStatusQuery.cs new file mode 100644 index 00000000..a4598f0d --- /dev/null +++ b/src/Lumina.Application/Core/Favorites/Queries/GetFavoriteStatus/GetFavoriteStatusQuery.cs @@ -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; + +/// +/// Query for finding out which media items of one kind are favorites of the current user. +/// +/// The kind of the media items to check. +/// The unique identifiers of the media items to check. +[DebuggerDisplay("MediaKind: {MediaKind}")] +public record GetFavoriteStatusQuery( + FavoriteMediaKind? MediaKind, + IReadOnlyList? MediaItemIds +) : IQuery; diff --git a/src/Lumina.Application/Core/Favorites/Queries/GetFavoriteStatus/GetFavoriteStatusQueryHandler.cs b/src/Lumina.Application/Core/Favorites/Queries/GetFavoriteStatus/GetFavoriteStatusQueryHandler.cs new file mode 100644 index 00000000..f045642b --- /dev/null +++ b/src/Lumina.Application/Core/Favorites/Queries/GetFavoriteStatus/GetFavoriteStatusQueryHandler.cs @@ -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; + +/// +/// Handler for the query to find out which media items of one kind are favorites of the current user. +/// +public class GetFavoriteStatusQueryHandler : IQueryHandler> +{ + private readonly IUnitOfWork _unitOfWork; + private readonly ICurrentUserService _currentUserService; + private readonly IValidator _validator; + + /// + /// Initializes a new instance of the class. + /// + /// Injected unit of work for interacting with the data access layer repositories. + /// Injected service to retrieve the current user information. + /// Injected validator for application validation rules. + public GetFavoriteStatusQueryHandler(IUnitOfWork unitOfWork, ICurrentUserService currentUserService, IValidator validator) + { + _unitOfWork = unitOfWork; + _currentUserService = currentUserService; + _validator = validator; + } + + /// + /// Handles the query to find out which media items of one kind are favorites of the current user. + /// + /// The query to be handled. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either the requested , or an error message. + /// + public async Task> HandleAsync(GetFavoriteStatusQuery query, CancellationToken cancellationToken) + { + List validationResult = _validator.Validate(query); + if (validationResult.Count > 0) + return validationResult; + + // An authenticated request must always carry a user identity. + Guid? currentUserId = _currentUserService.UserId; + if (currentUserId is null) + return ApplicationErrors.Authorization.NotAuthorized; + Guid userId = currentUserId.Value; + + // The validator guarantees that the 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 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> getFavoritedIdsResult = await _unitOfWork.FavoriteRepository + .GetFavoritedMediaItemIdsForUserAsync(userId, mediaKind, mediaItemIds, cancellationToken).ConfigureAwait(false); + if (getFavoritedIdsResult.IsFailure) + return getFavoritedIdsResult.Errors; + + return new FavoriteStatusResponse(getFavoritedIdsResult.Value); + } +} diff --git a/src/Lumina.Application/Core/Favorites/Queries/GetFavoriteStatus/GetFavoriteStatusQueryValidator.cs b/src/Lumina.Application/Core/Favorites/Queries/GetFavoriteStatus/GetFavoriteStatusQueryValidator.cs new file mode 100644 index 00000000..bd1cce8e --- /dev/null +++ b/src/Lumina.Application/Core/Favorites/Queries/GetFavoriteStatus/GetFavoriteStatusQueryValidator.cs @@ -0,0 +1,52 @@ +#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.Queries.GetFavoriteStatus; + +/// +/// Validates the needed validation rules for . +/// +public class GetFavoriteStatusQueryValidator : AbstractValidator +{ + private const int MAXIMUM_MEDIA_ITEM_COUNT = 100; + + /// + /// Initializes a new instance of the class. + /// + 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.MediaKind) + .Must(mediaKind => mediaKind != FavoriteMediaKind.None) + .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); + } +} diff --git a/src/Lumina.Application/Core/Favorites/Queries/GetFavorites/GetFavoritesQuery.cs b/src/Lumina.Application/Core/Favorites/Queries/GetFavorites/GetFavoritesQuery.cs new file mode 100644 index 00000000..e7961535 --- /dev/null +++ b/src/Lumina.Application/Core/Favorites/Queries/GetFavorites/GetFavoritesQuery.cs @@ -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; + +/// +/// Query for getting the favorites of the current user, from the most recently favorited. +/// +/// The kind of media item to restrict the favorites to, or for every kind. +/// The object containing the requested pagination data. +[DebuggerDisplay("MediaKind: {MediaKind}")] +public record GetFavoritesQuery( + FavoriteMediaKind? MediaKind, + PaginationDataDto? PaginationData +) : IQuery; diff --git a/src/Lumina.Application/Core/Favorites/Queries/GetFavorites/GetFavoritesQueryHandler.cs b/src/Lumina.Application/Core/Favorites/Queries/GetFavorites/GetFavoritesQueryHandler.cs new file mode 100644 index 00000000..f356bac4 --- /dev/null +++ b/src/Lumina.Application/Core/Favorites/Queries/GetFavorites/GetFavoritesQueryHandler.cs @@ -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; + +/// +/// Handler for the query to get a window of the favorites of the current user. +/// +public class GetFavoritesQueryHandler : IQueryHandler>> +{ + private readonly IUnitOfWork _unitOfWork; + private readonly ICurrentUserService _currentUserService; + private readonly IAuthorizationService _authorizationService; + private readonly IValidator _validator; + + /// + /// Initializes a new instance of the class. + /// + /// Injected unit of work for interacting with the data access layer repositories. + /// Injected service to retrieve the current user information. + /// Injected service for authorization related functionality. + /// Injected validator for application validation rules. + public GetFavoritesQueryHandler(IUnitOfWork unitOfWork, ICurrentUserService currentUserService, IAuthorizationService authorizationService, IValidator validator) + { + _unitOfWork = unitOfWork; + _currentUserService = currentUserService; + _authorizationService = authorizationService; + _validator = validator; + } + + /// + /// Handles the query to get a window of the favorites of the current user. + /// + /// The query to be handled. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either the requested page of favorites, or an error message. + /// + public async Task>> HandleAsync(GetFavoritesQuery query, CancellationToken cancellationToken) + { + List validationResult = _validator.Validate(query); + if (validationResult.Count > 0) + return validationResult; + + // An authenticated request must always carry a user identity. + Guid? currentUserId = _currentUserService.UserId; + if (currentUserId is null) + return ApplicationErrors.Authorization.NotAuthorized; + Guid userId = currentUserId.Value; + + // The favorites are scoped to the current user by the repository. + Result> 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 page = getFavoritesResult.Value; + List libraryIds = [.. page.Data + .Select(item => item.Display?.LibraryId ?? Guid.Empty) + .Where(libraryId => libraryId != Guid.Empty) + .Distinct()]; + Dictionary libraryAccess = []; + foreach (Guid libraryId in libraryIds) + { + bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync( + userId, new LibraryOwnershipPolicyContext(libraryId), cancellationToken).ConfigureAwait(false); + libraryAccess[libraryId] = canAccessLibrary; + } + + if (libraryAccess.Values.Any(canAccessLibrary => !canAccessLibrary)) + { + List 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()); + } +} diff --git a/src/Lumina.Application/Core/Favorites/Queries/GetFavorites/GetFavoritesQueryValidator.cs b/src/Lumina.Application/Core/Favorites/Queries/GetFavorites/GetFavoritesQueryValidator.cs new file mode 100644 index 00000000..371896c8 --- /dev/null +++ b/src/Lumina.Application/Core/Favorites/Queries/GetFavorites/GetFavoritesQueryValidator.cs @@ -0,0 +1,30 @@ +#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; +#endregion + +namespace Lumina.Application.Core.Favorites.Queries.GetFavorites; + +/// +/// Validates the needed validation rules for . +/// +public class GetFavoritesQueryValidator : AbstractValidator +{ + /// + /// Initializes a new instance of the class. + /// + public GetFavoritesQueryValidator() + { + RuleFor(query => query.MediaKind) + .IsInEnum() + .WithError(Errors.Favorites.FavoriteMediaKindIsInvalid) + .When(query => query.MediaKind is not null); + + RuleFor(query => query.MediaKind) + .Must(mediaKind => mediaKind != FavoriteMediaKind.None) + .WithError(Errors.Favorites.FavoriteMediaKindIsInvalid) + .When(query => query.MediaKind is not null); + } +} diff --git a/src/Lumina.Application/Core/MediaConsumption/Commands/ClearConsumptionHistory/ClearConsumptionHistoryCommand.cs b/src/Lumina.Application/Core/MediaConsumption/Commands/ClearConsumptionHistory/ClearConsumptionHistoryCommand.cs new file mode 100644 index 00000000..c05705e1 --- /dev/null +++ b/src/Lumina.Application/Core/MediaConsumption/Commands/ClearConsumptionHistory/ClearConsumptionHistoryCommand.cs @@ -0,0 +1,15 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Core.MediaConsumption.Commands.ClearConsumptionHistory; + +/// +/// Command for deleting every consumption record of a user. +/// +/// The Id of the user whose history is deleted, or for the current user. +[DebuggerDisplay("TargetUserId: {TargetUserId}")] +public record ClearConsumptionHistoryCommand( + string? TargetUserId +) : ICommand; diff --git a/src/Lumina.Application/Core/MediaConsumption/Commands/ClearConsumptionHistory/ClearConsumptionHistoryCommandHandler.cs b/src/Lumina.Application/Core/MediaConsumption/Commands/ClearConsumptionHistory/ClearConsumptionHistoryCommandHandler.cs new file mode 100644 index 00000000..4b4df6d6 --- /dev/null +++ b/src/Lumina.Application/Core/MediaConsumption/Commands/ClearConsumptionHistory/ClearConsumptionHistoryCommandHandler.cs @@ -0,0 +1,83 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Infrastructure.Authorization.Policies.ConsumptionActivity; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Domain.Common.Primitives; +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.Core.MediaConsumption.Commands.ClearConsumptionHistory; + +/// +/// Handler for the command to delete every consumption record of a user. +/// +public class ClearConsumptionHistoryCommandHandler : ICommandHandler> +{ + private readonly IUnitOfWork _unitOfWork; + private readonly ICurrentUserService _currentUserService; + private readonly IAuthorizationService _authorizationService; + private readonly IValidator _validator; + + /// + /// Initializes a new instance of the class. + /// + /// Injected unit of work for interacting with the data access layer repositories. + /// Injected service to retrieve the current user information. + /// Injected service for authorization related functionality. + /// Injected validator for application validation rules. + public ClearConsumptionHistoryCommandHandler( + IUnitOfWork unitOfWork, + ICurrentUserService currentUserService, + IAuthorizationService authorizationService, + IValidator validator) + { + _unitOfWork = unitOfWork; + _currentUserService = currentUserService; + _authorizationService = authorizationService; + _validator = validator; + } + + /// + /// Handles the command to delete every consumption record of a user. + /// + /// The command to be handled. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful deletion, or an error message. + public async Task> HandleAsync(ClearConsumptionHistoryCommand command, CancellationToken cancellationToken) + { + List validationResult = _validator.Validate(command); + if (validationResult.Count > 0) + return validationResult; + + // An authenticated request must always carry a user identity. + Guid? currentUserId = _currentUserService.UserId; + if (currentUserId is null) + return ApplicationErrors.Authorization.NotAuthorized; + Guid userId = currentUserId.Value; + + // The target defaults to the current user, and the access policy is the only place that decides whether the caller may act on it. + Guid targetUserId = command.TargetUserId is null ? userId : Guid.Parse(command.TargetUserId); + bool canAccessTarget = await _authorizationService.EvaluatePolicyAsync( + userId, new ConsumptionActivityAccessPolicyContext(targetUserId), cancellationToken).ConfigureAwait(false); + if (!canAccessTarget) + return ApplicationErrors.Authorization.NotAuthorized; + + // Clearing the history does not clear the resume points: the two are separate user actions, so the continue watching list survives. + Result deleteResult = await _unitOfWork.MediaConsumptionRecordRepository.DeleteAllForUserAsync(targetUserId, cancellationToken).ConfigureAwait(false); + if (deleteResult.IsFailure) + return deleteResult.Errors; + + Result saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + return saveChangesResult.Errors; + + return Result.Deleted; + } +} diff --git a/src/Lumina.Application/Core/MediaConsumption/Commands/ClearConsumptionHistory/ClearConsumptionHistoryCommandValidator.cs b/src/Lumina.Application/Core/MediaConsumption/Commands/ClearConsumptionHistory/ClearConsumptionHistoryCommandValidator.cs new file mode 100644 index 00000000..d115ced0 --- /dev/null +++ b/src/Lumina.Application/Core/MediaConsumption/Commands/ClearConsumptionHistory/ClearConsumptionHistoryCommandValidator.cs @@ -0,0 +1,26 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Utilities; +using Lumina.Domain.Common.Errors; +using System; +#endregion + +namespace Lumina.Application.Core.MediaConsumption.Commands.ClearConsumptionHistory; + +/// +/// Validates the needed validation rules for . +/// +public class ClearConsumptionHistoryCommandValidator : AbstractValidator +{ + /// + /// Initializes a new instance of the class. + /// + public ClearConsumptionHistoryCommandValidator() + { + // The target defaults to the current user, so an absent target is valid, but a supplied one must be a real user Id. + RuleFor(command => command.TargetUserId) + .Must(targetUserId => targetUserId is null || + (Guid.TryParse(targetUserId, out Guid parsedTargetUserId) && parsedTargetUserId != Guid.Empty)) + .WithError(Errors.MediaConsumption.TargetUserIdIsInvalid); + } +} diff --git a/src/Lumina.Application/Core/MediaConsumption/Commands/ClearResumePoints/ClearResumePointsCommand.cs b/src/Lumina.Application/Core/MediaConsumption/Commands/ClearResumePoints/ClearResumePointsCommand.cs new file mode 100644 index 00000000..43a69656 --- /dev/null +++ b/src/Lumina.Application/Core/MediaConsumption/Commands/ClearResumePoints/ClearResumePointsCommand.cs @@ -0,0 +1,17 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Core.MediaConsumption.Commands.ClearResumePoints; + +/// +/// Command for deleting the resume points of a user. +/// +/// The Id of the user whose resume points are deleted, or for the current user. +/// The Id of the media library to restrict the deletion to, or for every library. +[DebuggerDisplay("TargetUserId: {TargetUserId}; LibraryId: {LibraryId}")] +public record ClearResumePointsCommand( + string? TargetUserId, + string? LibraryId +) : ICommand; diff --git a/src/Lumina.Application/Core/MediaConsumption/Commands/ClearResumePoints/ClearResumePointsCommandHandler.cs b/src/Lumina.Application/Core/MediaConsumption/Commands/ClearResumePoints/ClearResumePointsCommandHandler.cs new file mode 100644 index 00000000..1cca1bd1 --- /dev/null +++ b/src/Lumina.Application/Core/MediaConsumption/Commands/ClearResumePoints/ClearResumePointsCommandHandler.cs @@ -0,0 +1,87 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Infrastructure.Authorization.Policies.ConsumptionActivity; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Domain.Common.Primitives; +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.Core.MediaConsumption.Commands.ClearResumePoints; + +/// +/// Handler for the command to delete the resume points of a user. +/// +public class ClearResumePointsCommandHandler : ICommandHandler> +{ + private readonly IUnitOfWork _unitOfWork; + private readonly ICurrentUserService _currentUserService; + private readonly IAuthorizationService _authorizationService; + private readonly IValidator _validator; + + /// + /// Initializes a new instance of the class. + /// + /// Injected unit of work for interacting with the data access layer repositories. + /// Injected service to retrieve the current user information. + /// Injected service for authorization related functionality. + /// Injected validator for application validation rules. + public ClearResumePointsCommandHandler( + IUnitOfWork unitOfWork, + ICurrentUserService currentUserService, + IAuthorizationService authorizationService, + IValidator validator) + { + _unitOfWork = unitOfWork; + _currentUserService = currentUserService; + _authorizationService = authorizationService; + _validator = validator; + } + + /// + /// Handles the command to delete the resume points of a user. + /// + /// The command to be handled. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful deletion, or an error message. + public async Task> HandleAsync(ClearResumePointsCommand command, CancellationToken cancellationToken) + { + List validationResult = _validator.Validate(command); + if (validationResult.Count > 0) + return validationResult; + + // An authenticated request must always carry a user identity. + Guid? currentUserId = _currentUserService.UserId; + if (currentUserId is null) + return ApplicationErrors.Authorization.NotAuthorized; + Guid userId = currentUserId.Value; + + // The target defaults to the current user, and the access policy is the only place that decides whether the caller may act on it. + Guid targetUserId = command.TargetUserId is null ? userId : Guid.Parse(command.TargetUserId); + bool canAccessTarget = await _authorizationService.EvaluatePolicyAsync( + userId, new ConsumptionActivityAccessPolicyContext(targetUserId), cancellationToken).ConfigureAwait(false); + if (!canAccessTarget) + return ApplicationErrors.Authorization.NotAuthorized; + + // Removing the resume points does not touch the history: the user asked only to clear the continue watching list. + Result deleteResult; + if (command.LibraryId is null) + deleteResult = await _unitOfWork.MediaResumePointRepository.DeleteAllForUserAsync(targetUserId, cancellationToken).ConfigureAwait(false); + else + deleteResult = await _unitOfWork.MediaResumePointRepository.DeleteAllForUserInLibraryAsync(targetUserId, Guid.Parse(command.LibraryId), cancellationToken).ConfigureAwait(false); + if (deleteResult.IsFailure) + return deleteResult.Errors; + + Result saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + return saveChangesResult.Errors; + + return Result.Deleted; + } +} diff --git a/src/Lumina.Application/Core/MediaConsumption/Commands/ClearResumePoints/ClearResumePointsCommandValidator.cs b/src/Lumina.Application/Core/MediaConsumption/Commands/ClearResumePoints/ClearResumePointsCommandValidator.cs new file mode 100644 index 00000000..8e1f1b7e --- /dev/null +++ b/src/Lumina.Application/Core/MediaConsumption/Commands/ClearResumePoints/ClearResumePointsCommandValidator.cs @@ -0,0 +1,31 @@ +#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.MediaConsumption.Commands.ClearResumePoints; + +/// +/// Validates the needed validation rules for . +/// +public class ClearResumePointsCommandValidator : AbstractValidator +{ + /// + /// Initializes a new instance of the class. + /// + public ClearResumePointsCommandValidator() + { + // The target defaults to the current user, so an absent target is valid, but a supplied one must be a real user Id. + RuleFor(command => command.TargetUserId) + .Must(targetUserId => targetUserId is null || + (Guid.TryParse(targetUserId, out Guid parsedTargetUserId) && parsedTargetUserId != Guid.Empty)) + .WithError(Errors.MediaConsumption.TargetUserIdIsInvalid); + + RuleFor(command => command.LibraryId) + .Must(libraryId => libraryId is null || + (Guid.TryParse(libraryId, out Guid parsedLibraryId) && parsedLibraryId != Guid.Empty)) + .WithError(Errors.Library.LibraryIdCannotBeEmpty); + } +} diff --git a/src/Lumina.Application/Core/MediaConsumption/Commands/CompleteConsumption/CompleteConsumptionCommand.cs b/src/Lumina.Application/Core/MediaConsumption/Commands/CompleteConsumption/CompleteConsumptionCommand.cs new file mode 100644 index 00000000..dbfcf101 --- /dev/null +++ b/src/Lumina.Application/Core/MediaConsumption/Commands/CompleteConsumption/CompleteConsumptionCommand.cs @@ -0,0 +1,28 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Core.MediaConsumption.Commands.CompleteConsumption; + +/// +/// Command for reporting that a consumption session of the current user completed. +/// +/// The unique identifier of the consumption record, taken from the route. +/// The name of the kind of the final position reached in the media item, if the client reported one. +/// The final position within the media item, in seconds, when the position is a time offset. +/// The final opaque locator within the media item, when the position is not a time offset. +/// The final fraction of the media item that the client reached, between 0 and 1. +/// The active duration consumed by the session, in seconds. +/// The number of consecutive pages read in the session, used by page based media such as books. +/// It must be absent or zero for other kinds. When it is absent, the count of the last progress report is kept. +[DebuggerDisplay("ConsumptionRecordId: {ConsumptionRecordId}; ProgressFraction: {ProgressFraction}; ConsecutivePagesRead: {ConsecutivePagesRead}")] +public record CompleteConsumptionCommand( + string? ConsumptionRecordId, + string? PositionKind, + double? PositionTimeOffsetInSeconds, + string? PositionLocation, + double? ProgressFraction, + double? ConsumedDurationInSeconds, + int? ConsecutivePagesRead +) : ICommand; diff --git a/src/Lumina.Application/Core/MediaConsumption/Commands/CompleteConsumption/CompleteConsumptionCommandHandler.cs b/src/Lumina.Application/Core/MediaConsumption/Commands/CompleteConsumption/CompleteConsumptionCommandHandler.cs new file mode 100644 index 00000000..38555a1c --- /dev/null +++ b/src/Lumina.Application/Core/MediaConsumption/Commands/CompleteConsumption/CompleteConsumptionCommandHandler.cs @@ -0,0 +1,174 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.DataAccess.Entities.MediaConsumption; +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.MediaConsumption; +using Lumina.Contracts.Responses.MediaConsumption; +using Lumina.Domain.Common.Events; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.Common.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.MediaConsumptionRecordAggregate; +using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption; +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.MediaConsumption.Commands.CompleteConsumption; + +/// +/// Handler for the command to report that a consumption session of the current user completed. +/// +public class CompleteConsumptionCommandHandler : ICommandHandler> +{ + /// + /// The maximum number of times the terminal state is applied when a concurrent progress report changes the record between its + /// read and its save. + /// + private const int MAXIMUM_TERMINAL_SAVE_ATTEMPTS = 3; + + private readonly IUnitOfWork _unitOfWork; + private readonly ICurrentUserService _currentUserService; + private readonly IDomainEventsQueue _domainEventsQueue; + private readonly IValidator _validator; + + /// + /// Initializes a new instance of the class. + /// + /// Injected unit of work for interacting with the data access layer repositories. + /// Injected service to retrieve the current user information. + /// Injected service for the queue of domain events. + /// Injected validator for application validation rules. + public CompleteConsumptionCommandHandler( + IUnitOfWork unitOfWork, + ICurrentUserService currentUserService, + IDomainEventsQueue domainEventsQueue, + IValidator validator) + { + _unitOfWork = unitOfWork; + _currentUserService = currentUserService; + _domainEventsQueue = domainEventsQueue; + _validator = validator; + } + + /// + /// Handles the command to report that a consumption session of the current user completed. + /// + /// The command to be handled. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either the completed , or an error message. + /// + public async Task> HandleAsync(CompleteConsumptionCommand command, CancellationToken cancellationToken) + { + List validationResult = _validator.Validate(command); + if (validationResult.Count > 0) + return validationResult; + + // An authenticated request must always carry a user identity. + Guid? currentUserId = _currentUserService.UserId; + if (currentUserId is null) + return ApplicationErrors.Authorization.NotAuthorized; + Guid userId = currentUserId.Value; + + // The validator guarantees that the route identifier and the reported measurements are valid before this point. + Guid consumptionRecordId = Guid.Parse(command.ConsumptionRecordId!); + + Optional position = ToMediaPosition(command.PositionKind, command.PositionTimeOffsetInSeconds, command.PositionLocation); + Optional consecutivePagesRead = command.ConsecutivePagesRead.HasValue + ? Optional.Some(command.ConsecutivePagesRead.Value) + : Optional.None(); + + // A terminal report can race with an in-flight progress report on the same record. The record is read, then saved with the + // version it was read with, so a progress report that commits in between makes the save fail with a concurrency conflict. + // The terminal payload is absolute, so the record is reloaded and the terminal state is applied again to the fresh version. + for (int attempt = 1; attempt <= MAXIMUM_TERMINAL_SAVE_ATTEMPTS; attempt++) + { + // The record is loaded scoped to the current user, so a record of another user is indistinguishable from a missing one. + Result getRecordResult = await _unitOfWork.MediaConsumptionRecordRepository + .GetByIdForUserAsync(consumptionRecordId, userId, cancellationToken: cancellationToken).ConfigureAwait(false); + if (getRecordResult.IsFailure) + return getRecordResult.Errors; + if (getRecordResult.Value is null) + return DomainErrors.MediaConsumption.ConsumptionRecordNotFound; + + Result toDomainEntityResult = getRecordResult.Value.ToDomainEntity(); + if (toDomainEntityResult.IsFailure) + return toDomainEntityResult.Errors; + MediaConsumptionRecord record = toDomainEntityResult.Value; + + Result completeResult = record.Complete(position, command.ProgressFraction!.Value, TimeSpan.FromSeconds(command.ConsumedDurationInSeconds!.Value), consecutivePagesRead); + if (completeResult.IsFailure) + return completeResult.Errors; + + // Completion discards the resume point, because the media item no longer has a point to continue from. A missing resume point is not an + // error, so an explicit completion after a completion that already deleted it stays idempotent. + Result deleteResumePointResult = await _unitOfWork.MediaResumePointRepository + .DeleteForUserAndMediaItemAsync(userId, record.MediaKind, record.MediaItemId.Value, cancellationToken).ConfigureAwait(false); + if (deleteResumePointResult.IsFailure) + return deleteResumePointResult.Errors; + + Result updateResult = await _unitOfWork.MediaConsumptionRecordRepository.UpdateForUserAsync(record.ToRepositoryEntity(), userId, cancellationToken).ConfigureAwait(false); + if (updateResult.IsFailure) + return updateResult.Errors; + + Result saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + { + // Only a concurrency conflict is worth retrying. The failed attempt is discarded, so the next loop reads the version + // the progress report committed and applies the terminal state to it. + if (attempt < MAXIMUM_TERMINAL_SAVE_ATTEMPTS && saveChangesResult.Errors.Any(error => error == ApplicationErrors.Persistence.ConcurrencyConflict)) + { + _unitOfWork.ClearTrackedEntities(); + continue; + } + return saveChangesResult.Errors; + } + + // Queue any domain events, to be published after the request has completed successfully. + foreach (IDomainEvent domainEvent in record.GetDomainEvents()) + _domainEventsQueue.Enqueue(domainEvent); + + // The persisted row is read back, so the response carries the timestamps and version the persistence medium actually stored. + Result getPersistedRecordResult = await _unitOfWork.MediaConsumptionRecordRepository + .GetByIdForUserAsync(record.Id.Value, userId, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false); + if (getPersistedRecordResult.IsFailure) + return getPersistedRecordResult.Errors; + if (getPersistedRecordResult.Value is null) + return DomainErrors.MediaConsumption.ConsumptionRecordNotFound; + + return getPersistedRecordResult.Value.ToDto().ToResponse(); + } + + // Every attempt conflicted with a concurrent write, so the terminal state could not be stored. + return ApplicationErrors.Persistence.ConcurrencyConflict; + } + + /// + /// Converts reported position fields that have already been validated to a . + /// + /// The name of the kind of the reported position, or when no position was reported. + /// The reported position within the media item, in seconds, when the position is a time offset. + /// The reported opaque locator within the media item, when the position is not a time offset. + /// The converted position, or no position when the client did not report one. + private static Optional ToMediaPosition(string? positionKind, double? timeOffsetInSeconds, string? location) + { + // A missing kind means the client did not report a position at all, which is different from a position at zero. + if (string.IsNullOrWhiteSpace(positionKind)) + return Optional.None(); + + // The validator already rejected unknown and undefined kinds, so the parse is safe here and no fallback value is invented. + MediaPositionKind parsedPositionKind = Enum.Parse(positionKind, ignoreCase: true); + // The kind names the single representation that the validator accepted, so only that representation is read. + return parsedPositionKind == MediaPositionKind.TimeOffset + ? Optional.Some(MediaPosition.CreateTimeOffset(TimeSpan.FromSeconds(timeOffsetInSeconds!.Value))) + : Optional.Some(MediaPosition.CreateLocation(location!)); + } +} diff --git a/src/Lumina.Application/Core/MediaConsumption/Commands/CompleteConsumption/CompleteConsumptionCommandValidator.cs b/src/Lumina.Application/Core/MediaConsumption/Commands/CompleteConsumption/CompleteConsumptionCommandValidator.cs new file mode 100644 index 00000000..4d936a09 --- /dev/null +++ b/src/Lumina.Application/Core/MediaConsumption/Commands/CompleteConsumption/CompleteConsumptionCommandValidator.cs @@ -0,0 +1,101 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Utilities; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption; +using System; +#endregion + +namespace Lumina.Application.Core.MediaConsumption.Commands.CompleteConsumption; + +/// +/// Validates the needed validation rules for . +/// +public class CompleteConsumptionCommandValidator : AbstractValidator +{ + /// + /// The maximum active duration, in seconds, that a client can report for one session or as a position within a media item. The limit keeps + /// accumulated totals representable as a and rejects durations that cannot describe real media. + /// + private const double MAXIMUM_REPORTED_DURATION_IN_SECONDS = 31 * 24 * 60 * 60; + + /// + /// Initializes a new instance of the class. + /// + public CompleteConsumptionCommandValidator() + { + // Validates the identifier of the consumption record, taken from the route. + RuleFor(command => command.ConsumptionRecordId) + .NotEmpty() + .WithError(Errors.MediaConsumption.ConsumptionRecordIdCannotBeEmpty); + + RuleFor(command => command.ConsumptionRecordId) + .Must(consumptionRecordId => Guid.TryParse(consumptionRecordId, out Guid parsedConsumptionRecordId) && parsedConsumptionRecordId != Guid.Empty) + .When(command => command.ConsumptionRecordId is not null && command.ConsumptionRecordId.Length > 0) + .WithError(Errors.MediaConsumption.ConsumptionRecordIdCannotBeEmpty); + + // Validates that the reported position describes exactly one position, using the representation its kind names. + RuleFor(command => command.PositionKind) + .Must((command, positionKind) => IsPositionShapeValid( + positionKind, command.PositionTimeOffsetInSeconds, command.PositionLocation)) + .WithError(Errors.MediaConsumption.InvalidMediaPosition); + + RuleFor(command => command.ProgressFraction) + .NotNull() + .WithError(Errors.MediaConsumption.InvalidProgressFraction); + + RuleFor(command => command.ProgressFraction) + .Must(progressFraction => progressFraction is null || + (double.IsFinite(progressFraction.Value) && progressFraction.Value >= 0 && progressFraction.Value <= 1)) + .WithError(Errors.MediaConsumption.InvalidProgressFraction); + + RuleFor(command => command.ConsumedDurationInSeconds) + .NotNull() + .WithError(Errors.MediaConsumption.ConsumedDurationMustBeNonNegative); + + RuleFor(command => command.ConsumedDurationInSeconds) + .Must(consumedDuration => consumedDuration is null || + (double.IsFinite(consumedDuration.Value) && consumedDuration.Value >= 0)) + .WithError(Errors.MediaConsumption.ConsumedDurationMustBeNonNegative); + + RuleFor(command => command.ConsumedDurationInSeconds) + .Must(consumedDuration => consumedDuration is null || + consumedDuration.Value <= MAXIMUM_REPORTED_DURATION_IN_SECONDS) + .WithError(Errors.MediaConsumption.ConsumedDurationIsOutOfRange); + + RuleFor(command => command.ConsecutivePagesRead) + .Must(consecutivePagesRead => consecutivePagesRead is null || consecutivePagesRead.Value >= 0) + .WithError(Errors.MediaConsumption.ConsecutivePagesReadMustBeNonNegative); + } + + /// + /// Determines whether the reported position fields describe exactly one valid position. + /// + /// The name of the kind of the reported position, or when no position was reported. + /// The reported position within the media item, in seconds, when the position is a time offset. + /// The reported opaque locator within the media item, when the position is not a time offset. + /// if the position fields are valid, otherwise. + private static bool IsPositionShapeValid(string? positionKind, double? timeOffsetInSeconds, string? location) + { + // No kind means no position was reported, so a time offset or a locator without a kind would make the representation ambiguous. + if (string.IsNullOrWhiteSpace(positionKind)) + return !timeOffsetInSeconds.HasValue && string.IsNullOrWhiteSpace(location); + // Unknown and numeric kind names are not valid positions, even when the other fields look well formed. + if (!Enum.TryParse(positionKind, ignoreCase: true, out MediaPositionKind parsedPositionKind) || !Enum.IsDefined(parsedPositionKind)) + return false; + + // A position uses exactly one representation, because MediaPosition stores one kind and one value, so the fields of the other representation must be absent instead of ignored. + return parsedPositionKind switch + { + MediaPositionKind.TimeOffset => timeOffsetInSeconds.HasValue && + double.IsFinite(timeOffsetInSeconds.Value) && + timeOffsetInSeconds.Value >= 0 && + timeOffsetInSeconds.Value <= MAXIMUM_REPORTED_DURATION_IN_SECONDS && + string.IsNullOrWhiteSpace(location), + MediaPositionKind.Location => !timeOffsetInSeconds.HasValue && + !string.IsNullOrWhiteSpace(location) && + location.Length <= 4096, + _ => false + }; + } +} diff --git a/src/Lumina.Application/Core/MediaConsumption/Commands/DeleteConsumptionItemHistory/DeleteConsumptionItemHistoryCommand.cs b/src/Lumina.Application/Core/MediaConsumption/Commands/DeleteConsumptionItemHistory/DeleteConsumptionItemHistoryCommand.cs new file mode 100644 index 00000000..2a18174b --- /dev/null +++ b/src/Lumina.Application/Core/MediaConsumption/Commands/DeleteConsumptionItemHistory/DeleteConsumptionItemHistoryCommand.cs @@ -0,0 +1,21 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Core.MediaConsumption.Commands.DeleteConsumptionItemHistory; + +/// +/// Command for deleting every consumption record of a media item of a user. +/// +/// The Id of the user the records must belong to, or for the current user. +/// The name of the kind of the consumed media item, taken from the route. +/// The Id of the consumed media item, taken from the route. +/// The Id of the media library that contains the media item, taken from the route. +[DebuggerDisplay("TargetUserId: {TargetUserId}; MediaKind: {MediaKind}; MediaItemId: {MediaItemId}")] +public record DeleteConsumptionItemHistoryCommand( + string? TargetUserId, + string? MediaKind, + string? MediaItemId, + string? LibraryId +) : ICommand; diff --git a/src/Lumina.Application/Core/MediaConsumption/Commands/DeleteConsumptionItemHistory/DeleteConsumptionItemHistoryCommandHandler.cs b/src/Lumina.Application/Core/MediaConsumption/Commands/DeleteConsumptionItemHistory/DeleteConsumptionItemHistoryCommandHandler.cs new file mode 100644 index 00000000..08cdc001 --- /dev/null +++ b/src/Lumina.Application/Core/MediaConsumption/Commands/DeleteConsumptionItemHistory/DeleteConsumptionItemHistoryCommandHandler.cs @@ -0,0 +1,91 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Infrastructure.Authorization.Policies.ConsumptionActivity; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.Core.MediaConsumption.Commands.DeleteConsumptionItemHistory; + +/// +/// Handler for the command to delete every consumption record of a media item of a user. +/// +public class DeleteConsumptionItemHistoryCommandHandler : ICommandHandler> +{ + private readonly IUnitOfWork _unitOfWork; + private readonly ICurrentUserService _currentUserService; + private readonly IAuthorizationService _authorizationService; + private readonly IValidator _validator; + + /// + /// Initializes a new instance of the class. + /// + /// Injected unit of work for interacting with the data access layer repositories. + /// Injected service to retrieve the current user information. + /// Injected service for authorization related functionality. + /// Injected validator for application validation rules. + public DeleteConsumptionItemHistoryCommandHandler( + IUnitOfWork unitOfWork, + ICurrentUserService currentUserService, + IAuthorizationService authorizationService, + IValidator validator) + { + _unitOfWork = unitOfWork; + _currentUserService = currentUserService; + _authorizationService = authorizationService; + _validator = validator; + } + + /// + /// Handles the command to delete every consumption record of a media item of a user. + /// + /// The command to be handled. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful deletion, or an error message. + public async Task> HandleAsync(DeleteConsumptionItemHistoryCommand command, CancellationToken cancellationToken) + { + List validationResult = _validator.Validate(command); + if (validationResult.Count > 0) + return validationResult; + + // An authenticated request must always carry a user identity. + Guid? currentUserId = _currentUserService.UserId; + if (currentUserId is null) + return ApplicationErrors.Authorization.NotAuthorized; + Guid userId = currentUserId.Value; + + // The target defaults to the current user, and the access policy is the only place that decides whether the caller may act on it. + Guid targetUserId = command.TargetUserId is null ? userId : Guid.Parse(command.TargetUserId); + bool canAccessTarget = await _authorizationService.EvaluatePolicyAsync( + userId, new ConsumptionActivityAccessPolicyContext(targetUserId), cancellationToken).ConfigureAwait(false); + if (!canAccessTarget) + return ApplicationErrors.Authorization.NotAuthorized; + + // The validator guarantees that the route values are well formed before this point. + MediaKind mediaKind = Enum.Parse(command.MediaKind!, ignoreCase: true); + Guid mediaItemId = Guid.Parse(command.MediaItemId!); + Guid libraryId = Guid.Parse(command.LibraryId!); + + // The deletion covers every recorded session of the item in its library, not only the sessions of a date range, so the row + // disappears from the history consistently with clearing the whole history. + Result deleteResult = await _unitOfWork.MediaConsumptionRecordRepository + .DeleteAllByMediaItemIdForUserAsync(targetUserId, mediaKind, mediaItemId, libraryId, cancellationToken).ConfigureAwait(false); + if (deleteResult.IsFailure) + return deleteResult.Errors; + + Result saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + return saveChangesResult.Errors; + + return Result.Deleted; + } +} diff --git a/src/Lumina.Application/Core/MediaConsumption/Commands/DeleteConsumptionItemHistory/DeleteConsumptionItemHistoryCommandValidator.cs b/src/Lumina.Application/Core/MediaConsumption/Commands/DeleteConsumptionItemHistory/DeleteConsumptionItemHistoryCommandValidator.cs new file mode 100644 index 00000000..31d9651d --- /dev/null +++ b/src/Lumina.Application/Core/MediaConsumption/Commands/DeleteConsumptionItemHistory/DeleteConsumptionItemHistoryCommandValidator.cs @@ -0,0 +1,59 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Utilities; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using System; +#endregion + +namespace Lumina.Application.Core.MediaConsumption.Commands.DeleteConsumptionItemHistory; + +/// +/// Validates the needed validation rules for . +/// +public class DeleteConsumptionItemHistoryCommandValidator : AbstractValidator +{ + /// + /// Initializes a new instance of the class. + /// + public DeleteConsumptionItemHistoryCommandValidator() + { + // The target defaults to the current user, so an absent target is valid, but a supplied one must be a real user Id. + RuleFor(command => command.TargetUserId) + .Must(targetUserId => targetUserId is null || + (Guid.TryParse(targetUserId, out Guid parsedTargetUserId) && parsedTargetUserId != Guid.Empty)) + .WithError(Errors.MediaConsumption.TargetUserIdIsInvalid); + + // Only the member names of the media kind enumeration are accepted, so a numeric value that happens to parse as a kind is rejected. + RuleFor(command => command.MediaKind) + .NotEmpty() + .WithError(Errors.MediaConsumption.UnsupportedMediaKind); + + RuleFor(command => command.MediaKind) + .IsInEnum() + .WithError(Errors.MediaConsumption.UnsupportedMediaKind); + + RuleFor(command => command.MediaKind) + .Must(mediaKind => mediaKind is null || + !string.Equals(mediaKind, nameof(MediaKind.None), StringComparison.OrdinalIgnoreCase)) + .WithError(Errors.MediaConsumption.UnsupportedMediaKind); + + RuleFor(command => command.MediaItemId) + .NotEmpty() + .WithError(Errors.MediaConsumption.MediaItemIdCannotBeEmpty); + + 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.MediaConsumption.MediaItemIdCannotBeEmpty); + + RuleFor(command => command.LibraryId) + .NotEmpty() + .WithError(Errors.Library.LibraryIdCannotBeEmpty); + + RuleFor(command => command.LibraryId) + .Must(libraryId => Guid.TryParse(libraryId, out Guid parsedLibraryId) && parsedLibraryId != Guid.Empty) + .When(command => command.LibraryId is not null && command.LibraryId.Length > 0) + .WithError(Errors.Library.LibraryIdCannotBeEmpty); + } +} diff --git a/src/Lumina.Application/Core/MediaConsumption/Commands/DeleteConsumptionRecord/DeleteConsumptionRecordCommand.cs b/src/Lumina.Application/Core/MediaConsumption/Commands/DeleteConsumptionRecord/DeleteConsumptionRecordCommand.cs new file mode 100644 index 00000000..42e94db7 --- /dev/null +++ b/src/Lumina.Application/Core/MediaConsumption/Commands/DeleteConsumptionRecord/DeleteConsumptionRecordCommand.cs @@ -0,0 +1,17 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Core.MediaConsumption.Commands.DeleteConsumptionRecord; + +/// +/// Command for deleting one consumption record of a user. +/// +/// The Id of the consumption record, taken from the route. +/// The Id of the user the record must belong to, or for the current user. +[DebuggerDisplay("ConsumptionRecordId: {ConsumptionRecordId}; TargetUserId: {TargetUserId}")] +public record DeleteConsumptionRecordCommand( + string? ConsumptionRecordId, + string? TargetUserId +) : ICommand; diff --git a/src/Lumina.Application/Core/MediaConsumption/Commands/DeleteConsumptionRecord/DeleteConsumptionRecordCommandHandler.cs b/src/Lumina.Application/Core/MediaConsumption/Commands/DeleteConsumptionRecord/DeleteConsumptionRecordCommandHandler.cs new file mode 100644 index 00000000..6f69bc13 --- /dev/null +++ b/src/Lumina.Application/Core/MediaConsumption/Commands/DeleteConsumptionRecord/DeleteConsumptionRecordCommandHandler.cs @@ -0,0 +1,86 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Infrastructure.Authorization.Policies.ConsumptionActivity; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Domain.Common.Primitives; +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.Core.MediaConsumption.Commands.DeleteConsumptionRecord; + +/// +/// Handler for the command to delete one consumption record of a user. +/// +public class DeleteConsumptionRecordCommandHandler : ICommandHandler> +{ + private readonly IUnitOfWork _unitOfWork; + private readonly ICurrentUserService _currentUserService; + private readonly IAuthorizationService _authorizationService; + private readonly IValidator _validator; + + /// + /// Initializes a new instance of the class. + /// + /// Injected unit of work for interacting with the data access layer repositories. + /// Injected service to retrieve the current user information. + /// Injected service for authorization related functionality. + /// Injected validator for application validation rules. + public DeleteConsumptionRecordCommandHandler( + IUnitOfWork unitOfWork, + ICurrentUserService currentUserService, + IAuthorizationService authorizationService, + IValidator validator) + { + _unitOfWork = unitOfWork; + _currentUserService = currentUserService; + _authorizationService = authorizationService; + _validator = validator; + } + + /// + /// Handles the command to delete one consumption record of a user. + /// + /// The command to be handled. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful deletion, or an error message. + public async Task> HandleAsync(DeleteConsumptionRecordCommand command, CancellationToken cancellationToken) + { + List validationResult = _validator.Validate(command); + if (validationResult.Count > 0) + return validationResult; + + // An authenticated request must always carry a user identity. + Guid? currentUserId = _currentUserService.UserId; + if (currentUserId is null) + return ApplicationErrors.Authorization.NotAuthorized; + Guid userId = currentUserId.Value; + + // The target defaults to the current user, and the access policy is the only place that decides whether the caller may act on it. + Guid targetUserId = command.TargetUserId is null ? userId : Guid.Parse(command.TargetUserId); + bool canAccessTarget = await _authorizationService.EvaluatePolicyAsync( + userId, new ConsumptionActivityAccessPolicyContext(targetUserId), cancellationToken).ConfigureAwait(false); + if (!canAccessTarget) + return ApplicationErrors.Authorization.NotAuthorized; + + // The validator guarantees that the route identifier is a non-empty Guid before this point. + Guid consumptionRecordId = Guid.Parse(command.ConsumptionRecordId!); + + // Deleting an absent record succeeds, so a retried deletion or a record deleted in another tab is not an error. + Result deleteResult = await _unitOfWork.MediaConsumptionRecordRepository.DeleteForUserAsync(consumptionRecordId, targetUserId, cancellationToken).ConfigureAwait(false); + if (deleteResult.IsFailure) + return deleteResult.Errors; + + Result saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + return saveChangesResult.Errors; + + return Result.Deleted; + } +} diff --git a/src/Lumina.Application/Core/MediaConsumption/Commands/DeleteConsumptionRecord/DeleteConsumptionRecordCommandValidator.cs b/src/Lumina.Application/Core/MediaConsumption/Commands/DeleteConsumptionRecord/DeleteConsumptionRecordCommandValidator.cs new file mode 100644 index 00000000..c0559bc4 --- /dev/null +++ b/src/Lumina.Application/Core/MediaConsumption/Commands/DeleteConsumptionRecord/DeleteConsumptionRecordCommandValidator.cs @@ -0,0 +1,35 @@ +#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.MediaConsumption.Commands.DeleteConsumptionRecord; + +/// +/// Validates the needed validation rules for . +/// +public class DeleteConsumptionRecordCommandValidator : AbstractValidator +{ + /// + /// Initializes a new instance of the class. + /// + public DeleteConsumptionRecordCommandValidator() + { + RuleFor(command => command.ConsumptionRecordId) + .NotEmpty() + .WithError(Errors.MediaConsumption.ConsumptionRecordIdCannotBeEmpty); + + RuleFor(command => command.ConsumptionRecordId) + .Must(consumptionRecordId => Guid.TryParse(consumptionRecordId, out Guid parsedConsumptionRecordId) && parsedConsumptionRecordId != Guid.Empty) + .When(command => command.ConsumptionRecordId is not null && command.ConsumptionRecordId.Length > 0) + .WithError(Errors.MediaConsumption.ConsumptionRecordIdCannotBeEmpty); + + // The target defaults to the current user, so an absent target is valid, but a supplied one must be a real user Id. + RuleFor(command => command.TargetUserId) + .Must(targetUserId => targetUserId is null || + (Guid.TryParse(targetUserId, out Guid parsedTargetUserId) && parsedTargetUserId != Guid.Empty)) + .WithError(Errors.MediaConsumption.TargetUserIdIsInvalid); + } +} diff --git a/src/Lumina.Application/Core/MediaConsumption/Commands/ReportConsumptionProgress/ReportConsumptionProgressCommand.cs b/src/Lumina.Application/Core/MediaConsumption/Commands/ReportConsumptionProgress/ReportConsumptionProgressCommand.cs new file mode 100644 index 00000000..02647dfc --- /dev/null +++ b/src/Lumina.Application/Core/MediaConsumption/Commands/ReportConsumptionProgress/ReportConsumptionProgressCommand.cs @@ -0,0 +1,27 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Core.MediaConsumption.Commands.ReportConsumptionProgress; + +/// +/// Command for reporting the progress of a consumption session of the current user. +/// +/// The unique identifier of the consumption record, taken from the route. +/// The name of the kind of the position reached in the media item, if the client reported one. +/// The position within the media item, in seconds, when the position is a time offset. +/// The opaque locator within the media item, when the position is not a time offset. +/// The fraction of the media item that the client reached, between 0 and 1. +/// The active duration consumed by the session, in seconds. +/// The number of consecutive pages read in the current session, used by page based media such as books. It must be zero for other kinds. Defaults to 0. Optional. +[DebuggerDisplay("ConsumptionRecordId: {ConsumptionRecordId}; ProgressFraction: {ProgressFraction}")] +public record ReportConsumptionProgressCommand( + string? ConsumptionRecordId, + string? PositionKind, + double? PositionTimeOffsetInSeconds, + string? PositionLocation, + double? ProgressFraction, + double? ConsumedDurationInSeconds, + int ConsecutivePagesRead +) : ICommand; diff --git a/src/Lumina.Application/Core/MediaConsumption/Commands/ReportConsumptionProgress/ReportConsumptionProgressCommandHandler.cs b/src/Lumina.Application/Core/MediaConsumption/Commands/ReportConsumptionProgress/ReportConsumptionProgressCommandHandler.cs new file mode 100644 index 00000000..2531336b --- /dev/null +++ b/src/Lumina.Application/Core/MediaConsumption/Commands/ReportConsumptionProgress/ReportConsumptionProgressCommandHandler.cs @@ -0,0 +1,218 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.DataAccess.Entities.MediaConsumption; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; +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.MediaConsumption; +using Lumina.Application.Common.Mapping.MediaLibrary.Management; +using Lumina.Contracts.Responses.MediaConsumption; +using Lumina.Domain.Common.Events; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.Common.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.MediaConsumptionRecordAggregate; +using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.MediaResumePointAggregate; +using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption; +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +using DomainErrors = Lumina.Domain.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.Core.MediaConsumption.Commands.ReportConsumptionProgress; + +/// +/// Handler for the command to report the progress of a consumption session of the current user. +/// +public class ReportConsumptionProgressCommandHandler : ICommandHandler> +{ + private readonly IUnitOfWork _unitOfWork; + private readonly ICurrentUserService _currentUserService; + private readonly IDomainEventsQueue _domainEventsQueue; + private readonly IValidator _validator; + + /// + /// Initializes a new instance of the class. + /// + /// Injected unit of work for interacting with the data access layer repositories. + /// Injected service to retrieve the current user information. + /// Injected service for the queue of domain events. + /// Injected validator for application validation rules. + public ReportConsumptionProgressCommandHandler( + IUnitOfWork unitOfWork, + ICurrentUserService currentUserService, + IDomainEventsQueue domainEventsQueue, + IValidator validator) + { + _unitOfWork = unitOfWork; + _currentUserService = currentUserService; + _domainEventsQueue = domainEventsQueue; + _validator = validator; + } + + /// + /// Handles the command to report the progress of a consumption session of the current user. + /// + /// The command to be handled. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either the updated , or an error message. + /// + public async Task> HandleAsync(ReportConsumptionProgressCommand command, CancellationToken cancellationToken) + { + List validationResult = _validator.Validate(command); + if (validationResult.Count > 0) + return validationResult; + + // An authenticated request must always carry a user identity. + Guid? currentUserId = _currentUserService.UserId; + if (currentUserId is null) + return ApplicationErrors.Authorization.NotAuthorized; + Guid userId = currentUserId.Value; + + // The validator guarantees that the route identifier and the reported measurements are valid before this point. + Guid consumptionRecordId = Guid.Parse(command.ConsumptionRecordId!); + + // The record is loaded scoped to the current user, so a record of another user is indistinguishable from a missing one. + Result getRecordResult = await _unitOfWork.MediaConsumptionRecordRepository + .GetByIdForUserAsync(consumptionRecordId, userId, cancellationToken: cancellationToken).ConfigureAwait(false); + if (getRecordResult.IsFailure) + return getRecordResult.Errors; + if (getRecordResult.Value is null) + return DomainErrors.MediaConsumption.ConsumptionRecordNotFound; + + Result toDomainEntityResult = getRecordResult.Value.ToDomainEntity(); + if (toDomainEntityResult.IsFailure) + return toDomainEntityResult.Errors; + MediaConsumptionRecord record = toDomainEntityResult.Value; + + // The settings of the library decide whether progress is tracked. If the library was deleted after the session started, the defaults of + // the media kind are used instead, so the reported session can still be closed consistently. + Result getLibraryResult = await _unitOfWork.LibraryRepository + .GetByIdAsync(record.LibraryId.Value, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false); + if (getLibraryResult.IsFailure) + return getLibraryResult.Errors; + LibraryConsumptionSettings consumptionSettings = getLibraryResult.Value is null + ? LibraryConsumptionSettings.CreateDefault(record.MediaKind) + : getLibraryResult.Value.ToDomainValueObject(); + + Optional position = ToMediaPosition(command.PositionKind, command.PositionTimeOffsetInSeconds, command.PositionLocation); + + // A report never completes a session, because seeking to the end of the media item is not the same as reaching the end of the session. + Result reportProgressResult = record.ReportProgress(position, command.ProgressFraction!.Value, TimeSpan.FromSeconds(command.ConsumedDurationInSeconds!.Value), command.ConsecutivePagesRead); + if (reportProgressResult.IsFailure) + return reportProgressResult.Errors; + + Optional ruleResult = MediaConsumptionRule.For(record.MediaKind); + if (!ruleResult.HasValue) + return DomainErrors.MediaConsumption.UnsupportedMediaKind; + + // Only libraries that track progress keep a resume point, and only for kinds that support resuming. When the client reported no position, + // the last known position of the session is reused, so the resume point does not lose a position that an earlier report supplied. + if (consumptionSettings.ShouldTrackConsumptionProgress && ruleResult.Value.CanResume) + { + Optional resumePosition = position.HasValue ? position : record.LastPosition; + if (resumePosition.HasValue) + { + Result upsertResumePointResult = await UpsertResumePointAsync(record, resumePosition.Value, record.LastProgressFraction, userId, cancellationToken).ConfigureAwait(false); + if (upsertResumePointResult.IsFailure) + return upsertResumePointResult.Errors; + } + } + + Result updateResult = await _unitOfWork.MediaConsumptionRecordRepository.UpdateForUserAsync(record.ToRepositoryEntity(), userId, cancellationToken).ConfigureAwait(false); + if (updateResult.IsFailure) + return updateResult.Errors; + + Result saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + return saveChangesResult.Errors; + + // Queue any domain events, to be published after the request has completed successfully. + foreach (IDomainEvent domainEvent in record.GetDomainEvents()) + _domainEventsQueue.Enqueue(domainEvent); + + // The persisted row is read back, so the response carries the timestamps and version the persistence medium actually stored. + Result getPersistedRecordResult = await _unitOfWork.MediaConsumptionRecordRepository + .GetByIdForUserAsync(record.Id.Value, userId, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false); + if (getPersistedRecordResult.IsFailure) + return getPersistedRecordResult.Errors; + if (getPersistedRecordResult.Value is null) + return DomainErrors.MediaConsumption.ConsumptionRecordNotFound; + + return getPersistedRecordResult.Value.ToDto().ToResponse(); + } + + /// + /// Converts reported position fields that have already been validated to a . + /// + /// The name of the kind of the reported position, or when no position was reported. + /// The reported position within the media item, in seconds, when the position is a time offset. + /// The reported opaque locator within the media item, when the position is not a time offset. + /// The converted position, or no position when the client did not report one. + private static Optional ToMediaPosition(string? positionKind, double? timeOffsetInSeconds, string? location) + { + // A missing kind means the client did not report a position at all, which is different from a position at zero. + if (string.IsNullOrWhiteSpace(positionKind)) + return Optional.None(); + + // The validator already rejected unknown and undefined kinds, so the parse is safe here and no fallback value is invented. + MediaPositionKind parsedPositionKind = Enum.Parse(positionKind, ignoreCase: true); + // The kind names the single representation that the validator accepted, so only that representation is read. + return parsedPositionKind == MediaPositionKind.TimeOffset + ? Optional.Some(MediaPosition.CreateTimeOffset(TimeSpan.FromSeconds(timeOffsetInSeconds!.Value))) + : Optional.Some(MediaPosition.CreateLocation(location!)); + } + + /// + /// Creates or updates the resume point of for the current user. + /// + /// The consumption record whose session is being tracked. + /// The position at which the media item can be resumed. + /// The progress fraction at which the media item can be resumed. + /// The Id of the user the resume point belongs to. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful save, or an error message. + private async Task> UpsertResumePointAsync(MediaConsumptionRecord record, MediaPosition position, double progressFraction, Guid userId, CancellationToken cancellationToken) + { + // The resume point is read without tracking because it is only used to build the domain aggregate. The upsert call locates and updates + // the stored row itself, so tracking this copy would put two tracked instances of the same row in the same unit of work. + Result getResumePointResult = await _unitOfWork.MediaResumePointRepository + .GetForUserAndMediaItemAsync(userId, record.MediaKind, record.MediaItemId.Value, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false); + if (getResumePointResult.IsFailure) + return getResumePointResult.Errors; + + MediaResumePoint resumePoint; + if (getResumePointResult.Value is null) + { + // A resume point that does not exist yet is created from the session identifiers and the effective position. The position and + // fraction are the ones the caller applied to the record, so the resume point and the record cannot disagree about the report. + Result createResumePointResult = MediaResumePoint.Create( + record.UserId, record.LibraryId, record.MediaItemId, record.MediaKind, position, progressFraction, record.LastActivityOnUtc); + if (createResumePointResult.IsFailure) + return createResumePointResult.Errors; + resumePoint = createResumePointResult.Value; + } + else + { + // An existing resume point is advanced instead of replaced, so its identifier and creation time survive and its own rules validate + // the new position and fraction before the update. The activity time is taken from the record, so both rows describe the same report. + Result toDomainEntityResult = getResumePointResult.Value.ToDomainEntity(); + if (toDomainEntityResult.IsFailure) + return toDomainEntityResult.Errors; + Result advanceResult = toDomainEntityResult.Value.Advance(position, progressFraction, record.LastActivityOnUtc); + if (advanceResult.IsFailure) + return advanceResult.Errors; + resumePoint = toDomainEntityResult.Value; + } + + // The upsert decides between the insert and the update from the unique business key, so a concurrent report that created the row + // between the read above and this call still ends with one resume point instead of a duplicate. + return await _unitOfWork.MediaResumePointRepository.UpsertForUserAsync(resumePoint.ToRepositoryEntity(), userId, cancellationToken).ConfigureAwait(false); + } +} diff --git a/src/Lumina.Application/Core/MediaConsumption/Commands/ReportConsumptionProgress/ReportConsumptionProgressCommandValidator.cs b/src/Lumina.Application/Core/MediaConsumption/Commands/ReportConsumptionProgress/ReportConsumptionProgressCommandValidator.cs new file mode 100644 index 00000000..0d28e3d3 --- /dev/null +++ b/src/Lumina.Application/Core/MediaConsumption/Commands/ReportConsumptionProgress/ReportConsumptionProgressCommandValidator.cs @@ -0,0 +1,101 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Utilities; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption; +using System; +#endregion + +namespace Lumina.Application.Core.MediaConsumption.Commands.ReportConsumptionProgress; + +/// +/// Validates the needed validation rules for . +/// +public class ReportConsumptionProgressCommandValidator : AbstractValidator +{ + /// + /// The maximum active duration, in seconds, that a client can report for one session or as a position within a media item. The limit keeps + /// accumulated totals representable as a and rejects durations that cannot describe real media. + /// + private const double MAXIMUM_REPORTED_DURATION_IN_SECONDS = 31 * 24 * 60 * 60; + + /// + /// Initializes a new instance of the class. + /// + public ReportConsumptionProgressCommandValidator() + { + // Validates the identifier of the consumption record, taken from the route. + RuleFor(command => command.ConsumptionRecordId) + .NotEmpty() + .WithError(Errors.MediaConsumption.ConsumptionRecordIdCannotBeEmpty); + + RuleFor(command => command.ConsumptionRecordId) + .Must(consumptionRecordId => Guid.TryParse(consumptionRecordId, out Guid parsedConsumptionRecordId) && parsedConsumptionRecordId != Guid.Empty) + .When(command => command.ConsumptionRecordId is not null && command.ConsumptionRecordId.Length > 0) + .WithError(Errors.MediaConsumption.ConsumptionRecordIdCannotBeEmpty); + + // Validates that the reported position describes exactly one position, using the representation its kind names. + RuleFor(command => command.PositionKind) + .Must((command, positionKind) => IsPositionShapeValid( + positionKind, command.PositionTimeOffsetInSeconds, command.PositionLocation)) + .WithError(Errors.MediaConsumption.InvalidMediaPosition); + + RuleFor(command => command.ProgressFraction) + .NotNull() + .WithError(Errors.MediaConsumption.InvalidProgressFraction); + + RuleFor(command => command.ProgressFraction) + .Must(progressFraction => progressFraction is null || + (double.IsFinite(progressFraction.Value) && progressFraction.Value >= 0 && progressFraction.Value <= 1)) + .WithError(Errors.MediaConsumption.InvalidProgressFraction); + + RuleFor(command => command.ConsumedDurationInSeconds) + .NotNull() + .WithError(Errors.MediaConsumption.ConsumedDurationMustBeNonNegative); + + RuleFor(command => command.ConsumedDurationInSeconds) + .Must(consumedDuration => consumedDuration is null || + (double.IsFinite(consumedDuration.Value) && consumedDuration.Value >= 0)) + .WithError(Errors.MediaConsumption.ConsumedDurationMustBeNonNegative); + + RuleFor(command => command.ConsumedDurationInSeconds) + .Must(consumedDuration => consumedDuration is null || + consumedDuration.Value <= MAXIMUM_REPORTED_DURATION_IN_SECONDS) + .WithError(Errors.MediaConsumption.ConsumedDurationIsOutOfRange); + + RuleFor(command => command.ConsecutivePagesRead) + .Must(consecutivePagesRead => consecutivePagesRead >= 0) + .WithError(Errors.MediaConsumption.ConsecutivePagesReadMustBeNonNegative); + } + + /// + /// Determines whether the reported position fields describe exactly one valid position. + /// + /// The name of the kind of the reported position, or when no position was reported. + /// The reported position within the media item, in seconds, when the position is a time offset. + /// The reported opaque locator within the media item, when the position is not a time offset. + /// if the position fields are valid, otherwise. + private static bool IsPositionShapeValid(string? positionKind, double? timeOffsetInSeconds, string? location) + { + // No kind means no position was reported, so a time offset or a locator without a kind would make the representation ambiguous. + if (string.IsNullOrWhiteSpace(positionKind)) + return !timeOffsetInSeconds.HasValue && string.IsNullOrWhiteSpace(location); + // Unknown and numeric kind names are not valid positions, even when the other fields look well formed. + if (!Enum.TryParse(positionKind, ignoreCase: true, out MediaPositionKind parsedPositionKind) || !Enum.IsDefined(parsedPositionKind)) + return false; + + // A position uses exactly one representation, because MediaPosition stores one kind and one value, so the fields of the other representation must be absent instead of ignored. + return parsedPositionKind switch + { + MediaPositionKind.TimeOffset => timeOffsetInSeconds.HasValue && + double.IsFinite(timeOffsetInSeconds.Value) && + timeOffsetInSeconds.Value >= 0 && + timeOffsetInSeconds.Value <= MAXIMUM_REPORTED_DURATION_IN_SECONDS && + string.IsNullOrWhiteSpace(location), + MediaPositionKind.Location => !timeOffsetInSeconds.HasValue && + !string.IsNullOrWhiteSpace(location) && + location.Length <= 4096, + _ => false + }; + } +} diff --git a/src/Lumina.Application/Core/MediaConsumption/Commands/StartConsumption/StartConsumptionCommand.cs b/src/Lumina.Application/Core/MediaConsumption/Commands/StartConsumption/StartConsumptionCommand.cs new file mode 100644 index 00000000..fd59cc96 --- /dev/null +++ b/src/Lumina.Application/Core/MediaConsumption/Commands/StartConsumption/StartConsumptionCommand.cs @@ -0,0 +1,19 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Core.MediaConsumption.Commands.StartConsumption; + +/// +/// Command for starting a consumption session of a media item by the current user. +/// +/// The unique identifier of the media library that contains the media item, taken from the route. +/// The kind of media that is consumed, taken from the route. +/// The unique identifier of the consumed media item, taken from the route. +[DebuggerDisplay("MediaKind: {MediaKind}; MediaItemId: {MediaItemId}")] +public record StartConsumptionCommand( + string? LibraryId, + string? MediaKind, + string? MediaItemId +) : ICommand; diff --git a/src/Lumina.Application/Core/MediaConsumption/Commands/StartConsumption/StartConsumptionCommandHandler.cs b/src/Lumina.Application/Core/MediaConsumption/Commands/StartConsumption/StartConsumptionCommandHandler.cs new file mode 100644 index 00000000..9cc18c87 --- /dev/null +++ b/src/Lumina.Application/Core/MediaConsumption/Commands/StartConsumption/StartConsumptionCommandHandler.cs @@ -0,0 +1,189 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.DataAccess.Entities.MediaConsumption; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.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.MediaConsumption; +using Lumina.Application.Common.Mapping.MediaLibrary.Management; +using Lumina.Contracts.Responses.MediaConsumption; +using Lumina.Domain.Common.Events; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.Common.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.ExternalIdentifiers.MediaLibraryBoundedContext.MediaItemAggregate; +using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.ExternalIdentifiers.UserManagementBoundedContext.UserAggregate; +using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.MediaConsumptionRecordAggregate; +using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.MediaResumePointAggregate; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +using ConsumptionLibraryId = Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.ExternalIdentifiers.LibraryManagementBoundedContext.LibraryAggregate.LibraryId; +using DomainErrors = Lumina.Domain.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.Core.MediaConsumption.Commands.StartConsumption; + +/// +/// Handler for the command to start a consumption session of a media item by the current user. +/// +public class StartConsumptionCommandHandler : ICommandHandler> +{ + private readonly IUnitOfWork _unitOfWork; + private readonly ICurrentUserService _currentUserService; + private readonly IAuthorizationService _authorizationService; + private readonly IDomainEventsQueue _domainEventsQueue; + private readonly IValidator _validator; + + /// + /// Initializes a new instance of the class. + /// + /// Injected unit of work for interacting with the data access layer repositories. + /// Injected service to retrieve the current user information. + /// Injected service for authorization related functionality. + /// Injected service for the queue of domain events. + /// Injected validator for application validation rules. + public StartConsumptionCommandHandler( + IUnitOfWork unitOfWork, + ICurrentUserService currentUserService, + IAuthorizationService authorizationService, + IDomainEventsQueue domainEventsQueue, + IValidator validator) + { + _unitOfWork = unitOfWork; + _currentUserService = currentUserService; + _authorizationService = authorizationService; + _domainEventsQueue = domainEventsQueue; + _validator = validator; + } + + /// + /// Handles the command to start a consumption session of a media item by the current user. + /// + /// The command to be handled. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either the created , or an error message. + /// + public async Task> HandleAsync(StartConsumptionCommand command, CancellationToken cancellationToken) + { + List validationResult = _validator.Validate(command); + if (validationResult.Count > 0) + return validationResult; + + // An authenticated request must always carry a user identity. + Guid? currentUserId = _currentUserService.UserId; + if (currentUserId is null) + return ApplicationErrors.Authorization.NotAuthorized; + Guid userId = currentUserId.Value; + + // The validator guarantees that the route identifiers are non-empty Guids and the media kind is a defined value before this point. + Guid libraryId = Guid.Parse(command.LibraryId!); + Guid mediaItemId = Guid.Parse(command.MediaItemId!); + MediaKind mediaKind = Enum.Parse(command.MediaKind!, ignoreCase: true); + + // Admins can start sessions in the libraries of all users; for everyone else, only in the libraries they own. Authorization is evaluated + // before the kind is checked or any library or media item is read, so an unauthorized caller cannot probe whether a resource exists. + bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync(userId, new LibraryOwnershipPolicyContext(libraryId), cancellationToken).ConfigureAwait(false); + if (!canAccessLibrary) + return ApplicationErrors.Authorization.NotAuthorized; + + // A kind that has no consumption rule, and a kind whose catalogue does not exist yet, cannot be consumed. + Optional ruleResult = MediaConsumptionRule.For(mediaKind); + if (!ruleResult.HasValue || !ruleResult.Value.IsSupportedByCurrentCatalogues) + return DomainErrors.MediaConsumption.UnsupportedMediaKind; + MediaConsumptionRule rule = ruleResult.Value; + + // The library is loaded after authorization, so an unauthorized caller cannot probe whether it exists. For an authorized caller, a missing + // library is reported as not found. + Result getLibraryResult = await _unitOfWork.LibraryRepository + .GetByIdAsync(libraryId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false); + if (getLibraryResult.IsFailure) + return getLibraryResult.Errors; + if (getLibraryResult.Value is null) + return DomainErrors.Library.LibraryNotFound; + LibraryConsumptionSettings consumptionSettings = getLibraryResult.Value.ToDomainValueObject(); + + // The item is resolved through the catalogue repository of its kind, and the route library is enforced on the loaded row. A wrong-library + // item is reported exactly like a missing item, so the route cannot be used to probe items of other libraries. + if (mediaKind == MediaKind.MusicTrack) + { + Result getTrackResult = await _unitOfWork.TrackRepository + .GetByIdAsync(mediaItemId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false); + if (getTrackResult.IsFailure) + return getTrackResult.Errors; + if (getTrackResult.Value is null || getTrackResult.Value.LibraryId != libraryId) + return DomainErrors.Music.TrackNotFound; + } + else if (mediaKind == MediaKind.Book) + { + Result getBookResult = await _unitOfWork.BookRepository + .GetByIdAsync(mediaItemId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false); + if (getBookResult.IsFailure) + return getBookResult.Errors; + if (getBookResult.Value is null || getBookResult.Value.LibraryId != libraryId) + return DomainErrors.WrittenContent.BookNotFound; + } + else + return DomainErrors.MediaConsumption.UnsupportedMediaKind; + + // When the library tracks progress and the kind can resume, the new session continues from the stored resume point. The consumed duration + // always starts at zero, because it measures this session only. + Optional initialPosition = Optional.None(); + double initialProgressFraction = 0; + if (consumptionSettings.ShouldTrackConsumptionProgress && rule.CanResume) + { + Result getResumePointResult = await _unitOfWork.MediaResumePointRepository + .GetForUserAndMediaItemAsync(userId, mediaKind, mediaItemId, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false); + if (getResumePointResult.IsFailure) + return getResumePointResult.Errors; + if (getResumePointResult.Value is not null) + { + Result toDomainEntityResult = getResumePointResult.Value.ToDomainEntity(); + if (toDomainEntityResult.IsFailure) + return toDomainEntityResult.Errors; + initialPosition = Optional.Some(toDomainEntityResult.Value.LastPosition); + initialProgressFraction = toDomainEntityResult.Value.LastProgressFraction; + } + } + + // A one-shot kind such as a photo completes in the same call, because a single view does not have a start and a stop request. + Result createRecordResult = rule.IsOneShot + ? MediaConsumptionRecord.StartCompleted(UserId.Create(userId), ConsumptionLibraryId.Create(libraryId), MediaItemId.Create(mediaItemId), mediaKind) + : MediaConsumptionRecord.Start(UserId.Create(userId), ConsumptionLibraryId.Create(libraryId), MediaItemId.Create(mediaItemId), mediaKind, initialPosition, initialProgressFraction); + if (createRecordResult.IsFailure) + return createRecordResult.Errors; + MediaConsumptionRecord record = createRecordResult.Value; + + Result insertResult = await _unitOfWork.MediaConsumptionRecordRepository.InsertAsync(record.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false); + if (insertResult.IsFailure) + return insertResult.Errors; + + Result saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + return saveChangesResult.Errors; + + // Queue any domain events, to be published after the request has completed successfully. + foreach (IDomainEvent domainEvent in record.GetDomainEvents()) + _domainEventsQueue.Enqueue(domainEvent); + + // The persisted row is read back, so the response carries the timestamps the auditing interceptor actually stored. + Result getPersistedRecordResult = await _unitOfWork.MediaConsumptionRecordRepository + .GetByIdForUserAsync(record.Id.Value, userId, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false); + if (getPersistedRecordResult.IsFailure) + return getPersistedRecordResult.Errors; + if (getPersistedRecordResult.Value is null) + return DomainErrors.MediaConsumption.ConsumptionRecordNotFound; + + return getPersistedRecordResult.Value.ToDto().ToResponse(); + } +} diff --git a/src/Lumina.Application/Core/MediaConsumption/Commands/StartConsumption/StartConsumptionCommandValidator.cs b/src/Lumina.Application/Core/MediaConsumption/Commands/StartConsumption/StartConsumptionCommandValidator.cs new file mode 100644 index 00000000..f12a2dab --- /dev/null +++ b/src/Lumina.Application/Core/MediaConsumption/Commands/StartConsumption/StartConsumptionCommandValidator.cs @@ -0,0 +1,52 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Utilities; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using System; +using System.Linq; +#endregion + +namespace Lumina.Application.Core.MediaConsumption.Commands.StartConsumption; + +/// +/// Validates the needed validation rules for . +/// +public class StartConsumptionCommandValidator : AbstractValidator +{ + /// + /// Initializes a new instance of the class. + /// + public StartConsumptionCommandValidator() + { + // Validates the identifier of the media library that contains the media item, taken from the route. + RuleFor(command => command.LibraryId) + .NotEmpty() + .WithError(Errors.Library.LibraryIdCannotBeEmpty); + + RuleFor(command => command.LibraryId) + .Must(libraryId => Guid.TryParse(libraryId, out Guid parsedLibraryId) && parsedLibraryId != Guid.Empty) + .When(command => command.LibraryId is not null && command.LibraryId.Length > 0) + .WithError(Errors.Library.LibraryIdCannotBeEmpty); + + // Validates the kind of media that is consumed, taken from the route. Only the member names are accepted, so a numeric route value that happens to parse as an enumeration value is rejected. Kinds that are not supported by the current catalogues are rejected by the handler, because that is a business rule. + RuleFor(command => command.MediaKind) + .NotEmpty() + .WithError(Errors.MediaConsumption.UnsupportedMediaKind); + + RuleFor(command => command.MediaKind) + .Must(mediaKind => Enum.GetNames().Contains(mediaKind, StringComparer.OrdinalIgnoreCase)) + .When(command => command.MediaKind is not null && command.MediaKind.Length > 0) + .WithError(Errors.MediaConsumption.UnsupportedMediaKind); + + // Validates the identifier of the consumed media item, taken from the route. + RuleFor(command => command.MediaItemId) + .NotEmpty() + .WithError(Errors.MediaConsumption.MediaItemIdCannotBeEmpty); + + 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.MediaConsumption.MediaItemIdCannotBeEmpty); + } +} diff --git a/src/Lumina.Application/Core/MediaConsumption/Commands/StopConsumption/StopConsumptionCommand.cs b/src/Lumina.Application/Core/MediaConsumption/Commands/StopConsumption/StopConsumptionCommand.cs new file mode 100644 index 00000000..53183900 --- /dev/null +++ b/src/Lumina.Application/Core/MediaConsumption/Commands/StopConsumption/StopConsumptionCommand.cs @@ -0,0 +1,27 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Core.MediaConsumption.Commands.StopConsumption; + +/// +/// Command for reporting that a consumption session of the current user stopped before it completed. +/// +/// The unique identifier of the consumption record, taken from the route. +/// The name of the kind of the final position reached in the media item, if the client reported one. +/// The final position within the media item, in seconds, when the position is a time offset. +/// The final opaque locator within the media item, when the position is not a time offset. +/// The final fraction of the media item that the client reached, between 0 and 1. +/// The active duration consumed by the session, in seconds. +/// The number of consecutive pages read in the session, used by page based media such as books. It must be absent or zero for other kinds. When it is absent, the count of the last progress report is kept. +[DebuggerDisplay("ConsumptionRecordId: {ConsumptionRecordId}; ProgressFraction: {ProgressFraction}; ConsecutivePagesRead: {ConsecutivePagesRead}")] +public record StopConsumptionCommand( + string? ConsumptionRecordId, + string? PositionKind, + double? PositionTimeOffsetInSeconds, + string? PositionLocation, + double? ProgressFraction, + double? ConsumedDurationInSeconds, + int? ConsecutivePagesRead +) : ICommand; diff --git a/src/Lumina.Application/Core/MediaConsumption/Commands/StopConsumption/StopConsumptionCommandHandler.cs b/src/Lumina.Application/Core/MediaConsumption/Commands/StopConsumption/StopConsumptionCommandHandler.cs new file mode 100644 index 00000000..44a1b919 --- /dev/null +++ b/src/Lumina.Application/Core/MediaConsumption/Commands/StopConsumption/StopConsumptionCommandHandler.cs @@ -0,0 +1,258 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.DataAccess.Entities.MediaConsumption; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; +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.MediaConsumption; +using Lumina.Application.Common.Mapping.MediaLibrary.Management; +using Lumina.Contracts.Responses.MediaConsumption; +using Lumina.Domain.Common.Events; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.Common.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.MediaConsumptionRecordAggregate; +using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.MediaResumePointAggregate; +using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption; +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.MediaConsumption.Commands.StopConsumption; + +/// +/// Handler for the command to report that a consumption session of the current user stopped before it completed. +/// +public class StopConsumptionCommandHandler : ICommandHandler> +{ + /// + /// The maximum number of times the terminal state is applied when a concurrent progress report changes the record between its + /// read and its save. + /// + private const int MAXIMUM_TERMINAL_SAVE_ATTEMPTS = 3; + + private readonly IUnitOfWork _unitOfWork; + private readonly ICurrentUserService _currentUserService; + private readonly IDomainEventsQueue _domainEventsQueue; + private readonly IValidator _validator; + + /// + /// Initializes a new instance of the class. + /// + /// Injected unit of work for interacting with the data access layer repositories. + /// Injected service to retrieve the current user information. + /// Injected service for the queue of domain events. + /// Injected validator for application validation rules. + public StopConsumptionCommandHandler( + IUnitOfWork unitOfWork, + ICurrentUserService currentUserService, + IDomainEventsQueue domainEventsQueue, + IValidator validator) + { + _unitOfWork = unitOfWork; + _currentUserService = currentUserService; + _domainEventsQueue = domainEventsQueue; + _validator = validator; + } + + /// + /// Handles the command to report that a consumption session of the current user stopped before it completed. + /// + /// The command to be handled. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either the stopped or completed , or an error message. + /// + public async Task> HandleAsync(StopConsumptionCommand command, CancellationToken cancellationToken) + { + List validationResult = _validator.Validate(command); + if (validationResult.Count > 0) + return validationResult; + + // An authenticated request must always carry a user identity. + Guid? currentUserId = _currentUserService.UserId; + if (currentUserId is null) + return ApplicationErrors.Authorization.NotAuthorized; + Guid userId = currentUserId.Value; + + // The validator guarantees that the route identifier and the reported measurements are valid before this point. + Guid consumptionRecordId = Guid.Parse(command.ConsumptionRecordId!); + + Optional position = ToMediaPosition(command.PositionKind, command.PositionTimeOffsetInSeconds, command.PositionLocation); + Optional consecutivePagesRead = command.ConsecutivePagesRead.HasValue + ? Optional.Some(command.ConsecutivePagesRead.Value) + : Optional.None(); + double progressFraction = command.ProgressFraction!.Value; + TimeSpan consumedDuration = TimeSpan.FromSeconds(command.ConsumedDurationInSeconds!.Value); + + // A terminal report can race with an in-flight progress report on the same record. The record is read, then saved with the + // version it was read with, so a progress report that commits in between makes the save fail with a concurrency conflict. + // The terminal payload is absolute, so the record is reloaded and the terminal state is applied again to the fresh version. + for (int attempt = 1; attempt <= MAXIMUM_TERMINAL_SAVE_ATTEMPTS; attempt++) + { + // The record is loaded scoped to the current user, so a record of another user is indistinguishable from a missing one. + Result getRecordResult = await _unitOfWork.MediaConsumptionRecordRepository.GetByIdForUserAsync(consumptionRecordId, userId, cancellationToken: cancellationToken).ConfigureAwait(false); + if (getRecordResult.IsFailure) + return getRecordResult.Errors; + if (getRecordResult.Value is null) + return DomainErrors.MediaConsumption.ConsumptionRecordNotFound; + + Result toDomainEntityResult = getRecordResult.Value.ToDomainEntity(); + if (toDomainEntityResult.IsFailure) + return toDomainEntityResult.Errors; + MediaConsumptionRecord record = toDomainEntityResult.Value; + + // The settings of the library decide whether reaching a threshold turns the stop into a completion. If the library was deleted after + // the session started, the defaults of the media kind are used instead, so the reported session can still be closed consistently. + Result getLibraryResult = await _unitOfWork.LibraryRepository + .GetByIdAsync(record.LibraryId.Value, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false); + if (getLibraryResult.IsFailure) + return getLibraryResult.Errors; + LibraryConsumptionSettings consumptionSettings = getLibraryResult.Value is null + ? LibraryConsumptionSettings.CreateDefault(record.MediaKind) + : getLibraryResult.Value.ToDomainValueObject(); + + // A session stopped at or after the completion threshold of its library is recorded as completed, not stopped, and loses its resume + // point. Tracking on without a threshold, and tracking off, never complete a session implicitly. The percentage is divided instead of + // multiplying the fraction by one hundred, because the multiplication can round a fraction that is exactly at the threshold below it. + bool isAtCompletionThreshold = consumptionSettings.ShouldTrackConsumptionProgress && + consumptionSettings.CompletionThresholdPercentage.HasValue && + progressFraction >= consumptionSettings.CompletionThresholdPercentage.Value / 100.0; + + Result terminalResult = isAtCompletionThreshold + ? record.Complete(position, progressFraction, consumedDuration, consecutivePagesRead) + : record.Stop(position, progressFraction, consumedDuration, consecutivePagesRead); + if (terminalResult.IsFailure) + return terminalResult.Errors; + + Optional ruleResult = MediaConsumptionRule.For(record.MediaKind); + if (!ruleResult.HasValue) + return DomainErrors.MediaConsumption.UnsupportedMediaKind; + + if (isAtCompletionThreshold) + { + // Completion discards the resume point, because the media item no longer has a point to continue from. + Result deleteResumePointResult = await _unitOfWork.MediaResumePointRepository.DeleteForUserAndMediaItemAsync(userId, record.MediaKind, record.MediaItemId.Value, cancellationToken).ConfigureAwait(false); + if (deleteResumePointResult.IsFailure) + return deleteResumePointResult.Errors; + } + else if (consumptionSettings.ShouldTrackConsumptionProgress && ruleResult.Value.CanResume && record.LastPosition.HasValue) + { + // A stopped session that did not reach the completion threshold keeps a resume point. Without a known position there is nothing to resume from, so no resume point is written. + Result upsertResumePointResult = await UpsertResumePointAsync(record, record.LastPosition.Value, record.LastProgressFraction, userId, cancellationToken).ConfigureAwait(false); + if (upsertResumePointResult.IsFailure) + return upsertResumePointResult.Errors; + } + + Result updateResult = await _unitOfWork.MediaConsumptionRecordRepository.UpdateForUserAsync(record.ToRepositoryEntity(), userId, cancellationToken).ConfigureAwait(false); + if (updateResult.IsFailure) + return updateResult.Errors; + + Result saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + { + // Only a concurrency conflict is worth retrying. The failed attempt is discarded, so the next loop reads the version + // the progress report committed and applies the terminal state to it. + if (attempt < MAXIMUM_TERMINAL_SAVE_ATTEMPTS && saveChangesResult.Errors.Any(error => error == ApplicationErrors.Persistence.ConcurrencyConflict)) + { + _unitOfWork.ClearTrackedEntities(); + continue; + } + return saveChangesResult.Errors; + } + + // Queue any domain events, to be published after the request has completed successfully. + foreach (IDomainEvent domainEvent in record.GetDomainEvents()) + _domainEventsQueue.Enqueue(domainEvent); + + // The persisted row is read back, so the response carries the timestamps and version the persistence medium actually stored. + Result getPersistedRecordResult = await _unitOfWork.MediaConsumptionRecordRepository + .GetByIdForUserAsync(record.Id.Value, userId, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false); + if (getPersistedRecordResult.IsFailure) + return getPersistedRecordResult.Errors; + if (getPersistedRecordResult.Value is null) + return DomainErrors.MediaConsumption.ConsumptionRecordNotFound; + + return getPersistedRecordResult.Value.ToDto().ToResponse(); + } + + // Every attempt conflicted with a concurrent write, so the terminal state could not be stored. + return ApplicationErrors.Persistence.ConcurrencyConflict; + } + + /// + /// Converts reported position fields that have already been validated to a . + /// + /// The name of the kind of the reported position, or when no position was reported. + /// The reported position within the media item, in seconds, when the position is a time offset. + /// The reported opaque locator within the media item, when the position is not a time offset. + /// The converted position, or no position when the client did not report one. + private static Optional ToMediaPosition(string? positionKind, double? timeOffsetInSeconds, string? location) + { + // A missing kind means the client did not report a position at all, which is different from a position at zero. + if (string.IsNullOrWhiteSpace(positionKind)) + return Optional.None(); + + // The validator already rejected unknown and undefined kinds, so the parse is safe here and no fallback value is invented. + MediaPositionKind parsedPositionKind = Enum.Parse(positionKind, ignoreCase: true); + // The kind names the single representation that the validator accepted, so only that representation is read. + return parsedPositionKind == MediaPositionKind.TimeOffset + ? Optional.Some(MediaPosition.CreateTimeOffset(TimeSpan.FromSeconds(timeOffsetInSeconds!.Value))) + : Optional.Some(MediaPosition.CreateLocation(location!)); + } + + /// + /// Creates or updates the resume point of for the current user. + /// + /// The consumption record whose session is being tracked. + /// The position at which the media item can be resumed. + /// The progress fraction at which the media item can be resumed. + /// The Id of the user the resume point belongs to. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful save, or an error message. + private async Task> UpsertResumePointAsync( + MediaConsumptionRecord record, MediaPosition position, double progressFraction, Guid userId, CancellationToken cancellationToken) + { + // The resume point is read without tracking because it is only used to build the domain aggregate. The upsert call locates and updates + // the stored row itself, so tracking this copy would put two tracked instances of the same row in the same unit of work. + Result getResumePointResult = await _unitOfWork.MediaResumePointRepository + .GetForUserAndMediaItemAsync(userId, record.MediaKind, record.MediaItemId.Value, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false); + if (getResumePointResult.IsFailure) + return getResumePointResult.Errors; + + MediaResumePoint resumePoint; + if (getResumePointResult.Value is null) + { + // A resume point that does not exist yet is created from the session identifiers and the effective position. The position and + // fraction are the ones the caller applied to the record, so the resume point and the record cannot disagree about the report. + Result createResumePointResult = MediaResumePoint.Create( + record.UserId, record.LibraryId, record.MediaItemId, record.MediaKind, position, progressFraction, record.LastActivityOnUtc); + if (createResumePointResult.IsFailure) + return createResumePointResult.Errors; + resumePoint = createResumePointResult.Value; + } + else + { + // An existing resume point is advanced instead of replaced, so its identifier and creation time survive and its own rules validate + // the new position and fraction before the update. The activity time is taken from the record, so both rows describe the same report. + Result toDomainEntityResult = getResumePointResult.Value.ToDomainEntity(); + if (toDomainEntityResult.IsFailure) + return toDomainEntityResult.Errors; + Result advanceResult = toDomainEntityResult.Value.Advance(position, progressFraction, record.LastActivityOnUtc); + if (advanceResult.IsFailure) + return advanceResult.Errors; + resumePoint = toDomainEntityResult.Value; + } + + // The upsert decides between the insert and the update from the unique business key, so a concurrent report that created the row + // between the read above and this call still ends with one resume point instead of a duplicate. + return await _unitOfWork.MediaResumePointRepository.UpsertForUserAsync(resumePoint.ToRepositoryEntity(), userId, cancellationToken).ConfigureAwait(false); + } +} diff --git a/src/Lumina.Application/Core/MediaConsumption/Commands/StopConsumption/StopConsumptionCommandValidator.cs b/src/Lumina.Application/Core/MediaConsumption/Commands/StopConsumption/StopConsumptionCommandValidator.cs new file mode 100644 index 00000000..69de6154 --- /dev/null +++ b/src/Lumina.Application/Core/MediaConsumption/Commands/StopConsumption/StopConsumptionCommandValidator.cs @@ -0,0 +1,101 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Utilities; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption; +using System; +#endregion + +namespace Lumina.Application.Core.MediaConsumption.Commands.StopConsumption; + +/// +/// Validates the needed validation rules for . +/// +public class StopConsumptionCommandValidator : AbstractValidator +{ + /// + /// The maximum active duration, in seconds, that a client can report for one session or as a position within a media item. The limit keeps + /// accumulated totals representable as a and rejects durations that cannot describe real media. + /// + private const double MAXIMUM_REPORTED_DURATION_IN_SECONDS = 31 * 24 * 60 * 60; + + /// + /// Initializes a new instance of the class. + /// + public StopConsumptionCommandValidator() + { + // Validates the identifier of the consumption record, taken from the route. + RuleFor(command => command.ConsumptionRecordId) + .NotEmpty() + .WithError(Errors.MediaConsumption.ConsumptionRecordIdCannotBeEmpty); + + RuleFor(command => command.ConsumptionRecordId) + .Must(consumptionRecordId => Guid.TryParse(consumptionRecordId, out Guid parsedConsumptionRecordId) && parsedConsumptionRecordId != Guid.Empty) + .When(command => command.ConsumptionRecordId is not null && command.ConsumptionRecordId.Length > 0) + .WithError(Errors.MediaConsumption.ConsumptionRecordIdCannotBeEmpty); + + // Validates that the reported position describes exactly one position, using the representation its kind names. + RuleFor(command => command.PositionKind) + .Must((command, positionKind) => IsPositionShapeValid( + positionKind, command.PositionTimeOffsetInSeconds, command.PositionLocation)) + .WithError(Errors.MediaConsumption.InvalidMediaPosition); + + RuleFor(command => command.ProgressFraction) + .NotNull() + .WithError(Errors.MediaConsumption.InvalidProgressFraction); + + RuleFor(command => command.ProgressFraction) + .Must(progressFraction => progressFraction is null || + (double.IsFinite(progressFraction.Value) && progressFraction.Value >= 0 && progressFraction.Value <= 1)) + .WithError(Errors.MediaConsumption.InvalidProgressFraction); + + RuleFor(command => command.ConsumedDurationInSeconds) + .NotNull() + .WithError(Errors.MediaConsumption.ConsumedDurationMustBeNonNegative); + + RuleFor(command => command.ConsumedDurationInSeconds) + .Must(consumedDuration => consumedDuration is null || + (double.IsFinite(consumedDuration.Value) && consumedDuration.Value >= 0)) + .WithError(Errors.MediaConsumption.ConsumedDurationMustBeNonNegative); + + RuleFor(command => command.ConsumedDurationInSeconds) + .Must(consumedDuration => consumedDuration is null || + consumedDuration.Value <= MAXIMUM_REPORTED_DURATION_IN_SECONDS) + .WithError(Errors.MediaConsumption.ConsumedDurationIsOutOfRange); + + RuleFor(command => command.ConsecutivePagesRead) + .Must(consecutivePagesRead => consecutivePagesRead is null || consecutivePagesRead.Value >= 0) + .WithError(Errors.MediaConsumption.ConsecutivePagesReadMustBeNonNegative); + } + + /// + /// Determines whether the reported position fields describe exactly one valid position. + /// + /// The name of the kind of the reported position, or when no position was reported. + /// The reported position within the media item, in seconds, when the position is a time offset. + /// The reported opaque locator within the media item, when the position is not a time offset. + /// if the position fields are valid, otherwise. + private static bool IsPositionShapeValid(string? positionKind, double? timeOffsetInSeconds, string? location) + { + // No kind means no position was reported, so a time offset or a locator without a kind would make the representation ambiguous. + if (string.IsNullOrWhiteSpace(positionKind)) + return !timeOffsetInSeconds.HasValue && string.IsNullOrWhiteSpace(location); + // Unknown and numeric kind names are not valid positions, even when the other fields look well formed. + if (!Enum.TryParse(positionKind, ignoreCase: true, out MediaPositionKind parsedPositionKind) || !Enum.IsDefined(parsedPositionKind)) + return false; + + // A position uses exactly one representation, because MediaPosition stores one kind and one value, so the fields of the other representation must be absent instead of ignored. + return parsedPositionKind switch + { + MediaPositionKind.TimeOffset => timeOffsetInSeconds.HasValue && + double.IsFinite(timeOffsetInSeconds.Value) && + timeOffsetInSeconds.Value >= 0 && + timeOffsetInSeconds.Value <= MAXIMUM_REPORTED_DURATION_IN_SECONDS && + string.IsNullOrWhiteSpace(location), + MediaPositionKind.Location => !timeOffsetInSeconds.HasValue && + !string.IsNullOrWhiteSpace(location) && + location.Length <= 4096, + _ => false + }; + } +} diff --git a/src/Lumina.Application/Core/MediaConsumption/Queries/GetAllUsersConsumptionStatistics/GetAllUsersConsumptionStatisticsQuery.cs b/src/Lumina.Application/Core/MediaConsumption/Queries/GetAllUsersConsumptionStatistics/GetAllUsersConsumptionStatisticsQuery.cs new file mode 100644 index 00000000..5d0a2166 --- /dev/null +++ b/src/Lumina.Application/Core/MediaConsumption/Queries/GetAllUsersConsumptionStatistics/GetAllUsersConsumptionStatisticsQuery.cs @@ -0,0 +1,21 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Core.MediaConsumption.Queries.GetAllUsersConsumptionStatistics; + +/// +/// Query for getting the consumption statistics of every user. +/// +/// The Id of the media library to restrict the statistics to, or for every library. +/// The name of the kind of media to restrict the statistics to, or for every kind. +/// The inclusive start of the date range, in UTC, or when the range has no start. +/// The inclusive end of the date range, in UTC, or when the range has no end. +[DebuggerDisplay("MediaKind: {MediaKind}")] +public record GetAllUsersConsumptionStatisticsQuery( + string? LibraryId, + string? MediaKind, + string? FromUtc, + string? ToUtc +) : IQuery; diff --git a/src/Lumina.Application/Core/MediaConsumption/Queries/GetAllUsersConsumptionStatistics/GetAllUsersConsumptionStatisticsQueryHandler.cs b/src/Lumina.Application/Core/MediaConsumption/Queries/GetAllUsersConsumptionStatistics/GetAllUsersConsumptionStatisticsQueryHandler.cs new file mode 100644 index 00000000..f8614720 --- /dev/null +++ b/src/Lumina.Application/Core/MediaConsumption/Queries/GetAllUsersConsumptionStatistics/GetAllUsersConsumptionStatisticsQueryHandler.cs @@ -0,0 +1,186 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.DataAccess.Entities.MediaConsumption; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.DTO.MediaConsumption; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Mapping.MediaConsumption; +using Lumina.Application.Common.Utilities; +using Lumina.Contracts.Responses.MediaConsumption; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.Common.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using System; +using System.Globalization; +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.MediaConsumption.Queries.GetAllUsersConsumptionStatistics; + +/// +/// Handler for the query to get the consumption statistics of every user. +/// +public class GetAllUsersConsumptionStatisticsQueryHandler : IQueryHandler> +{ + private readonly IUnitOfWork _unitOfWork; + private readonly ICurrentUserService _currentUserService; + private readonly IAuthorizationService _authorizationService; + private readonly IValidator _validator; + + /// + /// Initializes a new instance of the class. + /// + /// Injected unit of work for interacting with the data access layer repositories. + /// Injected service to retrieve the current user information. + /// Injected service for authorization related functionality. + /// Injected validator for application validation rules. + public GetAllUsersConsumptionStatisticsQueryHandler( + IUnitOfWork unitOfWork, + ICurrentUserService currentUserService, + IAuthorizationService authorizationService, + IValidator validator) + { + _unitOfWork = unitOfWork; + _currentUserService = currentUserService; + _authorizationService = authorizationService; + _validator = validator; + } + + /// + /// Handles the query to get the consumption statistics of every user. + /// + /// The query to be handled. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either the requested , or an error message. + /// + public async Task> HandleAsync(GetAllUsersConsumptionStatisticsQuery query, CancellationToken cancellationToken) + { + List validationResult = _validator.Validate(query); + if (validationResult.Count > 0) + return validationResult; + + // An authenticated request must always carry a user identity. + Guid? currentUserId = _currentUserService.UserId; + if (currentUserId is null) + return ApplicationErrors.Authorization.NotAuthorized; + Guid userId = currentUserId.Value; + + // Only admins can read the statistics of every user; the all-users summary is not derived from the per-user routes. + bool isAdmin = await _authorizationService.IsInRoleAsync(userId, AuthorizationRoles.ADMIN, cancellationToken).ConfigureAwait(false); + if (!isAdmin) + return ApplicationErrors.Authorization.NotAuthorized; + + Guid? libraryId = query.LibraryId is null ? null : Guid.Parse(query.LibraryId); + MediaKind? mediaKind = query.MediaKind is null ? null : Enum.Parse(query.MediaKind, ignoreCase: true); + DateTime? fromUtc = query.FromUtc is null ? null : DateTime.Parse(query.FromUtc, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal); + DateTime? toUtc = query.ToUtc is null ? null : DateTime.Parse(query.ToUtc, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal); + + // This is the only statistics query that loads the records of every user, and it is reachable only through the admin check above. + Result> getRecordsResult = await _unitOfWork.ConsumptionStatisticsRepository + .GetForAllUsersAsync(libraryId, mediaKind, fromUtc, toUtc, cancellationToken).ConfigureAwait(false); + if (getRecordsResult.IsFailure) + return getRecordsResult.Errors; + + // The user summaries are built in one pass over the grouped records. The server total is then derived from those summaries, so it can + // never disagree with the sum of the users and the records are not walked again for it. + List userSummaries = [.. getRecordsResult.Value + .GroupBy(record => record.UserId) + .OrderBy(group => group.Key) + .Select(group => BuildStatistics(group.Key, group))]; + + List totalMediaKindSummaries = [.. userSummaries + .SelectMany(summary => summary.MediaKindSummaries) + .GroupBy(summary => summary.MediaKind) + .OrderBy(group => group.Key) + .Select(group => + { + int countedSessionCount = group.Sum(summary => summary.CountedSessionCount); + int completedSessionCount = group.Sum(summary => summary.CompletedSessionCount); + return new MediaKindConsumptionStatisticsDto( + group.Key, + group.Sum(summary => summary.TotalConsumedDurationMilliseconds), + countedSessionCount, + completedSessionCount, + group.Sum(summary => summary.StoppedSessionCount), + countedSessionCount == 0 ? 0 : (double)completedSessionCount / countedSessionCount); + })]; + + int totalCountedSessionCount = userSummaries.Sum(summary => summary.CountedSessionCount); + int totalCompletedSessionCount = userSummaries.Sum(summary => summary.CompletedSessionCount); + ConsumptionTotalsDto totals = new( + userSummaries.Sum(summary => summary.TotalConsumedDurationMilliseconds), + totalCountedSessionCount, + totalCompletedSessionCount, + userSummaries.Sum(summary => summary.StoppedSessionCount), + totalCountedSessionCount == 0 ? 0 : (double)totalCompletedSessionCount / totalCountedSessionCount, + totalMediaKindSummaries); + + return new AllUsersConsumptionStatisticsDto(totals, userSummaries).ToResponse(); + } + + /// + /// Builds the consumption statistics of a user from the records of that user. + /// + /// The Id of the user the records belong to. + /// The records of the user, already filtered by the query. + /// The consumption statistics of the user. + private static ConsumptionStatisticsDto BuildStatistics(Guid userId, IEnumerable records) + { + // The rule is created once per media kind instead of once per record. A completed session always counts, while a stopped session counts + // only when it reaches the counting threshold of its media kind. Duration totals every session because it measures consumed time, not the + // subset of sessions that count towards the statistics. + List mediaKindSummaries = []; + foreach (IGrouping mediaKindGroup in records + .GroupBy(record => record.MediaKind) + .OrderBy(group => group.Key)) + { + Optional ruleResult = MediaConsumptionRule.For(mediaKindGroup.Key); + int countedSessionCount = 0; + int completedSessionCount = 0; + int stoppedSessionCount = 0; + long consumedDurationMilliseconds = 0; + foreach (MediaConsumptionRecordEntity record in mediaKindGroup) + { + consumedDurationMilliseconds += record.ConsumedDurationMilliseconds; + if (!ruleResult.HasValue) + continue; + if (record.Status == ConsumptionStatus.Completed) + completedSessionCount++; + if (!ruleResult.Value.Counts(record.Status, record.ConsumedDurationMilliseconds.ToClampedTimeSpan(), record.ConsecutivePagesRead)) + continue; + countedSessionCount++; + if (record.Status == ConsumptionStatus.Stopped) + stoppedSessionCount++; + } + mediaKindSummaries.Add(new MediaKindConsumptionStatisticsDto( + mediaKindGroup.Key, + consumedDurationMilliseconds, + countedSessionCount, + completedSessionCount, + stoppedSessionCount, + countedSessionCount == 0 ? 0 : (double)completedSessionCount / countedSessionCount)); + } + + // The overall totals are the sums of the per-kind summaries, so the completion rate can never disagree with the breakdown. + long totalConsumedDurationMilliseconds = mediaKindSummaries.Sum(summary => summary.TotalConsumedDurationMilliseconds); + int totalCountedSessionCount = mediaKindSummaries.Sum(summary => summary.CountedSessionCount); + int totalCompletedSessionCount = mediaKindSummaries.Sum(summary => summary.CompletedSessionCount); + int totalStoppedSessionCount = mediaKindSummaries.Sum(summary => summary.StoppedSessionCount); + return new ConsumptionStatisticsDto( + userId, + totalConsumedDurationMilliseconds, + totalCountedSessionCount, + totalCompletedSessionCount, + totalStoppedSessionCount, + totalCountedSessionCount == 0 ? 0 : (double)totalCompletedSessionCount / totalCountedSessionCount, + mediaKindSummaries); + } +} diff --git a/src/Lumina.Application/Core/MediaConsumption/Queries/GetAllUsersConsumptionStatistics/GetAllUsersConsumptionStatisticsQueryValidator.cs b/src/Lumina.Application/Core/MediaConsumption/Queries/GetAllUsersConsumptionStatistics/GetAllUsersConsumptionStatisticsQueryValidator.cs new file mode 100644 index 00000000..477bc71b --- /dev/null +++ b/src/Lumina.Application/Core/MediaConsumption/Queries/GetAllUsersConsumptionStatistics/GetAllUsersConsumptionStatisticsQueryValidator.cs @@ -0,0 +1,65 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Utilities; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using System; +using System.Globalization; +#endregion + +namespace Lumina.Application.Core.MediaConsumption.Queries.GetAllUsersConsumptionStatistics; + +/// +/// Validates the needed validation rules for . +/// +public class GetAllUsersConsumptionStatisticsQueryValidator : AbstractValidator +{ + /// + /// Initializes a new instance of the class. + /// + public GetAllUsersConsumptionStatisticsQueryValidator() + { + RuleFor(query => query.LibraryId) + .Must(libraryId => libraryId is null || + (Guid.TryParse(libraryId, out Guid parsedLibraryId) && parsedLibraryId != Guid.Empty)) + .WithError(Errors.Library.LibraryIdCannotBeEmpty); + + // Only the member names of the media kind enumeration are accepted, so a numeric value that happens to parse as a kind is rejected. + RuleFor(query => query.MediaKind) + .IsInEnum() + .WithError(Errors.MediaConsumption.UnsupportedMediaKind); + + RuleFor(query => query.MediaKind) + .Must(mediaKind => mediaKind is null || + !string.Equals(mediaKind, nameof(MediaKind.None), StringComparison.OrdinalIgnoreCase)) + .WithError(Errors.MediaConsumption.UnsupportedMediaKind); + + // A malformed bound, or an inverted range, would silently return no records, so both are rejected as an invalid request instead. + RuleFor(query => query.FromUtc) + .Must(fromUtc => fromUtc is null || DateTime.TryParse( + fromUtc, + CultureInfo.InvariantCulture, + DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal, + out _)) + .WithError(Errors.MediaConsumption.ConsumptionDateRangeIsInvalid); + + RuleFor(query => query.ToUtc) + .Must(toUtc => toUtc is null || DateTime.TryParse( + toUtc, + CultureInfo.InvariantCulture, + DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal, + out _)) + .WithError(Errors.MediaConsumption.ConsumptionDateRangeIsInvalid); + + RuleFor(query => query.FromUtc) + .Must((query, fromUtc) => + { + if (fromUtc is null || query.ToUtc is null || + !DateTime.TryParse(fromUtc, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal, out DateTime parsedFromUtc) || + !DateTime.TryParse(query.ToUtc, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal, out DateTime parsedToUtc)) + return true; + return parsedFromUtc <= parsedToUtc; + }) + .WithError(Errors.MediaConsumption.ConsumptionDateRangeIsInvalid); + } +} diff --git a/src/Lumina.Application/Core/MediaConsumption/Queries/GetConsumptionRecord/GetConsumptionRecordQuery.cs b/src/Lumina.Application/Core/MediaConsumption/Queries/GetConsumptionRecord/GetConsumptionRecordQuery.cs new file mode 100644 index 00000000..a6713c15 --- /dev/null +++ b/src/Lumina.Application/Core/MediaConsumption/Queries/GetConsumptionRecord/GetConsumptionRecordQuery.cs @@ -0,0 +1,15 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Core.MediaConsumption.Queries.GetConsumptionRecord; + +/// +/// Query for getting a consumption record of the current user. +/// +/// The Id of the consumption record, taken from the route. +[DebuggerDisplay("ConsumptionRecordId: {ConsumptionRecordId}")] +public record GetConsumptionRecordQuery( + string? ConsumptionRecordId +) : IQuery; diff --git a/src/Lumina.Application/Core/MediaConsumption/Queries/GetConsumptionRecord/GetConsumptionRecordQueryHandler.cs b/src/Lumina.Application/Core/MediaConsumption/Queries/GetConsumptionRecord/GetConsumptionRecordQueryHandler.cs new file mode 100644 index 00000000..834c448c --- /dev/null +++ b/src/Lumina.Application/Core/MediaConsumption/Queries/GetConsumptionRecord/GetConsumptionRecordQueryHandler.cs @@ -0,0 +1,78 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.DataAccess.Entities.MediaConsumption; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Mapping.MediaConsumption; +using Lumina.Contracts.Responses.MediaConsumption; +using Lumina.Domain.Common.Primitives; +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +using DomainErrors = Lumina.Domain.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.Core.MediaConsumption.Queries.GetConsumptionRecord; + +/// +/// Handler for the query to get a consumption record of the current user. +/// +public class GetConsumptionRecordQueryHandler : IQueryHandler> +{ + private readonly IUnitOfWork _unitOfWork; + private readonly ICurrentUserService _currentUserService; + private readonly IValidator _validator; + + /// + /// Initializes a new instance of the class. + /// + /// Injected unit of work for interacting with the data access layer repositories. + /// Injected service to retrieve the current user information. + /// Injected validator for application validation rules. + public GetConsumptionRecordQueryHandler( + IUnitOfWork unitOfWork, + ICurrentUserService currentUserService, + IValidator validator) + { + _unitOfWork = unitOfWork; + _currentUserService = currentUserService; + _validator = validator; + } + + /// + /// Handles the query to get a consumption record of the current user. + /// + /// The query to be handled. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either the requested , or an error message. + /// + public async Task> HandleAsync(GetConsumptionRecordQuery query, CancellationToken cancellationToken) + { + List validationResult = _validator.Validate(query); + if (validationResult.Count > 0) + return validationResult; + + // An authenticated request must always carry a user identity. + Guid? currentUserId = _currentUserService.UserId; + if (currentUserId is null) + return ApplicationErrors.Authorization.NotAuthorized; + Guid userId = currentUserId.Value; + + // The validator guarantees that the route identifier is a non-empty Guid before this point. + Guid consumptionRecordId = Guid.Parse(query.ConsumptionRecordId!); + + // The record is read without tracking and scoped to the current user, so a record of another user is indistinguishable from a missing one. + Result getRecordResult = await _unitOfWork.MediaConsumptionRecordRepository + .GetByIdForUserAsync(consumptionRecordId, userId, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false); + if (getRecordResult.IsFailure) + return getRecordResult.Errors; + if (getRecordResult.Value is null) + return DomainErrors.MediaConsumption.ConsumptionRecordNotFound; + + return getRecordResult.Value.ToDto().ToResponse(); + } +} diff --git a/src/Lumina.Application/Core/MediaConsumption/Queries/GetConsumptionRecord/GetConsumptionRecordQueryValidator.cs b/src/Lumina.Application/Core/MediaConsumption/Queries/GetConsumptionRecord/GetConsumptionRecordQueryValidator.cs new file mode 100644 index 00000000..3141e6e6 --- /dev/null +++ b/src/Lumina.Application/Core/MediaConsumption/Queries/GetConsumptionRecord/GetConsumptionRecordQueryValidator.cs @@ -0,0 +1,29 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Utilities; +using Lumina.Domain.Common.Errors; +using System; +#endregion + +namespace Lumina.Application.Core.MediaConsumption.Queries.GetConsumptionRecord; + +/// +/// Validates the needed validation rules for . +/// +public class GetConsumptionRecordQueryValidator : AbstractValidator +{ + /// + /// Initializes a new instance of the class. + /// + public GetConsumptionRecordQueryValidator() + { + RuleFor(query => query.ConsumptionRecordId) + .NotEmpty() + .WithError(Errors.MediaConsumption.ConsumptionRecordIdCannotBeEmpty); + + RuleFor(query => query.ConsumptionRecordId) + .Must(consumptionRecordId => Guid.TryParse(consumptionRecordId, out Guid parsedConsumptionRecordId) && parsedConsumptionRecordId != Guid.Empty) + .When(query => query.ConsumptionRecordId is not null && query.ConsumptionRecordId.Length > 0) + .WithError(Errors.MediaConsumption.ConsumptionRecordIdCannotBeEmpty); + } +} diff --git a/src/Lumina.Application/Core/MediaConsumption/Queries/GetConsumptionStatistics/GetConsumptionStatisticsQuery.cs b/src/Lumina.Application/Core/MediaConsumption/Queries/GetConsumptionStatistics/GetConsumptionStatisticsQuery.cs new file mode 100644 index 00000000..34b63d68 --- /dev/null +++ b/src/Lumina.Application/Core/MediaConsumption/Queries/GetConsumptionStatistics/GetConsumptionStatisticsQuery.cs @@ -0,0 +1,23 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Core.MediaConsumption.Queries.GetConsumptionStatistics; + +/// +/// Query for getting the consumption statistics of a user. +/// +/// The Id of the user whose statistics are retrieved, or for the current user. +/// The Id of the media library to restrict the statistics to, or for every library. +/// The name of the kind of media to restrict the statistics to, or for every kind. +/// The inclusive start of the date range, in UTC, or when the range has no start. +/// The inclusive end of the date range, in UTC, or when the range has no end. +[DebuggerDisplay("TargetUserId: {TargetUserId}; MediaKind: {MediaKind}")] +public record GetConsumptionStatisticsQuery( + string? TargetUserId, + string? LibraryId, + string? MediaKind, + string? FromUtc, + string? ToUtc +) : IQuery; diff --git a/src/Lumina.Application/Core/MediaConsumption/Queries/GetConsumptionStatistics/GetConsumptionStatisticsQueryHandler.cs b/src/Lumina.Application/Core/MediaConsumption/Queries/GetConsumptionStatistics/GetConsumptionStatisticsQueryHandler.cs new file mode 100644 index 00000000..812f62f0 --- /dev/null +++ b/src/Lumina.Application/Core/MediaConsumption/Queries/GetConsumptionStatistics/GetConsumptionStatisticsQueryHandler.cs @@ -0,0 +1,155 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.DataAccess.Entities.MediaConsumption; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.DTO.MediaConsumption; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Infrastructure.Authorization.Policies.ConsumptionActivity; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Mapping.MediaConsumption; +using Lumina.Application.Common.Utilities; +using Lumina.Contracts.Responses.MediaConsumption; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.Common.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using System; +using System.Globalization; +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.MediaConsumption.Queries.GetConsumptionStatistics; + +/// +/// Handler for the query to get the consumption statistics of a user. +/// +public class GetConsumptionStatisticsQueryHandler : IQueryHandler> +{ + private readonly IUnitOfWork _unitOfWork; + private readonly ICurrentUserService _currentUserService; + private readonly IAuthorizationService _authorizationService; + private readonly IValidator _validator; + + /// + /// Initializes a new instance of the class. + /// + /// Injected unit of work for interacting with the data access layer repositories. + /// Injected service to retrieve the current user information. + /// Injected service for authorization related functionality. + /// Injected validator for application validation rules. + public GetConsumptionStatisticsQueryHandler( + IUnitOfWork unitOfWork, + ICurrentUserService currentUserService, + IAuthorizationService authorizationService, + IValidator validator) + { + _unitOfWork = unitOfWork; + _currentUserService = currentUserService; + _authorizationService = authorizationService; + _validator = validator; + } + + /// + /// Handles the query to get the consumption statistics of a user. + /// + /// The query to be handled. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either the requested , or an error message. + /// + public async Task> HandleAsync(GetConsumptionStatisticsQuery query, CancellationToken cancellationToken) + { + List validationResult = _validator.Validate(query); + if (validationResult.Count > 0) + return validationResult; + + // An authenticated request must always carry a user identity. + Guid? currentUserId = _currentUserService.UserId; + if (currentUserId is null) + return ApplicationErrors.Authorization.NotAuthorized; + Guid userId = currentUserId.Value; + + // The target defaults to the current user, and the access policy is the only place that decides whether the caller may read it. + Guid targetUserId = query.TargetUserId is null ? userId : Guid.Parse(query.TargetUserId); + bool canAccessTarget = await _authorizationService.EvaluatePolicyAsync( + userId, new ConsumptionActivityAccessPolicyContext(targetUserId), cancellationToken).ConfigureAwait(false); + if (!canAccessTarget) + return ApplicationErrors.Authorization.NotAuthorized; + + Guid? libraryId = query.LibraryId is null ? null : Guid.Parse(query.LibraryId); + MediaKind? mediaKind = query.MediaKind is null ? null : Enum.Parse(query.MediaKind, ignoreCase: true); + DateTime? fromUtc = query.FromUtc is null ? null : DateTime.Parse(query.FromUtc, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal); + DateTime? toUtc = query.ToUtc is null ? null : DateTime.Parse(query.ToUtc, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal); + + // The handlers aggregate the records themselves; the repository only binds the filters and returns the records without tracking. + Result> getRecordsResult = await _unitOfWork.ConsumptionStatisticsRepository + .GetForUserAsync(targetUserId, libraryId, mediaKind, fromUtc, toUtc, cancellationToken).ConfigureAwait(false); + if (getRecordsResult.IsFailure) + return getRecordsResult.Errors; + + return BuildStatistics(targetUserId, getRecordsResult.Value).ToResponse(); + } + + /// + /// Builds the consumption statistics of a user from the records of that user. + /// + /// The Id of the user the records belong to. + /// The records of the user, already filtered by the query. + /// The consumption statistics of the user. + private static ConsumptionStatisticsDto BuildStatistics(Guid userId, IEnumerable records) + { + // The rule is created once per media kind instead of once per record. A completed session always counts, while a stopped session counts + // only when it reaches the counting threshold of its media kind. Duration totals every session because it measures consumed time, not the + // subset of sessions that count towards the statistics. + List mediaKindSummaries = []; + foreach (IGrouping mediaKindGroup in records + .GroupBy(record => record.MediaKind) + .OrderBy(group => group.Key)) + { + Optional ruleResult = MediaConsumptionRule.For(mediaKindGroup.Key); + int countedSessionCount = 0; + int completedSessionCount = 0; + int stoppedSessionCount = 0; + long consumedDurationMilliseconds = 0; + foreach (MediaConsumptionRecordEntity record in mediaKindGroup) + { + consumedDurationMilliseconds += record.ConsumedDurationMilliseconds; + if (!ruleResult.HasValue) + continue; + if (record.Status == ConsumptionStatus.Completed) + completedSessionCount++; + if (!ruleResult.Value.Counts(record.Status, record.ConsumedDurationMilliseconds.ToClampedTimeSpan(), record.ConsecutivePagesRead)) + continue; + countedSessionCount++; + if (record.Status == ConsumptionStatus.Stopped) + stoppedSessionCount++; + } + mediaKindSummaries.Add(new MediaKindConsumptionStatisticsDto( + mediaKindGroup.Key, + consumedDurationMilliseconds, + countedSessionCount, + completedSessionCount, + stoppedSessionCount, + countedSessionCount == 0 ? 0 : (double)completedSessionCount / countedSessionCount)); + } + + // The overall totals are the sums of the per-kind summaries, so the completion rate can never disagree with the breakdown. + long totalConsumedDurationMilliseconds = mediaKindSummaries.Sum(summary => summary.TotalConsumedDurationMilliseconds); + int totalCountedSessionCount = mediaKindSummaries.Sum(summary => summary.CountedSessionCount); + int totalCompletedSessionCount = mediaKindSummaries.Sum(summary => summary.CompletedSessionCount); + int totalStoppedSessionCount = mediaKindSummaries.Sum(summary => summary.StoppedSessionCount); + return new ConsumptionStatisticsDto( + userId, + totalConsumedDurationMilliseconds, + totalCountedSessionCount, + totalCompletedSessionCount, + totalStoppedSessionCount, + totalCountedSessionCount == 0 ? 0 : (double)totalCompletedSessionCount / totalCountedSessionCount, + mediaKindSummaries); + } +} diff --git a/src/Lumina.Application/Core/MediaConsumption/Queries/GetConsumptionStatistics/GetConsumptionStatisticsQueryValidator.cs b/src/Lumina.Application/Core/MediaConsumption/Queries/GetConsumptionStatistics/GetConsumptionStatisticsQueryValidator.cs new file mode 100644 index 00000000..4a51faeb --- /dev/null +++ b/src/Lumina.Application/Core/MediaConsumption/Queries/GetConsumptionStatistics/GetConsumptionStatisticsQueryValidator.cs @@ -0,0 +1,71 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Utilities; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using System; +using System.Globalization; +#endregion + +namespace Lumina.Application.Core.MediaConsumption.Queries.GetConsumptionStatistics; + +/// +/// Validates the needed validation rules for . +/// +public class GetConsumptionStatisticsQueryValidator : AbstractValidator +{ + /// + /// Initializes a new instance of the class. + /// + public GetConsumptionStatisticsQueryValidator() + { + // The target defaults to the current user, so an absent target is valid, but a supplied one must be a real user Id. + RuleFor(query => query.TargetUserId) + .Must(targetUserId => targetUserId is null || + (Guid.TryParse(targetUserId, out Guid parsedTargetUserId) && parsedTargetUserId != Guid.Empty)) + .WithError(Errors.MediaConsumption.TargetUserIdIsInvalid); + + RuleFor(query => query.LibraryId) + .Must(libraryId => libraryId is null || + (Guid.TryParse(libraryId, out Guid parsedLibraryId) && parsedLibraryId != Guid.Empty)) + .WithError(Errors.Library.LibraryIdCannotBeEmpty); + + // Only the member names of the media kind enumeration are accepted, so a numeric value that happens to parse as a kind is rejected. + RuleFor(query => query.MediaKind) + .IsInEnum() + .WithError(Errors.MediaConsumption.UnsupportedMediaKind); + + RuleFor(query => query.MediaKind) + .Must(mediaKind => mediaKind is null || + !string.Equals(mediaKind, nameof(MediaKind.None), StringComparison.OrdinalIgnoreCase)) + .WithError(Errors.MediaConsumption.UnsupportedMediaKind); + + // A malformed bound, or an inverted range, would silently return no records, so both are rejected as an invalid request instead. + RuleFor(query => query.FromUtc) + .Must(fromUtc => fromUtc is null || DateTime.TryParse( + fromUtc, + CultureInfo.InvariantCulture, + DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal, + out _)) + .WithError(Errors.MediaConsumption.ConsumptionDateRangeIsInvalid); + + RuleFor(query => query.ToUtc) + .Must(toUtc => toUtc is null || DateTime.TryParse( + toUtc, + CultureInfo.InvariantCulture, + DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal, + out _)) + .WithError(Errors.MediaConsumption.ConsumptionDateRangeIsInvalid); + + RuleFor(query => query.FromUtc) + .Must((query, fromUtc) => + { + if (fromUtc is null || query.ToUtc is null || + !DateTime.TryParse(fromUtc, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal, out DateTime parsedFromUtc) || + !DateTime.TryParse(query.ToUtc, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal, out DateTime parsedToUtc)) + return true; + return parsedFromUtc <= parsedToUtc; + }) + .WithError(Errors.MediaConsumption.ConsumptionDateRangeIsInvalid); + } +} diff --git a/src/Lumina.Application/Core/MediaConsumption/Queries/GetGenreConsumption/GetGenreConsumptionQuery.cs b/src/Lumina.Application/Core/MediaConsumption/Queries/GetGenreConsumption/GetGenreConsumptionQuery.cs new file mode 100644 index 00000000..1b11ae3c --- /dev/null +++ b/src/Lumina.Application/Core/MediaConsumption/Queries/GetGenreConsumption/GetGenreConsumptionQuery.cs @@ -0,0 +1,23 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Core.MediaConsumption.Queries.GetGenreConsumption; + +/// +/// Query for getting the consumption statistics of the genres of a user. +/// +/// The Id of the user whose statistics are retrieved, or for the current user. +/// The Id of the media library to restrict the statistics to, or for every library. +/// The name of the kind of media to restrict the statistics to, or for every kind. +/// The inclusive start of the date range, in UTC, as a text value, or when the range has no start. +/// The inclusive end of the date range, in UTC, as a text value, or when the range has no end. +[DebuggerDisplay("TargetUserId: {TargetUserId}; MediaKind: {MediaKind}")] +public record GetGenreConsumptionQuery( + string? TargetUserId, + string? LibraryId, + string? MediaKind, + string? FromUtc, + string? ToUtc +) : IQuery; diff --git a/src/Lumina.Application/Core/MediaConsumption/Queries/GetGenreConsumption/GetGenreConsumptionQueryHandler.cs b/src/Lumina.Application/Core/MediaConsumption/Queries/GetGenreConsumption/GetGenreConsumptionQueryHandler.cs new file mode 100644 index 00000000..1aa45038 --- /dev/null +++ b/src/Lumina.Application/Core/MediaConsumption/Queries/GetGenreConsumption/GetGenreConsumptionQueryHandler.cs @@ -0,0 +1,225 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.DataAccess.Entities.MediaConsumption; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.DTO.MediaConsumption; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Infrastructure.Authorization.Policies.ConsumptionActivity; +using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Mapping.MediaConsumption; +using Lumina.Application.Common.Utilities; +using Lumina.Contracts.Responses.MediaConsumption; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.Common.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.Core.MediaConsumption.Queries.GetGenreConsumption; + +/// +/// Handler for the query to get the consumption statistics of the genres of a user. +/// +public class GetGenreConsumptionQueryHandler : IQueryHandler>> +{ + private readonly IUnitOfWork _unitOfWork; + private readonly ICurrentUserService _currentUserService; + private readonly IAuthorizationService _authorizationService; + private readonly IValidator _validator; + + /// + /// Initializes a new instance of the class. + /// + /// Injected unit of work for interacting with the data access layer repositories. + /// Injected service to retrieve the current user information. + /// Injected service for authorization related functionality. + /// Injected validator for application validation rules. + public GetGenreConsumptionQueryHandler( + IUnitOfWork unitOfWork, + ICurrentUserService currentUserService, + IAuthorizationService authorizationService, + IValidator validator) + { + _unitOfWork = unitOfWork; + _currentUserService = currentUserService; + _authorizationService = authorizationService; + _validator = validator; + } + + /// + /// Handles the query to get the consumption statistics of the genres of a user. + /// + /// The query to be handled. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either the requested genre statistics, or an error message. + /// + public async Task>> HandleAsync(GetGenreConsumptionQuery query, CancellationToken cancellationToken) + { + List validationResult = _validator.Validate(query); + if (validationResult.Count > 0) + return validationResult; + + // An authenticated request must always carry a user identity. + Guid? currentUserId = _currentUserService.UserId; + if (currentUserId is null) + return ApplicationErrors.Authorization.NotAuthorized; + Guid userId = currentUserId.Value; + + // The target defaults to the current user, and the access policy is the only place that decides whether the caller may read it. + Guid targetUserId = query.TargetUserId is null ? userId : Guid.Parse(query.TargetUserId); + bool canAccessTarget = await _authorizationService.EvaluatePolicyAsync( + userId, new ConsumptionActivityAccessPolicyContext(targetUserId), cancellationToken).ConfigureAwait(false); + if (!canAccessTarget) + return ApplicationErrors.Authorization.NotAuthorized; + + Guid? libraryId = query.LibraryId is null ? null : Guid.Parse(query.LibraryId); + MediaKind? mediaKind = query.MediaKind is null ? null : Enum.Parse(query.MediaKind, ignoreCase: true); + DateTime? fromUtc = query.FromUtc is null ? null : DateTime.Parse(query.FromUtc, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal); + DateTime? toUtc = query.ToUtc is null ? null : DateTime.Parse(query.ToUtc, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal); + + Result> getRecordsResult = await _unitOfWork.ConsumptionStatisticsRepository + .GetForUserAsync(targetUserId, libraryId, mediaKind, fromUtc, toUtc, cancellationToken).ConfigureAwait(false); + if (getRecordsResult.IsFailure) + return getRecordsResult.Errors; + + // The access decision only needs the library Id that the records already carry, so it is made once per distinct library before any genre is + // loaded. Genres of a library the caller cannot access are never read. + Dictionary libraryAccess = []; + foreach (Guid recordLibraryId in getRecordsResult.Value.Select(record => record.LibraryId).Distinct()) + libraryAccess[recordLibraryId] = await _authorizationService.EvaluatePolicyAsync( + userId, new LibraryOwnershipPolicyContext(recordLibraryId), cancellationToken).ConfigureAwait(false); + + // Only the distinct item Ids of each kind in accessible libraries are read, through the catalogue repositories, in bounded chunks. + List trackIds = [.. getRecordsResult.Value + .Where(record => record.MediaKind == MediaKind.MusicTrack && libraryAccess[record.LibraryId]) + .Select(record => record.MediaItemId) + .Distinct()]; + List tracks = []; + if (trackIds.Count > 0) + { + Result> getTracksResult = await _unitOfWork.TrackRepository + .GetByIdsAsync(trackIds, shouldIncludeNavigationProperties: true, cancellationToken).ConfigureAwait(false); + if (getTracksResult.IsFailure) + return getTracksResult.Errors; + tracks = [.. getTracksResult.Value]; + } + + List bookIds = [.. getRecordsResult.Value + .Where(record => record.MediaKind == MediaKind.Book && libraryAccess[record.LibraryId]) + .Select(record => record.MediaItemId) + .Distinct()]; + List books = []; + if (bookIds.Count > 0) + { + Result> getBooksResult = await _unitOfWork.BookRepository + .GetByIdsAsync(bookIds, shouldIncludeNavigationProperties: true, cancellationToken).ConfigureAwait(false); + if (getBooksResult.IsFailure) + return getBooksResult.Errors; + books = [.. getBooksResult.Value]; + } + + Dictionary<(MediaKind MediaKind, Guid MediaItemId, Guid LibraryId), List> genreNamesByItem = []; + foreach (TrackEntity track in tracks) + { + List itemGenres = GetTrackGenreNames(track); + if (itemGenres.Count > 0) + genreNamesByItem[(MediaKind.MusicTrack, track.Id, track.LibraryId)] = itemGenres; + } + foreach (BookEntity book in books) + { + List itemGenres = [.. book.Genres.Select(genre => genre.Name).OfType()]; + if (itemGenres.Count > 0) + genreNamesByItem[(MediaKind.Book, book.Id, book.LibraryId)] = itemGenres; + } + + // The records are aggregated to one row per item and library first, so an item with several sessions contributes its genres once, not once per + // session. The library is part of the key because the item is resolved in its current library, and a record from another library must not + // borrow the genres or the access decision of the current one. An item that moved libraries after consumption is therefore excluded from the + // breakdown, matching the history lists that blank display data when the record and item libraries disagree. + Dictionary genres = []; + foreach (IGrouping<(MediaKind MediaKind, Guid MediaItemId, Guid LibraryId), MediaConsumptionRecordEntity> itemGroup in getRecordsResult.Value + .GroupBy(record => (record.MediaKind, record.MediaItemId, record.LibraryId))) + { + if (!libraryAccess[itemGroup.Key.LibraryId]) + continue; + if (!genreNamesByItem.TryGetValue((itemGroup.Key.MediaKind, itemGroup.Key.MediaItemId, itemGroup.Key.LibraryId), out List? itemGenres) || + itemGenres.Count == 0) + continue; + + // The breakdown mirrors the statistics, so an item whose sessions all fall below the counting threshold of their media kind does not + // contribute its genres or its duration to the breakdown. + Optional ruleResult = MediaConsumptionRule.For(itemGroup.Key.MediaKind); + if (!ruleResult.HasValue) + continue; + bool hasCountedSession = itemGroup.Any(record => ruleResult.Value.Counts( + record.Status, + record.ConsumedDurationMilliseconds.ToClampedTimeSpan(), + record.ConsecutivePagesRead)); + if (!hasCountedSession) + continue; + + long consumedDurationMilliseconds = itemGroup.Sum(record => record.ConsumedDurationMilliseconds); + AddGenres(genres, itemGenres, consumedDurationMilliseconds); + } + + List genreConsumptions = [.. genres + .Select(genre => new GenreConsumptionDto( + genre.Key, + genre.Value.ConsumedItemCount, + genre.Value.ConsumedDurationMilliseconds)) + .OrderByDescending(genreConsumption => genreConsumption.ConsumedItemCount) + .ThenByDescending(genreConsumption => genreConsumption.ConsumedDurationMilliseconds) + .ThenBy(genreConsumption => genreConsumption.Name)]; + + return Result.From(genreConsumptions.ToResponses()); + } + + /// + /// Gets the genre names of , falling back to the genres of its album and then its artist. + /// + /// The track whose genres are resolved. + /// The genre names of the track, its album, or its artist, in the first level that has any. + private static List GetTrackGenreNames(TrackEntity track) + { + List genreNames = [.. track.Genres.Select(genre => genre.Name).OfType()]; + if (genreNames.Count == 0 && track.Album is not null) + genreNames = [.. track.Album.Genres.Select(genre => genre.Name).OfType()]; + if (genreNames.Count == 0 && track.Album is not null && track.Album.Artist is not null) + genreNames = [.. track.Album.Artist.Genres.Select(genre => genre.Name).OfType()]; + return genreNames; + } + + /// + /// Adds the lowercase of one item to the accumulated . + /// + /// The accumulated genres, keyed by lowercase name. + /// The genre names carried by the item. + /// The duration consumed in the item, over all of its sessions, in milliseconds. + private static void AddGenres( + Dictionary genres, + List names, + long consumedDurationMilliseconds) + { + // The item is aggregated to one row, so each distinct lowercase name of the item is counted once, regardless of how many sessions it had. + foreach (string name in names.Select(name => name.Trim().ToLowerInvariant()).Distinct()) + { + if (name.Length == 0) + continue; + if (genres.TryGetValue(name, out (int ConsumedItemCount, long ConsumedDurationMilliseconds) current)) + genres[name] = (current.ConsumedItemCount + 1, current.ConsumedDurationMilliseconds + consumedDurationMilliseconds); + else + genres[name] = (1, consumedDurationMilliseconds); + } + } +} diff --git a/src/Lumina.Application/Core/MediaConsumption/Queries/GetGenreConsumption/GetGenreConsumptionQueryValidator.cs b/src/Lumina.Application/Core/MediaConsumption/Queries/GetGenreConsumption/GetGenreConsumptionQueryValidator.cs new file mode 100644 index 00000000..af8d4f0c --- /dev/null +++ b/src/Lumina.Application/Core/MediaConsumption/Queries/GetGenreConsumption/GetGenreConsumptionQueryValidator.cs @@ -0,0 +1,71 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Utilities; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using System; +using System.Globalization; +#endregion + +namespace Lumina.Application.Core.MediaConsumption.Queries.GetGenreConsumption; + +/// +/// Validates the needed validation rules for . +/// +public class GetGenreConsumptionQueryValidator : AbstractValidator +{ + /// + /// Initializes a new instance of the class. + /// + public GetGenreConsumptionQueryValidator() + { + // The target defaults to the current user, so an absent target is valid, but a supplied one must be a real user Id. + RuleFor(query => query.TargetUserId) + .Must(targetUserId => targetUserId is null || + (Guid.TryParse(targetUserId, out Guid parsedTargetUserId) && parsedTargetUserId != Guid.Empty)) + .WithError(Errors.MediaConsumption.TargetUserIdIsInvalid); + + RuleFor(query => query.LibraryId) + .Must(libraryId => libraryId is null || + (Guid.TryParse(libraryId, out Guid parsedLibraryId) && parsedLibraryId != Guid.Empty)) + .WithError(Errors.Library.LibraryIdCannotBeEmpty); + + // Only the member names of the media kind enumeration are accepted, so a numeric value that happens to parse as a kind is rejected. + RuleFor(query => query.MediaKind) + .IsInEnum() + .WithError(Errors.MediaConsumption.UnsupportedMediaKind); + + RuleFor(query => query.MediaKind) + .Must(mediaKind => mediaKind is null || + !string.Equals(mediaKind, nameof(MediaKind.None), StringComparison.OrdinalIgnoreCase)) + .WithError(Errors.MediaConsumption.UnsupportedMediaKind); + + // A malformed bound, or an inverted range, would silently return no records, so both are rejected as an invalid request instead. + RuleFor(query => query.FromUtc) + .Must(fromUtc => fromUtc is null || DateTime.TryParse( + fromUtc, + CultureInfo.InvariantCulture, + DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal, + out _)) + .WithError(Errors.MediaConsumption.ConsumptionDateRangeIsInvalid); + + RuleFor(query => query.ToUtc) + .Must(toUtc => toUtc is null || DateTime.TryParse( + toUtc, + CultureInfo.InvariantCulture, + DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal, + out _)) + .WithError(Errors.MediaConsumption.ConsumptionDateRangeIsInvalid); + + RuleFor(query => query.FromUtc) + .Must((query, fromUtc) => + { + if (fromUtc is null || query.ToUtc is null || + !DateTime.TryParse(fromUtc, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal, out DateTime parsedFromUtc) || + !DateTime.TryParse(query.ToUtc, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal, out DateTime parsedToUtc)) + return true; + return parsedFromUtc <= parsedToUtc; + }) + .WithError(Errors.MediaConsumption.ConsumptionDateRangeIsInvalid); + } +} diff --git a/src/Lumina.Application/Core/MediaConsumption/Queries/GetMostConsumed/GetMostConsumedQuery.cs b/src/Lumina.Application/Core/MediaConsumption/Queries/GetMostConsumed/GetMostConsumedQuery.cs new file mode 100644 index 00000000..3b0053fb --- /dev/null +++ b/src/Lumina.Application/Core/MediaConsumption/Queries/GetMostConsumed/GetMostConsumedQuery.cs @@ -0,0 +1,26 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.DTO.Pagination; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Core.MediaConsumption.Queries.GetMostConsumed; + +/// +/// Query for getting the most consumed media items of a user. +/// +/// The Id of the user whose history is retrieved, or for the current user. +/// The Id of the media library to restrict the history to, or for every library. +/// The name of the kind of media to restrict the history to, or for every kind. +/// The inclusive start of the date range, in UTC, or when the range has no start. +/// The inclusive end of the date range, in UTC, or when the range has no end. +/// The object containing the requested pagination data. When , every matching item is returned; when present, its requested page is returned. +[DebuggerDisplay("TargetUserId: {TargetUserId}; MediaKind: {MediaKind}")] +public record GetMostConsumedQuery( + string? TargetUserId, + string? LibraryId, + string? MediaKind, + string? FromUtc, + string? ToUtc, + PaginationDataDto? PaginationData +) : IQuery; diff --git a/src/Lumina.Application/Core/MediaConsumption/Queries/GetMostConsumed/GetMostConsumedQueryHandler.cs b/src/Lumina.Application/Core/MediaConsumption/Queries/GetMostConsumed/GetMostConsumedQueryHandler.cs new file mode 100644 index 00000000..4c3d5a81 --- /dev/null +++ b/src/Lumina.Application/Core/MediaConsumption/Queries/GetMostConsumed/GetMostConsumedQueryHandler.cs @@ -0,0 +1,349 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.DataAccess.Entities.MediaConsumption; +using Lumina.Application.Common.DataAccess.Entities.MediaContributors; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.DTO.MediaConsumption; +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.ConsumptionActivity; +using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Mapping.MediaConsumption; +using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; +using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +using Lumina.Application.Common.Utilities; +using Lumina.Contracts.Responses.Common; +using Lumina.Contracts.Responses.MediaConsumption; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.Common.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption; +using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using System; +using System.Globalization; +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.MediaConsumption.Queries.GetMostConsumed; + +/// +/// Handler for the query to get the most consumed media items of a user. +/// +public class GetMostConsumedQueryHandler : IQueryHandler>> +{ + private readonly IUnitOfWork _unitOfWork; + private readonly ICurrentUserService _currentUserService; + private readonly IAuthorizationService _authorizationService; + private readonly IValidator _validator; + + /// + /// Initializes a new instance of the class. + /// + /// Injected unit of work for interacting with the data access layer repositories. + /// Injected service to retrieve the current user information. + /// Injected service for authorization related functionality. + /// Injected validator for application validation rules. + public GetMostConsumedQueryHandler( + IUnitOfWork unitOfWork, + ICurrentUserService currentUserService, + IAuthorizationService authorizationService, + IValidator validator) + { + _unitOfWork = unitOfWork; + _currentUserService = currentUserService; + _authorizationService = authorizationService; + _validator = validator; + } + + /// + /// Handles the query to get the most consumed media items of a user. + /// + /// The query to be handled. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either the requested page of most consumed media items, or an error message. + /// + public async Task>> HandleAsync(GetMostConsumedQuery query, CancellationToken cancellationToken) + { + List validationResult = _validator.Validate(query); + if (validationResult.Count > 0) + return validationResult; + + // An authenticated request must always carry a user identity. + Guid? currentUserId = _currentUserService.UserId; + if (currentUserId is null) + return ApplicationErrors.Authorization.NotAuthorized; + Guid userId = currentUserId.Value; + + // The target defaults to the current user, and the access policy is the only place that decides whether the caller may read it. + Guid targetUserId = query.TargetUserId is null ? userId : Guid.Parse(query.TargetUserId); + bool canAccessTarget = await _authorizationService.EvaluatePolicyAsync( + userId, new ConsumptionActivityAccessPolicyContext(targetUserId), cancellationToken).ConfigureAwait(false); + if (!canAccessTarget) + return ApplicationErrors.Authorization.NotAuthorized; + + Guid? libraryId = query.LibraryId is null ? null : Guid.Parse(query.LibraryId); + MediaKind? mediaKind = query.MediaKind is null ? null : Enum.Parse(query.MediaKind, ignoreCase: true); + DateTime? fromUtc = query.FromUtc is null ? null : DateTime.Parse(query.FromUtc, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal); + DateTime? toUtc = query.ToUtc is null ? null : DateTime.Parse(query.ToUtc, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal); + + Result> getRecordsResult = await _unitOfWork.ConsumptionStatisticsRepository + .GetForUserAsync(targetUserId, libraryId, mediaKind, fromUtc, toUtc, cancellationToken).ConfigureAwait(false); + if (getRecordsResult.IsFailure) + return getRecordsResult.Errors; + + // The sessions are reduced to one row per media item before ordering and pagination, so an item consumed many times appears once. + List orderedAggregates = [.. BuildAggregates(getRecordsResult.Value) + .OrderByDescending(aggregate => aggregate.CountedSessionCount) + .ThenByDescending(aggregate => aggregate.ConsumedDurationMilliseconds) + .ThenByDescending(aggregate => aggregate.LastConsumedOnUtc) + .ThenBy(aggregate => aggregate.MediaItemId) + .ThenBy(aggregate => aggregate.MediaKind) + .ThenBy(aggregate => aggregate.LibraryId)]; + + PaginatedResultDto page; + if (query.PaginationData is null) + { + // Without pagination the caller asked for every matching item, which is bounded by the number of distinct items in the history. + Result> getItemsResult = await ToConsumedItemDtosAsync(orderedAggregates, userId, cancellationToken).ConfigureAwait(false); + if (getItemsResult.IsFailure) + return getItemsResult.Errors; + page = new PaginatedResultDto + { + Data = getItemsResult.Value, + CurrentPage = 1, + PerPage = orderedAggregates.Count, + Count = orderedAggregates.Count, + NumberOfPages = 1 + }; + } + else + { + int currentPage = query.PaginationData.CurrentPage; + int perPage = query.PaginationData.PerPage; + int count = orderedAggregates.Count; + int numberOfPages = (int)Math.Ceiling((double)count / perPage); + int pageNumber = Math.Min(currentPage, Math.Max(1, numberOfPages)); + List pageAggregates = [.. orderedAggregates + .Skip((pageNumber - 1) * perPage) + .Take(perPage)]; + Result> getItemsResult = await ToConsumedItemDtosAsync(pageAggregates, userId, cancellationToken).ConfigureAwait(false); + if (getItemsResult.IsFailure) + return getItemsResult.Errors; + page = new PaginatedResultDto + { + Data = getItemsResult.Value, + CurrentPage = pageNumber, + PerPage = perPage, + Count = count, + NumberOfPages = numberOfPages + }; + } + + return Result.From(page.ToResponses()); + } + + /// + /// Aggregates the consumption records of each media item into the counts and duration that the history lists show. + /// + /// The consumption records of the user, already filtered by the query. + /// One aggregate per media item, library, and media kind. + private static List BuildAggregates(IReadOnlyList records) + { + List aggregates = []; + foreach (IGrouping<(MediaKind MediaKind, Guid MediaItemId, Guid LibraryId), MediaConsumptionRecordEntity> itemGroup in records + .GroupBy(record => (record.MediaKind, record.MediaItemId, record.LibraryId))) + { + // Counted sessions follow the rule of the media kind, while the completed count is the subset that completed. Duration totals every + // session of the item, because it measures consumed time, not only the sessions that count. + Optional ruleResult = MediaConsumptionRule.For(itemGroup.Key.MediaKind); + int countedSessionCount = 0; + int completedSessionCount = 0; + long consumedDurationMilliseconds = 0; + DateTime lastConsumedOnUtc = DateTime.MinValue; + foreach (MediaConsumptionRecordEntity record in itemGroup) + { + consumedDurationMilliseconds += record.ConsumedDurationMilliseconds; + if (record.LastActivityOnUtc > lastConsumedOnUtc) + lastConsumedOnUtc = record.LastActivityOnUtc; + if (record.Status == ConsumptionStatus.Completed) + completedSessionCount++; + if (ruleResult.HasValue && + ruleResult.Value.Counts(record.Status, record.ConsumedDurationMilliseconds.ToClampedTimeSpan(), record.ConsecutivePagesRead)) + countedSessionCount++; + } + aggregates.Add(new ConsumedItemAggregate( + itemGroup.Key.MediaKind, + itemGroup.Key.MediaItemId, + itemGroup.Key.LibraryId, + lastConsumedOnUtc, + countedSessionCount, + completedSessionCount, + consumedDurationMilliseconds)); + } + return aggregates; + } + + /// + /// Resolves the display data of the media items of and builds their DTOs. + /// + /// The aggregated history rows of the requested page. + /// The Id of the current user, used to decide which library display data may be shown. + /// Cancellation token that can be used to stop the execution. + /// The history rows, with blank display data for missing or inaccessible items. + private async Task>> ToConsumedItemDtosAsync( + List aggregates, Guid currentUserId, CancellationToken cancellationToken) + { + if (aggregates.Count == 0) + return new List(); + + // The access decision only needs the library Id that the record already carries, so it is made once per distinct library before any item + // or artwork is loaded. Inaccessible items keep their counts and duration, but their display data is never read. + Dictionary libraryAccess = []; + foreach (Guid libraryId in aggregates.Select(aggregate => aggregate.LibraryId).Distinct()) + libraryAccess[libraryId] = await _authorizationService.EvaluatePolicyAsync( + currentUserId, new LibraryOwnershipPolicyContext(libraryId), cancellationToken).ConfigureAwait(false); + + List trackIds = [.. aggregates + .Where(aggregate => aggregate.MediaKind == MediaKind.MusicTrack && libraryAccess[aggregate.LibraryId]) + .Select(aggregate => aggregate.MediaItemId) + .Distinct()]; + Dictionary tracks = []; + if (trackIds.Count > 0) + { + Result> getTracksResult = await _unitOfWork.TrackRepository + .GetByIdsAsync(trackIds, shouldIncludeNavigationProperties: true, cancellationToken).ConfigureAwait(false); + if (getTracksResult.IsFailure) + return getTracksResult.Errors; + tracks = getTracksResult.Value.ToDictionary(track => track.Id); + } + + List albumIds = [.. tracks.Values.Select(track => track.AlbumId).Distinct()]; + Dictionary albumCovers = []; + if (albumIds.Count > 0) + { + Result> getArtworkResult = await _unitOfWork.MusicArtworkRepository + .GetByOwnersAsync(MusicArtworkOwnerType.Album, albumIds, cancellationToken).ConfigureAwait(false); + if (getArtworkResult.IsFailure) + return getArtworkResult.Errors; + albumCovers = getArtworkResult.Value + .Where(artwork => artwork.ArtworkType == ArtworkType.Cover) + .GroupBy(artwork => artwork.OwnerId) + .ToDictionary( + group => group.Key, + group => group.OrderBy(artwork => artwork.Ordinal).Select(artwork => artwork.FileName).FirstOrDefault()); + } + + List bookIds = [.. aggregates + .Where(aggregate => aggregate.MediaKind == MediaKind.Book && libraryAccess[aggregate.LibraryId]) + .Select(aggregate => aggregate.MediaItemId) + .Distinct()]; + Dictionary books = []; + if (bookIds.Count > 0) + { + Result> getBooksResult = await _unitOfWork.BookRepository + .GetByIdsAsync(bookIds, shouldIncludeNavigationProperties: true, cancellationToken).ConfigureAwait(false); + if (getBooksResult.IsFailure) + return getBooksResult.Errors; + books = getBooksResult.Value.ToDictionary(book => book.Id); + } + + List authorIds = [.. books.Values + .SelectMany(book => book.Contributors + .Where(contributor => contributor.Role == MediaContributorRole.Author) + .Select(contributor => contributor.MediaContributorId)) + .Distinct()]; + Dictionary authorNames = []; + if (authorIds.Count > 0) + { + Result> getAuthorsResult = await _unitOfWork.MediaContributorRepository + .GetByIdsAsync(authorIds, cancellationToken).ConfigureAwait(false); + if (getAuthorsResult.IsFailure) + return getAuthorsResult.Errors; + authorNames = getAuthorsResult.Value.ToDictionary(contributor => contributor.Id, contributor => contributor.DisplayName); + } + + List items = []; + foreach (ConsumedItemAggregate aggregate in aggregates) + { + if (aggregate.MediaKind == MediaKind.MusicTrack && + libraryAccess[aggregate.LibraryId] && + tracks.TryGetValue(aggregate.MediaItemId, out TrackEntity? track) && + track.LibraryId == aggregate.LibraryId) + { + string? coverPath = albumCovers.TryGetValue(track.AlbumId, out string? coverFileName) ? coverFileName : null; + items.Add(track.ToDto( + aggregate.LastConsumedOnUtc, + aggregate.CountedSessionCount, + aggregate.CompletedSessionCount, + aggregate.ConsumedDurationMilliseconds, + coverPath)); + continue; + } + + if (aggregate.MediaKind == MediaKind.Book && + libraryAccess[aggregate.LibraryId] && + books.TryGetValue(aggregate.MediaItemId, out BookEntity? book) && + book.LibraryId == aggregate.LibraryId) + { + string creatorName = book.Contributors + .Where(contributor => contributor.Role == MediaContributorRole.Author && authorNames.ContainsKey(contributor.MediaContributorId)) + .Select(contributor => authorNames[contributor.MediaContributorId]) + .OrderBy(name => name) + .FirstOrDefault() ?? string.Empty; + items.Add(book.ToDto( + aggregate.LastConsumedOnUtc, + aggregate.CountedSessionCount, + aggregate.CompletedSessionCount, + aggregate.ConsumedDurationMilliseconds, + creatorName)); + continue; + } + + // A deleted or inaccessible item keeps its counts and duration, because the sessions were really consumed, but its display data is blank. + items.Add(new ConsumedItemDto( + aggregate.MediaKind, + aggregate.MediaItemId, + aggregate.LibraryId, + false, + string.Empty, + string.Empty, + string.Empty, + null, + aggregate.LastConsumedOnUtc, + aggregate.CountedSessionCount, + aggregate.CompletedSessionCount, + aggregate.ConsumedDurationMilliseconds)); + } + return items; + } + + /// + /// The aggregated consumption of one media item in one library. + /// + /// The kind of the consumed media item. + /// The Id of the consumed media item. + /// The Id of the media library that contains the media item. + /// The date and time when the media item was last consumed. + /// The number of sessions that count towards statistics. + /// The number of sessions that completed. + /// The active duration consumed in the media item, over all of its sessions, in milliseconds. + private sealed record ConsumedItemAggregate( + MediaKind MediaKind, + Guid MediaItemId, + Guid LibraryId, + DateTime LastConsumedOnUtc, + int CountedSessionCount, + int CompletedSessionCount, + long ConsumedDurationMilliseconds + ); +} diff --git a/src/Lumina.Application/Core/MediaConsumption/Queries/GetMostConsumed/GetMostConsumedQueryValidator.cs b/src/Lumina.Application/Core/MediaConsumption/Queries/GetMostConsumed/GetMostConsumedQueryValidator.cs new file mode 100644 index 00000000..1e5ada9d --- /dev/null +++ b/src/Lumina.Application/Core/MediaConsumption/Queries/GetMostConsumed/GetMostConsumedQueryValidator.cs @@ -0,0 +1,71 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Utilities; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using System; +using System.Globalization; +#endregion + +namespace Lumina.Application.Core.MediaConsumption.Queries.GetMostConsumed; + +/// +/// Validates the needed validation rules for . +/// +public class GetMostConsumedQueryValidator : AbstractValidator +{ + /// + /// Initializes a new instance of the class. + /// + public GetMostConsumedQueryValidator() + { + // The target defaults to the current user, so an absent target is valid, but a supplied one must be a real user Id. + RuleFor(query => query.TargetUserId) + .Must(targetUserId => targetUserId is null || + (Guid.TryParse(targetUserId, out Guid parsedTargetUserId) && parsedTargetUserId != Guid.Empty)) + .WithError(Errors.MediaConsumption.TargetUserIdIsInvalid); + + RuleFor(query => query.LibraryId) + .Must(libraryId => libraryId is null || + (Guid.TryParse(libraryId, out Guid parsedLibraryId) && parsedLibraryId != Guid.Empty)) + .WithError(Errors.Library.LibraryIdCannotBeEmpty); + + // Only the member names of the media kind enumeration are accepted, so a numeric value that happens to parse as a kind is rejected. + RuleFor(query => query.MediaKind) + .IsInEnum() + .WithError(Errors.MediaConsumption.UnsupportedMediaKind); + + RuleFor(query => query.MediaKind) + .Must(mediaKind => mediaKind is null || + !string.Equals(mediaKind, nameof(MediaKind.None), StringComparison.OrdinalIgnoreCase)) + .WithError(Errors.MediaConsumption.UnsupportedMediaKind); + + // A malformed bound, or an inverted range, would silently return no records, so both are rejected as an invalid request instead. + RuleFor(query => query.FromUtc) + .Must(fromUtc => fromUtc is null || DateTime.TryParse( + fromUtc, + CultureInfo.InvariantCulture, + DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal, + out _)) + .WithError(Errors.MediaConsumption.ConsumptionDateRangeIsInvalid); + + RuleFor(query => query.ToUtc) + .Must(toUtc => toUtc is null || DateTime.TryParse( + toUtc, + CultureInfo.InvariantCulture, + DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal, + out _)) + .WithError(Errors.MediaConsumption.ConsumptionDateRangeIsInvalid); + + RuleFor(query => query.FromUtc) + .Must((query, fromUtc) => + { + if (fromUtc is null || query.ToUtc is null || + !DateTime.TryParse(fromUtc, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal, out DateTime parsedFromUtc) || + !DateTime.TryParse(query.ToUtc, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal, out DateTime parsedToUtc)) + return true; + return parsedFromUtc <= parsedToUtc; + }) + .WithError(Errors.MediaConsumption.ConsumptionDateRangeIsInvalid); + } +} diff --git a/src/Lumina.Application/Core/MediaConsumption/Queries/GetRecentlyConsumed/GetRecentlyConsumedQuery.cs b/src/Lumina.Application/Core/MediaConsumption/Queries/GetRecentlyConsumed/GetRecentlyConsumedQuery.cs new file mode 100644 index 00000000..68503691 --- /dev/null +++ b/src/Lumina.Application/Core/MediaConsumption/Queries/GetRecentlyConsumed/GetRecentlyConsumedQuery.cs @@ -0,0 +1,26 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.DTO.Pagination; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Core.MediaConsumption.Queries.GetRecentlyConsumed; + +/// +/// Query for getting the recently consumed media items of a user, from the most recently consumed. +/// +/// The Id of the user whose history is retrieved, or for the current user. +/// The Id of the media library to restrict the history to, or for every library. +/// The name of the kind of media to restrict the history to, or for every kind. +/// The inclusive start of the date range, in UTC, or when the range has no start. +/// The inclusive end of the date range, in UTC, or when the range has no end. +/// The object containing the requested pagination data. When , every matching item is returned; when present, its requested page is returned. +[DebuggerDisplay("TargetUserId: {TargetUserId}; MediaKind: {MediaKind}")] +public record GetRecentlyConsumedQuery( + string? TargetUserId, + string? LibraryId, + string? MediaKind, + string? FromUtc, + string? ToUtc, + PaginationDataDto? PaginationData +) : IQuery; diff --git a/src/Lumina.Application/Core/MediaConsumption/Queries/GetRecentlyConsumed/GetRecentlyConsumedQueryHandler.cs b/src/Lumina.Application/Core/MediaConsumption/Queries/GetRecentlyConsumed/GetRecentlyConsumedQueryHandler.cs new file mode 100644 index 00000000..118140f4 --- /dev/null +++ b/src/Lumina.Application/Core/MediaConsumption/Queries/GetRecentlyConsumed/GetRecentlyConsumedQueryHandler.cs @@ -0,0 +1,346 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.DataAccess.Entities.MediaConsumption; +using Lumina.Application.Common.DataAccess.Entities.MediaContributors; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.DTO.MediaConsumption; +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.ConsumptionActivity; +using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Mapping.MediaConsumption; +using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; +using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +using Lumina.Application.Common.Utilities; +using Lumina.Contracts.Responses.Common; +using Lumina.Contracts.Responses.MediaConsumption; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.Common.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption; +using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using System; +using System.Globalization; +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.MediaConsumption.Queries.GetRecentlyConsumed; + +/// +/// Handler for the query to get the recently consumed media items of a user. +/// +public class GetRecentlyConsumedQueryHandler : IQueryHandler>> +{ + private readonly IUnitOfWork _unitOfWork; + private readonly ICurrentUserService _currentUserService; + private readonly IAuthorizationService _authorizationService; + private readonly IValidator _validator; + + /// + /// Initializes a new instance of the class. + /// + /// Injected unit of work for interacting with the data access layer repositories. + /// Injected service to retrieve the current user information. + /// Injected service for authorization related functionality. + /// Injected validator for application validation rules. + public GetRecentlyConsumedQueryHandler( + IUnitOfWork unitOfWork, + ICurrentUserService currentUserService, + IAuthorizationService authorizationService, + IValidator validator) + { + _unitOfWork = unitOfWork; + _currentUserService = currentUserService; + _authorizationService = authorizationService; + _validator = validator; + } + + /// + /// Handles the query to get the recently consumed media items of a user. + /// + /// The query to be handled. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either the requested page of recently consumed media items, or an error message. + /// + public async Task>> HandleAsync(GetRecentlyConsumedQuery query, CancellationToken cancellationToken) + { + List validationResult = _validator.Validate(query); + if (validationResult.Count > 0) + return validationResult; + + // An authenticated request must always carry a user identity. + Guid? currentUserId = _currentUserService.UserId; + if (currentUserId is null) + return ApplicationErrors.Authorization.NotAuthorized; + Guid userId = currentUserId.Value; + + // The target defaults to the current user, and the access policy is the only place that decides whether the caller may read it. + Guid targetUserId = query.TargetUserId is null ? userId : Guid.Parse(query.TargetUserId); + bool canAccessTarget = await _authorizationService.EvaluatePolicyAsync( + userId, new ConsumptionActivityAccessPolicyContext(targetUserId), cancellationToken).ConfigureAwait(false); + if (!canAccessTarget) + return ApplicationErrors.Authorization.NotAuthorized; + + Guid? libraryId = query.LibraryId is null ? null : Guid.Parse(query.LibraryId); + MediaKind? mediaKind = query.MediaKind is null ? null : Enum.Parse(query.MediaKind, ignoreCase: true); + DateTime? fromUtc = query.FromUtc is null ? null : DateTime.Parse(query.FromUtc, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal); + DateTime? toUtc = query.ToUtc is null ? null : DateTime.Parse(query.ToUtc, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal); + + Result> getRecordsResult = await _unitOfWork.ConsumptionStatisticsRepository + .GetForUserAsync(targetUserId, libraryId, mediaKind, fromUtc, toUtc, cancellationToken).ConfigureAwait(false); + if (getRecordsResult.IsFailure) + return getRecordsResult.Errors; + + // The sessions are reduced to one row per media item before ordering and pagination, so an item consumed many times appears once. + List orderedAggregates = [.. BuildAggregates(getRecordsResult.Value) + .OrderByDescending(aggregate => aggregate.LastConsumedOnUtc) + .ThenBy(aggregate => aggregate.MediaKind) + .ThenBy(aggregate => aggregate.MediaItemId) + .ThenBy(aggregate => aggregate.LibraryId)]; + + PaginatedResultDto page; + if (query.PaginationData is null) + { + // Without pagination the caller asked for every matching item, which is bounded by the number of distinct items in the history. + Result> getItemsResult = await ToConsumedItemDtosAsync(orderedAggregates, userId, cancellationToken).ConfigureAwait(false); + if (getItemsResult.IsFailure) + return getItemsResult.Errors; + page = new PaginatedResultDto + { + Data = getItemsResult.Value, + CurrentPage = 1, + PerPage = orderedAggregates.Count, + Count = orderedAggregates.Count, + NumberOfPages = 1 + }; + } + else + { + int currentPage = query.PaginationData.CurrentPage; + int perPage = query.PaginationData.PerPage; + int count = orderedAggregates.Count; + int numberOfPages = (int)Math.Ceiling((double)count / perPage); + int pageNumber = Math.Min(currentPage, Math.Max(1, numberOfPages)); + List pageAggregates = [.. orderedAggregates + .Skip((pageNumber - 1) * perPage) + .Take(perPage)]; + Result> getItemsResult = await ToConsumedItemDtosAsync(pageAggregates, userId, cancellationToken).ConfigureAwait(false); + if (getItemsResult.IsFailure) + return getItemsResult.Errors; + page = new PaginatedResultDto + { + Data = getItemsResult.Value, + CurrentPage = pageNumber, + PerPage = perPage, + Count = count, + NumberOfPages = numberOfPages + }; + } + + return Result.From(page.ToResponses()); + } + + /// + /// Aggregates the consumption records of each media item into the counts and duration that the history lists show. + /// + /// The consumption records of the user, already filtered by the query. + /// One aggregate per media item, library, and media kind. + private static List BuildAggregates(IReadOnlyList records) + { + List aggregates = []; + foreach (IGrouping<(MediaKind MediaKind, Guid MediaItemId, Guid LibraryId), MediaConsumptionRecordEntity> itemGroup in records + .GroupBy(record => (record.MediaKind, record.MediaItemId, record.LibraryId))) + { + // Counted sessions follow the rule of the media kind, while the completed count is the subset that completed. Duration totals every + // session of the item, because it measures consumed time, not only the sessions that count. + Optional ruleResult = MediaConsumptionRule.For(itemGroup.Key.MediaKind); + int countedSessionCount = 0; + int completedSessionCount = 0; + long consumedDurationMilliseconds = 0; + DateTime lastConsumedOnUtc = DateTime.MinValue; + foreach (MediaConsumptionRecordEntity record in itemGroup) + { + consumedDurationMilliseconds += record.ConsumedDurationMilliseconds; + if (record.LastActivityOnUtc > lastConsumedOnUtc) + lastConsumedOnUtc = record.LastActivityOnUtc; + if (record.Status == ConsumptionStatus.Completed) + completedSessionCount++; + if (ruleResult.HasValue && + ruleResult.Value.Counts(record.Status, record.ConsumedDurationMilliseconds.ToClampedTimeSpan(), record.ConsecutivePagesRead)) + countedSessionCount++; + } + aggregates.Add(new ConsumedItemAggregate( + itemGroup.Key.MediaKind, + itemGroup.Key.MediaItemId, + itemGroup.Key.LibraryId, + lastConsumedOnUtc, + countedSessionCount, + completedSessionCount, + consumedDurationMilliseconds)); + } + return aggregates; + } + + /// + /// Resolves the display data of the media items of and builds their DTOs. + /// + /// The aggregated history rows of the requested page. + /// The Id of the current user, used to decide which library display data may be shown. + /// Cancellation token that can be used to stop the execution. + /// The history rows, with blank display data for missing or inaccessible items. + private async Task>> ToConsumedItemDtosAsync(List aggregates, Guid currentUserId, CancellationToken cancellationToken) + { + if (aggregates.Count == 0) + return new List(); + + // The access decision only needs the library Id that the record already carries, so it is made once per distinct library before any item + // or artwork is loaded. Inaccessible items keep their counts and duration, but their display data is never read. + Dictionary libraryAccess = []; + foreach (Guid libraryId in aggregates.Select(aggregate => aggregate.LibraryId).Distinct()) + libraryAccess[libraryId] = await _authorizationService.EvaluatePolicyAsync( + currentUserId, new LibraryOwnershipPolicyContext(libraryId), cancellationToken).ConfigureAwait(false); + + List trackIds = [.. aggregates + .Where(aggregate => aggregate.MediaKind == MediaKind.MusicTrack && libraryAccess[aggregate.LibraryId]) + .Select(aggregate => aggregate.MediaItemId) + .Distinct()]; + Dictionary tracks = []; + if (trackIds.Count > 0) + { + Result> getTracksResult = await _unitOfWork.TrackRepository + .GetByIdsAsync(trackIds, shouldIncludeNavigationProperties: true, cancellationToken).ConfigureAwait(false); + if (getTracksResult.IsFailure) + return getTracksResult.Errors; + tracks = getTracksResult.Value.ToDictionary(track => track.Id); + } + + List albumIds = [.. tracks.Values.Select(track => track.AlbumId).Distinct()]; + Dictionary albumCovers = []; + if (albumIds.Count > 0) + { + Result> getArtworkResult = await _unitOfWork.MusicArtworkRepository + .GetByOwnersAsync(MusicArtworkOwnerType.Album, albumIds, cancellationToken).ConfigureAwait(false); + if (getArtworkResult.IsFailure) + return getArtworkResult.Errors; + albumCovers = getArtworkResult.Value + .Where(artwork => artwork.ArtworkType == ArtworkType.Cover) + .GroupBy(artwork => artwork.OwnerId) + .ToDictionary( + group => group.Key, + group => group.OrderBy(artwork => artwork.Ordinal).Select(artwork => artwork.FileName).FirstOrDefault()); + } + + List bookIds = [.. aggregates + .Where(aggregate => aggregate.MediaKind == MediaKind.Book && libraryAccess[aggregate.LibraryId]) + .Select(aggregate => aggregate.MediaItemId) + .Distinct()]; + Dictionary books = []; + if (bookIds.Count > 0) + { + Result> getBooksResult = await _unitOfWork.BookRepository + .GetByIdsAsync(bookIds, shouldIncludeNavigationProperties: true, cancellationToken).ConfigureAwait(false); + if (getBooksResult.IsFailure) + return getBooksResult.Errors; + books = getBooksResult.Value.ToDictionary(book => book.Id); + } + + List authorIds = [.. books.Values + .SelectMany(book => book.Contributors + .Where(contributor => contributor.Role == MediaContributorRole.Author) + .Select(contributor => contributor.MediaContributorId)) + .Distinct()]; + Dictionary authorNames = []; + if (authorIds.Count > 0) + { + Result> getAuthorsResult = await _unitOfWork.MediaContributorRepository + .GetByIdsAsync(authorIds, cancellationToken).ConfigureAwait(false); + if (getAuthorsResult.IsFailure) + return getAuthorsResult.Errors; + authorNames = getAuthorsResult.Value.ToDictionary(contributor => contributor.Id, contributor => contributor.DisplayName); + } + + List items = []; + foreach (ConsumedItemAggregate aggregate in aggregates) + { + if (aggregate.MediaKind == MediaKind.MusicTrack && + libraryAccess[aggregate.LibraryId] && + tracks.TryGetValue(aggregate.MediaItemId, out TrackEntity? track) && + track.LibraryId == aggregate.LibraryId) + { + string? coverPath = albumCovers.TryGetValue(track.AlbumId, out string? coverFileName) ? coverFileName : null; + items.Add(track.ToDto( + aggregate.LastConsumedOnUtc, + aggregate.CountedSessionCount, + aggregate.CompletedSessionCount, + aggregate.ConsumedDurationMilliseconds, + coverPath)); + continue; + } + + if (aggregate.MediaKind == MediaKind.Book && + libraryAccess[aggregate.LibraryId] && + books.TryGetValue(aggregate.MediaItemId, out BookEntity? book) && + book.LibraryId == aggregate.LibraryId) + { + string creatorName = book.Contributors + .Where(contributor => contributor.Role == MediaContributorRole.Author && authorNames.ContainsKey(contributor.MediaContributorId)) + .Select(contributor => authorNames[contributor.MediaContributorId]) + .OrderBy(name => name) + .FirstOrDefault() ?? string.Empty; + items.Add(book.ToDto( + aggregate.LastConsumedOnUtc, + aggregate.CountedSessionCount, + aggregate.CompletedSessionCount, + aggregate.ConsumedDurationMilliseconds, + creatorName)); + continue; + } + + // A deleted or inaccessible item keeps its counts and duration, because the sessions were really consumed, but its display data is blank. + items.Add(new ConsumedItemDto( + aggregate.MediaKind, + aggregate.MediaItemId, + aggregate.LibraryId, + false, + string.Empty, + string.Empty, + string.Empty, + null, + aggregate.LastConsumedOnUtc, + aggregate.CountedSessionCount, + aggregate.CompletedSessionCount, + aggregate.ConsumedDurationMilliseconds)); + } + return items; + } + + /// + /// The aggregated consumption of one media item in one library. + /// + /// The kind of the consumed media item. + /// The Id of the consumed media item. + /// The Id of the media library that contains the media item. + /// The date and time when the media item was last consumed. + /// The number of sessions that count towards statistics. + /// The number of sessions that completed. + /// The active duration consumed in the media item, over all of its sessions, in milliseconds. + private sealed record ConsumedItemAggregate( + MediaKind MediaKind, + Guid MediaItemId, + Guid LibraryId, + DateTime LastConsumedOnUtc, + int CountedSessionCount, + int CompletedSessionCount, + long ConsumedDurationMilliseconds + ); +} diff --git a/src/Lumina.Application/Core/MediaConsumption/Queries/GetRecentlyConsumed/GetRecentlyConsumedQueryValidator.cs b/src/Lumina.Application/Core/MediaConsumption/Queries/GetRecentlyConsumed/GetRecentlyConsumedQueryValidator.cs new file mode 100644 index 00000000..3bebfb33 --- /dev/null +++ b/src/Lumina.Application/Core/MediaConsumption/Queries/GetRecentlyConsumed/GetRecentlyConsumedQueryValidator.cs @@ -0,0 +1,71 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Utilities; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using System; +using System.Globalization; +#endregion + +namespace Lumina.Application.Core.MediaConsumption.Queries.GetRecentlyConsumed; + +/// +/// Validates the needed validation rules for . +/// +public class GetRecentlyConsumedQueryValidator : AbstractValidator +{ + /// + /// Initializes a new instance of the class. + /// + public GetRecentlyConsumedQueryValidator() + { + // The target defaults to the current user, so an absent target is valid, but a supplied one must be a real user Id. + RuleFor(query => query.TargetUserId) + .Must(targetUserId => targetUserId is null || + (Guid.TryParse(targetUserId, out Guid parsedTargetUserId) && parsedTargetUserId != Guid.Empty)) + .WithError(Errors.MediaConsumption.TargetUserIdIsInvalid); + + RuleFor(query => query.LibraryId) + .Must(libraryId => libraryId is null || + (Guid.TryParse(libraryId, out Guid parsedLibraryId) && parsedLibraryId != Guid.Empty)) + .WithError(Errors.Library.LibraryIdCannotBeEmpty); + + // Only the member names of the media kind enumeration are accepted, so a numeric value that happens to parse as a kind is rejected. + RuleFor(query => query.MediaKind) + .IsInEnum() + .WithError(Errors.MediaConsumption.UnsupportedMediaKind); + + RuleFor(query => query.MediaKind) + .Must(mediaKind => mediaKind is null || + !string.Equals(mediaKind, nameof(MediaKind.None), StringComparison.OrdinalIgnoreCase)) + .WithError(Errors.MediaConsumption.UnsupportedMediaKind); + + // A malformed bound, or an inverted range, would silently return no records, so both are rejected as an invalid request instead. + RuleFor(query => query.FromUtc) + .Must(fromUtc => fromUtc is null || DateTime.TryParse( + fromUtc, + CultureInfo.InvariantCulture, + DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal, + out _)) + .WithError(Errors.MediaConsumption.ConsumptionDateRangeIsInvalid); + + RuleFor(query => query.ToUtc) + .Must(toUtc => toUtc is null || DateTime.TryParse( + toUtc, + CultureInfo.InvariantCulture, + DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal, + out _)) + .WithError(Errors.MediaConsumption.ConsumptionDateRangeIsInvalid); + + RuleFor(query => query.FromUtc) + .Must((query, fromUtc) => + { + if (fromUtc is null || query.ToUtc is null || + !DateTime.TryParse(fromUtc, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal, out DateTime parsedFromUtc) || + !DateTime.TryParse(query.ToUtc, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal, out DateTime parsedToUtc)) + return true; + return parsedFromUtc <= parsedToUtc; + }) + .WithError(Errors.MediaConsumption.ConsumptionDateRangeIsInvalid); + } +} diff --git a/src/Lumina.Application/Core/MediaConsumption/Queries/GetResumePoint/GetResumePointQuery.cs b/src/Lumina.Application/Core/MediaConsumption/Queries/GetResumePoint/GetResumePointQuery.cs new file mode 100644 index 00000000..5beb428b --- /dev/null +++ b/src/Lumina.Application/Core/MediaConsumption/Queries/GetResumePoint/GetResumePointQuery.cs @@ -0,0 +1,17 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Core.MediaConsumption.Queries.GetResumePoint; + +/// +/// Query for getting the resume point of the current user for a media item. +/// +/// The kind of media to resume, taken from the route. +/// The Id of the media item to resume, taken from the route. +[DebuggerDisplay("MediaKind: {MediaKind}; MediaItemId: {MediaItemId}")] +public record GetResumePointQuery( + string? MediaKind, + string? MediaItemId +) : IQuery; diff --git a/src/Lumina.Application/Core/MediaConsumption/Queries/GetResumePoint/GetResumePointQueryHandler.cs b/src/Lumina.Application/Core/MediaConsumption/Queries/GetResumePoint/GetResumePointQueryHandler.cs new file mode 100644 index 00000000..058cd5b4 --- /dev/null +++ b/src/Lumina.Application/Core/MediaConsumption/Queries/GetResumePoint/GetResumePointQueryHandler.cs @@ -0,0 +1,180 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.DataAccess.Entities.MediaConsumption; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Mapping.MediaConsumption; +using Lumina.Contracts.Responses.MediaConsumption; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.Common.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +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.MediaConsumption.Queries.GetResumePoint; + +/// +/// Handler for the query to get the resume point of the current user for a media item. +/// +public class GetResumePointQueryHandler : IQueryHandler> +{ + private readonly IUnitOfWork _unitOfWork; + private readonly ICurrentUserService _currentUserService; + private readonly IValidator _validator; + + /// + /// Initializes a new instance of the class. + /// + /// Injected unit of work for interacting with the data access layer repositories. + /// Injected service to retrieve the current user information. + /// Injected validator for application validation rules. + public GetResumePointQueryHandler( + IUnitOfWork unitOfWork, + ICurrentUserService currentUserService, + IValidator validator) + { + _unitOfWork = unitOfWork; + _currentUserService = currentUserService; + _validator = validator; + } + + /// + /// Handles the query to get the resume point of the current user for a media item. + /// + /// The query to be handled. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either the requested , or an error message. + /// + public async Task> HandleAsync(GetResumePointQuery query, CancellationToken cancellationToken) + { + List validationResult = _validator.Validate(query); + if (validationResult.Count > 0) + return validationResult; + + // An authenticated request must always carry a user identity. + Guid? currentUserId = _currentUserService.UserId; + if (currentUserId is null) + return ApplicationErrors.Authorization.NotAuthorized; + Guid userId = currentUserId.Value; + + // The validator guarantees that the media kind is a defined value and the media item identifier is a non-empty Guid before this point. + MediaKind mediaKind = Enum.Parse(query.MediaKind!, ignoreCase: true); + Guid mediaItemId = Guid.Parse(query.MediaItemId!); + + Optional ruleResult = MediaConsumptionRule.For(mediaKind); + if (!ruleResult.HasValue) + return DomainErrors.MediaConsumption.UnsupportedMediaKind; + if (!ruleResult.Value.CanResume) + return DomainErrors.MediaConsumption.MediaKindCannotResume; + // A planned kind cannot have a resume point, because its catalogue does not exist yet and start rejects it. Report it as unsupported instead of + // as a missing resume point, so the response does not imply that the kind is usable. + if (!ruleResult.Value.IsSupportedByCurrentCatalogues) + return DomainErrors.MediaConsumption.UnsupportedMediaKind; + + // The resume point is read without tracking and scoped to the current user, so a resume point of another user is indistinguishable from a missing one. + Result getResumePointResult = await _unitOfWork.MediaResumePointRepository + .GetForUserAndMediaItemAsync(userId, mediaKind, mediaItemId, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false); + if (getResumePointResult.IsFailure) + return getResumePointResult.Errors; + if (getResumePointResult.Value is null) + return DomainErrors.MediaConsumption.MediaResumePointNotFound; + + // A resume point stored before progress tracking was turned off must not be served, because the library no longer remembers positions. + // It is deleted as stale data, so turning tracking on again starts from a fresh position instead of an old one. + Result getLibraryResult = await _unitOfWork.LibraryRepository + .GetByIdAsync(getResumePointResult.Value.LibraryId, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false); + if (getLibraryResult.IsFailure) + return getLibraryResult.Errors; + if (getLibraryResult.Value is not null && !getLibraryResult.Value.ShouldTrackConsumptionProgress) + { + Result deleteStaleResumePointResult = await _unitOfWork.MediaResumePointRepository.DeleteForUserAndMediaItemAsync(userId, mediaKind, mediaItemId, cancellationToken).ConfigureAwait(false); + if (deleteStaleResumePointResult.IsFailure) + return deleteStaleResumePointResult.Errors; + Result saveStaleResumePointDeletionResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + // A concurrent deletion of the same stale resume point is the desired outcome, so only other persistence failures are returned. + if (saveStaleResumePointDeletionResult.IsFailure && + !saveStaleResumePointDeletionResult.Errors.Any(error => error == ApplicationErrors.Persistence.ConcurrencyConflict)) + return saveStaleResumePointDeletionResult.Errors; + // The response is a not-found one, which the request pipeline does not commit, so the deletion is committed here to survive the request. + await CommitResumePointDeletionAsync(saveStaleResumePointDeletionResult, cancellationToken).ConfigureAwait(false); + return DomainErrors.MediaConsumption.MediaResumePointNotFound; + } + + // The media item must still exist in the library the resume point was recorded in. A resume point whose item was deleted, or whose item no + // longer belongs to that library, is an orphan, so it is removed before the same not-found result as a missing item is returned. + if (mediaKind == MediaKind.MusicTrack) + { + Result getTrackResult = await _unitOfWork.TrackRepository + .GetByIdAsync(mediaItemId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false); + if (getTrackResult.IsFailure) + return getTrackResult.Errors; + if (getTrackResult.Value is null || getTrackResult.Value.LibraryId != getResumePointResult.Value.LibraryId) + { + Result deleteResult = await _unitOfWork.MediaResumePointRepository.DeleteForUserAndMediaItemAsync(userId, mediaKind, mediaItemId, cancellationToken).ConfigureAwait(false); + if (deleteResult.IsFailure) + return deleteResult.Errors; + Result saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + // Another request may have deleted the same orphan between the delete and this save. That race is the desired outcome, so a + // concurrency conflict is treated as success; any other persistence failure is still returned. + if (saveChangesResult.IsFailure && !saveChangesResult.Errors.Any(error => error == ApplicationErrors.Persistence.ConcurrencyConflict)) + return saveChangesResult.Errors; + // The response is a not-found one, which the request pipeline does not commit, so the deletion is committed here to survive the request. + await CommitResumePointDeletionAsync(saveChangesResult, cancellationToken).ConfigureAwait(false); + return DomainErrors.Music.TrackNotFound; + } + } + else if (mediaKind == MediaKind.Book) + { + Result getBookResult = await _unitOfWork.BookRepository + .GetByIdAsync(mediaItemId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false); + if (getBookResult.IsFailure) + return getBookResult.Errors; + if (getBookResult.Value is null || getBookResult.Value.LibraryId != getResumePointResult.Value.LibraryId) + { + Result deleteResult = await _unitOfWork.MediaResumePointRepository.DeleteForUserAndMediaItemAsync(userId, mediaKind, mediaItemId, cancellationToken).ConfigureAwait(false); + if (deleteResult.IsFailure) + return deleteResult.Errors; + Result saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + // Another request may have deleted the same orphan between the delete and this save. That race is the desired outcome, so a + // concurrency conflict is treated as success; any other persistence failure is still returned. + if (saveChangesResult.IsFailure && !saveChangesResult.Errors.Any(error => error == ApplicationErrors.Persistence.ConcurrencyConflict)) + return saveChangesResult.Errors; + // The response is a not-found one, which the request pipeline does not commit, so the deletion is committed here to survive the request. + await CommitResumePointDeletionAsync(saveChangesResult, cancellationToken).ConfigureAwait(false); + return DomainErrors.WrittenContent.BookNotFound; + } + } + else + return DomainErrors.MediaConsumption.UnsupportedMediaKind; + + return getResumePointResult.Value.ToDto().ToResponse(); + } + + /// + /// Commits the deletion of a stale or orphan resume point, so that the cleanup survives the not-found response of this query. + /// + /// + /// The request transaction is committed by only when the response is a success, and this query intentionally + /// responds with a not-found error after it cleans up, so the deletion is committed here. A failed save has nothing to persist, and a concurrency + /// conflict means that the row is already gone, which is the desired outcome. Committing when no transaction is open is a no-op, which keeps the handler usable outside of the HTTP pipeline. + /// + /// The result of saving the resume point deletion. + /// Cancellation token that can be used to stop the execution. + private async Task CommitResumePointDeletionAsync(Result saveChangesResult, CancellationToken cancellationToken) + { + if (saveChangesResult.IsFailure) + return; + await _unitOfWork.CommitTransactionAsync(cancellationToken).ConfigureAwait(false); + } +} diff --git a/src/Lumina.Application/Core/MediaConsumption/Queries/GetResumePoint/GetResumePointQueryValidator.cs b/src/Lumina.Application/Core/MediaConsumption/Queries/GetResumePoint/GetResumePointQueryValidator.cs new file mode 100644 index 00000000..389ae690 --- /dev/null +++ b/src/Lumina.Application/Core/MediaConsumption/Queries/GetResumePoint/GetResumePointQueryValidator.cs @@ -0,0 +1,42 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Utilities; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using System; +using System.Linq; +#endregion + +namespace Lumina.Application.Core.MediaConsumption.Queries.GetResumePoint; + +/// +/// Validates the needed validation rules for . +/// +public class GetResumePointQueryValidator : AbstractValidator +{ + /// + /// Initializes a new instance of the class. + /// + public GetResumePointQueryValidator() + { + // Validates the kind of media to resume, taken from the route. Only the member names are accepted, so a numeric route value that happens to parse as an enumeration value is rejected. + RuleFor(query => query.MediaKind) + .NotEmpty() + .WithError(Errors.MediaConsumption.UnsupportedMediaKind); + + RuleFor(query => query.MediaKind) + .Must(mediaKind => Enum.GetNames().Contains(mediaKind, StringComparer.OrdinalIgnoreCase)) + .When(query => query.MediaKind is not null && query.MediaKind.Length > 0) + .WithError(Errors.MediaConsumption.UnsupportedMediaKind); + + // Validates the identifier of the media item to resume, taken from the route. + RuleFor(query => query.MediaItemId) + .NotEmpty() + .WithError(Errors.MediaConsumption.MediaItemIdCannotBeEmpty); + + RuleFor(query => query.MediaItemId) + .Must(mediaItemId => Guid.TryParse(mediaItemId, out Guid parsedMediaItemId) && parsedMediaItemId != Guid.Empty) + .When(query => query.MediaItemId is not null && query.MediaItemId.Length > 0) + .WithError(Errors.MediaConsumption.MediaItemIdCannotBeEmpty); + } +} diff --git a/src/Lumina.Application/Core/MediaConsumption/Queries/GetTagConsumption/GetTagConsumptionQuery.cs b/src/Lumina.Application/Core/MediaConsumption/Queries/GetTagConsumption/GetTagConsumptionQuery.cs new file mode 100644 index 00000000..1abff580 --- /dev/null +++ b/src/Lumina.Application/Core/MediaConsumption/Queries/GetTagConsumption/GetTagConsumptionQuery.cs @@ -0,0 +1,23 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Core.MediaConsumption.Queries.GetTagConsumption; + +/// +/// Query for getting the consumption statistics of the tags of a user. +/// +/// The Id of the user whose statistics are retrieved, or for the current user. +/// The Id of the media library to restrict the statistics to, or for every library. +/// The name of the kind of media to restrict the statistics to, or for every kind. +/// The inclusive start of the date range, in UTC, or when the range has no start. +/// The inclusive end of the date range, in UTC, or when the range has no end. +[DebuggerDisplay("TargetUserId: {TargetUserId}; MediaKind: {MediaKind}")] +public record GetTagConsumptionQuery( + string? TargetUserId, + string? LibraryId, + string? MediaKind, + string? FromUtc, + string? ToUtc +) : IQuery; diff --git a/src/Lumina.Application/Core/MediaConsumption/Queries/GetTagConsumption/GetTagConsumptionQueryHandler.cs b/src/Lumina.Application/Core/MediaConsumption/Queries/GetTagConsumption/GetTagConsumptionQueryHandler.cs new file mode 100644 index 00000000..24c5792a --- /dev/null +++ b/src/Lumina.Application/Core/MediaConsumption/Queries/GetTagConsumption/GetTagConsumptionQueryHandler.cs @@ -0,0 +1,225 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.DataAccess.Entities.MediaConsumption; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.DTO.MediaConsumption; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Infrastructure.Authorization.Policies.ConsumptionActivity; +using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Mapping.MediaConsumption; +using Lumina.Application.Common.Utilities; +using Lumina.Contracts.Responses.MediaConsumption; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.Common.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using System; +using System.Globalization; +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.MediaConsumption.Queries.GetTagConsumption; + +/// +/// Handler for the query to get the consumption statistics of the tags of a user. +/// +public class GetTagConsumptionQueryHandler : IQueryHandler>> +{ + private readonly IUnitOfWork _unitOfWork; + private readonly ICurrentUserService _currentUserService; + private readonly IAuthorizationService _authorizationService; + private readonly IValidator _validator; + + /// + /// Initializes a new instance of the class. + /// + /// Injected unit of work for interacting with the data access layer repositories. + /// Injected service to retrieve the current user information. + /// Injected service for authorization related functionality. + /// Injected validator for application validation rules. + public GetTagConsumptionQueryHandler( + IUnitOfWork unitOfWork, + ICurrentUserService currentUserService, + IAuthorizationService authorizationService, + IValidator validator) + { + _unitOfWork = unitOfWork; + _currentUserService = currentUserService; + _authorizationService = authorizationService; + _validator = validator; + } + + /// + /// Handles the query to get the consumption statistics of the tags of a user. + /// + /// The query to be handled. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either the requested tag statistics, or an error message. + /// + public async Task>> HandleAsync(GetTagConsumptionQuery query, CancellationToken cancellationToken) + { + List validationResult = _validator.Validate(query); + if (validationResult.Count > 0) + return validationResult; + + // An authenticated request must always carry a user identity. + Guid? currentUserId = _currentUserService.UserId; + if (currentUserId is null) + return ApplicationErrors.Authorization.NotAuthorized; + Guid userId = currentUserId.Value; + + // The target defaults to the current user, and the access policy is the only place that decides whether the caller may read it. + Guid targetUserId = query.TargetUserId is null ? userId : Guid.Parse(query.TargetUserId); + bool canAccessTarget = await _authorizationService.EvaluatePolicyAsync( + userId, new ConsumptionActivityAccessPolicyContext(targetUserId), cancellationToken).ConfigureAwait(false); + if (!canAccessTarget) + return ApplicationErrors.Authorization.NotAuthorized; + + Guid? libraryId = query.LibraryId is null ? null : Guid.Parse(query.LibraryId); + MediaKind? mediaKind = query.MediaKind is null ? null : Enum.Parse(query.MediaKind, ignoreCase: true); + DateTime? fromUtc = query.FromUtc is null ? null : DateTime.Parse(query.FromUtc, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal); + DateTime? toUtc = query.ToUtc is null ? null : DateTime.Parse(query.ToUtc, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal); + + Result> getRecordsResult = await _unitOfWork.ConsumptionStatisticsRepository + .GetForUserAsync(targetUserId, libraryId, mediaKind, fromUtc, toUtc, cancellationToken).ConfigureAwait(false); + if (getRecordsResult.IsFailure) + return getRecordsResult.Errors; + + // The access decision only needs the library Id that the records already carry, so it is made once per distinct library before any tag is + // loaded. Tags of a library the caller cannot access are never read. + Dictionary libraryAccess = []; + foreach (Guid recordLibraryId in getRecordsResult.Value.Select(record => record.LibraryId).Distinct()) + libraryAccess[recordLibraryId] = await _authorizationService.EvaluatePolicyAsync( + userId, new LibraryOwnershipPolicyContext(recordLibraryId), cancellationToken).ConfigureAwait(false); + + // Only the distinct item Ids of each kind in accessible libraries are read, through the catalogue repositories, in bounded chunks. + List trackIds = [.. getRecordsResult.Value + .Where(record => record.MediaKind == MediaKind.MusicTrack && libraryAccess[record.LibraryId]) + .Select(record => record.MediaItemId) + .Distinct()]; + List tracks = []; + if (trackIds.Count > 0) + { + Result> getTracksResult = await _unitOfWork.TrackRepository + .GetByIdsAsync(trackIds, shouldIncludeNavigationProperties: true, cancellationToken).ConfigureAwait(false); + if (getTracksResult.IsFailure) + return getTracksResult.Errors; + tracks = [.. getTracksResult.Value]; + } + + List bookIds = [.. getRecordsResult.Value + .Where(record => record.MediaKind == MediaKind.Book && libraryAccess[record.LibraryId]) + .Select(record => record.MediaItemId) + .Distinct()]; + List books = []; + if (bookIds.Count > 0) + { + Result> getBooksResult = await _unitOfWork.BookRepository + .GetByIdsAsync(bookIds, shouldIncludeNavigationProperties: true, cancellationToken).ConfigureAwait(false); + if (getBooksResult.IsFailure) + return getBooksResult.Errors; + books = [.. getBooksResult.Value]; + } + + Dictionary<(MediaKind MediaKind, Guid MediaItemId, Guid LibraryId), List> tagNamesByItem = []; + foreach (TrackEntity track in tracks) + { + List itemTags = GetTrackTagNames(track); + if (itemTags.Count > 0) + tagNamesByItem[(MediaKind.MusicTrack, track.Id, track.LibraryId)] = itemTags; + } + foreach (BookEntity book in books) + { + List itemTags = [.. book.Tags.Select(tag => tag.Name).OfType()]; + if (itemTags.Count > 0) + tagNamesByItem[(MediaKind.Book, book.Id, book.LibraryId)] = itemTags; + } + + // The records are aggregated to one row per item and library first, so an item with several sessions contributes its tags once, not once per + // session. The library is part of the key because the item is resolved in its current library, and a record from another library must not + // borrow the tags or the access decision of the current one. An item that moved libraries after consumption is therefore excluded from the + // breakdown, matching the history lists that blank display data when the record and item libraries disagree. + Dictionary tags = []; + foreach (IGrouping<(MediaKind MediaKind, Guid MediaItemId, Guid LibraryId), MediaConsumptionRecordEntity> itemGroup in getRecordsResult.Value + .GroupBy(record => (record.MediaKind, record.MediaItemId, record.LibraryId))) + { + if (!libraryAccess[itemGroup.Key.LibraryId]) + continue; + if (!tagNamesByItem.TryGetValue((itemGroup.Key.MediaKind, itemGroup.Key.MediaItemId, itemGroup.Key.LibraryId), out List? itemTags) || + itemTags.Count == 0) + continue; + + // The breakdown mirrors the statistics, so an item whose sessions all fall below the counting threshold of their media kind does not + // contribute its tags or its duration to the breakdown. + Optional ruleResult = MediaConsumptionRule.For(itemGroup.Key.MediaKind); + if (!ruleResult.HasValue) + continue; + bool hasCountedSession = itemGroup.Any(record => ruleResult.Value.Counts( + record.Status, + record.ConsumedDurationMilliseconds.ToClampedTimeSpan(), + record.ConsecutivePagesRead)); + if (!hasCountedSession) + continue; + + long consumedDurationMilliseconds = itemGroup.Sum(record => record.ConsumedDurationMilliseconds); + AddTags(tags, itemTags, consumedDurationMilliseconds); + } + + List tagConsumptions = [.. tags + .Select(tag => new TagConsumptionDto( + tag.Key, + tag.Value.ConsumedItemCount, + tag.Value.ConsumedDurationMilliseconds)) + .OrderByDescending(tagConsumption => tagConsumption.ConsumedItemCount) + .ThenByDescending(tagConsumption => tagConsumption.ConsumedDurationMilliseconds) + .ThenBy(tagConsumption => tagConsumption.Name)]; + + return Result.From(tagConsumptions.ToResponses()); + } + + /// + /// Gets the tag names of , falling back to the tags of its album and then its artist. + /// + /// The track whose tags are resolved. + /// The tag names of the track, its album, or its artist, in the first level that has any. + private static List GetTrackTagNames(TrackEntity track) + { + List tagNames = [.. track.Tags.Select(tag => tag.Name).OfType()]; + if (tagNames.Count == 0 && track.Album is not null) + tagNames = [.. track.Album.Tags.Select(tag => tag.Name).OfType()]; + if (tagNames.Count == 0 && track.Album is not null && track.Album.Artist is not null) + tagNames = [.. track.Album.Artist.Tags.Select(tag => tag.Name).OfType()]; + return tagNames; + } + + /// + /// Adds the lowercase of one item to the accumulated . + /// + /// The accumulated tags, keyed by lowercase name. + /// The tag names carried by the item. + /// The duration consumed in the item, over all of its sessions, in milliseconds. + private static void AddTags( + Dictionary tags, + List names, + long consumedDurationMilliseconds) + { + // The item is aggregated to one row, so each distinct lowercase name of the item is counted once, regardless of how many sessions it had. + foreach (string name in names.Select(name => name.Trim().ToLowerInvariant()).Distinct()) + { + if (name.Length == 0) + continue; + if (tags.TryGetValue(name, out (int ConsumedItemCount, long ConsumedDurationMilliseconds) current)) + tags[name] = (current.ConsumedItemCount + 1, current.ConsumedDurationMilliseconds + consumedDurationMilliseconds); + else + tags[name] = (1, consumedDurationMilliseconds); + } + } +} diff --git a/src/Lumina.Application/Core/MediaConsumption/Queries/GetTagConsumption/GetTagConsumptionQueryValidator.cs b/src/Lumina.Application/Core/MediaConsumption/Queries/GetTagConsumption/GetTagConsumptionQueryValidator.cs new file mode 100644 index 00000000..3c7bf4e1 --- /dev/null +++ b/src/Lumina.Application/Core/MediaConsumption/Queries/GetTagConsumption/GetTagConsumptionQueryValidator.cs @@ -0,0 +1,71 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Utilities; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using System; +using System.Globalization; +#endregion + +namespace Lumina.Application.Core.MediaConsumption.Queries.GetTagConsumption; + +/// +/// Validates the needed validation rules for . +/// +public class GetTagConsumptionQueryValidator : AbstractValidator +{ + /// + /// Initializes a new instance of the class. + /// + public GetTagConsumptionQueryValidator() + { + // The target defaults to the current user, so an absent target is valid, but a supplied one must be a real user Id. + RuleFor(query => query.TargetUserId) + .Must(targetUserId => targetUserId is null || + (Guid.TryParse(targetUserId, out Guid parsedTargetUserId) && parsedTargetUserId != Guid.Empty)) + .WithError(Errors.MediaConsumption.TargetUserIdIsInvalid); + + RuleFor(query => query.LibraryId) + .Must(libraryId => libraryId is null || + (Guid.TryParse(libraryId, out Guid parsedLibraryId) && parsedLibraryId != Guid.Empty)) + .WithError(Errors.Library.LibraryIdCannotBeEmpty); + + // Only the member names of the media kind enumeration are accepted, so a numeric value that happens to parse as a kind is rejected. + RuleFor(query => query.MediaKind) + .IsInEnum() + .WithError(Errors.MediaConsumption.UnsupportedMediaKind); + + RuleFor(query => query.MediaKind) + .Must(mediaKind => mediaKind is null || + !string.Equals(mediaKind, nameof(MediaKind.None), StringComparison.OrdinalIgnoreCase)) + .WithError(Errors.MediaConsumption.UnsupportedMediaKind); + + // A malformed bound, or an inverted range, would silently return no records, so both are rejected as an invalid request instead. + RuleFor(query => query.FromUtc) + .Must(fromUtc => fromUtc is null || DateTime.TryParse( + fromUtc, + CultureInfo.InvariantCulture, + DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal, + out _)) + .WithError(Errors.MediaConsumption.ConsumptionDateRangeIsInvalid); + + RuleFor(query => query.ToUtc) + .Must(toUtc => toUtc is null || DateTime.TryParse( + toUtc, + CultureInfo.InvariantCulture, + DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal, + out _)) + .WithError(Errors.MediaConsumption.ConsumptionDateRangeIsInvalid); + + RuleFor(query => query.FromUtc) + .Must((query, fromUtc) => + { + if (fromUtc is null || query.ToUtc is null || + !DateTime.TryParse(fromUtc, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal, out DateTime parsedFromUtc) || + !DateTime.TryParse(query.ToUtc, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal, out DateTime parsedToUtc)) + return true; + return parsedFromUtc <= parsedToUtc; + }) + .WithError(Errors.MediaConsumption.ConsumptionDateRangeIsInvalid); + } +} diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/IPlaybackDeliveryHandleService.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/IPlaybackDeliveryHandleService.cs new file mode 100644 index 00000000..4fb828d0 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/IPlaybackDeliveryHandleService.cs @@ -0,0 +1,39 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback; +using Lumina.Domain.Common.Primitives; +using System; +using Lumina.Domain.Common.Errors; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback; + +/// +/// Interface for the service that issues and resolves the opaque delivery handles of the playback manifest. +/// +/// +/// A delivery handle binds the delivery decision, the quality cap, the source file identity and the user to one opaque value, so the segment route +/// never recomputes them from inputs that can change while the track plays. A handle is only accepted from the user it was issued to, and only for +/// the track it describes, so it is not a capability that can be transferred to another user or track. Its format is exactly 32 lowercase +/// hexadecimal characters, the N format of a , and that format is the only rule every producer and consumer applies: a value +/// that does not match it is rejected, never normalized into another handle. +/// +public interface IPlaybackDeliveryHandleService +{ + /// + /// Issues an opaque handle for a delivery, which the playback manifest reports so its segments can be addressed by that handle. + /// + /// The delivery, its source file identity, its quality cap and its user. + /// The opaque delivery handle. + string IssueDeliveryId(PlaybackDeliveryHandleDto delivery); + + /// + /// Resolves the delivery a handle addresses, after verifying that it was issued to the provided user and describes the provided track. + /// + /// The opaque delivery handle reported by the playback manifest. + /// The Id of the current user, which the handle must have been issued to. + /// The Id of the track named by the route, which the handle must describe. + /// + /// An containing either the delivery, or when the handle is unknown, expired, or belongs to another user or track. + /// + Result GetDelivery(string? deliveryId, Guid userId, Guid trackId); +} diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/IPlaybackFormatService.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/IPlaybackFormatService.cs new file mode 100644 index 00000000..6f83888b --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/IPlaybackFormatService.cs @@ -0,0 +1,25 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback; +using Lumina.Domain.Common.Primitives; +using System.Collections.Generic; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback; + +/// +/// Interface for the service that decides whether the audio of a track can be played as stored by a player, or has to be +/// repackaged into another container or re-encoded into another codec before the player can play it. +/// +public interface IPlaybackFormatService +{ + /// + /// Decides how the audio of a track, described by , is delivered to a player that advertises . + /// + /// The container and codec of the audio of the track, read from its stored probe result. + /// The container and codec combinations the player advertises it can demux and decode directly. + /// + /// An containing either the delivery decision, or an error when the server cannot produce any + /// format the player advertises it supports. + /// + Result DecideDelivery(PlaybackSourceFormatDto sourceFormat, IReadOnlyList capabilities); +} diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/ITrackNormalizationService.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/ITrackNormalizationService.cs new file mode 100644 index 00000000..998ab9cc --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/ITrackNormalizationService.cs @@ -0,0 +1,62 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Common.Errors; +using System; +using System.IO; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback; + +/// +/// Interface for the service that produces, caches and serves the normalized audio of a track, when the player cannot play the stored audio directly. +/// +/// +/// The caller is responsible for authorizing the request. The service re-validates the source path against the allowed roots carried by the request and +/// re-checks it after opening, as defense in depth, so a caller that forgets containment cannot hand an arbitrary path to the transcoder. The service +/// itself only handles the media pipeline: it never reads or writes a database row, and it never emits a domain event. Every entry is bound to the track +/// it was produced for, so a cache handle can never be used to read the audio of another track. +/// A production is atomic: the cache entry is published only after ffmpeg has finished the whole track, so the first request waits for a complete +/// production. Streaming in this contract means serving the produced segments from the cache without buffering them into memory, not publishing a partial +/// track. Incremental publication of segment 0 while the rest is produced would be a different contract. Admission is bounded: when every normalization job +/// slot is in use, a request for an entry that is not cached yet is reported as unavailable instead of being queued behind the running jobs, and a single +/// user can only occupy a configured number of those slots, so a prefetch or a burst of requests from one user cannot make another user's playback fail. +/// A production that was admitted outlives the request that started it, so repeated aborts converge to a cached entry. A production that needs a toolchain the startup +/// probe found unusable reports as well, while an entry that is already +/// cached is still served. The playback stream surface exposes the produced segments to the player through the segment route of the track stream contract. +/// +public interface ITrackNormalizationService +{ + /// + /// Gets the normalized audio of a track from the cache, or produces it and caches it when it is not cached yet. + /// + /// The track, the requesting user, the delivery decision, the source file and the quality cap the normalized audio is produced with. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either the cached normalized audio of the track, or an error message. + /// + /// + /// Thrown when is canceled while the caller is waiting. The production continues in the background, so this is a + /// disconnect signal and must not be treated as a production failure. + /// + Task> GetOrCreateNormalizedTrackAsync(NormalizedTrackRequestDto request, CancellationToken cancellationToken); + + /// + /// Opens a read stream over a single segment of a cached normalized track, after verifying that the entry belongs to the provided track. + /// + /// + /// A missing or evicted cache entry, a segment that is no longer present, an entry that cannot be read, or a value that is not a well formed handle is + /// reported with . That is the caller's signal to request the + /// playback manifest again, or to trigger a new production, instead of treating the result as a broken transcode. A genuine production failure keeps + /// its own error. A service that has already been disposed reports . + /// + /// The opaque identifier of the cached entry that holds the normalized audio. + /// The Id of the track the caller authorized and whose segment is opened. + /// The zero based position of the segment in the delivered audio. + /// + /// An containing either a read stream over the segment, or an error message. The caller owns the returned stream. + /// + Result OpenNormalizedSegment(string cacheId, Guid trackId, int segmentIndex); +} diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackCapabilitiesParser.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackCapabilitiesParser.cs new file mode 100644 index 00000000..6739cd9a --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackCapabilitiesParser.cs @@ -0,0 +1,90 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback; +using System; +using System.Collections.Generic; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback; + +/// +/// Parses the capabilities input of a playback manifest request into the container and codec combinations a player advertises it +/// can demux and decode directly. +/// +/// +/// The input is a comma separated list of container/codec pairs, for example +/// mp3/mp3,flac/flac,ogg/opus,ogg/vorbis,wav/pcm,mp4/aac. The container and the codec of a pair are matched case +/// insensitively, and a pair that does not name both, with a non-empty container and codec, is ignored. The number of pairs is +/// capped, and the input is scanned entry by entry over its own characters, so a request never materializes an array of all its +/// entries and never yields more than a fixed number of capabilities, regardless of its length. When the input is absent or lists no +/// valid pair, the capabilities of the bundled player apply. +/// +public static class PlaybackCapabilitiesParser +{ + /// + /// The maximum number of capability pairs that are read from a single request, so that the parsing work stays bounded. + /// + public const int MAX_CAPABILITY_COUNT = 32; + + /// + /// The character that separates the container from the codec of a single capability pair. + /// + public const char CONTAINER_CODEC_SEPARATOR = '/'; + + /// + /// The character that separates the capability pairs of a capability set. + /// + public const char CAPABILITY_SEPARATOR = ','; + + /// + /// Gets the capability set the bundled player advertises, used when a request does not advertise any capability. + /// + public static IReadOnlyList Default { get; } = + [ + new PlaybackCapabilityDto("MP3", "MP3"), + new PlaybackCapabilityDto("FLAC", "FLAC"), + new PlaybackCapabilityDto("OGG", "OPUS"), + new PlaybackCapabilityDto("OGG", "VORBIS"), + new PlaybackCapabilityDto("WAV", "PCM"), + new PlaybackCapabilityDto("AAC", "AAC") + ]; + + /// + /// Parses the capabilities input of a playback manifest request into a capability set. + /// + /// The value of the capabilities input, a comma separated list of container/codec pairs. + /// The parsed capabilities, or when the input is absent, empty or lists no valid pair. + public static IReadOnlyList Parse(string? capabilitiesInput) + { + if (string.IsNullOrWhiteSpace(capabilitiesInput)) + return Default; + + List capabilities = []; + // The input is scanned entry by entry over its own characters, so the entries are never all materialized at once: only the + // container and the codec of an accepted pair are allocated, and the number of accepted pairs is capped. + ReadOnlySpan remainingEntries = capabilitiesInput.AsSpan(); + while (!remainingEntries.IsEmpty) + { + // The number of accepted pairs is capped, so a request never yields more than a fixed number of capabilities. + if (capabilities.Count >= MAX_CAPABILITY_COUNT) + break; + + int entrySeparatorIndex = remainingEntries.IndexOf(CAPABILITY_SEPARATOR); + ReadOnlySpan entry = entrySeparatorIndex < 0 ? remainingEntries : remainingEntries[..entrySeparatorIndex]; + remainingEntries = entrySeparatorIndex < 0 ? ReadOnlySpan.Empty : remainingEntries[(entrySeparatorIndex + 1)..]; + + // A pair names exactly one container and one codec, so exactly one separator must be present, and both parts must be + // named: a container or a codec that is empty (for example "a//b" or "/wav") does not name a pair. + int containerCodecSeparatorIndex = entry.IndexOf(CONTAINER_CODEC_SEPARATOR); + if (containerCodecSeparatorIndex < 0) + continue; + ReadOnlySpan container = entry[..containerCodecSeparatorIndex].Trim(); + ReadOnlySpan codec = entry[(containerCodecSeparatorIndex + 1)..].Trim(); + if (container.IsEmpty || codec.IsEmpty || codec.Contains(CONTAINER_CODEC_SEPARATOR)) + continue; + + capabilities.Add(new PlaybackCapabilityDto(container.ToString(), codec.ToString())); + } + + return capabilities.Count == 0 ? Default : capabilities; + } +} diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackDeliveryId.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackDeliveryId.cs new file mode 100644 index 00000000..655ad28d --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackDeliveryId.cs @@ -0,0 +1,31 @@ +namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback; + +/// +/// Defines the format of the opaque delivery handle of a playback manifest. +/// +/// +/// A handle is a rendered with the N format: exactly 32 lowercase hexadecimal characters, with no separator. Every producer +/// and consumer of a handle uses this rule, so a handle is never silently normalized into another value. +/// +public static class PlaybackDeliveryId +{ + /// + /// The number of characters of a delivery handle. + /// + public const int CHARACTER_COUNT = 32; + + /// + /// Checks whether a value has the format of a delivery handle. + /// + /// The value to check. + /// when the value is exactly 32 lowercase hexadecimal characters, otherwise . + public static bool IsValid(string? value) + { + if (value is null || value.Length != CHARACTER_COUNT) + return false; + foreach (char character in value) + if (!((character >= '0' && character <= '9') || (character >= 'a' && character <= 'f'))) + return false; + return true; + } +} diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/UpdateTrack/UpdateTrackCommand.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/UpdateTrack/UpdateTrackCommand.cs index 9f5c15f0..6230619f 100644 --- a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/UpdateTrack/UpdateTrackCommand.cs +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/UpdateTrack/UpdateTrackCommand.cs @@ -19,7 +19,6 @@ namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks. /// The unique identifier of the artist this track belongs to, taken from the route. /// The unique identifier of the album this track belongs to, taken from the route. /// The unique identifier of the track, taken from the route. -/// The file system path of the track. /// The audio metadata of the track. /// The number of the track on its disc. /// The number of the disc the track belongs to, if applicable. @@ -39,7 +38,6 @@ public record UpdateTrackCommand( string? ArtistId, string? AlbumId, string? TrackId, - string? Path, MusicTrackMetadataDto? Metadata, int? TrackNumber, int? DiscNumber, diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/UpdateTrack/UpdateTrackCommandHandler.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/UpdateTrack/UpdateTrackCommandHandler.cs index bced0f6d..edf2a6ad 100644 --- a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/UpdateTrack/UpdateTrackCommandHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/UpdateTrack/UpdateTrackCommandHandler.cs @@ -26,7 +26,6 @@ using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.ExternalIden using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate; using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.Entities; using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects; -using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; using Lumina.Domain.SharedKernel.Common.Enums.Common; using System; @@ -48,7 +47,6 @@ public class UpdateTrackCommandHandler : ICommandHandler _validator; - private readonly IPathService _pathService; /// /// Initializes a new instance of the class. @@ -57,14 +55,12 @@ public class UpdateTrackCommandHandler : ICommandHandlerInjected service for authorization related functionality. /// Injected service to retrieve the current user information. /// Injected validator for application validation rules. - /// Injected service for file system path related functionality. - public UpdateTrackCommandHandler(IUnitOfWork unitOfWork, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IValidator validator, IPathService pathService) + public UpdateTrackCommandHandler(IUnitOfWork unitOfWork, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IValidator validator) { _unitOfWork = unitOfWork; _authorizationService = authorizationService; _currentUserService = currentUserService; _validator = validator; - _pathService = pathService; } /// @@ -127,11 +123,6 @@ public class UpdateTrackCommandHandler : ICommandHandler> getContributorsResult = await GetExistingContributorsAsync(command, cancellationToken).ConfigureAwait(false); if (getContributorsResult.IsFailure) @@ -164,17 +155,6 @@ public class UpdateTrackCommandHandler : ICommandHandler - /// Determines whether the track path referenced by is stored inside one of the content locations of . - /// - /// The media library that owns the track. - /// The command carrying the referenced track. - /// when the referenced track path is within a content location of the library; otherwise, . - private bool AreTrackPathsWithinLibraryContentLocations(LibraryEntity library, UpdateTrackCommand command) - { - return library.ContentLocations.Any(contentLocation => _pathService.IsPathWithin(command.Path!, contentLocation.Path)); - } - /// /// Gets the media contributors referenced by , requiring each referenced Id to already exist. /// diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/UpdateTrack/UpdateTrackCommandValidator.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/UpdateTrack/UpdateTrackCommandValidator.cs index aee75a3e..04ae999c 100644 --- a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/UpdateTrack/UpdateTrackCommandValidator.cs +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/UpdateTrack/UpdateTrackCommandValidator.cs @@ -57,12 +57,6 @@ public class UpdateTrackCommandValidator : AbstractValidator .When(command => command.TrackId is not null && command.TrackId.Length > 0) .WithError(Errors.Music.TrackIdCannotBeEmpty); - RuleFor(command => command.Path) - .NotEmpty() - .WithError(Errors.Music.TrackPathCannotBeEmpty) - .MaximumLength(2048) - .WithError(Errors.Music.TrackPathMustBeMaximum2048CharactersLong); - // Validates the audio metadata of the track: title, lengths, release information, languages, genres and tags. RuleFor(command => command.Metadata) .NotNull() diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetPlaybackManifest/GetPlaybackManifestQuery.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetPlaybackManifest/GetPlaybackManifestQuery.cs new file mode 100644 index 00000000..469ff1c9 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetPlaybackManifest/GetPlaybackManifestQuery.cs @@ -0,0 +1,27 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Queries.GetPlaybackManifest; + +/// +/// Query for getting the playback manifest of a track. +/// +/// The unique identifier of the media library the track belongs to, taken from the route. +/// The unique identifier of the artist the album of the track belongs to, taken from the route. +/// The unique identifier of the album the track belongs to, taken from the route. +/// The unique identifier of the track whose playback manifest is retrieved, taken from the route. +/// The container and codec pairs the player advertises it can demux and decode directly, taken from the request, or when it advertises none. +/// The path of the track stream, relative to the API, taken from the endpoint so that it always matches the stream route. +/// The path template of the segment route, relative to the API, with a {deliveryId} and a {segmentIndex} placeholder, taken from the endpoint so that it always matches the segment route. +[DebuggerDisplay("TrackId: {TrackId}")] +public record GetPlaybackManifestQuery( + string? LibraryId, + string? ArtistId, + string? AlbumId, + string? TrackId, + string? Capabilities, + string StreamPath, + string SegmentStreamPathTemplate +) : IQuery; diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetPlaybackManifest/GetPlaybackManifestQueryHandler.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetPlaybackManifest/GetPlaybackManifestQueryHandler.cs new file mode 100644 index 00000000..b3d33cca --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetPlaybackManifest/GetPlaybackManifestQueryHandler.cs @@ -0,0 +1,212 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback; +using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback; +using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Playback; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; +using Lumina.Domain.SharedKernel.Common.Enums.Playback; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Queries.GetPlaybackManifest; + +/// +/// Handler for the query to get the playback manifest of a track. +/// +public class GetPlaybackManifestQueryHandler : IQueryHandler> +{ + private readonly IUnitOfWork _unitOfWork; + private readonly IPlaybackFormatService _playbackFormatService; + private readonly IPlaybackDeliveryHandleService _playbackDeliveryHandleService; + private readonly IAuthorizationService _authorizationService; + private readonly ICurrentUserService _currentUserService; + private readonly IPathService _pathService; + private readonly IValidator _validator; + + /// + /// Initializes a new instance of the class. + /// + /// Injected unit of work for interacting with the data access layer repositories. + /// Injected service for deciding how a track's audio is delivered to a player. + /// Injected service that issues the opaque delivery handles of a normalized manifest. + /// Injected service for authorization related functionality. + /// Injected service to retrieve the current user information. + /// Injected service for file system path related functionality. + /// Injected validator for application validation rules. + public GetPlaybackManifestQueryHandler(IUnitOfWork unitOfWork, IPlaybackFormatService playbackFormatService, IPlaybackDeliveryHandleService playbackDeliveryHandleService, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IPathService pathService, IValidator validator) + { + _unitOfWork = unitOfWork; + _playbackFormatService = playbackFormatService; + _playbackDeliveryHandleService = playbackDeliveryHandleService; + _authorizationService = authorizationService; + _currentUserService = currentUserService; + _pathService = pathService; + _validator = validator; + } + + /// + /// Handles the query to get the playback manifest of a track. + /// + /// The query to be handled. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either the playback manifest of the track, or an error message. + /// + public async Task> HandleAsync(GetPlaybackManifestQuery query, CancellationToken cancellationToken) + { + List validationResult = _validator.Validate(query); + if (validationResult.Count > 0) + return validationResult; + + // An authenticated request must always carry a user identity. + Guid? currentUserId = _currentUserService.UserId; + if (currentUserId is null) + return ApplicationErrors.Authorization.NotAuthorized; + Guid userId = currentUserId.Value; + + // The validator guarantees that the route identifiers are non-empty Guids before this point. + Guid libraryId = Guid.Parse(query.LibraryId!); + Guid artistId = Guid.Parse(query.ArtistId!); + Guid albumId = Guid.Parse(query.AlbumId!); + Guid trackId = Guid.Parse(query.TrackId!); + + // Admins can build the manifest of the tracks of all libraries; for everyone else, only the tracks of the libraries they own. + bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync( + userId, new LibraryOwnershipPolicyContext(libraryId), cancellationToken).ConfigureAwait(false); + if (!canAccessLibrary) + return ApplicationErrors.Authorization.NotAuthorized; + + // The projection is filtered by the library, the album and the artist named by the route as well as by the track, so a null row + // means the track either does not exist or is not in scope for the route, which is reported as not found without disclosing anything further. + Result getTrackResult = await _unitOfWork.TrackRepository.GetPlaybackManifestInfoAsync(libraryId, albumId, artistId, trackId, cancellationToken).ConfigureAwait(false); + if (getTrackResult.IsFailure) + return getTrackResult.Errors; + if (getTrackResult.Value is null) + return Errors.Music.TrackNotFound; + TrackPlaybackManifestDto track = getTrackResult.Value; + + // The stored container and codec of the probe result are the source format the delivery is decided on, and the capabilities + // the player advertises, or the default capabilities of the bundled player when it advertises none, decide the delivery. + IReadOnlyList capabilities = PlaybackCapabilitiesParser.Parse(query.Capabilities); + Result decisionResult = _playbackFormatService.DecideDelivery(new PlaybackSourceFormatDto(track.Container, track.AudioCodec), capabilities); + if (decisionResult.IsFailure) + return decisionResult.Errors; + PlaybackDeliveryDecisionDto decision = decisionResult.Value; + + bool isDirectPlay = decision.Mode == PlaybackDeliveryMode.DirectPlay; + // Whether the delivered audio can be seeked is a property of the shape it is delivered in, so the rule lives on the shape itself. + bool isSeekable = decision.Shape.IsSeekable(); + + string? deliveryId = null; + if (!isDirectPlay) + { + // The quality cap and the source file version are captured now, so the segment route never recomputes the delivery from a + // setting the user may change, or from a file that may be replaced, while the track is playing. + PlaybackStreamingQuality quality = PlaybackStreamingQuality.Auto; + Result getSettingsResult = await _unitOfWork.UserSettingsRepository.GetByUserIdAsync(userId, cancellationToken).ConfigureAwait(false); + if (getSettingsResult.IsFailure) + return getSettingsResult.Errors; + if (getSettingsResult.Value is not null) + quality = getSettingsResult.Value.StreamingQuality; + + // The content locations are captured with the delivery, so the segment route does not have to load the library and the track again + // for every six second segment, and it still re-checks path containment on every request. + Result getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(libraryId, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false); + if (getLibraryResult.IsFailure) + return getLibraryResult.Errors; + if (getLibraryResult.Value is null) + return Errors.Library.LibraryNotFound; + IReadOnlyList allowedRoots = [.. getLibraryResult.Value.ContentLocations.Select(contentLocation => contentLocation.Path)]; + // The containment invariant is enforced before the file is even stat'ed, exactly as the stream route does, so a normalized manifest never + // touches a path outside the content locations of its library. A path that is not inside them is not stat'ed, and the segment route is + // what rejects it when it tries to resolve the delivery. + bool isInsideContentLocation = allowedRoots.Count > 0 && allowedRoots.Any(contentLocation => _pathService.IsPathWithin(track.Path, contentLocation)); + + // The identity is captured only when the path is inside the library's content locations. A normalized delivery declared for a missing, + // unreadable or out-of-root file records no identity, and the segment route is the authority that rejects it when the delivery is resolved. + long sourceLength = 0; + DateTime sourceLastModifiedUtc = DateTime.MinValue; + if (isInsideContentLocation) + { + try + { + FileInfo sourceFile = new(track.Path); + if (sourceFile.Exists) + { + sourceLength = sourceFile.Length; + sourceLastModifiedUtc = sourceFile.LastWriteTimeUtc; + } + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException or NotSupportedException) + { + sourceLength = 0; + sourceLastModifiedUtc = DateTime.MinValue; + } + } + + NormalizedTrackRequestDto normalizationRequest = new( + trackId, + userId, + track.Path, + allowedRoots, + track.Container, + decision.Mode, + decision.Container, + decision.Codec, + decision.SegmentDurationSeconds, + track.DurationInSeconds, + track.Bitrate, + track.SampleRate, + track.Channels, + track.BitDepth, + quality, + sourceLength, + sourceLastModifiedUtc); + PlaybackDeliveryHandleDto delivery = new( + normalizationRequest, + decision.Shape, + libraryId, + albumId, + artistId); + deliveryId = _playbackDeliveryHandleService.IssueDeliveryId(delivery); + } + + return new PlaybackManifestResponse( + trackId, + track.DurationInSeconds, + track.Container, + track.AudioCodec, + track.SampleRate, + track.Channels, + track.BitDepth, + track.ReplayGainTrackGain, + track.ReplayGainTrackPeak, + track.ReplayGainAlbumGain, + track.ReplayGainAlbumPeak, + isDirectPlay, + isDirectPlay ? null : decision.Container, + isDirectPlay ? null : decision.Codec, + isDirectPlay ? null : decision.Shape, + decision.Shape == PlaybackDeliveryShape.TimeAddressedSegments ? decision.SegmentDurationSeconds : null, + isSeekable, + query.StreamPath, + deliveryId, + deliveryId is null ? null : query.SegmentStreamPathTemplate); + } +} diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetPlaybackManifest/GetPlaybackManifestQueryValidator.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetPlaybackManifest/GetPlaybackManifestQueryValidator.cs new file mode 100644 index 00000000..b61d0496 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetPlaybackManifest/GetPlaybackManifestQueryValidator.cs @@ -0,0 +1,60 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Utilities; +using Lumina.Domain.Common.Errors; +using System; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Queries.GetPlaybackManifest; + +/// +/// Validates the needed validation rules for . +/// +public class GetPlaybackManifestQueryValidator : AbstractValidator +{ + /// + /// Initializes a new instance of the class. + /// + public GetPlaybackManifestQueryValidator() + { + // Validates the identifier of the media library the track belongs to, taken from the route. + RuleFor(query => query.LibraryId) + .NotEmpty() + .WithError(Errors.Library.LibraryIdCannotBeEmpty); + + RuleFor(query => query.LibraryId) + .Must(libraryId => Guid.TryParse(libraryId, out Guid parsedLibraryId) && parsedLibraryId != Guid.Empty) + .When(query => query.LibraryId is not null && query.LibraryId.Length > 0) + .WithError(Errors.Library.LibraryIdCannotBeEmpty); + + // Validates the identifier of the artist the album of the track belongs to, taken from the route. + RuleFor(query => query.ArtistId) + .NotEmpty() + .WithError(Errors.Music.ArtistIdCannotBeEmpty); + + RuleFor(query => query.ArtistId) + .Must(artistId => Guid.TryParse(artistId, out Guid parsedArtistId) && parsedArtistId != Guid.Empty) + .When(query => query.ArtistId is not null && query.ArtistId.Length > 0) + .WithError(Errors.Music.ArtistIdCannotBeEmpty); + + // Validates the identifier of the album the track belongs to, taken from the route. + RuleFor(query => query.AlbumId) + .NotEmpty() + .WithError(Errors.Music.AlbumIdCannotBeEmpty); + + RuleFor(query => query.AlbumId) + .Must(albumId => Guid.TryParse(albumId, out Guid parsedAlbumId) && parsedAlbumId != Guid.Empty) + .When(query => query.AlbumId is not null && query.AlbumId.Length > 0) + .WithError(Errors.Music.AlbumIdCannotBeEmpty); + + // Validates the identifier of the track whose playback manifest is retrieved, taken from the route. + RuleFor(query => query.TrackId) + .NotEmpty() + .WithError(Errors.Music.TrackIdCannotBeEmpty); + + RuleFor(query => query.TrackId) + .Must(trackId => Guid.TryParse(trackId, out Guid parsedTrackId) && parsedTrackId != Guid.Empty) + .When(query => query.TrackId is not null && query.TrackId.Length > 0) + .WithError(Errors.Music.TrackIdCannotBeEmpty); + } +} diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetTrackSegment/GetTrackSegmentQuery.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetTrackSegment/GetTrackSegmentQuery.cs new file mode 100644 index 00000000..ab718af4 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetTrackSegment/GetTrackSegmentQuery.cs @@ -0,0 +1,25 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Queries.GetTrackSegment; + +/// +/// Query for getting a single segment of the normalized audio of a track, for streaming. +/// +/// The unique identifier of the media library the track belongs to, taken from the route. +/// The unique identifier of the artist the album of the track belongs to, taken from the route. +/// The unique identifier of the album the track belongs to, taken from the route. +/// The unique identifier of the track whose normalized audio is streamed, taken from the route. +/// The opaque handle of the normalized delivery the segment belongs to, taken from the route. +/// The zero based index of the segment of the normalized audio, taken from the route. +[DebuggerDisplay("TrackId: {TrackId} DeliveryId: {DeliveryId} SegmentIndex: {SegmentIndex}")] +public record GetTrackSegmentQuery( + string? LibraryId, + string? ArtistId, + string? AlbumId, + string? TrackId, + string? DeliveryId, + string? SegmentIndex +) : IQuery; diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetTrackSegment/GetTrackSegmentQueryHandler.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetTrackSegment/GetTrackSegmentQueryHandler.cs new file mode 100644 index 00000000..fc80f5b5 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetTrackSegment/GetTrackSegmentQueryHandler.cs @@ -0,0 +1,130 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; +using Lumina.Domain.SharedKernel.Common.Enums.Playback; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Queries.GetTrackSegment; + +/// +/// Handler for the query to get a single segment of the normalized audio of a track, for streaming. +/// +public class GetTrackSegmentQueryHandler : IQueryHandler> +{ + private readonly ITrackNormalizationService _trackNormalizationService; + private readonly IPlaybackDeliveryHandleService _playbackDeliveryHandleService; + private readonly IAuthorizationService _authorizationService; + private readonly ICurrentUserService _currentUserService; + private readonly IPathService _pathService; + private readonly IValidator _validator; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service that produces, caches and serves the normalized audio of a track. + /// Injected service that resolves the opaque delivery handle of the playback manifest. + /// Injected service for authorization related functionality. + /// Injected service to retrieve the current user information. + /// Injected service for file system path related functionality. + /// Injected validator for application validation rules. + public GetTrackSegmentQueryHandler(ITrackNormalizationService trackNormalizationService, IPlaybackDeliveryHandleService playbackDeliveryHandleService, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IPathService pathService, IValidator validator) + { + _trackNormalizationService = trackNormalizationService; + _playbackDeliveryHandleService = playbackDeliveryHandleService; + _authorizationService = authorizationService; + _currentUserService = currentUserService; + _pathService = pathService; + _validator = validator; + } + + /// + /// Handles the query to get a single segment of the normalized audio of a track, for streaming. + /// + /// The query to be handled. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either the data of the requested segment, or an error message. + /// + public async Task> HandleAsync(GetTrackSegmentQuery query, CancellationToken cancellationToken) + { + List validationResult = _validator.Validate(query); + if (validationResult.Count > 0) + return validationResult; + + // An authenticated request must always carry a user identity. + Guid? currentUserId = _currentUserService.UserId; + if (currentUserId is null) + return ApplicationErrors.Authorization.NotAuthorized; + Guid userId = currentUserId.Value; + + // The validator guarantees that the route identifiers and the segment index are well formed before this point. + Guid libraryId = Guid.Parse(query.LibraryId!); + Guid artistId = Guid.Parse(query.ArtistId!); + Guid albumId = Guid.Parse(query.AlbumId!); + Guid trackId = Guid.Parse(query.TrackId!); + int segmentIndex = int.Parse(query.SegmentIndex!); + + // Admins can stream the tracks of all libraries; for everyone else, only the tracks of the libraries they own. This is the only database + // read of a segment request: the track, library and delivery context were resolved at manifest time and are carried by the delivery handle. + bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync( + userId, new LibraryOwnershipPolicyContext(libraryId), cancellationToken).ConfigureAwait(false); + if (!canAccessLibrary) + return ApplicationErrors.Authorization.NotAuthorized; + + // The delivery handle is the only authority on the delivery of the segments: it was issued to this user for this track, and it holds the + // decision, the quality cap, the source file version and the library context the manifest declared. It is never recomputed from a capability + // list, a setting or a file that may have changed since the manifest was read. + Result getDeliveryResult = _playbackDeliveryHandleService.GetDelivery(query.DeliveryId, userId, trackId); + if (getDeliveryResult.IsFailure) + return getDeliveryResult.Errors; + PlaybackDeliveryHandleDto delivery = getDeliveryResult.Value; + if (delivery.LibraryId != libraryId || delivery.AlbumId != albumId || delivery.ArtistId != artistId) + return Errors.Playback.PlaybackDeliveryNotFound; + // A direct play is served by the stream route itself, so a delivery handle for it has no segment. The delivery must also be addressed as + // time addressed segments with a positive segment duration, or the segment route has nothing it can index. + if (delivery.Request.Mode == PlaybackDeliveryMode.DirectPlay) + return Errors.Playback.NormalizationIsNotRequiredForDirectPlay; + if (delivery.Shape != PlaybackDeliveryShape.TimeAddressedSegments || delivery.Request.SegmentDurationSeconds <= 0) + return Errors.Playback.PlaybackDeliveryChanged; + + // The audio file is only handed to the normalization pipeline when it is stored inside one of the content locations of its library, so + // that a stored path can never be used to read an arbitrary file of the host; the failure is reported as not found without the path. + if (!delivery.Request.AllowedRoots.Any(contentLocation => _pathService.IsPathWithin(delivery.Request.SourcePath, contentLocation))) + return Errors.Music.TrackFileNotFound; + + NormalizedTrackRequestDto normalizationRequest = delivery.Request; + + // The segment is read from a cached production, or the whole track is produced and cached first. A production is atomic, so the first + // segment request waits for the complete normalized audio, and every later segment request is served from the cache. A file that changed + // since the manifest declared the delivery is rejected by the service instead of starting a second, incompatible production. + Result normalizedTrackResult = await _trackNormalizationService.GetOrCreateNormalizedTrackAsync(normalizationRequest, cancellationToken).ConfigureAwait(false); + if (normalizedTrackResult.IsFailure) + return normalizedTrackResult.Errors; + NormalizedTrackDto normalizedTrack = normalizedTrackResult.Value; + + NormalizedTrackSegmentDto? segment = normalizedTrack.Segments.FirstOrDefault(candidate => candidate.Index == segmentIndex); + if (segment is null) + return Errors.Playback.NormalizedTrackSegmentNotFound; + + Result openSegmentResult = _trackNormalizationService.OpenNormalizedSegment(normalizedTrack.CacheId, trackId, segmentIndex); + if (openSegmentResult.IsFailure) + return openSegmentResult.Errors; + + return new NormalizedTrackSegmentDataDto(openSegmentResult.Value, segment.Length, segment.StartSeconds, normalizedTrack.Container, normalizedTrack.Segments.Count, normalizedTrack.DurationInSeconds); + } +} diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetTrackSegment/GetTrackSegmentQueryValidator.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetTrackSegment/GetTrackSegmentQueryValidator.cs new file mode 100644 index 00000000..9e80e4e7 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetTrackSegment/GetTrackSegmentQueryValidator.cs @@ -0,0 +1,81 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Utilities; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback; +using Lumina.Domain.Common.Errors; +using System; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Queries.GetTrackSegment; + +/// +/// Validates the needed validation rules for . +/// +public class GetTrackSegmentQueryValidator : AbstractValidator +{ + /// + /// Initializes a new instance of the class. + /// + public GetTrackSegmentQueryValidator() + { + // Validates the identifier of the media library the track belongs to, taken from the route. + RuleFor(query => query.LibraryId) + .NotEmpty() + .WithError(Errors.Library.LibraryIdCannotBeEmpty); + + RuleFor(query => query.LibraryId) + .Must(libraryId => Guid.TryParse(libraryId, out Guid parsedLibraryId) && parsedLibraryId != Guid.Empty) + .When(query => query.LibraryId is not null && query.LibraryId.Length > 0) + .WithError(Errors.Library.LibraryIdCannotBeEmpty); + + // Validates the identifier of the artist the album of the track belongs to, taken from the route. + RuleFor(query => query.ArtistId) + .NotEmpty() + .WithError(Errors.Music.ArtistIdCannotBeEmpty); + + RuleFor(query => query.ArtistId) + .Must(artistId => Guid.TryParse(artistId, out Guid parsedArtistId) && parsedArtistId != Guid.Empty) + .When(query => query.ArtistId is not null && query.ArtistId.Length > 0) + .WithError(Errors.Music.ArtistIdCannotBeEmpty); + + // Validates the identifier of the album the track belongs to, taken from the route. + RuleFor(query => query.AlbumId) + .NotEmpty() + .WithError(Errors.Music.AlbumIdCannotBeEmpty); + + RuleFor(query => query.AlbumId) + .Must(albumId => Guid.TryParse(albumId, out Guid parsedAlbumId) && parsedAlbumId != Guid.Empty) + .When(query => query.AlbumId is not null && query.AlbumId.Length > 0) + .WithError(Errors.Music.AlbumIdCannotBeEmpty); + + // Validates the identifier of the track whose normalized audio is streamed, taken from the route. + RuleFor(query => query.TrackId) + .NotEmpty() + .WithError(Errors.Music.TrackIdCannotBeEmpty); + + RuleFor(query => query.TrackId) + .Must(trackId => Guid.TryParse(trackId, out Guid parsedTrackId) && parsedTrackId != Guid.Empty) + .When(query => query.TrackId is not null && query.TrackId.Length > 0) + .WithError(Errors.Music.TrackIdCannotBeEmpty); + + // Validates the opaque delivery handle the segment belongs to, taken from the route. + RuleFor(query => query.DeliveryId) + .NotEmpty() + .WithError(Errors.Playback.DeliveryIdCannotBeEmpty); + + RuleFor(query => query.DeliveryId) + .Must(PlaybackDeliveryId.IsValid) + .When(query => query.DeliveryId is not null && query.DeliveryId.Length > 0) + .WithError(Errors.Playback.DeliveryIdIsInvalid); + + // Validates the index of the segment of the normalized audio, taken from the route. + RuleFor(query => query.SegmentIndex) + .NotEmpty() + .WithError(Errors.Playback.SegmentIndexCannotBeEmpty); + + RuleFor(query => query.SegmentIndex) + .Must(segmentIndex => int.TryParse(segmentIndex, out int parsedSegmentIndex) && parsedSegmentIndex >= 0) + .When(query => query.SegmentIndex is not null && query.SegmentIndex.Length > 0) + .WithError(Errors.Playback.SegmentIndexMustBeValid); + } +} diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetTrackStream/GetTrackStreamQuery.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetTrackStream/GetTrackStreamQuery.cs new file mode 100644 index 00000000..6f6f2506 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetTrackStream/GetTrackStreamQuery.cs @@ -0,0 +1,21 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Queries.GetTrackStream; + +/// +/// Query for getting the audio file of a track, for streaming. +/// +/// The unique identifier of the media library the track belongs to, taken from the route. +/// The unique identifier of the artist the album of the track belongs to, taken from the route. +/// The unique identifier of the album the track belongs to, taken from the route. +/// The unique identifier of the track whose audio file is streamed, taken from the route. +[DebuggerDisplay("TrackId: {TrackId}")] +public record GetTrackStreamQuery( + string? LibraryId, + string? ArtistId, + string? AlbumId, + string? TrackId +) : IQuery; diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetTrackStream/GetTrackStreamQueryHandler.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetTrackStream/GetTrackStreamQueryHandler.cs new file mode 100644 index 00000000..d5c56f6c --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetTrackStream/GetTrackStreamQueryHandler.cs @@ -0,0 +1,124 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; +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.Utilities; +using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Queries.GetTrackStream; + +/// +/// Handler for the query to get the audio file of a track, for streaming. +/// +public class GetTrackStreamQueryHandler : IQueryHandler> +{ + private readonly IUnitOfWork _unitOfWork; + private readonly IAuthorizationService _authorizationService; + private readonly ICurrentUserService _currentUserService; + private readonly IPathService _pathService; + private readonly IValidator _validator; + + /// + /// Initializes a new instance of the class. + /// + /// Injected unit of work for interacting with the data access layer repositories. + /// Injected service for authorization related functionality. + /// Injected service to retrieve the current user information. + /// Injected service for file system path related functionality. + /// Injected validator for application validation rules. + public GetTrackStreamQueryHandler(IUnitOfWork unitOfWork, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IPathService pathService, IValidator validator) + { + _unitOfWork = unitOfWork; + _authorizationService = authorizationService; + _currentUserService = currentUserService; + _pathService = pathService; + _validator = validator; + } + + /// + /// Handles the query to get the audio file of a track, for streaming. + /// + /// The query to be handled. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either the data of the audio file of the track, or an error message. + /// + public async Task> HandleAsync(GetTrackStreamQuery query, CancellationToken cancellationToken) + { + List validationResult = _validator.Validate(query); + if (validationResult.Count > 0) + return validationResult; + + // An authenticated request must always carry a user identity. + Guid? currentUserId = _currentUserService.UserId; + if (currentUserId is null) + return ApplicationErrors.Authorization.NotAuthorized; + Guid userId = currentUserId.Value; + + // The validator guarantees that the route identifiers are non-empty Guids before this point. + Guid libraryId = Guid.Parse(query.LibraryId!); + Guid artistId = Guid.Parse(query.ArtistId!); + Guid albumId = Guid.Parse(query.AlbumId!); + Guid trackId = Guid.Parse(query.TrackId!); + + // Admins can stream the tracks of all libraries; for everyone else, only the tracks of the libraries they own. + bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync( + userId, new LibraryOwnershipPolicyContext(libraryId), cancellationToken).ConfigureAwait(false); + if (!canAccessLibrary) + return ApplicationErrors.Authorization.NotAuthorized; + + // The projection is filtered by the library, the album and the artist named by the route as well as by the track, so a null row + // means the track either does not exist or is not in scope for the route, which is reported as not found without disclosing anything further. + Result getTrackResult = await _unitOfWork.TrackRepository.GetTrackStreamInfoAsync(libraryId, albumId, artistId, trackId, cancellationToken).ConfigureAwait(false); + if (getTrackResult.IsFailure) + return getTrackResult.Errors; + if (getTrackResult.Value is null) + return Errors.Music.TrackNotFound; + TrackStreamDto track = getTrackResult.Value; + + Result getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(track.LibraryId, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false); + if (getLibraryResult.IsFailure) + return getLibraryResult.Errors; + if (getLibraryResult.Value is null) + return Errors.Library.LibraryNotFound; + LibraryEntity library = getLibraryResult.Value; + + // The audio file is only served when it is stored inside one of the content locations of its library, so that a stored path can never + // be used to read an arbitrary file of the host; the failure is reported as not found, and it never includes the path. + if (!library.ContentLocations.Any(contentLocation => _pathService.IsPathWithin(track.Path, contentLocation.Path))) + return Errors.Music.TrackFileNotFound; + + try + { + // The file is read once, before the response starts, so that the response can be streamed without any further database or file system work. + FileInfo fileInformation = new(track.Path); + if (!fileInformation.Exists) + return Errors.Music.TrackFileNotFound; + + long length = fileInformation.Length; + DateTimeOffset lastModified = new(fileInformation.LastWriteTimeUtc, TimeSpan.Zero); + return new TrackStreamDataDto(track.Path, track.Path.ToAudioFileFormat(), length, lastModified); + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException or NotSupportedException) + { + // A file that cannot be read is indistinguishable, to the caller, from a file that does not exist, so the same not found error is returned. + return Errors.Music.TrackFileNotFound; + } + } +} diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetTrackStream/GetTrackStreamQueryValidator.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetTrackStream/GetTrackStreamQueryValidator.cs new file mode 100644 index 00000000..4eec9b17 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetTrackStream/GetTrackStreamQueryValidator.cs @@ -0,0 +1,60 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Utilities; +using Lumina.Domain.Common.Errors; +using System; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Queries.GetTrackStream; + +/// +/// Validates the needed validation rules for . +/// +public class GetTrackStreamQueryValidator : AbstractValidator +{ + /// + /// Initializes a new instance of the class. + /// + public GetTrackStreamQueryValidator() + { + // Validates the identifier of the media library the track belongs to, taken from the route. + RuleFor(query => query.LibraryId) + .NotEmpty() + .WithError(Errors.Library.LibraryIdCannotBeEmpty); + + RuleFor(query => query.LibraryId) + .Must(libraryId => Guid.TryParse(libraryId, out Guid parsedLibraryId) && parsedLibraryId != Guid.Empty) + .When(query => query.LibraryId is not null && query.LibraryId.Length > 0) + .WithError(Errors.Library.LibraryIdCannotBeEmpty); + + // Validates the identifier of the artist the album of the track belongs to, taken from the route. + RuleFor(query => query.ArtistId) + .NotEmpty() + .WithError(Errors.Music.ArtistIdCannotBeEmpty); + + RuleFor(query => query.ArtistId) + .Must(artistId => Guid.TryParse(artistId, out Guid parsedArtistId) && parsedArtistId != Guid.Empty) + .When(query => query.ArtistId is not null && query.ArtistId.Length > 0) + .WithError(Errors.Music.ArtistIdCannotBeEmpty); + + // Validates the identifier of the album the track belongs to, taken from the route. + RuleFor(query => query.AlbumId) + .NotEmpty() + .WithError(Errors.Music.AlbumIdCannotBeEmpty); + + RuleFor(query => query.AlbumId) + .Must(albumId => Guid.TryParse(albumId, out Guid parsedAlbumId) && parsedAlbumId != Guid.Empty) + .When(query => query.AlbumId is not null && query.AlbumId.Length > 0) + .WithError(Errors.Music.AlbumIdCannotBeEmpty); + + // Validates the identifier of the track whose audio file is streamed, taken from the route. + RuleFor(query => query.TrackId) + .NotEmpty() + .WithError(Errors.Music.TrackIdCannotBeEmpty); + + RuleFor(query => query.TrackId) + .Must(trackId => Guid.TryParse(trackId, out Guid parsedTrackId) && parsedTrackId != Guid.Empty) + .When(query => query.TrackId is not null && query.TrackId.Length > 0) + .WithError(Errors.Music.TrackIdCannotBeEmpty); + } +} diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/ShuffleTracks/ShuffleTracksQuery.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/ShuffleTracks/ShuffleTracksQuery.cs new file mode 100644 index 00000000..9056c01d --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/ShuffleTracks/ShuffleTracksQuery.cs @@ -0,0 +1,25 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using System; +using System.Collections.Generic; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Queries.ShuffleTracks; + +/// +/// Query for getting a random selection of tracks from a media library, an artist or an album. +/// +/// The unique identifier of the media library the tracks are sampled from, taken from the route. +/// The maximum number of tracks to return. +/// The unique identifier of the artist whose tracks are sampled, if applicable. +/// The unique identifier of the album whose tracks are sampled, if applicable. +/// The tracks that must not be returned, if any. +[DebuggerDisplay("LibraryId: {LibraryId} Count: {Count}")] +public record ShuffleTracksQuery( + string? LibraryId, + int Count, + Guid? ArtistId, + Guid? AlbumId, + IReadOnlyList? ExcludedTrackIds +) : IQuery; diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/ShuffleTracks/ShuffleTracksQueryHandler.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/ShuffleTracks/ShuffleTracksQueryHandler.cs new file mode 100644 index 00000000..6514ab72 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/ShuffleTracks/ShuffleTracksQueryHandler.cs @@ -0,0 +1,85 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; +using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Queries.ShuffleTracks; + +/// +/// Handler for the query to draw a random selection of tracks from a media library, an artist or an album. +/// +public class ShuffleTracksQueryHandler : IQueryHandler>> +{ + private readonly IUnitOfWork _unitOfWork; + private readonly IAuthorizationService _authorizationService; + private readonly ICurrentUserService _currentUserService; + private readonly IValidator _validator; + + /// + /// Initializes a new instance of the class. + /// + /// Injected unit of work for interacting with the data access layer repositories. + /// Injected service for authorization related functionality. + /// Injected service to retrieve the current user information. + /// Injected validator for application validation rules. + public ShuffleTracksQueryHandler(IUnitOfWork unitOfWork, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IValidator validator) + { + _unitOfWork = unitOfWork; + _authorizationService = authorizationService; + _currentUserService = currentUserService; + _validator = validator; + } + + /// + /// Handles the query to draw a random selection of tracks from a media library, an artist or an album. + /// + /// The query to be handled. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either a collection of , or an error message. + /// + public async Task>> HandleAsync(ShuffleTracksQuery query, CancellationToken cancellationToken) + { + List validationResult = _validator.Validate(query); + if (validationResult.Count > 0) + return validationResult; + + // An authenticated request must always carry a user identity. + Guid? currentUserId = _currentUserService.UserId; + if (currentUserId is null) + return ApplicationErrors.Authorization.NotAuthorized; + Guid userId = currentUserId.Value; + + // The validator guarantees that the route identifier is a non-empty Guid before this point. + Guid libraryId = Guid.Parse(query.LibraryId!); + + // Admins can shuffle all libraries; for everyone else, only the libraries they own. + bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync( + userId, new LibraryOwnershipPolicyContext(libraryId), cancellationToken).ConfigureAwait(false); + if (!canAccessLibrary) + return ApplicationErrors.Authorization.NotAuthorized; + + IReadOnlyCollection excludedTrackIds = query.ExcludedTrackIds is null + ? [] + : [.. query.ExcludedTrackIds.Where(trackId => trackId != Guid.Empty).Distinct()]; + + Result> shuffleTracksResult = await _unitOfWork.TrackRepository.GetShuffleTracksLiteAsync( + libraryId, query.ArtistId, query.AlbumId, excludedTrackIds, query.Count, cancellationToken).ConfigureAwait(false); + return shuffleTracksResult.Match(value => Result.From(value.ToResponses()), errors => errors); + } +} diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/ShuffleTracks/ShuffleTracksQueryValidator.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/ShuffleTracks/ShuffleTracksQueryValidator.cs new file mode 100644 index 00000000..8aa816a9 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/ShuffleTracks/ShuffleTracksQueryValidator.cs @@ -0,0 +1,46 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Domain.Common.Errors; +using System; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Queries.ShuffleTracks; + +/// +/// Validates the needed validation rules for . +/// +public class ShuffleTracksQueryValidator : AbstractValidator +{ + /// + /// Initializes a new instance of the class. + /// + public ShuffleTracksQueryValidator() + { + // Validates the identifier of the media library whose tracks are sampled, taken from the route. + RuleFor(query => query.LibraryId) + .Must(libraryId => !string.IsNullOrEmpty(libraryId)) + .WithError(Errors.Library.LibraryIdCannotBeEmpty); + + RuleFor(query => query.LibraryId) + .Must(libraryId => Guid.TryParse(libraryId, out Guid parsedLibraryId) && parsedLibraryId != Guid.Empty) + .When(query => !string.IsNullOrEmpty(query.LibraryId)) + .WithError(Errors.Library.LibraryIdCannotBeEmpty); + + RuleFor(query => query.Count) + .Must(count => count > 0) + .WithError(Errors.Music.ShuffleTrackCountMustBeGreaterThanZero); + + RuleFor(query => query.Count) + .Must(count => count <= 500) + .WithError(Errors.Music.ShuffleTrackCountMustBeAtMost500); + + // The optional scoping identifiers must be real identifiers when they are present. + RuleFor(query => query.ArtistId) + .Must(artistId => !artistId.HasValue || artistId.Value != Guid.Empty) + .WithError(Errors.Music.ArtistIdCannotBeEmpty); + + RuleFor(query => query.AlbumId) + .Must(albumId => !albumId.HasValue || albumId.Value != Guid.Empty) + .WithError(Errors.Music.AlbumIdCannotBeEmpty); + } +} diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommand.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommand.cs index e1ff00bf..98a3a3c6 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommand.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommand.cs @@ -18,6 +18,8 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Commands.AddLibrary; /// Whether this media library should update the metadata of its elements from the web, or not. /// Whether this media library should copy the downloaded metadata into the media library content locations, or not. /// Whether this media library should skip the directories whose contents have not changed since the last scan, during the scan, or not. +/// Whether the consumption progress of the media library items should be tracked, or not. When absent, the default of the library type is used. +/// The percentage of a media library item that must be consumed for its session to be considered completed. When absent, the default of the library type is used on creation. /// The ordered parts of the template describing the structure of the media library on disk. [DebuggerDisplay("Title: {Title}")] public record AddLibraryCommand( @@ -30,5 +32,7 @@ public record AddLibraryCommand( bool CanDownloadMetadataFromWeb, bool ShouldSaveMetadataInMediaDirectories, bool ShouldSkipUnchangedDirectoriesDuringScan, + bool? ShouldTrackConsumptionProgress, + int? CompletionThresholdPercentage, LibraryPathTemplatePartDto[]? PathTemplateParts ) : ICommand; diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandHandler.cs index 7372692d..d6c2fb97 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandHandler.cs @@ -96,7 +96,7 @@ public class AddLibraryCommandHandler : ICommandHandler(command.LibraryType!); + // A library created without explicit consumption settings uses the defaults of its type. When progress tracking is on and no threshold is + // supplied, the default threshold of the type is used; a type without one keeps no threshold, which means completion is recorded explicitly. + LibraryConsumptionSettings defaultConsumptionSettings = LibraryConsumptionSettings.CreateDefault(libraryType); + bool shouldTrackConsumptionProgress = command.ShouldTrackConsumptionProgress ?? defaultConsumptionSettings.ShouldTrackConsumptionProgress; + Optional completionThresholdPercentage = Optional.FromNullable(command.CompletionThresholdPercentage); + if (completionThresholdPercentage.HasValue && !shouldTrackConsumptionProgress) + return DomainErrors.Library.CompletionThresholdPercentageMustBeNullWhenProgressTrackingIsOff; + if (!completionThresholdPercentage.HasValue && shouldTrackConsumptionProgress) + completionThresholdPercentage = defaultConsumptionSettings.CompletionThresholdPercentage; + LibraryConsumptionSettings consumptionSettings = LibraryConsumptionSettings.Create(shouldTrackConsumptionProgress, completionThresholdPercentage); + // A library always carries a path template: the one provided by the user, or the ideal structure of the library type as its default. Result> pathTemplatePartsResult = command.PathTemplateParts.ToDomainParts(); if (pathTemplatePartsResult.IsFailure) @@ -136,6 +147,7 @@ public class AddLibraryCommandHandler : ICommandHandler .MaximumLength(255) .WithError(Errors.Library.TitleMustBeMaximum255CharactersLong); + RuleFor(command => command.CompletionThresholdPercentage) + .Must((command, completionThresholdPercentage) => command.ShouldTrackConsumptionProgress != false || completionThresholdPercentage is null) + .WithError(Errors.Library.CompletionThresholdPercentageMustBeNullWhenProgressTrackingIsOff); + + RuleFor(command => command.CompletionThresholdPercentage) + .InclusiveBetween(0, 100) + .WithError(Errors.Library.CompletionThresholdPercentageMustBeBetweenZeroAndOneHundred); + RuleForEach(command => command.PathTemplateParts) .ChildRules(part => { diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/CancelLibrariesScan/CancelLibrariesScanCommandHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/CancelLibrariesScan/CancelLibrariesScanCommandHandler.cs index c32ba282..a141ae47 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/CancelLibrariesScan/CancelLibrariesScanCommandHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/CancelLibrariesScan/CancelLibrariesScanCommandHandler.cs @@ -72,7 +72,7 @@ public class CancelLibrariesScanCommandHandler : ICommandHandler authorizedLibraryScans = []; // Admins can see all library scans. - if (await _authorizationService.IsInRoleAsync(userId, "Admin", cancellationToken).ConfigureAwait(false)) + if (await _authorizationService.IsInRoleAsync(userId, AuthorizationRoles.ADMIN, cancellationToken).ConfigureAwait(false)) authorizedLibraryScans.AddRange(getRunningLibraryScansResult.Value); else // For regular users, only take the library scans that belong to them. authorizedLibraryScans.AddRange(getRunningLibraryScansResult.Value.Where(libraryScan => libraryScan.UserId == userId)); diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/ScanLibraries/ScanLibrariesCommandHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/ScanLibraries/ScanLibrariesCommandHandler.cs index 139ab583..7239ca9d 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/ScanLibraries/ScanLibrariesCommandHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/ScanLibraries/ScanLibrariesCommandHandler.cs @@ -76,7 +76,7 @@ public class ScanLibrariesCommandHandler : ICommandHandler> domainEntitiesResult = getLibrariesResult.Value.ToDomainEntities(); // If the current user is not an admin, they can only scan the libraries that belong to them. - if (!await _authorizationService.IsInRoleAsync(userId, "Admin", cancellationToken).ConfigureAwait(false)) + if (!await _authorizationService.IsInRoleAsync(userId, AuthorizationRoles.ADMIN, cancellationToken).ConfigureAwait(false)) domainEntitiesResult = domainEntitiesResult.Where(libraryResult => libraryResult.Value.UserId.Value == userId); List responses = []; diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommand.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommand.cs index 27965444..08c31818 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommand.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommand.cs @@ -21,6 +21,8 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Commands.UpdateLibrary /// Whether this media library should update the metadata of its elements from the web, or not. /// Whether this media library should copy the downloaded metadata into the media library content locations, or not. /// Whether this media library should skip the directories whose contents have not changed since the last scan, during the scan, or not. +/// Whether the consumption progress of the media library items should be tracked, or not. When absent, the stored value is kept. +/// The percentage of a media library item that must be consumed for its session to be considered completed. When absent, the stored value is kept. /// The ordered parts of the template describing the structure of the media library on disk. [DebuggerDisplay("Title: {Title}")] public record UpdateLibraryCommand( @@ -35,5 +37,7 @@ public record UpdateLibraryCommand( bool CanDownloadMetadataFromWeb, bool ShouldSaveMetadataInMediaDirectories, bool ShouldSkipUnchangedDirectoriesDuringScan, + bool? ShouldTrackConsumptionProgress, + int? CompletionThresholdPercentage, LibraryPathTemplatePartDto[]? PathTemplateParts ) : ICommand; diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandHandler.cs index cc961c0b..7ad62473 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandHandler.cs @@ -130,6 +130,25 @@ public class UpdateLibraryCommandHandler : ICommandHandler(command.LibraryType!); + // Keep the stored consumption settings unless the request explicitly changes them. When progress tracking is enabled and + // no threshold is supplied, the stored threshold is kept; the value object never retains a threshold while tracking is disabled. + LibraryConsumptionSettings existingConsumptionSettings = LibraryConsumptionSettings.Create( + getLibraryResult.Value.ShouldTrackConsumptionProgress, + Optional.FromNullable(getLibraryResult.Value.CompletionThresholdPercentage)); + bool shouldTrackConsumptionProgress = command.ShouldTrackConsumptionProgress ?? existingConsumptionSettings.ShouldTrackConsumptionProgress; + bool isEnablingConsumptionProgressTracking = shouldTrackConsumptionProgress && !existingConsumptionSettings.ShouldTrackConsumptionProgress; + Optional completionThresholdPercentage = Optional.FromNullable(command.CompletionThresholdPercentage); + if (completionThresholdPercentage.HasValue && !shouldTrackConsumptionProgress) + return DomainErrors.Library.CompletionThresholdPercentageMustBeNullWhenProgressTrackingIsOff; + if (!completionThresholdPercentage.HasValue && shouldTrackConsumptionProgress) + { + completionThresholdPercentage = existingConsumptionSettings.CompletionThresholdPercentage; + // Enabling progress tracking on a library that did not track it yet must use the same type default that creating the library would have used. + if (!completionThresholdPercentage.HasValue && isEnablingConsumptionProgressTracking) + completionThresholdPercentage = LibraryConsumptionSettings.CreateDefault(newLibraryType).CompletionThresholdPercentage; + } + LibraryConsumptionSettings consumptionSettings = LibraryConsumptionSettings.Create(shouldTrackConsumptionProgress, completionThresholdPercentage); + // A library always carries a path template: the one provided by the user, or the ideal structure of the library type as its default. Result> pathTemplatePartsResult = command.PathTemplateParts.ToDomainParts(); if (pathTemplatePartsResult.IsFailure) @@ -150,6 +169,7 @@ public class UpdateLibraryCommandHandler : ICommandHandler ScanId.Create(libraryScan.Id))] ); diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandValidator.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandValidator.cs index febdd879..d0a2c721 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandValidator.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandValidator.cs @@ -54,6 +54,14 @@ public class UpdateLibraryCommandValidator : AbstractValidator command.CompletionThresholdPercentage) + .Must((command, completionThresholdPercentage) => command.ShouldTrackConsumptionProgress != false || completionThresholdPercentage is null) + .WithError(Errors.Library.CompletionThresholdPercentageMustBeNullWhenProgressTrackingIsOff); + + RuleFor(command => command.CompletionThresholdPercentage) + .InclusiveBetween(0, 100) + .WithError(Errors.Library.CompletionThresholdPercentageMustBeBetweenZeroAndOneHundred); + RuleForEach(command => command.PathTemplateParts) .ChildRules(part => { diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetEnabledLibraries/GetEnabledLibrariesQueryHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetEnabledLibraries/GetEnabledLibrariesQueryHandler.cs index 1bf2803b..8c71b154 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetEnabledLibraries/GetEnabledLibrariesQueryHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetEnabledLibraries/GetEnabledLibrariesQueryHandler.cs @@ -53,23 +53,23 @@ public class GetEnabledLibrariesQueryHandler : IQueryHandler public async Task> HandleAsync(GetEnabledLibrariesQuery query, CancellationToken cancellationToken) { - // an authenticated request must always carry a user identity + // An authenticated request must always carry a user identity. Guid? currentUserId = _currentUserService.UserId; if (currentUserId is null) return Errors.Authorization.NotAuthorized; Guid userId = currentUserId.Value; - // get the enabled libraries from the repository + // Get the enabled libraries from the repository. Result> getEnabledLibrariesResult = await _unitOfWork.LibraryRepository.GetAllEnabledAsync(cancellationToken).ConfigureAwait(false); if (getEnabledLibrariesResult.IsFailure) return getEnabledLibrariesResult.Errors; - // admins can see all libraries - if (await _authorizationService.IsInRoleAsync(userId, "Admin", cancellationToken).ConfigureAwait(false)) + // Admins can see all libraries. + if (await _authorizationService.IsInRoleAsync(userId, AuthorizationRoles.ADMIN, cancellationToken).ConfigureAwait(false)) return Result.From(getEnabledLibrariesResult.Value.Select(library => library.ToResponse()).ToArray()); else { - // for regular users, only take the libraries that belong to them + // For regular users, only take the libraries that belong to them. LibraryResponse[] userEnabledLibraries = [.. getEnabledLibrariesResult.Value .Where(library => library.UserId == userId) .Select(library => library.ToResponse())]; diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetLibraries/GetLibrariesQueryHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetLibraries/GetLibrariesQueryHandler.cs index 56b7ac87..bea35665 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetLibraries/GetLibrariesQueryHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetLibraries/GetLibrariesQueryHandler.cs @@ -67,7 +67,7 @@ public class GetLibrariesQueryHandler : IQueryHandler library.ToResponse()).ToArray()); else { diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetRunningLibraryScans/GetRunningLibraryScansQueryHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetRunningLibraryScans/GetRunningLibraryScansQueryHandler.cs index 2a5da4c6..b87a20da 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetRunningLibraryScans/GetRunningLibraryScansQueryHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetRunningLibraryScans/GetRunningLibraryScansQueryHandler.cs @@ -1,14 +1,13 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.CQRS; using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; -using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary; using Lumina.Application.Common.DataAccess.UoW; using Lumina.Application.Common.Errors; using Lumina.Application.Common.Infrastructure.Authentication; using Lumina.Application.Common.Infrastructure.Authorization; using Lumina.Application.Common.Mapping.MediaLibrary.Management; using Lumina.Contracts.Responses.MediaLibrary.Management; +using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Progress; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; @@ -60,26 +59,25 @@ public class GetRunningLibraryScansQueryHandler : IQueryHandler public async Task>> HandleAsync(GetRunningLibraryScansQuery query, CancellationToken cancellationToken) { - // an authenticated request must always carry a user identity + // An authenticated request must always carry a user identity. Guid? currentUserId = _currentUserService.UserId; if (currentUserId is null) return Errors.Authorization.NotAuthorized; Guid userId = currentUserId.Value; - // get the ongoing library scans from the repository + // Get the ongoing library scans from the repository. Result> getRunningScansResult = await _unitOfWork.LibraryScanRepository.GetRunningScansAsync(cancellationToken).ConfigureAwait(false); if (getRunningScansResult.IsFailure) return getRunningScansResult.Errors; - // filter the library scans by what the user is allowed to see: admins see all libraries, regular users only their own + // Filter the library scans by what the user is allowed to see: admins see all libraries, regular users only their own. LibraryScanEntity[] userRunningRepositoryLibraryScans = []; - if (await _authorizationService.IsInRoleAsync(userId, "Admin", cancellationToken).ConfigureAwait(false)) + if (await _authorizationService.IsInRoleAsync(userId, AuthorizationRoles.ADMIN, cancellationToken).ConfigureAwait(false)) userRunningRepositoryLibraryScans = [.. getRunningScansResult.Value]; else - userRunningRepositoryLibraryScans = getRunningScansResult.Value - .Where(libraryScan => libraryScan.UserId == userId).ToArray(); + userRunningRepositoryLibraryScans = [.. getRunningScansResult.Value.Where(libraryScan => libraryScan.UserId == userId)]; - // for each of the filtered library scans, get their progress + // For each of the filtered library scans, get their progress. List libraryScanProgresses = []; IEnumerable> userRunningDomainLibraryScans = userRunningRepositoryLibraryScans.ToDomainEntities(); foreach (Result userRunningDomainLibraryScan in userRunningDomainLibraryScans) diff --git a/src/Lumina.Application/Core/Playlists/Commands/AddPlaylistEntries/AddPlaylistEntriesCommand.cs b/src/Lumina.Application/Core/Playlists/Commands/AddPlaylistEntries/AddPlaylistEntriesCommand.cs new file mode 100644 index 00000000..0650403d --- /dev/null +++ b/src/Lumina.Application/Core/Playlists/Commands/AddPlaylistEntries/AddPlaylistEntriesCommand.cs @@ -0,0 +1,19 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using System; +using System.Collections.Generic; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Core.Playlists.Commands.AddPlaylistEntries; + +/// +/// Command for adding several tracks to a playlist of the current user, in order. +/// +/// The unique identifier of the playlist, taken from the route. +/// The unique identifiers of the tracks to add, in the order they must take. +[DebuggerDisplay("PlaylistId: {PlaylistId}; TrackCount: {TrackIds.Count}")] +public record AddPlaylistEntriesCommand( + string? PlaylistId, + List? TrackIds +) : ICommand; diff --git a/src/Lumina.Application/Core/Playlists/Commands/AddPlaylistEntries/AddPlaylistEntriesCommandHandler.cs b/src/Lumina.Application/Core/Playlists/Commands/AddPlaylistEntries/AddPlaylistEntriesCommandHandler.cs new file mode 100644 index 00000000..fdce4262 --- /dev/null +++ b/src/Lumina.Application/Core/Playlists/Commands/AddPlaylistEntries/AddPlaylistEntriesCommandHandler.cs @@ -0,0 +1,120 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.DataAccess.Entities.Playlists; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; +using Lumina.Application.Common.DTO.Playlists; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Contracts.Responses.Playlists; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate; +using Lumina.Domain.SharedKernel.Common.Enums.Playlists; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +using DomainErrors = Lumina.Domain.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.Core.Playlists.Commands.AddPlaylistEntries; + +/// +/// Handler for the command to add several tracks to a playlist of the current user, in order. +/// +public class AddPlaylistEntriesCommandHandler : ICommandHandler> +{ + private readonly IUnitOfWork _unitOfWork; + private readonly ICurrentUserService _currentUserService; + private readonly IAuthorizationService _authorizationService; + private readonly IValidator _validator; + + /// + /// Initializes a new instance of the class. + /// + /// Injected unit of work for interacting with the data access layer repositories. + /// Injected service to retrieve the current user information. + /// Injected service for authorization related functionality. + /// Injected validator for application validation rules. + public AddPlaylistEntriesCommandHandler( + IUnitOfWork unitOfWork, + ICurrentUserService currentUserService, + IAuthorizationService authorizationService, + IValidator validator) + { + _unitOfWork = unitOfWork; + _currentUserService = currentUserService; + _authorizationService = authorizationService; + _validator = validator; + } + + /// + /// Handles the command to add several tracks to a playlist of the current user, in order. + /// + /// The command to be handled. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either the number of appended entries and the playlist activity time, or an error message. + /// + public async Task> HandleAsync(AddPlaylistEntriesCommand command, CancellationToken cancellationToken) + { + List validationResult = _validator.Validate(command); + if (validationResult.Count > 0) + return validationResult; + + // An authenticated request must always carry a user identity. + Guid? currentUserId = _currentUserService.UserId; + if (currentUserId is null) + return ApplicationErrors.Authorization.NotAuthorized; + Guid userId = currentUserId.Value; + + // The validator guarantees that the identifier is a non-empty Guid before this point. + Guid playlistId = Guid.Parse(command.PlaylistId!); + + // A missing playlist is reported before any track is read. + Result getPlaylistResult = await _unitOfWork.PlaylistRepository + .GetByIdForUserAsync(playlistId, userId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false); + if (getPlaylistResult.IsFailure) + return getPlaylistResult.Errors; + if (getPlaylistResult.Value is null) + return DomainErrors.Playlists.PlaylistNotFound; + + // The referenced tracks are resolved in a few bounded chunks, grouped by library, so adding a long queue does not turn into one query per entry. + // Duplicate track Ids are collapsed for the lookup, because the same track may legitimately appear more than once in a playlist. + List distinctTrackIds = [.. command.TrackIds!.Distinct()]; + Result getAccessInfoResult = await _unitOfWork.TrackRepository.GetAccessInfoByIdsAsync(distinctTrackIds, cancellationToken).ConfigureAwait(false); + if (getAccessInfoResult.IsFailure) + return getAccessInfoResult.Errors; + if (getAccessInfoResult.Value.TrackCount != distinctTrackIds.Count) + return DomainErrors.Music.TrackNotFound; + + // Every library that owns one of the referenced tracks must be reachable by the current user. The libraries are checked once each, + // so a queue made of many tracks of the same library does not evaluate the policy once per track. + foreach (Guid libraryId in getAccessInfoResult.Value.LibraryIds) + { + bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync( + userId, new LibraryOwnershipPolicyContext(libraryId), cancellationToken).ConfigureAwait(false); + // A track whose library is not reachable is reported exactly like a missing track, so the response cannot be used to probe whether a track exists in another user's library. + if (!canAccessLibrary) + return DomainErrors.Music.TrackNotFound; + } + + if (!Playlist.CanContain(getPlaylistResult.Value.Type, PlaylistMediaItemType.MusicTrack)) + return DomainErrors.Playlists.PlaylistDoesNotAcceptMediaItems; + + DateTime updatedOnUtc = DateTime.UtcNow; + Result addEntriesResult = await _unitOfWork.PlaylistRepository + .AddEntriesAsync(playlistId, userId, command.TrackIds!, PlaylistMediaItemType.MusicTrack, entryIds: null, updatedOnUtc, cancellationToken).ConfigureAwait(false); + if (addEntriesResult.IsFailure) + return addEntriesResult.Errors; + + return new PlaylistEntriesAddedResponse( + playlistId, + addEntriesResult.Value.AddedCount, + updatedOnUtc); + } +} diff --git a/src/Lumina.Application/Core/Playlists/Commands/AddPlaylistEntries/AddPlaylistEntriesCommandValidator.cs b/src/Lumina.Application/Core/Playlists/Commands/AddPlaylistEntries/AddPlaylistEntriesCommandValidator.cs new file mode 100644 index 00000000..1e3d637f --- /dev/null +++ b/src/Lumina.Application/Core/Playlists/Commands/AddPlaylistEntries/AddPlaylistEntriesCommandValidator.cs @@ -0,0 +1,42 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Utilities; +using Lumina.Domain.Common.Errors; +using System; +#endregion + +namespace Lumina.Application.Core.Playlists.Commands.AddPlaylistEntries; + +/// +/// Validates the needed validation rules for . +/// +public class AddPlaylistEntriesCommandValidator : AbstractValidator +{ + /// + /// Initializes a new instance of the class. + /// + public AddPlaylistEntriesCommandValidator() + { + RuleFor(command => command.PlaylistId) + .NotEmpty() + .WithError(Errors.Playlists.PlaylistIdCannotBeEmpty); + + RuleFor(command => command.PlaylistId) + .Must(playlistId => Guid.TryParse(playlistId, out Guid parsedPlaylistId) && parsedPlaylistId != Guid.Empty) + .When(command => command.PlaylistId is not null && command.PlaylistId.Length > 0) + .WithError(Errors.Playlists.PlaylistIdCannotBeEmpty); + + RuleFor(command => command.TrackIds) + .NotNull() + .WithError(Errors.Music.TrackIdCannotBeEmpty); + + RuleFor(command => command.TrackIds) + .NotEmpty() + .WithError(Errors.Music.TrackIdCannotBeEmpty) + .When(command => command.TrackIds is not null); + + RuleForEach(command => command.TrackIds) + .NotEmpty() + .WithError(Errors.Music.TrackIdCannotBeEmpty); + } +} diff --git a/src/Lumina.Application/Core/Playlists/Commands/AddPlaylistEntry/AddPlaylistEntryCommand.cs b/src/Lumina.Application/Core/Playlists/Commands/AddPlaylistEntry/AddPlaylistEntryCommand.cs new file mode 100644 index 00000000..c9afd81c --- /dev/null +++ b/src/Lumina.Application/Core/Playlists/Commands/AddPlaylistEntry/AddPlaylistEntryCommand.cs @@ -0,0 +1,18 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Core.Playlists.Commands.AddPlaylistEntry; + +/// +/// Command for adding a track to a playlist of the current user. +/// +/// The unique identifier of the playlist, taken from the route. +/// The unique identifier of the track to add. +[DebuggerDisplay("PlaylistId: {PlaylistId}; TrackId: {TrackId}")] +public record AddPlaylistEntryCommand( + string? PlaylistId, + Guid? TrackId +) : ICommand; diff --git a/src/Lumina.Application/Core/Playlists/Commands/AddPlaylistEntry/AddPlaylistEntryCommandHandler.cs b/src/Lumina.Application/Core/Playlists/Commands/AddPlaylistEntry/AddPlaylistEntryCommandHandler.cs new file mode 100644 index 00000000..35f021d5 --- /dev/null +++ b/src/Lumina.Application/Core/Playlists/Commands/AddPlaylistEntry/AddPlaylistEntryCommandHandler.cs @@ -0,0 +1,124 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Common.DataAccess.Entities.Playlists; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.DTO.Playlists; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Mapping.Playlists; +using Lumina.Contracts.Responses.Playlists; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate; +using Lumina.Domain.SharedKernel.Common.Enums.Playlists; +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +using DomainErrors = Lumina.Domain.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.Core.Playlists.Commands.AddPlaylistEntry; + +/// +/// Handler for the command to add a track to a playlist of the current user. +/// +public class AddPlaylistEntryCommandHandler : ICommandHandler> +{ + private readonly IUnitOfWork _unitOfWork; + private readonly ICurrentUserService _currentUserService; + private readonly IAuthorizationService _authorizationService; + private readonly IValidator _validator; + + /// + /// Initializes a new instance of the class. + /// + /// Injected unit of work for interacting with the data access layer repositories. + /// Injected service to retrieve the current user information. + /// Injected service for authorization related functionality. + /// Injected validator for application validation rules. + public AddPlaylistEntryCommandHandler( + IUnitOfWork unitOfWork, + ICurrentUserService currentUserService, + IAuthorizationService authorizationService, + IValidator validator) + { + _unitOfWork = unitOfWork; + _currentUserService = currentUserService; + _authorizationService = authorizationService; + _validator = validator; + } + + /// + /// Handles the command to add a track to a playlist of the current user. + /// + /// The command to be handled. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either the appended entry and the playlist activity time, or an error message. + /// + public async Task> HandleAsync(AddPlaylistEntryCommand command, CancellationToken cancellationToken) + { + List validationResult = _validator.Validate(command); + if (validationResult.Count > 0) + return validationResult; + + // An authenticated request must always carry a user identity. + Guid? currentUserId = _currentUserService.UserId; + if (currentUserId is null) + return ApplicationErrors.Authorization.NotAuthorized; + Guid userId = currentUserId.Value; + + // The validator guarantees that the identifiers are non-empty Guids before this point. + Guid playlistId = Guid.Parse(command.PlaylistId!); + Guid trackId = command.TrackId!.Value; + + // A missing playlist is reported before the track is read. + Result getPlaylistResult = await _unitOfWork.PlaylistRepository + .GetByIdForUserAsync(playlistId, userId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false); + if (getPlaylistResult.IsFailure) + return getPlaylistResult.Errors; + if (getPlaylistResult.Value is null) + return DomainErrors.Playlists.PlaylistNotFound; + + // The track must exist, and its library must be reachable by the current user, so another user's library cannot be used as a source. + Result getTrackResult = await _unitOfWork.TrackRepository + .GetByIdAsync(trackId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false); + if (getTrackResult.IsFailure) + return getTrackResult.Errors; + if (getTrackResult.Value is null) + return DomainErrors.Music.TrackNotFound; + + bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync( + userId, new LibraryOwnershipPolicyContext(getTrackResult.Value.LibraryId), cancellationToken).ConfigureAwait(false); + // A track whose library is not reachable is reported exactly like a missing track, so the response cannot be used to probe whether a track exists in another user's library. + if (!canAccessLibrary) + return DomainErrors.Music.TrackNotFound; + + if (!Playlist.CanContain(getPlaylistResult.Value.Type, PlaylistMediaItemType.MusicTrack)) + return DomainErrors.Playlists.PlaylistDoesNotAcceptMediaItems; + + Guid entryId = Guid.NewGuid(); + DateTime updatedOnUtc = DateTime.UtcNow; + Result addEntryResult = await _unitOfWork.PlaylistRepository + .AddEntriesAsync(playlistId, userId, [trackId], PlaylistMediaItemType.MusicTrack, [entryId], updatedOnUtc, cancellationToken).ConfigureAwait(false); + if (addEntryResult.IsFailure) + return addEntryResult.Errors; + + // Only the appended entry is read back, with the display details of its track, so a single add does not return the whole playlist. + // The appended entry is the last one, so the read-back derives its display position from the stored entry count. + Result getEntryResult = await _unitOfWork.PlaylistRepository.GetAppendedEntryDetailsForUserAsync(playlistId, userId, entryId, cancellationToken).ConfigureAwait(false); + if (getEntryResult.IsFailure) + return getEntryResult.Errors; + if (getEntryResult.Value is null) + return DomainErrors.Playlists.PlaylistEntryNotFound; + + return new PlaylistEntryAddedResponse( + playlistId, + getEntryResult.Value.ToResponse(), + updatedOnUtc); + } +} diff --git a/src/Lumina.Application/Core/Playlists/Commands/AddPlaylistEntry/AddPlaylistEntryCommandValidator.cs b/src/Lumina.Application/Core/Playlists/Commands/AddPlaylistEntry/AddPlaylistEntryCommandValidator.cs new file mode 100644 index 00000000..fb1e7e57 --- /dev/null +++ b/src/Lumina.Application/Core/Playlists/Commands/AddPlaylistEntry/AddPlaylistEntryCommandValidator.cs @@ -0,0 +1,38 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Utilities; +using Lumina.Domain.Common.Errors; +using System; +#endregion + +namespace Lumina.Application.Core.Playlists.Commands.AddPlaylistEntry; + +/// +/// Validates the needed validation rules for . +/// +public class AddPlaylistEntryCommandValidator : AbstractValidator +{ + /// + /// Initializes a new instance of the class. + /// + public AddPlaylistEntryCommandValidator() + { + RuleFor(command => command.PlaylistId) + .NotEmpty() + .WithError(Errors.Playlists.PlaylistIdCannotBeEmpty); + + RuleFor(command => command.PlaylistId) + .Must(playlistId => Guid.TryParse(playlistId, out Guid parsedPlaylistId) && parsedPlaylistId != Guid.Empty) + .When(command => command.PlaylistId is not null && command.PlaylistId.Length > 0) + .WithError(Errors.Playlists.PlaylistIdCannotBeEmpty); + + RuleFor(command => command.TrackId) + .NotNull() + .WithError(Errors.Music.TrackIdCannotBeEmpty); + + RuleFor(command => command.TrackId) + .NotEmpty() + .WithError(Errors.Music.TrackIdCannotBeEmpty) + .When(command => command.TrackId is not null); + } +} diff --git a/src/Lumina.Application/Core/Playlists/Commands/AddPlaylistScopeEntries/AddPlaylistScopeEntriesCommand.cs b/src/Lumina.Application/Core/Playlists/Commands/AddPlaylistScopeEntries/AddPlaylistScopeEntriesCommand.cs new file mode 100644 index 00000000..deee7e4a --- /dev/null +++ b/src/Lumina.Application/Core/Playlists/Commands/AddPlaylistScopeEntries/AddPlaylistScopeEntriesCommand.cs @@ -0,0 +1,22 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Core.Playlists.Commands.AddPlaylistScopeEntries; + +/// +/// Command to add every track of a music library, an artist or an album to a playlist, with the track Ids resolved by the server. +/// +/// The Id of the playlist, taken from the route. +/// The Id of the music library the scope belongs to. +/// The Id of the artist the scope is limited to, if applicable. +/// The Id of the album the scope is limited to, if applicable. +[DebuggerDisplay("PlaylistId: {PlaylistId}; LibraryId: {LibraryId}; ArtistId: {ArtistId}; AlbumId: {AlbumId}")] +public record AddPlaylistScopeEntriesCommand( + string? PlaylistId, + Guid? LibraryId, + Guid? ArtistId, + Guid? AlbumId +) : ICommand; diff --git a/src/Lumina.Application/Core/Playlists/Commands/AddPlaylistScopeEntries/AddPlaylistScopeEntriesCommandHandler.cs b/src/Lumina.Application/Core/Playlists/Commands/AddPlaylistScopeEntries/AddPlaylistScopeEntriesCommandHandler.cs new file mode 100644 index 00000000..7f169e67 --- /dev/null +++ b/src/Lumina.Application/Core/Playlists/Commands/AddPlaylistScopeEntries/AddPlaylistScopeEntriesCommandHandler.cs @@ -0,0 +1,107 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.DataAccess.Entities.Playlists; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.DTO.Playlists; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Contracts.Responses.Playlists; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate; +using Lumina.Domain.SharedKernel.Common.Enums.Playlists; +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +using DomainErrors = Lumina.Domain.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.Core.Playlists.Commands.AddPlaylistScopeEntries; + +/// +/// Handler for the command to add every track of a music library, an artist or an album to a playlist. +/// +public class AddPlaylistScopeEntriesCommandHandler : ICommandHandler> +{ + private readonly IUnitOfWork _unitOfWork; + private readonly ICurrentUserService _currentUserService; + private readonly IAuthorizationService _authorizationService; + private readonly IValidator _validator; + + /// + /// Initializes a new instance of the class. + /// + /// Injected unit of work for interacting with the data access layer repositories. + /// Injected service to retrieve the current user information. + /// Injected service for authorization related functionality. + /// Injected validator for application validation rules. + public AddPlaylistScopeEntriesCommandHandler( + IUnitOfWork unitOfWork, + ICurrentUserService currentUserService, + IAuthorizationService authorizationService, + IValidator validator) + { + _unitOfWork = unitOfWork; + _currentUserService = currentUserService; + _authorizationService = authorizationService; + _validator = validator; + } + + /// + /// Handles the command to add every track of a music library, an artist or an album to a playlist. + /// + /// The command to be handled. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either the number of appended entries and the playlist activity time, or an error message. + /// + public async Task> HandleAsync(AddPlaylistScopeEntriesCommand command, CancellationToken cancellationToken) + { + List validationResult = _validator.Validate(command); + if (validationResult.Count > 0) + return validationResult; + + // An authenticated request must always carry a user identity. + Guid? currentUserId = _currentUserService.UserId; + if (currentUserId is null) + return ApplicationErrors.Authorization.NotAuthorized; + Guid userId = currentUserId.Value; + + // The validator guarantees that the identifiers are non-empty Guids before this point. + Guid playlistId = Guid.Parse(command.PlaylistId!); + Guid libraryId = command.LibraryId!.Value; + + // A missing playlist is reported before a whole library is resolved. + Result getPlaylistResult = await _unitOfWork.PlaylistRepository + .GetByIdForUserAsync(playlistId, userId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false); + if (getPlaylistResult.IsFailure) + return getPlaylistResult.Errors; + if (getPlaylistResult.Value is null) + return DomainErrors.Playlists.PlaylistNotFound; + + // The whole scope belongs to one library, so access is evaluated once for the entire scope. + bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync( + userId, new LibraryOwnershipPolicyContext(libraryId), cancellationToken).ConfigureAwait(false); + if (!canAccessLibrary) + return ApplicationErrors.Authorization.NotAuthorized; + + if (!Playlist.CanContain(getPlaylistResult.Value.Type, PlaylistMediaItemType.MusicTrack)) + return DomainErrors.Playlists.PlaylistDoesNotAcceptMediaItems; + + // The repository resolves the scope and appends it in one set-based statement, so a whole library of any size is appended without + // materializing its track Ids, sorting them in memory, or constructing one domain event per track. + DateTime updatedOnUtc = DateTime.UtcNow; + Result addEntriesResult = await _unitOfWork.PlaylistRepository + .AddScopeEntriesAsync(playlistId, userId, libraryId, command.ArtistId, command.AlbumId, PlaylistMediaItemType.MusicTrack, updatedOnUtc, cancellationToken).ConfigureAwait(false); + if (addEntriesResult.IsFailure) + return addEntriesResult.Errors; + + return new PlaylistEntriesAddedResponse( + playlistId, + addEntriesResult.Value.AddedCount, + addEntriesResult.Value.AddedCount == 0 ? null : updatedOnUtc); + } +} diff --git a/src/Lumina.Application/Core/Playlists/Commands/AddPlaylistScopeEntries/AddPlaylistScopeEntriesCommandValidator.cs b/src/Lumina.Application/Core/Playlists/Commands/AddPlaylistScopeEntries/AddPlaylistScopeEntriesCommandValidator.cs new file mode 100644 index 00000000..ce9bb13d --- /dev/null +++ b/src/Lumina.Application/Core/Playlists/Commands/AddPlaylistScopeEntries/AddPlaylistScopeEntriesCommandValidator.cs @@ -0,0 +1,41 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Utilities; +using Lumina.Domain.Common.Errors; +using System; +#endregion + +namespace Lumina.Application.Core.Playlists.Commands.AddPlaylistScopeEntries; + +/// +/// Validates the needed validation rules for . +/// +public class AddPlaylistScopeEntriesCommandValidator : AbstractValidator +{ + /// + /// Initializes a new instance of the class. + /// + public AddPlaylistScopeEntriesCommandValidator() + { + RuleFor(command => command.PlaylistId) + .NotEmpty() + .WithError(Errors.Playlists.PlaylistIdCannotBeEmpty); + + RuleFor(command => command.PlaylistId) + .Must(playlistId => Guid.TryParse(playlistId, out Guid parsedPlaylistId) && parsedPlaylistId != Guid.Empty) + .When(command => command.PlaylistId is not null && command.PlaylistId.Length > 0) + .WithError(Errors.Playlists.PlaylistIdCannotBeEmpty); + + RuleFor(command => command.LibraryId) + .Must(libraryId => libraryId.HasValue && libraryId.Value != Guid.Empty) + .WithError(Errors.Library.LibraryIdCannotBeEmpty); + + RuleFor(command => command.ArtistId) + .Must(artistId => !artistId.HasValue || artistId.Value != Guid.Empty) + .WithError(Errors.Music.ArtistIdCannotBeEmpty); + + RuleFor(command => command.AlbumId) + .Must(albumId => !albumId.HasValue || albumId.Value != Guid.Empty) + .WithError(Errors.Music.AlbumIdCannotBeEmpty); + } +} diff --git a/src/Lumina.Application/Core/Playlists/Commands/CreatePlaylist/CreatePlaylistCommand.cs b/src/Lumina.Application/Core/Playlists/Commands/CreatePlaylist/CreatePlaylistCommand.cs new file mode 100644 index 00000000..4be34f54 --- /dev/null +++ b/src/Lumina.Application/Core/Playlists/Commands/CreatePlaylist/CreatePlaylistCommand.cs @@ -0,0 +1,20 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Domain.SharedKernel.Common.Enums.Playlists; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Core.Playlists.Commands.CreatePlaylist; + +/// +/// Command for creating a playlist of the current user. +/// +/// The name of the playlist. +/// The optional description of the playlist. +/// The kind of media the playlist holds. +[DebuggerDisplay("Name: {Name}")] +public record CreatePlaylistCommand( + string? Name, + string? Description, + PlaylistType? Type +) : ICommand; diff --git a/src/Lumina.Application/Core/Playlists/Commands/CreatePlaylist/CreatePlaylistCommandHandler.cs b/src/Lumina.Application/Core/Playlists/Commands/CreatePlaylist/CreatePlaylistCommandHandler.cs new file mode 100644 index 00000000..777d049c --- /dev/null +++ b/src/Lumina.Application/Core/Playlists/Commands/CreatePlaylist/CreatePlaylistCommandHandler.cs @@ -0,0 +1,105 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.DomainEvents; +using Lumina.Application.Common.DTO.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.Contracts.Responses.Playlists; +using Lumina.Domain.Common.Events; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.ExternalIdentifiers.UserManagementBoundedContext.UserAggregate; +using Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate; +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +using DomainErrors = Lumina.Domain.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.Core.Playlists.Commands.CreatePlaylist; + +/// +/// Handler for the command to create a playlist of the current user. +/// +public class CreatePlaylistCommandHandler : ICommandHandler> +{ + private readonly IUnitOfWork _unitOfWork; + private readonly ICurrentUserService _currentUserService; + private readonly IDomainEventsQueue _domainEventsQueue; + private readonly IValidator _validator; + + /// + /// Initializes a new instance of the class. + /// + /// Injected unit of work for interacting with the data access layer repositories. + /// Injected service to retrieve the current user information. + /// Injected service for the queue of domain events. + /// Injected validator for application validation rules. + public CreatePlaylistCommandHandler( + IUnitOfWork unitOfWork, + ICurrentUserService currentUserService, + IDomainEventsQueue domainEventsQueue, + IValidator validator) + { + _unitOfWork = unitOfWork; + _currentUserService = currentUserService; + _domainEventsQueue = domainEventsQueue; + _validator = validator; + } + + /// + /// Handles the command to create a playlist of the current user. + /// + /// The command to be handled. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either the created , or an error message. + /// + public async Task> HandleAsync(CreatePlaylistCommand command, CancellationToken cancellationToken) + { + List validationResult = _validator.Validate(command); + if (validationResult.Count > 0) + return validationResult; + + // An authenticated request must always carry a user identity. + Guid? currentUserId = _currentUserService.UserId; + if (currentUserId is null) + return ApplicationErrors.Authorization.NotAuthorized; + Guid userId = currentUserId.Value; + + Result createPlaylistResult = Playlist.Create( + UserId.Create(userId), + command.Name!, + Optional.FromNullable(command.Description), + command.Type!.Value); + if (createPlaylistResult.IsFailure) + return createPlaylistResult.Errors; + Playlist playlist = createPlaylistResult.Value; + + Result insertResult = await _unitOfWork.PlaylistRepository.InsertAsync(playlist.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false); + if (insertResult.IsFailure) + return insertResult.Errors; + + Result saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + return saveChangesResult.Errors; + + // Queue any domain events, to be published after the request has completed successfully. + foreach (IDomainEvent domainEvent in playlist.GetDomainEvents()) + _domainEventsQueue.Enqueue(domainEvent); + + // The persisted row is read back, so the response carries the timestamps the auditing interceptor actually stored. + Result getDetailsResult = await _unitOfWork.PlaylistRepository + .GetDetailsForUserAsync(playlist.Id.Value, userId, new PaginationDataDto(), cancellationToken).ConfigureAwait(false); + if (getDetailsResult.IsFailure) + return getDetailsResult.Errors; + if (getDetailsResult.Value is null) + return DomainErrors.Playlists.PlaylistNotFound; + + return getDetailsResult.Value.ToResponse(); + } +} diff --git a/src/Lumina.Application/Core/Playlists/Commands/CreatePlaylist/CreatePlaylistCommandValidator.cs b/src/Lumina.Application/Core/Playlists/Commands/CreatePlaylist/CreatePlaylistCommandValidator.cs new file mode 100644 index 00000000..5f1f8fa6 --- /dev/null +++ b/src/Lumina.Application/Core/Playlists/Commands/CreatePlaylist/CreatePlaylistCommandValidator.cs @@ -0,0 +1,40 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Utilities; +using Lumina.Domain.Common.Errors; +#endregion + +namespace Lumina.Application.Core.Playlists.Commands.CreatePlaylist; + +/// +/// Validates the needed validation rules for . +/// +public class CreatePlaylistCommandValidator : AbstractValidator +{ + /// + /// Initializes a new instance of the class. + /// + public CreatePlaylistCommandValidator() + { + RuleFor(command => command.Name) + .NotEmpty() + .WithError(Errors.Playlists.PlaylistNameCannotBeEmpty); + + RuleFor(command => command.Name) + .MaximumLength(255) + .WithError(Errors.Playlists.PlaylistNameMustBeMaximum255CharactersLong); + + RuleFor(command => command.Description) + .MaximumLength(2000) + .WithError(Errors.Playlists.PlaylistDescriptionMustBeMaximum2000CharactersLong); + + RuleFor(command => command.Type) + .NotNull() + .WithError(Errors.Playlists.PlaylistTypeIsInvalid); + + RuleFor(command => command.Type) + .IsInEnum() + .WithError(Errors.Playlists.PlaylistTypeIsInvalid) + .When(command => command.Type is not null); + } +} diff --git a/src/Lumina.Application/Core/Playlists/Commands/DeletePlaylist/DeletePlaylistCommand.cs b/src/Lumina.Application/Core/Playlists/Commands/DeletePlaylist/DeletePlaylistCommand.cs new file mode 100644 index 00000000..9d5dfd6e --- /dev/null +++ b/src/Lumina.Application/Core/Playlists/Commands/DeletePlaylist/DeletePlaylistCommand.cs @@ -0,0 +1,15 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Core.Playlists.Commands.DeletePlaylist; + +/// +/// Command for deleting a playlist of the current user. +/// +/// The unique identifier of the playlist, taken from the route. +[DebuggerDisplay("PlaylistId: {PlaylistId}")] +public record DeletePlaylistCommand( + string? PlaylistId +) : ICommand; diff --git a/src/Lumina.Application/Core/Playlists/Commands/DeletePlaylist/DeletePlaylistCommandHandler.cs b/src/Lumina.Application/Core/Playlists/Commands/DeletePlaylist/DeletePlaylistCommandHandler.cs new file mode 100644 index 00000000..0849b509 --- /dev/null +++ b/src/Lumina.Application/Core/Playlists/Commands/DeletePlaylist/DeletePlaylistCommandHandler.cs @@ -0,0 +1,102 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.DataAccess.Entities.Playlists; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.DomainEvents; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Mapping.Playlists; +using Lumina.Domain.Common.Events; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate; +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +using DomainErrors = Lumina.Domain.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.Core.Playlists.Commands.DeletePlaylist; + +/// +/// Handler for the command to delete a playlist of the current user. +/// +public class DeletePlaylistCommandHandler : ICommandHandler> +{ + private readonly IUnitOfWork _unitOfWork; + private readonly ICurrentUserService _currentUserService; + private readonly IDomainEventsQueue _domainEventsQueue; + private readonly IValidator _validator; + + /// + /// Initializes a new instance of the class. + /// + /// Injected unit of work for interacting with the data access layer repositories. + /// Injected service to retrieve the current user information. + /// Injected service for the queue of domain events. + /// Injected validator for application validation rules. + public DeletePlaylistCommandHandler( + IUnitOfWork unitOfWork, + ICurrentUserService currentUserService, + IDomainEventsQueue domainEventsQueue, + IValidator validator) + { + _unitOfWork = unitOfWork; + _currentUserService = currentUserService; + _domainEventsQueue = domainEventsQueue; + _validator = validator; + } + + /// + /// Handles the command to delete a playlist of the current user. + /// + /// The command to be handled. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + public async Task> HandleAsync(DeletePlaylistCommand command, CancellationToken cancellationToken) + { + List validationResult = _validator.Validate(command); + if (validationResult.Count > 0) + return validationResult; + + // An authenticated request must always carry a user identity. + Guid? currentUserId = _currentUserService.UserId; + if (currentUserId is null) + return ApplicationErrors.Authorization.NotAuthorized; + Guid userId = currentUserId.Value; + + // The validator guarantees that the route identifier is a non-empty Guid before this point. + Guid playlistId = Guid.Parse(command.PlaylistId!); + + // The playlist is loaded so that its aggregate can raise the deletion event before the row is removed. + Result getPlaylistResult = await _unitOfWork.PlaylistRepository + .GetByIdForUserAsync(playlistId, userId, shouldIncludeNavigationProperties: false, shouldTrackEntities: true, cancellationToken: cancellationToken).ConfigureAwait(false); + if (getPlaylistResult.IsFailure) + return getPlaylistResult.Errors; + if (getPlaylistResult.Value is null) + return DomainErrors.Playlists.PlaylistNotFound; + + Result toDomainEntityResult = getPlaylistResult.Value.ToDomainEntity(); + if (toDomainEntityResult.IsFailure) + return toDomainEntityResult.Errors; + Playlist playlist = toDomainEntityResult.Value; + + Result deleteResult = playlist.Delete(); + if (deleteResult.IsFailure) + return deleteResult.Errors; + + Result deletePlaylistResult = await _unitOfWork.PlaylistRepository.DeleteByIdAsync(playlist.Id.Value, cancellationToken).ConfigureAwait(false); + if (deletePlaylistResult.IsFailure) + return deletePlaylistResult.Errors; + + Result saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + return saveChangesResult.Errors; + + foreach (IDomainEvent domainEvent in playlist.GetDomainEvents()) + _domainEventsQueue.Enqueue(domainEvent); + + return Result.Deleted; + } +} diff --git a/src/Lumina.Application/Core/Playlists/Commands/DeletePlaylist/DeletePlaylistCommandValidator.cs b/src/Lumina.Application/Core/Playlists/Commands/DeletePlaylist/DeletePlaylistCommandValidator.cs new file mode 100644 index 00000000..0498533f --- /dev/null +++ b/src/Lumina.Application/Core/Playlists/Commands/DeletePlaylist/DeletePlaylistCommandValidator.cs @@ -0,0 +1,29 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Utilities; +using Lumina.Domain.Common.Errors; +using System; +#endregion + +namespace Lumina.Application.Core.Playlists.Commands.DeletePlaylist; + +/// +/// Validates the needed validation rules for . +/// +public class DeletePlaylistCommandValidator : AbstractValidator +{ + /// + /// Initializes a new instance of the class. + /// + public DeletePlaylistCommandValidator() + { + RuleFor(command => command.PlaylistId) + .NotEmpty() + .WithError(Errors.Playlists.PlaylistIdCannotBeEmpty); + + RuleFor(command => command.PlaylistId) + .Must(playlistId => Guid.TryParse(playlistId, out Guid parsedPlaylistId) && parsedPlaylistId != Guid.Empty) + .When(command => command.PlaylistId is not null && command.PlaylistId.Length > 0) + .WithError(Errors.Playlists.PlaylistIdCannotBeEmpty); + } +} diff --git a/src/Lumina.Application/Core/Playlists/Commands/MovePlaylistEntry/MovePlaylistEntryCommand.cs b/src/Lumina.Application/Core/Playlists/Commands/MovePlaylistEntry/MovePlaylistEntryCommand.cs new file mode 100644 index 00000000..6f27d432 --- /dev/null +++ b/src/Lumina.Application/Core/Playlists/Commands/MovePlaylistEntry/MovePlaylistEntryCommand.cs @@ -0,0 +1,20 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Core.Playlists.Commands.MovePlaylistEntry; + +/// +/// Command for moving one entry of a playlist of the current user to a new position. +/// +/// The unique identifier of the playlist, taken from the route. +/// The unique identifier of the entry to move, taken from the route. +/// The new zero based position of the entry. +[DebuggerDisplay("PlaylistId: {PlaylistId}; PlaylistEntryId: {PlaylistEntryId}; TargetPosition: {TargetPosition}")] +public record MovePlaylistEntryCommand( + string? PlaylistId, + string? PlaylistEntryId, + int? TargetPosition +) : ICommand; diff --git a/src/Lumina.Application/Core/Playlists/Commands/MovePlaylistEntry/MovePlaylistEntryCommandHandler.cs b/src/Lumina.Application/Core/Playlists/Commands/MovePlaylistEntry/MovePlaylistEntryCommandHandler.cs new file mode 100644 index 00000000..ce82bf08 --- /dev/null +++ b/src/Lumina.Application/Core/Playlists/Commands/MovePlaylistEntry/MovePlaylistEntryCommandHandler.cs @@ -0,0 +1,80 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Contracts.Responses.Playlists; +using Lumina.Domain.Common.Primitives; +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.Core.Playlists.Commands.MovePlaylistEntry; + +/// +/// Handler for the command to move one entry of a playlist of the current user to a new position. +/// +public class MovePlaylistEntryCommandHandler : ICommandHandler> +{ + private readonly IUnitOfWork _unitOfWork; + private readonly ICurrentUserService _currentUserService; + private readonly IValidator _validator; + + /// + /// Initializes a new instance of the class. + /// + /// Injected unit of work for interacting with the data access layer repositories. + /// Injected service to retrieve the current user information. + /// Injected validator for application validation rules. + public MovePlaylistEntryCommandHandler( + IUnitOfWork unitOfWork, + ICurrentUserService currentUserService, + IValidator validator) + { + _unitOfWork = unitOfWork; + _currentUserService = currentUserService; + _validator = validator; + } + + /// + /// Handles the command to move one entry of a playlist of the current user to a new position. + /// + /// The command to be handled. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either the moved entry and its position, or an error message. + /// + public async Task> HandleAsync(MovePlaylistEntryCommand command, CancellationToken cancellationToken) + { + List validationResult = _validator.Validate(command); + if (validationResult.Count > 0) + return validationResult; + + // An authenticated request must always carry a user identity. + Guid? currentUserId = _currentUserService.UserId; + if (currentUserId is null) + return ApplicationErrors.Authorization.NotAuthorized; + Guid userId = currentUserId.Value; + + // The validator guarantees that the route identifiers are non-empty Guids before this point. + Guid playlistId = Guid.Parse(command.PlaylistId!); + Guid playlistEntryId = Guid.Parse(command.PlaylistEntryId!); + int targetPosition = command.TargetPosition!.Value; + + // The entry is moved directly in the storage medium, so a playlist of any size is not loaded into memory for one move. + DateTime updatedOnUtc = DateTime.UtcNow; + Result moveEntryResult = await _unitOfWork.PlaylistRepository + .MoveEntryAsync(playlistId, userId, playlistEntryId, targetPosition, updatedOnUtc, cancellationToken).ConfigureAwait(false); + if (moveEntryResult.IsFailure) + return moveEntryResult.Errors; + + return new PlaylistEntryMovedResponse( + playlistId, + playlistEntryId, + targetPosition, + updatedOnUtc); + } +} diff --git a/src/Lumina.Application/Core/Playlists/Commands/MovePlaylistEntry/MovePlaylistEntryCommandValidator.cs b/src/Lumina.Application/Core/Playlists/Commands/MovePlaylistEntry/MovePlaylistEntryCommandValidator.cs new file mode 100644 index 00000000..afa6ca29 --- /dev/null +++ b/src/Lumina.Application/Core/Playlists/Commands/MovePlaylistEntry/MovePlaylistEntryCommandValidator.cs @@ -0,0 +1,47 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Utilities; +using Lumina.Domain.Common.Errors; +using System; +#endregion + +namespace Lumina.Application.Core.Playlists.Commands.MovePlaylistEntry; + +/// +/// Validates the needed validation rules for . +/// +public class MovePlaylistEntryCommandValidator : AbstractValidator +{ + /// + /// Initializes a new instance of the class. + /// + public MovePlaylistEntryCommandValidator() + { + RuleFor(command => command.PlaylistId) + .NotEmpty() + .WithError(Errors.Playlists.PlaylistIdCannotBeEmpty); + + RuleFor(command => command.PlaylistId) + .Must(playlistId => Guid.TryParse(playlistId, out Guid parsedPlaylistId) && parsedPlaylistId != Guid.Empty) + .When(command => command.PlaylistId is not null && command.PlaylistId.Length > 0) + .WithError(Errors.Playlists.PlaylistIdCannotBeEmpty); + + RuleFor(command => command.PlaylistEntryId) + .NotEmpty() + .WithError(Errors.Playlists.PlaylistEntryIdCannotBeEmpty); + + RuleFor(command => command.PlaylistEntryId) + .Must(entryId => Guid.TryParse(entryId, out Guid parsedEntryId) && parsedEntryId != Guid.Empty) + .When(command => command.PlaylistEntryId is not null && command.PlaylistEntryId.Length > 0) + .WithError(Errors.Playlists.PlaylistEntryIdCannotBeEmpty); + + RuleFor(command => command.TargetPosition) + .NotNull() + .WithError(Errors.Playlists.PlaylistMoveTargetPositionIsInvalid); + + RuleFor(command => command.TargetPosition) + .Must(targetPosition => targetPosition.HasValue && targetPosition.Value >= 0) + .When(command => command.TargetPosition.HasValue) + .WithError(Errors.Playlists.PlaylistMoveTargetPositionIsInvalid); + } +} diff --git a/src/Lumina.Application/Core/Playlists/Commands/RemovePlaylistEntry/RemovePlaylistEntryCommand.cs b/src/Lumina.Application/Core/Playlists/Commands/RemovePlaylistEntry/RemovePlaylistEntryCommand.cs new file mode 100644 index 00000000..99ab3010 --- /dev/null +++ b/src/Lumina.Application/Core/Playlists/Commands/RemovePlaylistEntry/RemovePlaylistEntryCommand.cs @@ -0,0 +1,17 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Core.Playlists.Commands.RemovePlaylistEntry; + +/// +/// Command for removing an entry from a playlist of the current user. +/// +/// The unique identifier of the playlist, taken from the route. +/// The unique identifier of the entry to remove, taken from the route. +[DebuggerDisplay("PlaylistId: {PlaylistId}; PlaylistEntryId: {PlaylistEntryId}")] +public record RemovePlaylistEntryCommand( + string? PlaylistId, + string? PlaylistEntryId +) : ICommand; diff --git a/src/Lumina.Application/Core/Playlists/Commands/RemovePlaylistEntry/RemovePlaylistEntryCommandHandler.cs b/src/Lumina.Application/Core/Playlists/Commands/RemovePlaylistEntry/RemovePlaylistEntryCommandHandler.cs new file mode 100644 index 00000000..e317f787 --- /dev/null +++ b/src/Lumina.Application/Core/Playlists/Commands/RemovePlaylistEntry/RemovePlaylistEntryCommandHandler.cs @@ -0,0 +1,78 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Contracts.Responses.Playlists; +using Lumina.Domain.Common.Primitives; +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.Core.Playlists.Commands.RemovePlaylistEntry; + +/// +/// Handler for the command to remove an entry from a playlist of the current user. +/// +public class RemovePlaylistEntryCommandHandler : ICommandHandler> +{ + private readonly IUnitOfWork _unitOfWork; + private readonly ICurrentUserService _currentUserService; + private readonly IValidator _validator; + + /// + /// Initializes a new instance of the class. + /// + /// Injected unit of work for interacting with the data access layer repositories. + /// Injected service to retrieve the current user information. + /// Injected validator for application validation rules. + public RemovePlaylistEntryCommandHandler( + IUnitOfWork unitOfWork, + ICurrentUserService currentUserService, + IValidator validator) + { + _unitOfWork = unitOfWork; + _currentUserService = currentUserService; + _validator = validator; + } + + /// + /// Handles the command to remove an entry from a playlist of the current user. + /// + /// The command to be handled. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either the removed entry with zero repositioned entries, or an error message. + /// + public async Task> HandleAsync(RemovePlaylistEntryCommand command, CancellationToken cancellationToken) + { + List validationResult = _validator.Validate(command); + if (validationResult.Count > 0) + return validationResult; + + // An authenticated request must always carry a user identity. + Guid? currentUserId = _currentUserService.UserId; + if (currentUserId is null) + return ApplicationErrors.Authorization.NotAuthorized; + Guid userId = currentUserId.Value; + + // The validator guarantees that the route identifiers are non-empty Guids before this point. + Guid playlistId = Guid.Parse(command.PlaylistId!); + Guid playlistEntryId = Guid.Parse(command.PlaylistEntryId!); + + // The row is deleted and the gap is closed in set-based statements, so a playlist of any size is not loaded into memory for one removal. + DateTime updatedOnUtc = DateTime.UtcNow; + Result removeEntryResult = await _unitOfWork.PlaylistRepository.RemoveEntryAsync(playlistId, userId, playlistEntryId, updatedOnUtc, cancellationToken).ConfigureAwait(false); + if (removeEntryResult.IsFailure) + return removeEntryResult.Errors; + + return new PlaylistEntryRemovedResponse( + playlistId, + playlistEntryId, + removeEntryResult.Value, + updatedOnUtc); + } +} diff --git a/src/Lumina.Application/Core/Playlists/Commands/RemovePlaylistEntry/RemovePlaylistEntryCommandValidator.cs b/src/Lumina.Application/Core/Playlists/Commands/RemovePlaylistEntry/RemovePlaylistEntryCommandValidator.cs new file mode 100644 index 00000000..ffcaf9eb --- /dev/null +++ b/src/Lumina.Application/Core/Playlists/Commands/RemovePlaylistEntry/RemovePlaylistEntryCommandValidator.cs @@ -0,0 +1,38 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Utilities; +using Lumina.Domain.Common.Errors; +using System; +#endregion + +namespace Lumina.Application.Core.Playlists.Commands.RemovePlaylistEntry; + +/// +/// Validates the needed validation rules for . +/// +public class RemovePlaylistEntryCommandValidator : AbstractValidator +{ + /// + /// Initializes a new instance of the class. + /// + public RemovePlaylistEntryCommandValidator() + { + RuleFor(command => command.PlaylistId) + .NotEmpty() + .WithError(Errors.Playlists.PlaylistIdCannotBeEmpty); + + RuleFor(command => command.PlaylistId) + .Must(playlistId => Guid.TryParse(playlistId, out Guid parsedPlaylistId) && parsedPlaylistId != Guid.Empty) + .When(command => command.PlaylistId is not null && command.PlaylistId.Length > 0) + .WithError(Errors.Playlists.PlaylistIdCannotBeEmpty); + + RuleFor(command => command.PlaylistEntryId) + .NotEmpty() + .WithError(Errors.Playlists.PlaylistEntryIdCannotBeEmpty); + + RuleFor(command => command.PlaylistEntryId) + .Must(entryId => Guid.TryParse(entryId, out Guid parsedEntryId) && parsedEntryId != Guid.Empty) + .When(command => command.PlaylistEntryId is not null && command.PlaylistEntryId.Length > 0) + .WithError(Errors.Playlists.PlaylistEntryIdCannotBeEmpty); + } +} diff --git a/src/Lumina.Application/Core/Playlists/Commands/UpdatePlaylist/UpdatePlaylistCommand.cs b/src/Lumina.Application/Core/Playlists/Commands/UpdatePlaylist/UpdatePlaylistCommand.cs new file mode 100644 index 00000000..f7a8bfbb --- /dev/null +++ b/src/Lumina.Application/Core/Playlists/Commands/UpdatePlaylist/UpdatePlaylistCommand.cs @@ -0,0 +1,19 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Core.Playlists.Commands.UpdatePlaylist; + +/// +/// Command for updating the details of a playlist of the current user. +/// +/// The unique identifier of the playlist, taken from the route. +/// The name of the playlist. +/// The optional description of the playlist. +[DebuggerDisplay("PlaylistId: {PlaylistId}")] +public record UpdatePlaylistCommand( + string? PlaylistId, + string? Name, + string? Description +) : ICommand; diff --git a/src/Lumina.Application/Core/Playlists/Commands/UpdatePlaylist/UpdatePlaylistCommandHandler.cs b/src/Lumina.Application/Core/Playlists/Commands/UpdatePlaylist/UpdatePlaylistCommandHandler.cs new file mode 100644 index 00000000..0e353107 --- /dev/null +++ b/src/Lumina.Application/Core/Playlists/Commands/UpdatePlaylist/UpdatePlaylistCommandHandler.cs @@ -0,0 +1,112 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.DataAccess.Entities.Playlists; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.DomainEvents; +using Lumina.Application.Common.DTO.Playlists; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Mapping.Playlists; +using Lumina.Contracts.Responses.Playlists; +using Lumina.Domain.Common.Events; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate; +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +using DomainErrors = Lumina.Domain.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.Core.Playlists.Commands.UpdatePlaylist; + +/// +/// Handler for the command to update the details of a playlist of the current user. +/// +public class UpdatePlaylistCommandHandler : ICommandHandler> +{ + private readonly IUnitOfWork _unitOfWork; + private readonly ICurrentUserService _currentUserService; + private readonly IDomainEventsQueue _domainEventsQueue; + private readonly IValidator _validator; + + /// + /// Initializes a new instance of the class. + /// + /// Injected unit of work for interacting with the data access layer repositories. + /// Injected service to retrieve the current user information. + /// Injected service for the queue of domain events. + /// Injected validator for application validation rules. + public UpdatePlaylistCommandHandler( + IUnitOfWork unitOfWork, + ICurrentUserService currentUserService, + IDomainEventsQueue domainEventsQueue, + IValidator validator) + { + _unitOfWork = unitOfWork; + _currentUserService = currentUserService; + _domainEventsQueue = domainEventsQueue; + _validator = validator; + } + + /// + /// Handles the command to update the details of a playlist of the current user. + /// + /// The command to be handled. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either the updated , or an error message. + /// + public async Task> HandleAsync(UpdatePlaylistCommand command, CancellationToken cancellationToken) + { + List validationResult = _validator.Validate(command); + if (validationResult.Count > 0) + return validationResult; + + // An authenticated request must always carry a user identity. + Guid? currentUserId = _currentUserService.UserId; + if (currentUserId is null) + return ApplicationErrors.Authorization.NotAuthorized; + Guid userId = currentUserId.Value; + + // The validator guarantees that the route identifier is a non-empty Guid before this point. + Guid playlistId = Guid.Parse(command.PlaylistId!); + + // The playlist is scoped to the current user by the repository, so a playlist of another user is indistinguishable from a missing one. + Result getPlaylistResult = await _unitOfWork.PlaylistRepository + .GetByIdForUserAsync(playlistId, userId, shouldIncludeNavigationProperties: false, shouldTrackEntities: true, cancellationToken: cancellationToken).ConfigureAwait(false); + if (getPlaylistResult.IsFailure) + return getPlaylistResult.Errors; + if (getPlaylistResult.Value is null) + return DomainErrors.Playlists.PlaylistNotFound; + + Result toDomainEntityResult = getPlaylistResult.Value.ToDomainEntity(); + if (toDomainEntityResult.IsFailure) + return toDomainEntityResult.Errors; + Playlist playlist = toDomainEntityResult.Value; + + Result updateDetailsResult = playlist.UpdateDetails(command.Name!, Optional.FromNullable(command.Description)); + if (updateDetailsResult.IsFailure) + return updateDetailsResult.Errors; + + Result updateResult = await _unitOfWork.PlaylistRepository.UpdateAsync(playlist.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false); + if (updateResult.IsFailure) + return updateResult.Errors; + + Result saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + return saveChangesResult.Errors; + + foreach (IDomainEvent domainEvent in playlist.GetDomainEvents()) + _domainEventsQueue.Enqueue(domainEvent); + + // A details update only changes the playlist scalars, so the response carries those scalars and the audit timestamp the interceptor actually stored. + return new PlaylistDetailsResponse( + playlist.Id.Value, + playlist.Name, + playlist.Description.HasValue ? playlist.Description.Value : null, + playlist.Type, + getPlaylistResult.Value.UpdatedOnUtc); + } +} diff --git a/src/Lumina.Application/Core/Playlists/Commands/UpdatePlaylist/UpdatePlaylistCommandValidator.cs b/src/Lumina.Application/Core/Playlists/Commands/UpdatePlaylist/UpdatePlaylistCommandValidator.cs new file mode 100644 index 00000000..50f7fa16 --- /dev/null +++ b/src/Lumina.Application/Core/Playlists/Commands/UpdatePlaylist/UpdatePlaylistCommandValidator.cs @@ -0,0 +1,41 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Utilities; +using Lumina.Domain.Common.Errors; +using System; +#endregion + +namespace Lumina.Application.Core.Playlists.Commands.UpdatePlaylist; + +/// +/// Validates the needed validation rules for . +/// +public class UpdatePlaylistCommandValidator : AbstractValidator +{ + /// + /// Initializes a new instance of the class. + /// + public UpdatePlaylistCommandValidator() + { + RuleFor(command => command.PlaylistId) + .NotEmpty() + .WithError(Errors.Playlists.PlaylistIdCannotBeEmpty); + + RuleFor(command => command.PlaylistId) + .Must(playlistId => Guid.TryParse(playlistId, out Guid parsedPlaylistId) && parsedPlaylistId != Guid.Empty) + .When(command => command.PlaylistId is not null && command.PlaylistId.Length > 0) + .WithError(Errors.Playlists.PlaylistIdCannotBeEmpty); + + RuleFor(command => command.Name) + .NotEmpty() + .WithError(Errors.Playlists.PlaylistNameCannotBeEmpty); + + RuleFor(command => command.Name) + .MaximumLength(255) + .WithError(Errors.Playlists.PlaylistNameMustBeMaximum255CharactersLong); + + RuleFor(command => command.Description) + .MaximumLength(2000) + .WithError(Errors.Playlists.PlaylistDescriptionMustBeMaximum2000CharactersLong); + } +} diff --git a/src/Lumina.Application/Core/Playlists/Queries/GetPlaylist/GetPlaylistQuery.cs b/src/Lumina.Application/Core/Playlists/Queries/GetPlaylist/GetPlaylistQuery.cs new file mode 100644 index 00000000..17d6c9a3 --- /dev/null +++ b/src/Lumina.Application/Core/Playlists/Queries/GetPlaylist/GetPlaylistQuery.cs @@ -0,0 +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; + +/// +/// Query for getting a playlist of the current user, together with a page of its ordered entries. +/// +/// The unique identifier of the playlist, taken from the route. +/// The object containing the requested pagination data. +[DebuggerDisplay("PlaylistId: {PlaylistId}")] +public record GetPlaylistQuery( + string? PlaylistId, + PaginationDataDto? PaginationData +) : IQuery; diff --git a/src/Lumina.Application/Core/Playlists/Queries/GetPlaylist/GetPlaylistQueryHandler.cs b/src/Lumina.Application/Core/Playlists/Queries/GetPlaylist/GetPlaylistQueryHandler.cs new file mode 100644 index 00000000..6d79979b --- /dev/null +++ b/src/Lumina.Application/Core/Playlists/Queries/GetPlaylist/GetPlaylistQueryHandler.cs @@ -0,0 +1,110 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.DTO.Playlists; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Mapping.Playlists; +using Lumina.Contracts.Responses.Playlists; +using Lumina.Domain.Common.Primitives; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +using DomainErrors = Lumina.Domain.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.Core.Playlists.Queries.GetPlaylist; + +/// +/// Handler for the query to get a playlist of the current user, together with its ordered entries. +/// +public class GetPlaylistQueryHandler : IQueryHandler> +{ + private readonly IUnitOfWork _unitOfWork; + private readonly ICurrentUserService _currentUserService; + private readonly IAuthorizationService _authorizationService; + private readonly IValidator _validator; + + /// + /// Initializes a new instance of the class. + /// + /// Injected unit of work for interacting with the data access layer repositories. + /// Injected service to retrieve the current user information. + /// Injected service for authorization related functionality. + /// Injected validator for application validation rules. + public GetPlaylistQueryHandler(IUnitOfWork unitOfWork, ICurrentUserService currentUserService, IAuthorizationService authorizationService, IValidator validator) + { + _unitOfWork = unitOfWork; + _currentUserService = currentUserService; + _authorizationService = authorizationService; + _validator = validator; + } + + /// + /// Handles the query to get a playlist of the current user, together with its ordered entries. + /// + /// The query to be handled. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either the requested , or an error message. + /// + public async Task> HandleAsync(GetPlaylistQuery query, CancellationToken cancellationToken) + { + List validationResult = _validator.Validate(query); + if (validationResult.Count > 0) + return validationResult; + + // An authenticated request must always carry a user identity. + Guid? currentUserId = _currentUserService.UserId; + if (currentUserId is null) + return ApplicationErrors.Authorization.NotAuthorized; + Guid userId = currentUserId.Value; + + // The validator guarantees that the route identifier is a non-empty Guid before this point. + Guid playlistId = Guid.Parse(query.PlaylistId!); + + // The playlist is scoped to the current user by the repository, so a playlist of another user is indistinguishable from a missing one. + Result getPlaylistResult = await _unitOfWork.PlaylistRepository + .GetDetailsForUserAsync(playlistId, userId, query.PaginationData, cancellationToken).ConfigureAwait(false); + if (getPlaylistResult.IsFailure) + return getPlaylistResult.Errors; + if (getPlaylistResult.Value is null) + return DomainErrors.Playlists.PlaylistNotFound; + + // Check the access permissions for each library that the tracks in the playlist might belong to. + PlaylistDetailsDto playlist = getPlaylistResult.Value; + List libraryIds = [.. playlist.Entries.Data + .Select(entry => entry.Display?.LibraryId ?? Guid.Empty) + .Where(libraryId => libraryId != Guid.Empty) + .Distinct()]; + Dictionary libraryAccess = []; + foreach (Guid libraryId in libraryIds) + { + bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync( + userId, new LibraryOwnershipPolicyContext(libraryId), cancellationToken).ConfigureAwait(false); + libraryAccess[libraryId] = canAccessLibrary; + } + + if (libraryAccess.Values.Any(canAccessLibrary => !canAccessLibrary)) + { + List entries = []; + foreach (PlaylistEntryDto entry in playlist.Entries.Data) + { + Guid libraryId = entry.Display?.LibraryId ?? Guid.Empty; + if (libraryId == Guid.Empty || libraryAccess[libraryId]) + entries.Add(entry); + else + // Keep the row so its owner can see and remove it, but do not expose display data from a library the user cannot access. + entries.Add(entry with { Display = null }); + } + playlist = playlist with { Entries = playlist.Entries with { Data = entries } }; + } + + return playlist.ToResponse(); + } +} diff --git a/src/Lumina.Application/Core/Playlists/Queries/GetPlaylist/GetPlaylistQueryValidator.cs b/src/Lumina.Application/Core/Playlists/Queries/GetPlaylist/GetPlaylistQueryValidator.cs new file mode 100644 index 00000000..cf26c60b --- /dev/null +++ b/src/Lumina.Application/Core/Playlists/Queries/GetPlaylist/GetPlaylistQueryValidator.cs @@ -0,0 +1,29 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Utilities; +using Lumina.Domain.Common.Errors; +using System; +#endregion + +namespace Lumina.Application.Core.Playlists.Queries.GetPlaylist; + +/// +/// Validates the needed validation rules for . +/// +public class GetPlaylistQueryValidator : AbstractValidator +{ + /// + /// Initializes a new instance of the class. + /// + public GetPlaylistQueryValidator() + { + RuleFor(query => query.PlaylistId) + .NotEmpty() + .WithError(Errors.Playlists.PlaylistIdCannotBeEmpty); + + RuleFor(query => query.PlaylistId) + .Must(playlistId => Guid.TryParse(playlistId, out Guid parsedPlaylistId) && parsedPlaylistId != Guid.Empty) + .When(query => query.PlaylistId is not null && query.PlaylistId.Length > 0) + .WithError(Errors.Playlists.PlaylistIdCannotBeEmpty); + } +} diff --git a/src/Lumina.Application/Core/Playlists/Queries/GetPlaylists/GetPlaylistsQuery.cs b/src/Lumina.Application/Core/Playlists/Queries/GetPlaylists/GetPlaylistsQuery.cs new file mode 100644 index 00000000..8901463f --- /dev/null +++ b/src/Lumina.Application/Core/Playlists/Queries/GetPlaylists/GetPlaylistsQuery.cs @@ -0,0 +1,10 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +#endregion + +namespace Lumina.Application.Core.Playlists.Queries.GetPlaylists; + +/// +/// Query for getting the playlists of the current user. +/// +public record GetPlaylistsQuery : IQuery; diff --git a/src/Lumina.Application/Core/Playlists/Queries/GetPlaylists/GetPlaylistsQueryHandler.cs b/src/Lumina.Application/Core/Playlists/Queries/GetPlaylists/GetPlaylistsQueryHandler.cs new file mode 100644 index 00000000..7b55808e --- /dev/null +++ b/src/Lumina.Application/Core/Playlists/Queries/GetPlaylists/GetPlaylistsQueryHandler.cs @@ -0,0 +1,60 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.DTO.Playlists; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Mapping.Playlists; +using Lumina.Contracts.Responses.Playlists; +using Lumina.Domain.Common.Primitives; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.Core.Playlists.Queries.GetPlaylists; + +/// +/// Handler for the query to get the playlists of the current user. +/// +public class GetPlaylistsQueryHandler : IQueryHandler> +{ + private readonly IUnitOfWork _unitOfWork; + private readonly ICurrentUserService _currentUserService; + + /// + /// Initializes a new instance of the class. + /// + /// Injected unit of work for interacting with the data access layer repositories. + /// Injected service to retrieve the current user information. + public GetPlaylistsQueryHandler(IUnitOfWork unitOfWork, ICurrentUserService currentUserService) + { + _unitOfWork = unitOfWork; + _currentUserService = currentUserService; + } + + /// + /// Handles the query to get the playlists of the current user. + /// + /// The query to be handled. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either the playlists of the current user, or an error message. + /// + public async Task> HandleAsync(GetPlaylistsQuery query, CancellationToken cancellationToken) + { + // An authenticated request must always carry a user identity. + Guid? currentUserId = _currentUserService.UserId; + if (currentUserId is null) + return ApplicationErrors.Authorization.NotAuthorized; + Guid userId = currentUserId.Value; + + Result> getPlaylistsResult = await _unitOfWork.PlaylistRepository.GetAllForUserAsync(userId, cancellationToken).ConfigureAwait(false); + if (getPlaylistsResult.IsFailure) + return getPlaylistsResult.Errors; + + return Result.From(getPlaylistsResult.Value.Select(playlist => playlist.ToResponse()).ToArray()); + } +} diff --git a/src/Lumina.Application/Core/Plugins/Commands/InstallPlugin/InstallPluginCommandHandler.cs b/src/Lumina.Application/Core/Plugins/Commands/InstallPlugin/InstallPluginCommandHandler.cs index 9cbf250f..b6bcef73 100644 --- a/src/Lumina.Application/Core/Plugins/Commands/InstallPlugin/InstallPluginCommandHandler.cs +++ b/src/Lumina.Application/Core/Plugins/Commands/InstallPlugin/InstallPluginCommandHandler.cs @@ -62,8 +62,8 @@ public class InstallPluginCommandHandler : ICommandHandler installResult = await _pluginInstaller.InstallAsync(command.Archive!, command.FileName!, cancellationToken).ConfigureAwait(false); diff --git a/src/Lumina.Application/Core/Scheduling/Commands/AddScheduledJob/AddScheduledJobCommandHandler.cs b/src/Lumina.Application/Core/Scheduling/Commands/AddScheduledJob/AddScheduledJobCommandHandler.cs index 64cb0016..9db35861 100644 --- a/src/Lumina.Application/Core/Scheduling/Commands/AddScheduledJob/AddScheduledJobCommandHandler.cs +++ b/src/Lumina.Application/Core/Scheduling/Commands/AddScheduledJob/AddScheduledJobCommandHandler.cs @@ -78,7 +78,7 @@ public class AddScheduledJobCommandHandler : ICommandHandler getThemeResult = await _unitOfWork.ThemeRepository.GetByThemeIdAsync(command.ThemeId!, cancellationToken).ConfigureAwait(false); diff --git a/src/Lumina.Application/Core/Themes/Management/Commands/InstallTheme/InstallThemeCommandHandler.cs b/src/Lumina.Application/Core/Themes/Management/Commands/InstallTheme/InstallThemeCommandHandler.cs index 1f9e1268..ca44c670 100644 --- a/src/Lumina.Application/Core/Themes/Management/Commands/InstallTheme/InstallThemeCommandHandler.cs +++ b/src/Lumina.Application/Core/Themes/Management/Commands/InstallTheme/InstallThemeCommandHandler.cs @@ -1,8 +1,8 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.CQRS; using Lumina.Application.Common.DataAccess.Entities.Themes; -using Lumina.Application.Common.DataAccess.Repositories.Themes; using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Errors; using Lumina.Application.Common.Infrastructure.Authentication; using Lumina.Application.Common.Infrastructure.Authorization; using Lumina.Application.Common.Infrastructure.Models.DTO.Themes; @@ -16,8 +16,6 @@ using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; -using ApplicationErrors = Lumina.Application.Common.Errors.Errors; -using DomainErrors = Lumina.Domain.Common.Errors.Errors; #endregion namespace Lumina.Application.Core.Themes.Management.Commands.InstallTheme; @@ -71,12 +69,12 @@ public class InstallThemeCommandHandler : ICommandHandler installResult = await _themeService.InstallAsync(command.Archive!, cancellationToken).ConfigureAwait(false); diff --git a/src/Lumina.Application/Core/Themes/Management/Commands/RestoreTheme/RestoreThemeCommandHandler.cs b/src/Lumina.Application/Core/Themes/Management/Commands/RestoreTheme/RestoreThemeCommandHandler.cs index ec4b1a68..e818fdc2 100644 --- a/src/Lumina.Application/Core/Themes/Management/Commands/RestoreTheme/RestoreThemeCommandHandler.cs +++ b/src/Lumina.Application/Core/Themes/Management/Commands/RestoreTheme/RestoreThemeCommandHandler.cs @@ -71,7 +71,7 @@ public class RestoreThemeCommandHandler : ICommandHandler getThemeResult = await _unitOfWork.ThemeRepository.GetByThemeIdAsync(command.ThemeId!, cancellationToken).ConfigureAwait(false); diff --git a/src/Lumina.Application/Core/Themes/Management/Commands/SetCurrentTheme/SetCurrentThemeCommandHandler.cs b/src/Lumina.Application/Core/Themes/Management/Commands/SetCurrentTheme/SetCurrentThemeCommandHandler.cs index 0fa7bb67..bda9df19 100644 --- a/src/Lumina.Application/Core/Themes/Management/Commands/SetCurrentTheme/SetCurrentThemeCommandHandler.cs +++ b/src/Lumina.Application/Core/Themes/Management/Commands/SetCurrentTheme/SetCurrentThemeCommandHandler.cs @@ -67,7 +67,7 @@ public class SetCurrentThemeCommandHandler : ICommandHandler getThemeResult = await _unitOfWork.ThemeRepository.GetByThemeIdAsync(command.ThemeId!, cancellationToken).ConfigureAwait(false); diff --git a/src/Lumina.Application/Core/UsersManagement/Authentication/Queries/GetUsers/GetUsersQueryHandler.cs b/src/Lumina.Application/Core/UsersManagement/Authentication/Queries/GetUsers/GetUsersQueryHandler.cs index 1797831b..8bc17d5f 100644 --- a/src/Lumina.Application/Core/UsersManagement/Authentication/Queries/GetUsers/GetUsersQueryHandler.cs +++ b/src/Lumina.Application/Core/UsersManagement/Authentication/Queries/GetUsers/GetUsersQueryHandler.cs @@ -1,8 +1,6 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.CQRS; using Lumina.Application.Common.DataAccess.Entities.UsersManagement; -using Lumina.Application.Common.DataAccess.Repositories.Users; using Lumina.Application.Common.DataAccess.UoW; using Lumina.Application.Common.DTO.Filtering; using Lumina.Application.Common.DTO.Pagination; @@ -12,6 +10,7 @@ using Lumina.Application.Common.Infrastructure.Authorization; using Lumina.Application.Common.Mapping.Authorization; using Lumina.Application.Common.Mapping.UsersManagement.Users; using Lumina.Contracts.Responses.UsersManagement.Users; +using Lumina.Domain.Common.Primitives; using System; using System.Collections.Generic; using System.Threading; @@ -59,7 +58,7 @@ public class GetUsersQueryHandler : IQueryHandler> getRolesResult = await _unitOfWork.UserRepository.GetAllAsync(cancellationToken: cancellationToken).ConfigureAwait(false); diff --git a/src/Lumina.Application/Core/UsersManagement/Authorization/Commands/UpdateUserRoleAndPermissions/UpdateUserRoleAndPermissionsCommandHandler.cs b/src/Lumina.Application/Core/UsersManagement/Authorization/Commands/UpdateUserRoleAndPermissions/UpdateUserRoleAndPermissionsCommandHandler.cs index f53c150f..21ca9776 100644 --- a/src/Lumina.Application/Core/UsersManagement/Authorization/Commands/UpdateUserRoleAndPermissions/UpdateUserRoleAndPermissionsCommandHandler.cs +++ b/src/Lumina.Application/Core/UsersManagement/Authorization/Commands/UpdateUserRoleAndPermissions/UpdateUserRoleAndPermissionsCommandHandler.cs @@ -1,10 +1,7 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.CQRS; using Lumina.Application.Common.DataAccess.Entities.Authorization; using Lumina.Application.Common.DataAccess.Entities.UsersManagement; -using Lumina.Application.Common.DataAccess.Repositories.Authorization; -using Lumina.Application.Common.DataAccess.Repositories.Users; using Lumina.Application.Common.DataAccess.UoW; using Lumina.Application.Common.DTO.Filtering; using Lumina.Application.Common.DTO.Pagination; @@ -12,6 +9,7 @@ using Lumina.Application.Common.Infrastructure.Authentication; using Lumina.Application.Common.Infrastructure.Authorization; using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Contracts.Responses.Authorization; +using Lumina.Domain.Common.Primitives; using System; using System.Collections.Generic; using System.Linq; @@ -69,7 +67,7 @@ public class UpdateUserRoleAndPermissionsCommandHandler : ICommandHandler> getAllUsersResult = await _unitOfWork.UserRepository.GetAllAsync(cancellationToken: cancellationToken).ConfigureAwait(false); if (getAllUsersResult.IsFailure) return getAllUsersResult.Errors; - int adminCount = getAllUsersResult.Value.Data.Count(user => user.UserRole?.Role.RoleName == "Admin"); + int adminCount = getAllUsersResult.Value.Data.Count(user => user.UserRole?.Role.RoleName == AuthorizationRoles.ADMIN); if (adminCount <= 1) return ApplicationErrors.Authorization.CannotRemoveLastAdmin; } diff --git a/src/Lumina.Application/Core/UsersManagement/Authorization/Queries/GetAuthorization/GetAuthorizationQueryHandler.cs b/src/Lumina.Application/Core/UsersManagement/Authorization/Queries/GetAuthorization/GetAuthorizationQueryHandler.cs index b97a35ee..d448b54b 100644 --- a/src/Lumina.Application/Core/UsersManagement/Authorization/Queries/GetAuthorization/GetAuthorizationQueryHandler.cs +++ b/src/Lumina.Application/Core/UsersManagement/Authorization/Queries/GetAuthorization/GetAuthorizationQueryHandler.cs @@ -1,5 +1,4 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.CQRS; using Lumina.Application.Common.DataAccess.Entities.Authorization; using Lumina.Application.Common.Errors; @@ -8,9 +7,9 @@ using Lumina.Application.Common.Infrastructure.Authorization; using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Common.Mapping.Authorization; using Lumina.Contracts.Responses.Authorization; +using Lumina.Domain.Common.Primitives; using System; using System.Collections.Generic; -using System.Linq; using System.Threading; using System.Threading.Tasks; #endregion @@ -53,21 +52,21 @@ public class GetAuthorizationQueryHandler : IQueryHandler 0) return validationResult; - // an authenticated request must always carry a user identity + // An authenticated request must always carry a user identity. Guid? currentUserId = _currentUserService.UserId; if (currentUserId is null) return Errors.Authorization.NotAuthorized; Guid userId = currentUserId.Value; - // first, check if the Id of the user for whom to get the permission list is different from the Id currently making the request + // First, check if the Id of the user for whom to get the permission list is different from the Id currently making the request. if (userId != query.UserId) { - // if it is, get the role of the current user, and see if they are Admin + // If it is, get the role of the current user, and see if they are Admin. Result getCurrentUserPermissionResult = await _authorizationService.GetUserAuthorizationAsync(userId, cancellationToken).ConfigureAwait(false); if (getCurrentUserPermissionResult.IsFailure) return getCurrentUserPermissionResult.Errors; - // if the current user is not an Admin, and the account for whom they request the permissions list is not theirs, deny the request - if (getCurrentUserPermissionResult.Value.Role != "Admin") + // If the current user is not an Admin, and the account for whom they request the permissions list is not theirs, deny the request. + if (getCurrentUserPermissionResult.Value.Role != AuthorizationRoles.ADMIN) return Errors.Authorization.NotAuthorized; } Result getUserPermissionResult = await _authorizationService.GetUserAuthorizationAsync(query.UserId!.Value, cancellationToken).ConfigureAwait(false); diff --git a/src/Lumina.Application/Core/UsersManagement/Authorization/Queries/GetUserPermissions/GetUserPermissionsQueryHandler.cs b/src/Lumina.Application/Core/UsersManagement/Authorization/Queries/GetUserPermissions/GetUserPermissionsQueryHandler.cs index ae8e36e1..b031c2e8 100644 --- a/src/Lumina.Application/Core/UsersManagement/Authorization/Queries/GetUserPermissions/GetUserPermissionsQueryHandler.cs +++ b/src/Lumina.Application/Core/UsersManagement/Authorization/Queries/GetUserPermissions/GetUserPermissionsQueryHandler.cs @@ -1,8 +1,6 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.CQRS; using Lumina.Application.Common.DataAccess.Entities.UsersManagement; -using Lumina.Application.Common.DataAccess.Repositories.Users; using Lumina.Application.Common.DataAccess.UoW; using Lumina.Application.Common.Errors; using Lumina.Application.Common.Infrastructure.Authentication; @@ -10,6 +8,7 @@ using Lumina.Application.Common.Infrastructure.Authorization; using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Common.Mapping.Authorization; using Lumina.Contracts.Responses.Authorization; +using Lumina.Domain.Common.Primitives; using System; using System.Collections.Generic; using System.Linq; @@ -65,7 +64,7 @@ public class GetUserPermissionsQueryHandler : IQueryHandler +/// Command for updating the playback state the player reports for the current user automatically. These values are not part of the settings the user edits. +/// +/// The last volume the player reported, as a value between 0 and 1. +/// The last mute state the player reported. +public record UpdatePlaybackStateCommand( + double? Volume, + bool? IsMuted +) : ICommand; diff --git a/src/Lumina.Application/Core/UsersManagement/Settings/Commands/UpdatePlaybackState/UpdatePlaybackStateCommandHandler.cs b/src/Lumina.Application/Core/UsersManagement/Settings/Commands/UpdatePlaybackState/UpdatePlaybackStateCommandHandler.cs new file mode 100644 index 00000000..d9b429bd --- /dev/null +++ b/src/Lumina.Application/Core/UsersManagement/Settings/Commands/UpdatePlaybackState/UpdatePlaybackStateCommandHandler.cs @@ -0,0 +1,104 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Errors; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Mapping.UsersManagement.Users; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserSettingsAggregate; +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Application.Core.UsersManagement.Settings.Commands.UpdatePlaybackState; + +/// +/// Handler for the command to update the playback state the player reports for the current user automatically. +/// +public class UpdatePlaybackStateCommandHandler : ICommandHandler> +{ + private readonly IUnitOfWork _unitOfWork; + private readonly ICurrentUserService _currentUserService; + private readonly IValidator _validator; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service to retrieve the current user information. + /// Injected unit of work for interacting with the data access layer repositories. + /// Injected validator for application validation rules. + public UpdatePlaybackStateCommandHandler(ICurrentUserService currentUserService, IUnitOfWork unitOfWork, IValidator validator) + { + _currentUserService = currentUserService; + _unitOfWork = unitOfWork; + _validator = validator; + } + + /// + /// Handles the command to update the playback state the player reports for the current user automatically. + /// + /// The command to be handled. + /// Cancellation token that can be used to stop the execution. + /// + /// An representing either a successful update, or an error message. + /// + public async Task> HandleAsync(UpdatePlaybackStateCommand command, CancellationToken cancellationToken) + { + List validationResult = _validator.Validate(command); + if (validationResult.Count > 0) + return validationResult; + + // An authenticated request must always carry a user identity. + Guid? currentUserId = _currentUserService.UserId; + if (currentUserId is null) + return Errors.Authorization.NotAuthorized; + Guid userId = currentUserId.Value; + + // Get the existing settings of the current user, if any. + Result getSettingsResult = await _unitOfWork.UserSettingsRepository.GetByUserIdAsync(userId, cancellationToken).ConfigureAwait(false); + if (getSettingsResult.IsFailure) + return getSettingsResult.Errors; + + if (getSettingsResult.Value is null) + { + // Create the settings of the current user, since they are not stored yet, keeping the settings the user edits by hand at their default. + Result createSettingsResult = UserSettings.Create(UserId.Create(userId)); + if (createSettingsResult.IsFailure) + return createSettingsResult.Errors; + + Result applyResult = createSettingsResult.Value.UpdatePlaybackState(command.Volume!.Value, command.IsMuted!.Value); + if (applyResult.IsFailure) + return applyResult.Errors; + + Result insertResult = await _unitOfWork.UserSettingsRepository.InsertAsync(createSettingsResult.Value.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false); + if (insertResult.IsFailure) + return insertResult.Errors; + } + else + { + // Update the stored settings of the current user. + Result toDomainEntityResult = getSettingsResult.Value.ToDomainEntity(); + if (toDomainEntityResult.IsFailure) + return toDomainEntityResult.Errors; + + Result applyResult = toDomainEntityResult.Value.UpdatePlaybackState(command.Volume!.Value, command.IsMuted!.Value); + if (applyResult.IsFailure) + return applyResult.Errors; + + Result updateResult = await _unitOfWork.UserSettingsRepository.UpdateAsync(toDomainEntityResult.Value.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false); + if (updateResult.IsFailure) + return updateResult.Errors; + } + + Result saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + return saveChangesResult.Errors; + + return Result.Updated; + } +} diff --git a/src/Lumina.Application/Core/UsersManagement/Settings/Commands/UpdatePlaybackState/UpdatePlaybackStateCommandValidator.cs b/src/Lumina.Application/Core/UsersManagement/Settings/Commands/UpdatePlaybackState/UpdatePlaybackStateCommandValidator.cs new file mode 100644 index 00000000..43edb206 --- /dev/null +++ b/src/Lumina.Application/Core/UsersManagement/Settings/Commands/UpdatePlaybackState/UpdatePlaybackStateCommandValidator.cs @@ -0,0 +1,31 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Utilities; +using Lumina.Domain.Common.Errors; +#endregion + +namespace Lumina.Application.Core.UsersManagement.Settings.Commands.UpdatePlaybackState; + +/// +/// Validates the needed validation rules for . +/// +public class UpdatePlaybackStateCommandValidator : AbstractValidator +{ + /// + /// Initializes a new instance of the class. + /// + public UpdatePlaybackStateCommandValidator() + { + RuleFor(command => command.Volume) + .NotNull() + .WithError(Errors.UserSettings.VolumeCannotBeNull); + + RuleFor(command => command.Volume) + .Must(volume => volume is null || (volume.Value >= 0.0 && volume.Value <= 1.0)) + .WithError(Errors.UserSettings.VolumeMustBeBetweenZeroAndOne); + + RuleFor(command => command.IsMuted) + .NotNull() + .WithError(Errors.UserSettings.IsMutedCannotBeNull); + } +} diff --git a/src/Lumina.Application/Core/UsersManagement/Settings/Commands/UpdateUserSettings/UpdateUserSettingsCommand.cs b/src/Lumina.Application/Core/UsersManagement/Settings/Commands/UpdateUserSettings/UpdateUserSettingsCommand.cs index 7dbaa12e..23acd6bf 100644 --- a/src/Lumina.Application/Core/UsersManagement/Settings/Commands/UpdateUserSettings/UpdateUserSettingsCommand.cs +++ b/src/Lumina.Application/Core/UsersManagement/Settings/Commands/UpdateUserSettings/UpdateUserSettingsCommand.cs @@ -1,5 +1,6 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.CQRS; +using Lumina.Domain.SharedKernel.Common.Enums.Playback; #endregion namespace Lumina.Application.Core.UsersManagement.Settings.Commands.UpdateUserSettings; @@ -15,6 +16,20 @@ namespace Lumina.Application.Core.UsersManagement.Settings.Commands.UpdateUserSe /// Whether the artwork of the media library items is aggregated from multiple providers, when it is missing, or not. /// Whether PDF books are rendered as page images for the user, or not. /// Whether the styles of the book content are preserved when it is rendered for the user, or not. +/// Whether the player keeps downloading a track while playback is paused, or not. +/// Whether the player continues playback at the end of an album or artist, or not. +/// Whether the player transitions between consecutive tracks without a gap, or not. +/// The way ReplayGain normalization is applied to the tracks the user plays. +/// The quality cap applied to the audio the server normalizes for the user. +/// The direction in which each channel of the VU meter of the audio player grows. +/// The number of segments each channel of the VU meter is divided into. +/// The gap, in pixels, between the segments and the channels of the VU meter. +/// The level, between 0 and 1, above which a segment of the VU meter is drawn with its medium state. +/// The level, between 0 and 1, above which a segment of the VU meter is drawn with its high state. +/// Whether the VU meter holds the peak level of each channel after it falls, or not. +/// The time, in milliseconds, a peak of the VU meter is held before it starts falling. +/// The number of level units the display of the VU meter falls per second when the input level drops. +/// The number of level units the peak of the VU meter falls per second after its hold time elapsed. public record UpdateUserSettingsCommand( bool IsPaginationEnabled, int ItemsPerPage, @@ -23,5 +38,19 @@ public record UpdateUserSettingsCommand( bool ShouldAggregateMetadataWhenMissing, bool ShouldAggregateArtworkWhenMissing, bool ShouldRenderPdfAsImages, - bool ShouldPreserveBookStyles + bool ShouldPreserveBookStyles, + bool? ShouldKeepDownloadingWhilePaused, + bool? ShouldAutoplay, + bool? IsGaplessPlaybackEnabled, + ReplayGainMode? ReplayGainMode, + PlaybackStreamingQuality? StreamingQuality, + VuMeterOrientation? VuMeterOrientation, + int? VuMeterSegmentCount, + int? VuMeterSegmentGap, + double? VuMeterMediumThreshold, + double? VuMeterHighThreshold, + bool? VuMeterShowPeak, + int? VuMeterPeakHoldDurationInMilliseconds, + double? VuMeterReleasePerSecond, + double? VuMeterPeakReleasePerSecond ) : ICommand; diff --git a/src/Lumina.Application/Core/UsersManagement/Settings/Commands/UpdateUserSettings/UpdateUserSettingsCommandHandler.cs b/src/Lumina.Application/Core/UsersManagement/Settings/Commands/UpdateUserSettings/UpdateUserSettingsCommandHandler.cs index 73317f73..402f31f2 100644 --- a/src/Lumina.Application/Core/UsersManagement/Settings/Commands/UpdateUserSettings/UpdateUserSettingsCommandHandler.cs +++ b/src/Lumina.Application/Core/UsersManagement/Settings/Commands/UpdateUserSettings/UpdateUserSettingsCommandHandler.cs @@ -66,20 +66,16 @@ public class UpdateUserSettingsCommandHandler : ICommandHandler createSettingsResult = UserSettings.Create( - UserId.Create(userId), - command.IsPaginationEnabled, - command.ItemsPerPage, - command.ShouldIgnoreThePrefixForAlphaPicker, - command.IsThemeCachingEnabled, - command.ShouldAggregateMetadataWhenMissing, - command.ShouldAggregateArtworkWhenMissing, - command.ShouldRenderPdfAsImages, - command.ShouldPreserveBookStyles); + // Create the settings of the current user, since they are not stored yet. The playback state the player reports automatically is left + // at its default, because this command only carries the settings the user edits by hand. + Result createSettingsResult = UserSettings.Create(UserId.Create(userId)); if (createSettingsResult.IsFailure) return createSettingsResult.Errors; + Result applySettingsResult = ApplySettings(createSettingsResult.Value, command); + if (applySettingsResult.IsFailure) + return applySettingsResult.Errors; + Result insertResult = await _unitOfWork.UserSettingsRepository.InsertAsync(createSettingsResult.Value.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false); if (insertResult.IsFailure) return insertResult.Errors; @@ -91,15 +87,7 @@ public class UpdateUserSettingsCommandHandler : ICommandHandler updateSettingsResult = toDomainEntityResult.Value.UpdateSettings( - command.IsPaginationEnabled, - command.ItemsPerPage, - command.ShouldIgnoreThePrefixForAlphaPicker, - command.IsThemeCachingEnabled, - command.ShouldAggregateMetadataWhenMissing, - command.ShouldAggregateArtworkWhenMissing, - command.ShouldRenderPdfAsImages, - command.ShouldPreserveBookStyles); + Result updateSettingsResult = ApplySettings(toDomainEntityResult.Value, command); if (updateSettingsResult.IsFailure) return updateSettingsResult.Errors; @@ -114,4 +102,37 @@ public class UpdateUserSettingsCommandHandler : ICommandHandler + /// Applies the values carried by to the settings of the current user. + /// + /// The settings of the current user to update. + /// The command carrying the new values of the settings. + /// An representing either a successful update, or an error. + private static Result ApplySettings(UserSettings settings, UpdateUserSettingsCommand command) + { + return settings.UpdateSettings( + command.IsPaginationEnabled, + command.ItemsPerPage, + command.ShouldIgnoreThePrefixForAlphaPicker, + command.IsThemeCachingEnabled, + command.ShouldAggregateMetadataWhenMissing, + command.ShouldAggregateArtworkWhenMissing, + command.ShouldRenderPdfAsImages, + command.ShouldPreserveBookStyles, + command.ShouldKeepDownloadingWhilePaused!.Value, + command.ShouldAutoplay!.Value, + command.IsGaplessPlaybackEnabled!.Value, + command.ReplayGainMode!.Value, + command.StreamingQuality!.Value, + command.VuMeterOrientation!.Value, + command.VuMeterSegmentCount!.Value, + command.VuMeterSegmentGap!.Value, + command.VuMeterMediumThreshold!.Value, + command.VuMeterHighThreshold!.Value, + command.VuMeterShowPeak!.Value, + command.VuMeterPeakHoldDurationInMilliseconds!.Value, + command.VuMeterReleasePerSecond!.Value, + command.VuMeterPeakReleasePerSecond!.Value); + } } diff --git a/src/Lumina.Application/Core/UsersManagement/Settings/Commands/UpdateUserSettings/UpdateUserSettingsCommandValidator.cs b/src/Lumina.Application/Core/UsersManagement/Settings/Commands/UpdateUserSettings/UpdateUserSettingsCommandValidator.cs index ba8ff630..328d3f6f 100644 --- a/src/Lumina.Application/Core/UsersManagement/Settings/Commands/UpdateUserSettings/UpdateUserSettingsCommandValidator.cs +++ b/src/Lumina.Application/Core/UsersManagement/Settings/Commands/UpdateUserSettings/UpdateUserSettingsCommandValidator.cs @@ -19,5 +19,108 @@ public class UpdateUserSettingsCommandValidator : AbstractValidator command.ItemsPerPage) .GreaterThan(0) .WithError(Errors.UserSettings.ItemsPerPageMustBeGreaterThanZero); + + RuleFor(command => command.ShouldKeepDownloadingWhilePaused) + .NotNull() + .WithError(Errors.UserSettings.ShouldKeepDownloadingWhilePausedCannotBeNull); + + RuleFor(command => command.ShouldAutoplay) + .NotNull() + .WithError(Errors.UserSettings.ShouldAutoplayCannotBeNull); + + RuleFor(command => command.IsGaplessPlaybackEnabled) + .NotNull() + .WithError(Errors.UserSettings.IsGaplessPlaybackEnabledCannotBeNull); + + RuleFor(command => command.ReplayGainMode) + .NotNull() + .WithError(Errors.UserSettings.ReplayGainModeCannotBeNull); + + RuleFor(command => command.ReplayGainMode) + .IsInEnum() + .WithError(Errors.UserSettings.InvalidReplayGainMode) + .When(command => command.ReplayGainMode is not null); + + RuleFor(command => command.StreamingQuality) + .NotNull() + .WithError(Errors.UserSettings.StreamingQualityCannotBeNull); + + RuleFor(command => command.StreamingQuality) + .IsInEnum() + .WithError(Errors.UserSettings.InvalidStreamingQuality) + .When(command => command.StreamingQuality is not null); + + RuleFor(command => command.VuMeterOrientation) + .NotNull() + .WithError(Errors.UserSettings.VuMeterOrientationCannotBeNull); + + RuleFor(command => command.VuMeterOrientation) + .IsInEnum() + .WithError(Errors.UserSettings.InvalidVuMeterOrientation) + .When(command => command.VuMeterOrientation is not null); + + RuleFor(command => command.VuMeterSegmentCount) + .NotNull() + .WithError(Errors.UserSettings.VuMeterSegmentCountCannotBeNull); + + RuleFor(command => command.VuMeterSegmentCount) + .InclusiveBetween(1, 128) + .WithError(Errors.UserSettings.VuMeterSegmentCountMustBeBetweenOneAndOneHundredTwentyEight); + + RuleFor(command => command.VuMeterSegmentGap) + .NotNull() + .WithError(Errors.UserSettings.VuMeterSegmentGapCannotBeNull); + + RuleFor(command => command.VuMeterSegmentGap) + .InclusiveBetween(0, 32) + .WithError(Errors.UserSettings.VuMeterSegmentGapMustBeBetweenZeroAndThirtyTwo); + + RuleFor(command => command.VuMeterMediumThreshold) + .NotNull() + .WithError(Errors.UserSettings.VuMeterMediumThresholdCannotBeNull); + + RuleFor(command => command.VuMeterMediumThreshold) + .InclusiveBetween(0d, 1d) + .WithError(Errors.UserSettings.VuMeterMediumThresholdMustBeBetweenZeroAndOne); + + RuleFor(command => command.VuMeterHighThreshold) + .NotNull() + .WithError(Errors.UserSettings.VuMeterHighThresholdCannotBeNull); + + RuleFor(command => command.VuMeterHighThreshold) + .InclusiveBetween(0d, 1d) + .WithError(Errors.UserSettings.VuMeterHighThresholdMustBeBetweenZeroAndOne); + + RuleFor(command => command.VuMeterHighThreshold) + .GreaterThanOrEqualTo(command => command.VuMeterMediumThreshold) + .WithError(Errors.UserSettings.VuMeterHighThresholdMustBeGreaterThanOrEqualToMediumThreshold); + + RuleFor(command => command.VuMeterShowPeak) + .NotNull() + .WithError(Errors.UserSettings.VuMeterShowPeakCannotBeNull); + + RuleFor(command => command.VuMeterPeakHoldDurationInMilliseconds) + .NotNull() + .WithError(Errors.UserSettings.VuMeterPeakHoldDurationCannotBeNull); + + RuleFor(command => command.VuMeterPeakHoldDurationInMilliseconds) + .InclusiveBetween(0, 10000) + .WithError(Errors.UserSettings.VuMeterPeakHoldDurationMustBeBetweenZeroAndTenThousandMilliseconds); + + RuleFor(command => command.VuMeterReleasePerSecond) + .NotNull() + .WithError(Errors.UserSettings.VuMeterReleasePerSecondCannotBeNull); + + RuleFor(command => command.VuMeterReleasePerSecond) + .InclusiveBetween(0d, 100d) + .WithError(Errors.UserSettings.VuMeterReleasePerSecondMustBeBetweenZeroAndOneHundred); + + RuleFor(command => command.VuMeterPeakReleasePerSecond) + .NotNull() + .WithError(Errors.UserSettings.VuMeterPeakReleasePerSecondCannotBeNull); + + RuleFor(command => command.VuMeterPeakReleasePerSecond) + .InclusiveBetween(0d, 100d) + .WithError(Errors.UserSettings.VuMeterPeakReleasePerSecondMustBeBetweenZeroAndOneHundred); } } diff --git a/src/Lumina.Application/Core/UsersManagement/Settings/Queries/GetPlaybackState/GetPlaybackStateQuery.cs b/src/Lumina.Application/Core/UsersManagement/Settings/Queries/GetPlaybackState/GetPlaybackStateQuery.cs new file mode 100644 index 00000000..d18d4f83 --- /dev/null +++ b/src/Lumina.Application/Core/UsersManagement/Settings/Queries/GetPlaybackState/GetPlaybackStateQuery.cs @@ -0,0 +1,10 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +#endregion + +namespace Lumina.Application.Core.UsersManagement.Settings.Queries.GetPlaybackState; + +/// +/// Query for getting the playback state the player reported for the current user automatically. These values are not part of the settings the user edits. +/// +public record GetPlaybackStateQuery : IQuery; diff --git a/src/Lumina.Application/Core/UsersManagement/Settings/Queries/GetPlaybackState/GetPlaybackStateQueryHandler.cs b/src/Lumina.Application/Core/UsersManagement/Settings/Queries/GetPlaybackState/GetPlaybackStateQueryHandler.cs new file mode 100644 index 00000000..2039eb5b --- /dev/null +++ b/src/Lumina.Application/Core/UsersManagement/Settings/Queries/GetPlaybackState/GetPlaybackStateQueryHandler.cs @@ -0,0 +1,68 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Errors; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Contracts.Responses.UsersManagement.Settings; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserSettingsAggregate; +using System; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Application.Core.UsersManagement.Settings.Queries.GetPlaybackState; + +/// +/// Handler for the query to get the playback state the player reported for the current user automatically. +/// +public class GetPlaybackStateQueryHandler : IQueryHandler> +{ + private readonly IUnitOfWork _unitOfWork; + private readonly ICurrentUserService _currentUserService; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service to retrieve the current user information. + /// Injected unit of work for interacting with the data access layer repositories. + public GetPlaybackStateQueryHandler(ICurrentUserService currentUserService, IUnitOfWork unitOfWork) + { + _currentUserService = currentUserService; + _unitOfWork = unitOfWork; + } + + /// + /// Handles the query to get the playback state the player reported for the current user automatically. + /// + /// The query to be handled. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either a successfully retrieved , or an error message. + /// + public async Task> HandleAsync(GetPlaybackStateQuery query, CancellationToken cancellationToken) + { + // An authenticated request must always carry a user identity. + Guid? currentUserId = _currentUserService.UserId; + if (currentUserId is null) + return Errors.Authorization.NotAuthorized; + Guid userId = currentUserId.Value; + + // Get the settings of the current user from the repository. + Result getSettingsResult = await _unitOfWork.UserSettingsRepository.GetByUserIdAsync(userId, cancellationToken).ConfigureAwait(false); + if (getSettingsResult.IsFailure) + return getSettingsResult.Errors; + + // When no settings are stored for the current user yet, return the default playback state. + if (getSettingsResult.Value is null) + { + Result defaultSettingsResult = UserSettings.Create(); + if (defaultSettingsResult.IsFailure) + return defaultSettingsResult.Errors; + return new PlaybackStateResponse(defaultSettingsResult.Value.Volume, defaultSettingsResult.Value.IsMuted); + } + + return new PlaybackStateResponse(getSettingsResult.Value.Volume, getSettingsResult.Value.IsMuted); + } +} diff --git a/src/Lumina.Application/Core/UsersManagement/Settings/Queries/GetUserSettings/GetUserSettingsQueryHandler.cs b/src/Lumina.Application/Core/UsersManagement/Settings/Queries/GetUserSettings/GetUserSettingsQueryHandler.cs index 0d40b9df..94b1d97c 100644 --- a/src/Lumina.Application/Core/UsersManagement/Settings/Queries/GetUserSettings/GetUserSettingsQueryHandler.cs +++ b/src/Lumina.Application/Core/UsersManagement/Settings/Queries/GetUserSettings/GetUserSettingsQueryHandler.cs @@ -46,18 +46,18 @@ public class GetUserSettingsQueryHandler : IQueryHandler public async Task> HandleAsync(GetUserSettingsQuery query, CancellationToken cancellationToken) { - // an authenticated request must always carry a user identity + // An authenticated request must always carry a user identity. Guid? currentUserId = _currentUserService.UserId; if (currentUserId is null) return Errors.Authorization.NotAuthorized; Guid userId = currentUserId.Value; - // get the settings of the current user from the repository + // Get the settings of the current user from the repository. Result getSettingsResult = await _unitOfWork.UserSettingsRepository.GetByUserIdAsync(userId, cancellationToken).ConfigureAwait(false); if (getSettingsResult.IsFailure) return getSettingsResult.Errors; - // when no settings are stored for the current user yet, return the default settings + // When no settings are stored for the current user yet, return the default settings. if (getSettingsResult.Value is null) { Result defaultSettingsResult = UserSettings.Create(); diff --git a/src/Lumina.Contracts/DTO/MediaLibrary/AudioLibrary/MusicLibrary/AudioMetadataDto.cs b/src/Lumina.Contracts/DTO/MediaLibrary/AudioLibrary/MusicLibrary/AudioMetadataDto.cs index 35114938..028e1f4b 100644 --- a/src/Lumina.Contracts/DTO/MediaLibrary/AudioLibrary/MusicLibrary/AudioMetadataDto.cs +++ b/src/Lumina.Contracts/DTO/MediaLibrary/AudioLibrary/MusicLibrary/AudioMetadataDto.cs @@ -34,6 +34,7 @@ namespace Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary; /// The number of audio channels of the track. Required. /// The bit depth of the audio of the track. Optional. /// The audio codec used by the track. Optional. +/// The container of the audio file of the track, for example MP3, FLAC, OGG, AAC, MP4 or WAV. Optional. /// The bitrate of the audio of the track in kbps. Optional. /// The MusicBrainz identifier of the recording. Optional. /// The MusicBrainz identifier of the track. Optional. @@ -62,6 +63,7 @@ public sealed record AudioMetadataDto( int? Channels, int? BitDepth, string? AudioCodec, + string? Container, int? Bitrate, Guid? MusicBrainzRecordingId, Guid? MusicBrainzTrackId, diff --git a/src/Lumina.Contracts/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackStreamDataDto.cs b/src/Lumina.Contracts/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackStreamDataDto.cs new file mode 100644 index 00000000..08f594ae --- /dev/null +++ b/src/Lumina.Contracts/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackStreamDataDto.cs @@ -0,0 +1,22 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; + +/// +/// Data transfer object for the data of the audio file of a track, needed to stream it. +/// +/// The file system path of the audio file of the track. +/// The file format of the audio file of the track. +/// The length of the audio file of the track, in bytes. +/// The date and time when the audio file of the track was last modified. +[DebuggerDisplay("Format: {Format} Length: {Length}")] +public sealed record TrackStreamDataDto( + string Path, + AudioFileFormat Format, + long Length, + DateTimeOffset LastModified +); diff --git a/src/Lumina.Contracts/Requests/Favorites/AddFavoriteRequest.cs b/src/Lumina.Contracts/Requests/Favorites/AddFavoriteRequest.cs new file mode 100644 index 00000000..e8f00635 --- /dev/null +++ b/src/Lumina.Contracts/Requests/Favorites/AddFavoriteRequest.cs @@ -0,0 +1,18 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.SharedKernel.Common.Enums.Favorites; +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Requests.Favorites; + +/// +/// Represents a request for marking a media item as a favorite of the current user. +/// +/// The kind of the media item to favorite. Required. +/// The Id of the media item to favorite. Required. +[DebuggerDisplay("MediaKind: {MediaKind}; MediaItemId: {MediaItemId}")] +public record AddFavoriteRequest( + FavoriteMediaKind? MediaKind, + Guid? MediaItemId +); diff --git a/src/Lumina.Contracts/Requests/Favorites/GetFavoriteStatusRequest.cs b/src/Lumina.Contracts/Requests/Favorites/GetFavoriteStatusRequest.cs new file mode 100644 index 00000000..b846a8fb --- /dev/null +++ b/src/Lumina.Contracts/Requests/Favorites/GetFavoriteStatusRequest.cs @@ -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; + +/// +/// Represents a request for finding out which media items of one kind are favorites of the current user. +/// +/// The kind of the media items to check. Required. +/// The Ids of the media items to check, from 1 to 100. Required. +[DebuggerDisplay("MediaKind: {MediaKind}")] +public record GetFavoriteStatusRequest( + FavoriteMediaKind? MediaKind, + List? MediaItemIds +); diff --git a/src/Lumina.Contracts/Requests/Favorites/GetFavoritesRequest.cs b/src/Lumina.Contracts/Requests/Favorites/GetFavoritesRequest.cs new file mode 100644 index 00000000..432c688b --- /dev/null +++ b/src/Lumina.Contracts/Requests/Favorites/GetFavoritesRequest.cs @@ -0,0 +1,19 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.SharedKernel.Common.Enums.Favorites; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Requests.Favorites; + +/// +/// Represents a request for getting a window of the favorites of the current user. +/// +/// The kind of media item to restrict the favorites to. Optional; every kind is returned when omitted. +/// The one based page of favorites to return. Optional; defaults to 1 when a page size is provided. +/// 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. +[DebuggerDisplay("MediaKind: {MediaKind}; CurrentPage: {CurrentPage}; PerPage: {PerPage}")] +public record GetFavoritesRequest( + FavoriteMediaKind? MediaKind, + int? CurrentPage, + int? PerPage +); diff --git a/src/Lumina.Contracts/Requests/MediaConsumption/ClearResumePointsRequest.cs b/src/Lumina.Contracts/Requests/MediaConsumption/ClearResumePointsRequest.cs new file mode 100644 index 00000000..596db58c --- /dev/null +++ b/src/Lumina.Contracts/Requests/MediaConsumption/ClearResumePointsRequest.cs @@ -0,0 +1,14 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Requests.MediaConsumption; + +/// +/// Represents a request to delete the resume points of a user. +/// +/// The Id of the media library to restrict the deletion to. Optional. +[DebuggerDisplay("LibraryId: {LibraryId}")] +public sealed record ClearResumePointsRequest( + string? LibraryId +); diff --git a/src/Lumina.Contracts/Requests/MediaConsumption/CompleteConsumptionRequest.cs b/src/Lumina.Contracts/Requests/MediaConsumption/CompleteConsumptionRequest.cs new file mode 100644 index 00000000..e3810e1a --- /dev/null +++ b/src/Lumina.Contracts/Requests/MediaConsumption/CompleteConsumptionRequest.cs @@ -0,0 +1,21 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Requests.MediaConsumption; + +/// +/// Represents a request to report that a media consumption session completed. +/// +/// The final position reported for the media item, if the client knows it. Optional. +/// The fraction of the media item that the client reached, between 0 and 1. Required. +/// The active duration consumed by the session, in seconds. Required. +/// The number of consecutive pages read in the session, used by page based media such as books. +/// It must be omitted or zero for other kinds; a positive value is rejected with a forbidden error. When omitted, the count stored by the last progress report is kept. Optional. +[DebuggerDisplay("ProgressFraction: {ProgressFraction}; ConsumedDurationInSeconds: {ConsumedDurationInSeconds}; ConsecutivePagesRead: {ConsecutivePagesRead}")] +public sealed record CompleteConsumptionRequest( + MediaPositionRequest? Position, + double? ProgressFraction, + double? ConsumedDurationInSeconds, + int? ConsecutivePagesRead = null +); diff --git a/src/Lumina.Contracts/Requests/MediaConsumption/DeleteConsumptionItemHistoryRequest.cs b/src/Lumina.Contracts/Requests/MediaConsumption/DeleteConsumptionItemHistoryRequest.cs new file mode 100644 index 00000000..7a2847bb --- /dev/null +++ b/src/Lumina.Contracts/Requests/MediaConsumption/DeleteConsumptionItemHistoryRequest.cs @@ -0,0 +1,18 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Requests.MediaConsumption; + +/// +/// Represents a request to delete every consumption record of a media item. +/// +/// The name of the kind of the consumed media item, taken from the route. +/// The Id of the consumed media item, taken from the route. +/// The Id of the media library that contains the media item, taken from the route. +[DebuggerDisplay("MediaKind: {MediaKind}; MediaItemId: {MediaItemId}; LibraryId: {LibraryId}")] +public sealed record DeleteConsumptionItemHistoryRequest( + string? MediaKind, + string? MediaItemId, + string? LibraryId +); diff --git a/src/Lumina.Contracts/Requests/MediaConsumption/GetAllUsersConsumptionStatisticsRequest.cs b/src/Lumina.Contracts/Requests/MediaConsumption/GetAllUsersConsumptionStatisticsRequest.cs new file mode 100644 index 00000000..05aca708 --- /dev/null +++ b/src/Lumina.Contracts/Requests/MediaConsumption/GetAllUsersConsumptionStatisticsRequest.cs @@ -0,0 +1,20 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Requests.MediaConsumption; + +/// +/// Represents a request for getting the consumption statistics of every user. +/// +/// The Id of the media library to restrict the statistics to. Optional. +/// The name of the kind of media to restrict the statistics to. Optional. +/// The inclusive start of the date range, in UTC, as a text value. Optional. +/// The inclusive end of the date range, in UTC, as a text value. Optional. +[DebuggerDisplay("MediaKind: {MediaKind}; FromUtc: {FromUtc}; ToUtc: {ToUtc}")] +public sealed record GetAllUsersConsumptionStatisticsRequest( + string? LibraryId, + string? MediaKind, + string? FromUtc, + string? ToUtc +); diff --git a/src/Lumina.Contracts/Requests/MediaConsumption/GetConsumptionStatisticsRequest.cs b/src/Lumina.Contracts/Requests/MediaConsumption/GetConsumptionStatisticsRequest.cs new file mode 100644 index 00000000..2b744907 --- /dev/null +++ b/src/Lumina.Contracts/Requests/MediaConsumption/GetConsumptionStatisticsRequest.cs @@ -0,0 +1,20 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Requests.MediaConsumption; + +/// +/// Represents a request for getting the consumption statistics of a user. +/// +/// The Id of the media library to restrict the statistics to. Optional. +/// The name of the kind of media to restrict the statistics to. Optional. +/// The inclusive start of the date range, in UTC, as a text value. Optional. +/// The inclusive end of the date range, in UTC, as a text value. Optional. +[DebuggerDisplay("MediaKind: {MediaKind}; FromUtc: {FromUtc}; ToUtc: {ToUtc}")] +public sealed record GetConsumptionStatisticsRequest( + string? LibraryId, + string? MediaKind, + string? FromUtc, + string? ToUtc +); diff --git a/src/Lumina.Contracts/Requests/MediaConsumption/GetGenreConsumptionRequest.cs b/src/Lumina.Contracts/Requests/MediaConsumption/GetGenreConsumptionRequest.cs new file mode 100644 index 00000000..85eb76d9 --- /dev/null +++ b/src/Lumina.Contracts/Requests/MediaConsumption/GetGenreConsumptionRequest.cs @@ -0,0 +1,20 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Requests.MediaConsumption; + +/// +/// Represents a request for getting the consumption statistics of the genres of a user. +/// +/// The Id of the media library to restrict the statistics to. Optional. +/// The name of the kind of media to restrict the statistics to. Optional. +/// The inclusive start of the date range, in UTC, as a text value. Optional. +/// The inclusive end of the date range, in UTC, as a text value. Optional. +[DebuggerDisplay("MediaKind: {MediaKind}; FromUtc: {FromUtc}; ToUtc: {ToUtc}")] +public sealed record GetGenreConsumptionRequest( + string? LibraryId, + string? MediaKind, + string? FromUtc, + string? ToUtc +); diff --git a/src/Lumina.Contracts/Requests/MediaConsumption/GetMostConsumedRequest.cs b/src/Lumina.Contracts/Requests/MediaConsumption/GetMostConsumedRequest.cs new file mode 100644 index 00000000..153ea40d --- /dev/null +++ b/src/Lumina.Contracts/Requests/MediaConsumption/GetMostConsumedRequest.cs @@ -0,0 +1,24 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Requests.MediaConsumption; + +/// +/// Represents a request for getting a window of the most consumed media items of a user. +/// +/// The Id of the media library to restrict the history to. Optional. +/// The name of the kind of media to restrict the history to. Optional. +/// The one based page of media items to return. Optional. +/// The number of media items per page. Optional. +/// The inclusive start of the date range, in UTC, as a text value. Optional. +/// The inclusive end of the date range, in UTC, as a text value. Optional. +[DebuggerDisplay("MediaKind: {MediaKind}; CurrentPage: {CurrentPage}; PerPage: {PerPage}")] +public sealed record GetMostConsumedRequest( + string? LibraryId, + string? MediaKind, + int? CurrentPage, + int? PerPage, + string? FromUtc, + string? ToUtc +); diff --git a/src/Lumina.Contracts/Requests/MediaConsumption/GetRecentlyConsumedRequest.cs b/src/Lumina.Contracts/Requests/MediaConsumption/GetRecentlyConsumedRequest.cs new file mode 100644 index 00000000..223c549f --- /dev/null +++ b/src/Lumina.Contracts/Requests/MediaConsumption/GetRecentlyConsumedRequest.cs @@ -0,0 +1,24 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Requests.MediaConsumption; + +/// +/// Represents a request for getting a window of the recently consumed media items of a user. +/// +/// The Id of the media library to restrict the history to. Optional. +/// The name of the kind of media to restrict the history to. Optional. +/// The one based page of media items to return. Optional. +/// The number of media items per page. Optional. +/// The inclusive start of the date range, in UTC, as a text value. Optional. +/// The inclusive end of the date range, in UTC, as a text value. Optional. +[DebuggerDisplay("MediaKind: {MediaKind}; CurrentPage: {CurrentPage}; PerPage: {PerPage}")] +public sealed record GetRecentlyConsumedRequest( + string? LibraryId, + string? MediaKind, + int? CurrentPage, + int? PerPage, + string? FromUtc, + string? ToUtc +); diff --git a/src/Lumina.Contracts/Requests/MediaConsumption/GetTagConsumptionRequest.cs b/src/Lumina.Contracts/Requests/MediaConsumption/GetTagConsumptionRequest.cs new file mode 100644 index 00000000..336f1ad8 --- /dev/null +++ b/src/Lumina.Contracts/Requests/MediaConsumption/GetTagConsumptionRequest.cs @@ -0,0 +1,20 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Requests.MediaConsumption; + +/// +/// Represents a request for getting the consumption statistics of the tags of a user. +/// +/// The Id of the media library to restrict the statistics to. Optional. +/// The name of the kind of media to restrict the statistics to. Optional. +/// The inclusive start of the date range, in UTC, as a text value. Optional. +/// The inclusive end of the date range, in UTC, as a text value. Optional. +[DebuggerDisplay("MediaKind: {MediaKind}; FromUtc: {FromUtc}; ToUtc: {ToUtc}")] +public sealed record GetTagConsumptionRequest( + string? LibraryId, + string? MediaKind, + string? FromUtc, + string? ToUtc +); diff --git a/src/Lumina.Contracts/Requests/MediaConsumption/MediaPositionRequest.cs b/src/Lumina.Contracts/Requests/MediaConsumption/MediaPositionRequest.cs new file mode 100644 index 00000000..5ed05fb0 --- /dev/null +++ b/src/Lumina.Contracts/Requests/MediaConsumption/MediaPositionRequest.cs @@ -0,0 +1,18 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Requests.MediaConsumption; + +/// +/// Represents a request to report a position in a media consumption session. +/// +/// The kind of the position. Required. +/// The position within the media item, in seconds, when the position is a time offset. Optional. +/// The opaque locator within the media item, when the position is not a time offset. Optional. +[DebuggerDisplay("Kind: {Kind}; TimeOffsetSeconds: {TimeOffsetSeconds}")] +public sealed record MediaPositionRequest( + string? Kind, + double? TimeOffsetSeconds, + string? Location +); diff --git a/src/Lumina.Contracts/Requests/MediaConsumption/ReportConsumptionProgressRequest.cs b/src/Lumina.Contracts/Requests/MediaConsumption/ReportConsumptionProgressRequest.cs new file mode 100644 index 00000000..41604055 --- /dev/null +++ b/src/Lumina.Contracts/Requests/MediaConsumption/ReportConsumptionProgressRequest.cs @@ -0,0 +1,21 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Requests.MediaConsumption; + +/// +/// Represents a request to report the progress of a media consumption session. +/// +/// The last position reported for the media item, if the client knows it. Optional. +/// The fraction of the media item that the client reached, between 0 and 1. Required. +/// The active duration consumed by the session, in seconds. Required. +/// The number of consecutive pages read in the current session, used by page based media such as books. +/// It must be zero for other kinds; a positive value is rejected with a forbidden error. Defaults to 0. Optional. +[DebuggerDisplay("ProgressFraction: {ProgressFraction}; ConsumedDurationInSeconds: {ConsumedDurationInSeconds}; ConsecutivePagesRead: {ConsecutivePagesRead}")] +public sealed record ReportConsumptionProgressRequest( + MediaPositionRequest? Position, + double? ProgressFraction, + double? ConsumedDurationInSeconds, + int ConsecutivePagesRead = 0 +); diff --git a/src/Lumina.Contracts/Requests/MediaConsumption/StopConsumptionRequest.cs b/src/Lumina.Contracts/Requests/MediaConsumption/StopConsumptionRequest.cs new file mode 100644 index 00000000..c189d147 --- /dev/null +++ b/src/Lumina.Contracts/Requests/MediaConsumption/StopConsumptionRequest.cs @@ -0,0 +1,21 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Requests.MediaConsumption; + +/// +/// Represents a request to report that a media consumption session stopped. +/// +/// The final position reported for the media item, if the client knows it. Optional. +/// The fraction of the media item that the client reached, between 0 and 1. Required. +/// The active duration consumed by the session, in seconds. Required. +/// The number of consecutive pages read in the session, used by page based media such as books. +/// It must be omitted or zero for other kinds; a positive value is rejected with a forbidden error. When omitted, the count stored by the last progress report is kept. Optional. +[DebuggerDisplay("ProgressFraction: {ProgressFraction}; ConsumedDurationInSeconds: {ConsumedDurationInSeconds}; ConsecutivePagesRead: {ConsecutivePagesRead}")] +public sealed record StopConsumptionRequest( + MediaPositionRequest? Position, + double? ProgressFraction, + double? ConsumedDurationInSeconds, + int? ConsecutivePagesRead = null +); diff --git a/src/Lumina.Contracts/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/ShuffleTracksRequest.cs b/src/Lumina.Contracts/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/ShuffleTracksRequest.cs new file mode 100644 index 00000000..7812883d --- /dev/null +++ b/src/Lumina.Contracts/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/ShuffleTracksRequest.cs @@ -0,0 +1,22 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Collections.Generic; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; + +/// +/// Represents a request to draw a random selection of tracks from a media library, an artist or an album. +/// +/// The maximum number of tracks to return. Required. +/// The unique identifier of the artist whose tracks are sampled. Optional. +/// The unique identifier of the album whose tracks are sampled. Optional. +/// The tracks that must not be returned, usually the ones already in the queue. Optional. +[DebuggerDisplay("Count: {Count}")] +public record ShuffleTracksRequest( + int Count, + Guid? ArtistId, + Guid? AlbumId, + List? ExcludedTrackIds +); diff --git a/src/Lumina.Contracts/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/UpdateTrackRequest.cs b/src/Lumina.Contracts/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/UpdateTrackRequest.cs index 34cb73d8..c2e624ad 100644 --- a/src/Lumina.Contracts/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/UpdateTrackRequest.cs +++ b/src/Lumina.Contracts/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/UpdateTrackRequest.cs @@ -14,7 +14,6 @@ namespace Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Track /// /// Represents a request to update an existing track. /// -/// The file system path of the track. Required. /// The audio metadata of the track. Required. /// The number of the track on its disc. Required. /// The number of the disc the track belongs to. Optional. @@ -30,7 +29,6 @@ namespace Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Track /// The list of ratings for this track. Required. [DebuggerDisplay("Title: {Metadata.Title}")] public record UpdateTrackRequest( - string? Path, MusicTrackMetadataDto? Metadata, int? TrackNumber, int? DiscNumber, diff --git a/src/Lumina.Contracts/Requests/MediaLibrary/Management/AddLibraryRequest.cs b/src/Lumina.Contracts/Requests/MediaLibrary/Management/AddLibraryRequest.cs index 8f8e7196..68246693 100644 --- a/src/Lumina.Contracts/Requests/MediaLibrary/Management/AddLibraryRequest.cs +++ b/src/Lumina.Contracts/Requests/MediaLibrary/Management/AddLibraryRequest.cs @@ -16,6 +16,8 @@ namespace Lumina.Contracts.Requests.MediaLibrary.Management; /// Whether this media library should update the metadata of its elements from the web, or not. Optional. /// Whether this media library should copy the downloaded metadata into the media library content locations, or not. Optional. /// Whether this media library should skip the directories whose contents have not changed since the last scan, during the scan, or not. Optional. +/// Whether the consumption progress of the media library items should be tracked, or not. Optional, the default of the library type is used when absent. +/// The percentage of a media library item that must be consumed for its session to be considered completed. Optional, the default of the library type is used when absent. /// The ordered parts of the template describing the structure of the media library on disk. Optional, the ideal structure of the library type is used when absent. [DebuggerDisplay("Title: {Title}")] public record AddLibraryRequest( @@ -28,5 +30,7 @@ public record AddLibraryRequest( bool CanDownloadMetadataFromWeb, bool ShouldSaveMetadataInMediaDirectories, bool ShouldSkipUnchangedDirectoriesDuringScan, + bool? ShouldTrackConsumptionProgress, + int? CompletionThresholdPercentage, LibraryPathTemplatePartRequest[]? PathTemplateParts ); diff --git a/src/Lumina.Contracts/Requests/MediaLibrary/Management/UpdateLibraryRequest.cs b/src/Lumina.Contracts/Requests/MediaLibrary/Management/UpdateLibraryRequest.cs index ba3b9226..6e967af2 100644 --- a/src/Lumina.Contracts/Requests/MediaLibrary/Management/UpdateLibraryRequest.cs +++ b/src/Lumina.Contracts/Requests/MediaLibrary/Management/UpdateLibraryRequest.cs @@ -19,6 +19,8 @@ namespace Lumina.Contracts.Requests.MediaLibrary.Management; /// Whether this media library should update the metadata of its elements from the web, or not. Optional. /// Whether this media library should copy the downloaded metadata into the media library content locations, or not. /// Whether this media library should skip the directories whose contents have not changed since the last scan, during the scan, or not. Optional. +/// Whether the consumption progress of the media library items should be tracked, or not. Optional, the stored value is kept when absent. +/// The percentage of a media library item that must be consumed for its session to be considered completed. Optional, the stored value is kept when absent. /// The ordered parts of the template describing the structure of the media library on disk. Optional, the ideal structure of the library type is used when absent. [DebuggerDisplay("Title: {Title}")] public record class UpdateLibraryRequest( @@ -33,5 +35,7 @@ public record class UpdateLibraryRequest( bool CanDownloadMetadataFromWeb, bool ShouldSaveMetadataInMediaDirectories, bool ShouldSkipUnchangedDirectoriesDuringScan, + bool? ShouldTrackConsumptionProgress, + int? CompletionThresholdPercentage, LibraryPathTemplatePartRequest[]? PathTemplateParts ); diff --git a/src/Lumina.Contracts/Requests/Playlists/AddPlaylistEntriesRequest.cs b/src/Lumina.Contracts/Requests/Playlists/AddPlaylistEntriesRequest.cs new file mode 100644 index 00000000..84d5dcd1 --- /dev/null +++ b/src/Lumina.Contracts/Requests/Playlists/AddPlaylistEntriesRequest.cs @@ -0,0 +1,16 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Collections.Generic; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Requests.Playlists; + +/// +/// Represents a request for adding several tracks to a playlist of the current user, in order. +/// +/// The Ids of the tracks to add, in the order they must take. Required. +[DebuggerDisplay("TrackCount: {TrackIds.Count}")] +public record AddPlaylistEntriesRequest( + List? TrackIds +); diff --git a/src/Lumina.Contracts/Requests/Playlists/AddPlaylistEntryRequest.cs b/src/Lumina.Contracts/Requests/Playlists/AddPlaylistEntryRequest.cs new file mode 100644 index 00000000..dbc52982 --- /dev/null +++ b/src/Lumina.Contracts/Requests/Playlists/AddPlaylistEntryRequest.cs @@ -0,0 +1,15 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Requests.Playlists; + +/// +/// Represents a request for adding a track to a playlist of the current user. +/// +/// The Id of the track to add. Required. +[DebuggerDisplay("TrackId: {TrackId}")] +public record AddPlaylistEntryRequest( + Guid? TrackId +); diff --git a/src/Lumina.Contracts/Requests/Playlists/AddPlaylistScopeEntriesRequest.cs b/src/Lumina.Contracts/Requests/Playlists/AddPlaylistScopeEntriesRequest.cs new file mode 100644 index 00000000..6d040899 --- /dev/null +++ b/src/Lumina.Contracts/Requests/Playlists/AddPlaylistScopeEntriesRequest.cs @@ -0,0 +1,19 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Requests.Playlists; + +/// +/// Represents a request to add every track of a music library, an artist or an album to a playlist, resolved on the server. +/// +/// The Id of the music library the scope belongs to. Required. +/// The Id of the artist the scope is limited to. Optional. +/// The Id of the album the scope is limited to. Optional. +[DebuggerDisplay("LibraryId: {LibraryId}; ArtistId: {ArtistId}; AlbumId: {AlbumId}")] +public record AddPlaylistScopeEntriesRequest( + Guid LibraryId, + Guid? ArtistId = null, + Guid? AlbumId = null +); diff --git a/src/Lumina.Contracts/Requests/Playlists/CreatePlaylistRequest.cs b/src/Lumina.Contracts/Requests/Playlists/CreatePlaylistRequest.cs new file mode 100644 index 00000000..a929ee46 --- /dev/null +++ b/src/Lumina.Contracts/Requests/Playlists/CreatePlaylistRequest.cs @@ -0,0 +1,19 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.SharedKernel.Common.Enums.Playlists; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Requests.Playlists; + +/// +/// Represents a request for creating a playlist of the current user. +/// +/// The name of the playlist. Required. +/// The description of the playlist. Optional. +/// The kind of media the playlist holds. Required. +[DebuggerDisplay("Name: {Name}")] +public record CreatePlaylistRequest( + string? Name, + string? Description, + PlaylistType? Type +); diff --git a/src/Lumina.Contracts/Requests/Playlists/GetPlaylistRequest.cs b/src/Lumina.Contracts/Requests/Playlists/GetPlaylistRequest.cs new file mode 100644 index 00000000..e8bfe22a --- /dev/null +++ b/src/Lumina.Contracts/Requests/Playlists/GetPlaylistRequest.cs @@ -0,0 +1,16 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Requests.Playlists; + +/// +/// Represents a request for getting a page of the entries of a playlist of the current user. +/// +/// The one based page of entries to return. Optional; defaults to 1 when a page size is provided. +/// 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. +[DebuggerDisplay("CurrentPage: {CurrentPage}; PerPage: {PerPage}")] +public record GetPlaylistRequest( + int? CurrentPage, + int? PerPage +); diff --git a/src/Lumina.Contracts/Requests/Playlists/MovePlaylistEntryRequest.cs b/src/Lumina.Contracts/Requests/Playlists/MovePlaylistEntryRequest.cs new file mode 100644 index 00000000..dd8e06ee --- /dev/null +++ b/src/Lumina.Contracts/Requests/Playlists/MovePlaylistEntryRequest.cs @@ -0,0 +1,14 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Requests.Playlists; + +/// +/// Represents a request for moving one entry of a playlist of the current user to a new position. +/// +/// The new zero based position of the entry. Required. +[DebuggerDisplay("TargetPosition: {TargetPosition}")] +public record MovePlaylistEntryRequest( + int? TargetPosition +); diff --git a/src/Lumina.Contracts/Requests/Playlists/UpdatePlaylistRequest.cs b/src/Lumina.Contracts/Requests/Playlists/UpdatePlaylistRequest.cs new file mode 100644 index 00000000..277abc0d --- /dev/null +++ b/src/Lumina.Contracts/Requests/Playlists/UpdatePlaylistRequest.cs @@ -0,0 +1,16 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Requests.Playlists; + +/// +/// Represents a request for updating the details of a playlist of the current user. +/// +/// The name of the playlist. Required. +/// The description of the playlist. Optional. +[DebuggerDisplay("Name: {Name}")] +public record UpdatePlaylistRequest( + string? Name, + string? Description +); diff --git a/src/Lumina.Contracts/Requests/UsersManagement/Settings/UpdatePlaybackStateRequest.cs b/src/Lumina.Contracts/Requests/UsersManagement/Settings/UpdatePlaybackStateRequest.cs new file mode 100644 index 00000000..bfd0de94 --- /dev/null +++ b/src/Lumina.Contracts/Requests/UsersManagement/Settings/UpdatePlaybackStateRequest.cs @@ -0,0 +1,16 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Requests.UsersManagement.Settings; + +/// +/// Represents a request to report the playback state of the current user. The player sends this automatically, and these values are not part of the settings the user edits. +/// +/// The last volume the player reported, as a value between 0 and 1. Required. +/// The last mute state the player reported. Required. +[DebuggerDisplay("Volume: {Volume}; IsMuted: {IsMuted}")] +public sealed record UpdatePlaybackStateRequest( + double? Volume, + bool? IsMuted +); diff --git a/src/Lumina.Contracts/Requests/UsersManagement/Settings/UpdateUserSettingsRequest.cs b/src/Lumina.Contracts/Requests/UsersManagement/Settings/UpdateUserSettingsRequest.cs index f42474fa..44ad87c3 100644 --- a/src/Lumina.Contracts/Requests/UsersManagement/Settings/UpdateUserSettingsRequest.cs +++ b/src/Lumina.Contracts/Requests/UsersManagement/Settings/UpdateUserSettingsRequest.cs @@ -1,4 +1,5 @@ #region ========================================================================= USING ===================================================================================== +using Lumina.Domain.SharedKernel.Common.Enums.Playback; using System.Diagnostics; #endregion @@ -15,6 +16,20 @@ namespace Lumina.Contracts.Requests.UsersManagement.Settings; /// Whether the artwork of the media library items is aggregated from multiple providers, when it is missing, or not. Required. /// Whether PDF books are rendered as page images for the user, or not. Required. /// Whether the styles of the book content are preserved when it is rendered for the user, or not. Required. +/// Whether the player keeps downloading a track while playback is paused, or not. Required. +/// Whether the player continues playback at the end of an album or artist, or not. Required. +/// Whether the player transitions between consecutive tracks without a gap, or not. Required. +/// The way ReplayGain normalization is applied to the tracks the user plays. Required. +/// The quality cap applied to the audio the server normalizes for the user. Required. +/// The direction in which each channel of the VU meter of the audio player grows. Required. +/// The number of segments each channel of the VU meter is divided into. Required. +/// The gap, in pixels, between the segments and the channels of the VU meter. Required. +/// The level, between 0 and 1, above which a segment of the VU meter is drawn with its medium state. Required. +/// The level, between 0 and 1, above which a segment of the VU meter is drawn with its high state. Required. +/// Whether the VU meter holds the peak level of each channel after it falls, or not. Required. +/// The time, in milliseconds, a peak of the VU meter is held before it starts falling. Required. +/// The number of level units the display of the VU meter falls per second when the input level drops. Required. +/// The number of level units the peak of the VU meter falls per second after its hold time elapsed. Required. [DebuggerDisplay("IsPaginationEnabled: {IsPaginationEnabled}; ItemsPerPage: {ItemsPerPage}")] public sealed record UpdateUserSettingsRequest( bool IsPaginationEnabled, @@ -24,5 +39,19 @@ public sealed record UpdateUserSettingsRequest( bool ShouldAggregateMetadataWhenMissing, bool ShouldAggregateArtworkWhenMissing, bool ShouldRenderPdfAsImages, - bool ShouldPreserveBookStyles + bool ShouldPreserveBookStyles, + bool? ShouldKeepDownloadingWhilePaused, + bool? ShouldAutoplay, + bool? IsGaplessPlaybackEnabled, + ReplayGainMode? ReplayGainMode, + PlaybackStreamingQuality? StreamingQuality, + VuMeterOrientation? VuMeterOrientation, + int? VuMeterSegmentCount, + int? VuMeterSegmentGap, + double? VuMeterMediumThreshold, + double? VuMeterHighThreshold, + bool? VuMeterShowPeak, + int? VuMeterPeakHoldDurationInMilliseconds, + double? VuMeterReleasePerSecond, + double? VuMeterPeakReleasePerSecond ); diff --git a/src/Lumina.Contracts/Responses/Favorites/FavoriteItemResponse.cs b/src/Lumina.Contracts/Responses/Favorites/FavoriteItemResponse.cs new file mode 100644 index 00000000..319ad5c5 --- /dev/null +++ b/src/Lumina.Contracts/Responses/Favorites/FavoriteItemResponse.cs @@ -0,0 +1,39 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.SharedKernel.Common.Enums.Favorites; +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Responses.Favorites; + +/// +/// Represents a response for a favorite of the current user together with the display details of the media item it references. +/// +/// +/// 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. +/// +/// The kind of the favorited media item. +/// The Id of the favorited media item. +/// Whether the media item still exists and can be accessed by the user. When , every display field is empty. +/// The Id of the media library that contains the media item, or an empty Guid when the item is not available. +/// The title of the media item, or an empty string when the item is not available. +/// The Id of the collection that contains the media item, or an empty Guid when there is none. +/// The title of the collection that contains the media item, or an empty string when there is none. +/// The Id of the creator of the media item, or an empty Guid when there is none. +/// The name of the creator of the media item, or an empty string when there is none. +/// The path of the cover art of the media item, if available. +[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 +); diff --git a/src/Lumina.Contracts/Responses/Favorites/FavoriteResponse.cs b/src/Lumina.Contracts/Responses/Favorites/FavoriteResponse.cs new file mode 100644 index 00000000..5453a4d4 --- /dev/null +++ b/src/Lumina.Contracts/Responses/Favorites/FavoriteResponse.cs @@ -0,0 +1,22 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.SharedKernel.Common.Enums.Favorites; +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Responses.Favorites; + +/// +/// Represents a response for a favorite of the current user. +/// +/// The Id of the favorite. +/// The kind of the favorited media item. +/// The Id of the favorited media item. +/// The date and time when the media item was favorited. +[DebuggerDisplay("Id: {Id}; MediaKind: {MediaKind}; MediaItemId: {MediaItemId}")] +public sealed record FavoriteResponse( + Guid Id, + FavoriteMediaKind MediaKind, + Guid MediaItemId, + DateTime FavoritedOnUtc +); diff --git a/src/Lumina.Contracts/Responses/Favorites/FavoriteStatusResponse.cs b/src/Lumina.Contracts/Responses/Favorites/FavoriteStatusResponse.cs new file mode 100644 index 00000000..b950438e --- /dev/null +++ b/src/Lumina.Contracts/Responses/Favorites/FavoriteStatusResponse.cs @@ -0,0 +1,16 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Collections.Generic; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Responses.Favorites; + +/// +/// Represents a response that tells which of the checked media items are favorites of the current user. +/// +/// The Ids, among the checked ones, of the media items that are favorites of the current user. +[DebuggerDisplay("Favorited: {FavoritedMediaItemIds.Count}")] +public sealed record FavoriteStatusResponse( + IReadOnlyList FavoritedMediaItemIds +); diff --git a/src/Lumina.Contracts/Responses/MediaConsumption/AllUsersConsumptionStatisticsResponse.cs b/src/Lumina.Contracts/Responses/MediaConsumption/AllUsersConsumptionStatisticsResponse.cs new file mode 100644 index 00000000..558982ae --- /dev/null +++ b/src/Lumina.Contracts/Responses/MediaConsumption/AllUsersConsumptionStatisticsResponse.cs @@ -0,0 +1,17 @@ +#region ========================================================================= USING ===================================================================================== +using System.Collections.Generic; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Responses.MediaConsumption; + +/// +/// Represents the consumption statistics of every user, together with their combined totals. +/// +/// The combined consumption statistics of every user. +/// The consumption statistics of each user. +[DebuggerDisplay("UserCount: {Users.Count}; CountedSessionCount: {Total.CountedSessionCount}")] +public sealed record AllUsersConsumptionStatisticsResponse( + ConsumptionTotalsResponse Total, + IReadOnlyList Users +); diff --git a/src/Lumina.Contracts/Responses/MediaConsumption/ConsumedItemResponse.cs b/src/Lumina.Contracts/Responses/MediaConsumption/ConsumedItemResponse.cs new file mode 100644 index 00000000..d6b9f2f0 --- /dev/null +++ b/src/Lumina.Contracts/Responses/MediaConsumption/ConsumedItemResponse.cs @@ -0,0 +1,38 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Responses.MediaConsumption; + +/// +/// Represents a media item of the consumption history, together with its aggregated consumption counts and display details. +/// +/// The kind of the consumed media item. +/// The Id of the consumed media item. +/// The Id of the media library that contains the media item. +/// Whether the media item still exists and can be accessed by the user. When , the title, collection title, creator name, and cover path are blank, while the identity and aggregation fields remain. +/// The title of the media item, or an empty string when the item is not available. +/// The title of the collection that contains the media item, or an empty string when there is none. +/// The name of the creator of the media item, or an empty string when there is none. +/// The path of the cover art of the media item, if available. +/// The date and time when the media item was last consumed. +/// The number of consumption sessions of the media item that count towards statistics. +/// The number of consumption sessions of the media item that completed. +/// The active duration consumed in the media item, over all of its sessions, in seconds. +[DebuggerDisplay("MediaKind: {MediaKind}; MediaItemId: {MediaItemId}; CountedSessionCount: {CountedSessionCount}")] +public sealed record ConsumedItemResponse( + MediaKind MediaKind, + Guid MediaItemId, + Guid LibraryId, + bool IsAvailable, + string Title, + string CollectionTitle, + string CreatorName, + string? CoverPath, + DateTime LastConsumedOnUtc, + int CountedSessionCount, + int CompletedSessionCount, + double ConsumedDurationInSeconds +); diff --git a/src/Lumina.Contracts/Responses/MediaConsumption/ConsumptionRecordResponse.cs b/src/Lumina.Contracts/Responses/MediaConsumption/ConsumptionRecordResponse.cs new file mode 100644 index 00000000..96f222b4 --- /dev/null +++ b/src/Lumina.Contracts/Responses/MediaConsumption/ConsumptionRecordResponse.cs @@ -0,0 +1,39 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Responses.MediaConsumption; + +/// +/// Represents a media consumption session. +/// +/// The Id of the consumption record. +/// The Id of the media library that contains the consumed media item. +/// The Id of the consumed media item. +/// The kind of media that was consumed. +/// The state of the consumption session. +/// The date and time when the session started. +/// The date and time when the session last received activity. +/// The date and time when the session completed or stopped, if it has ended. +/// The active duration consumed by the session, in seconds. +/// The last known position for the media item, if any. +/// The latest reported progress fraction of the media item. +/// The number of consecutive pages read in the session. +[DebuggerDisplay("Id: {Id}; MediaKind: {MediaKind}; Status: {Status}")] +public sealed record ConsumptionRecordResponse( + Guid Id, + Guid LibraryId, + Guid MediaItemId, + MediaKind MediaKind, + ConsumptionStatus Status, + DateTime StartedOnUtc, + DateTime LastActivityOnUtc, + DateTime? EndedOnUtc, + double ConsumedDurationInSeconds, + MediaPositionResponse? LastPosition, + double LastProgressFraction, + int ConsecutivePagesRead +); diff --git a/src/Lumina.Contracts/Responses/MediaConsumption/ConsumptionSummaryResponse.cs b/src/Lumina.Contracts/Responses/MediaConsumption/ConsumptionSummaryResponse.cs new file mode 100644 index 00000000..8b39265f --- /dev/null +++ b/src/Lumina.Contracts/Responses/MediaConsumption/ConsumptionSummaryResponse.cs @@ -0,0 +1,28 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Collections.Generic; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Responses.MediaConsumption; + +/// +/// Represents the consumption statistics of a user. +/// +/// The Id of the user the statistics belong to. +/// The total duration consumed over every recorded session, in seconds. +/// The number of recorded sessions that count towards statistics. +/// The number of recorded sessions that completed. +/// The number of recorded sessions that stopped before they completed and count towards statistics. +/// The fraction of the counted sessions that completed, between 0 and 1, or 0 when there is no counted session. +/// The consumption statistics broken down by media kind. +[DebuggerDisplay("UserId: {UserId}; CountedSessionCount: {CountedSessionCount}")] +public sealed record ConsumptionSummaryResponse( + Guid UserId, + double TotalConsumedDurationInSeconds, + int CountedSessionCount, + int CompletedSessionCount, + int StoppedSessionCount, + double CompletionRate, + IReadOnlyList MediaKindSummaries +); diff --git a/src/Lumina.Contracts/Responses/MediaConsumption/ConsumptionTotalsResponse.cs b/src/Lumina.Contracts/Responses/MediaConsumption/ConsumptionTotalsResponse.cs new file mode 100644 index 00000000..d5390a4d --- /dev/null +++ b/src/Lumina.Contracts/Responses/MediaConsumption/ConsumptionTotalsResponse.cs @@ -0,0 +1,25 @@ +#region ========================================================================= USING ===================================================================================== +using System.Collections.Generic; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Responses.MediaConsumption; + +/// +/// Represents the combined consumption statistics of every user. +/// +/// The total duration consumed over every recorded session of every user, in seconds. +/// The number of recorded sessions of every user that count towards statistics. +/// The number of recorded sessions of every user that completed. +/// The number of recorded sessions of every user that stopped before they completed and count towards statistics. +/// The fraction of the counted sessions of every user that completed, between 0 and 1, or 0 when there is no counted session. +/// The combined consumption statistics broken down by media kind. +[DebuggerDisplay("CountedSessionCount: {CountedSessionCount}; CompletedSessionCount: {CompletedSessionCount}")] +public sealed record ConsumptionTotalsResponse( + double TotalConsumedDurationInSeconds, + int CountedSessionCount, + int CompletedSessionCount, + int StoppedSessionCount, + double CompletionRate, + IReadOnlyList MediaKindSummaries +); diff --git a/src/Lumina.Contracts/Responses/MediaConsumption/GenreConsumptionResponse.cs b/src/Lumina.Contracts/Responses/MediaConsumption/GenreConsumptionResponse.cs new file mode 100644 index 00000000..b78a9c22 --- /dev/null +++ b/src/Lumina.Contracts/Responses/MediaConsumption/GenreConsumptionResponse.cs @@ -0,0 +1,18 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Responses.MediaConsumption; + +/// +/// Represents the consumption statistics of a genre, grouped across media kinds. +/// +/// The lowercase name of the genre. +/// The number of distinct media items that carry the genre and were consumed. +/// The active duration consumed in the media items that carry the genre, in seconds. +[DebuggerDisplay("Name: {Name}; ConsumedItemCount: {ConsumedItemCount}")] +public sealed record GenreConsumptionResponse( + string Name, + int ConsumedItemCount, + double ConsumedDurationInSeconds +); diff --git a/src/Lumina.Contracts/Responses/MediaConsumption/MediaKindConsumptionSummaryResponse.cs b/src/Lumina.Contracts/Responses/MediaConsumption/MediaKindConsumptionSummaryResponse.cs new file mode 100644 index 00000000..2984741a --- /dev/null +++ b/src/Lumina.Contracts/Responses/MediaConsumption/MediaKindConsumptionSummaryResponse.cs @@ -0,0 +1,25 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Responses.MediaConsumption; + +/// +/// Represents the consumption statistics of a user for one kind of media. +/// +/// The kind of media the statistics belong to. +/// The total duration consumed over every recorded session of the media kind, in seconds. +/// The number of recorded sessions of the media kind that count towards statistics. +/// The number of recorded sessions of the media kind that completed. +/// The number of recorded sessions of the media kind that stopped before they completed and count towards statistics. +/// The fraction of the counted sessions of the media kind that completed, between 0 and 1, or 0 when there is no counted session. +[DebuggerDisplay("MediaKind: {MediaKind}; CountedSessionCount: {CountedSessionCount}")] +public sealed record MediaKindConsumptionSummaryResponse( + MediaKind MediaKind, + double TotalConsumedDurationInSeconds, + int CountedSessionCount, + int CompletedSessionCount, + int StoppedSessionCount, + double CompletionRate +); diff --git a/src/Lumina.Contracts/Responses/MediaConsumption/MediaPositionResponse.cs b/src/Lumina.Contracts/Responses/MediaConsumption/MediaPositionResponse.cs new file mode 100644 index 00000000..0c0d0f2e --- /dev/null +++ b/src/Lumina.Contracts/Responses/MediaConsumption/MediaPositionResponse.cs @@ -0,0 +1,19 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Responses.MediaConsumption; + +/// +/// Represents a position reached in a media item during a consumption session. +/// +/// The kind of representation used by the position. +/// The position within the media item, in seconds, when the position is a time offset. +/// The opaque locator within the media item, when the position is not a time offset. +[DebuggerDisplay("Kind: {Kind}; TimeOffsetSeconds: {TimeOffsetSeconds}")] +public sealed record MediaPositionResponse( + MediaPositionKind Kind, + double? TimeOffsetSeconds, + string? Location +); diff --git a/src/Lumina.Contracts/Responses/MediaConsumption/ResumePointResponse.cs b/src/Lumina.Contracts/Responses/MediaConsumption/ResumePointResponse.cs new file mode 100644 index 00000000..7bb35a0b --- /dev/null +++ b/src/Lumina.Contracts/Responses/MediaConsumption/ResumePointResponse.cs @@ -0,0 +1,28 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Responses.MediaConsumption; + +/// +/// Represents the point at which a user can resume consuming a media item. +/// +/// The Id of the resume point. +/// The Id of the media library that contains the media item. +/// The Id of the media item to resume. +/// The kind of media that is resumed. +/// The position at which the media item can be resumed. +/// The progress fraction at which the media item can be resumed. +/// The date and time when the media item was last consumed. +[DebuggerDisplay("Id: {Id}; MediaKind: {MediaKind}; MediaItemId: {MediaItemId}")] +public sealed record ResumePointResponse( + Guid Id, + Guid LibraryId, + Guid MediaItemId, + MediaKind MediaKind, + MediaPositionResponse LastPosition, + double LastProgressFraction, + DateTime LastConsumedOnUtc +); diff --git a/src/Lumina.Contracts/Responses/MediaConsumption/TagConsumptionResponse.cs b/src/Lumina.Contracts/Responses/MediaConsumption/TagConsumptionResponse.cs new file mode 100644 index 00000000..48468318 --- /dev/null +++ b/src/Lumina.Contracts/Responses/MediaConsumption/TagConsumptionResponse.cs @@ -0,0 +1,18 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Responses.MediaConsumption; + +/// +/// Represents the consumption statistics of a tag, grouped across media kinds. +/// +/// The lowercase name of the tag. +/// The number of distinct media items that carry the tag and were consumed. +/// The active duration consumed in the media items that carry the tag, in seconds. +[DebuggerDisplay("Name: {Name}; ConsumedItemCount: {ConsumedItemCount}")] +public sealed record TagConsumptionResponse( + string Name, + int ConsumedItemCount, + double ConsumedDurationInSeconds +); diff --git a/src/Lumina.Contracts/Responses/MediaLibrary/AudioLibrary/MusicLibrary/Albums/AlbumResponse.cs b/src/Lumina.Contracts/Responses/MediaLibrary/AudioLibrary/MusicLibrary/Albums/AlbumResponse.cs index cd72e94a..4cc1f354 100644 --- a/src/Lumina.Contracts/Responses/MediaLibrary/AudioLibrary/MusicLibrary/Albums/AlbumResponse.cs +++ b/src/Lumina.Contracts/Responses/MediaLibrary/AudioLibrary/MusicLibrary/Albums/AlbumResponse.cs @@ -17,6 +17,7 @@ namespace Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albu /// /// The Id of the album. /// The Id of the artist the album belongs to. +/// The name of the artist the album belongs to. /// The Id of the media library this album belongs to. /// The album metadata of the album. /// The physical or digital medium of the album, if applicable. @@ -39,6 +40,7 @@ namespace Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albu public record AlbumResponse( Guid Id, Guid ArtistId, + string ArtistName, Guid LibraryId, MusicAlbumMetadataDto Metadata, MusicMediaFormat? MediaFormat, diff --git a/src/Lumina.Contracts/Responses/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackManifestResponse.cs b/src/Lumina.Contracts/Responses/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackManifestResponse.cs new file mode 100644 index 00000000..54642b46 --- /dev/null +++ b/src/Lumina.Contracts/Responses/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackManifestResponse.cs @@ -0,0 +1,61 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.SharedKernel.Common.Enums.Playback; +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Playback; + +/// +/// Represents a response for the playback manifest of a track, containing the format of its stored audio, the delivery the server decided on for the +/// requesting player, and the path of the track stream, so that a player is told what to fetch and how before it fetches any audio. +/// +/// The Id of the track the manifest describes. +/// The duration of the audio of the track, in seconds, as stored by the probe. A normalized production can differ slightly; its exact produced duration is reported by the segment responses. +/// The container of the audio file of the track, as stored by the probe, for example MP3, FLAC, OGG, AAC, MP4 or WAV. Optional. +/// The codec of the audio of the track, as stored by the probe. Optional. +/// The sample rate of the audio of the track, in Hz. +/// The number of audio channels of the track. +/// The bit depth of the audio of the track. Optional. +/// The ReplayGain track gain of the track, in decibels. Optional. +/// The ReplayGain track peak of the track. Optional. +/// The ReplayGain album gain of the track, in decibels. Optional. +/// The ReplayGain album peak of the track. Optional. +/// Whether the player can play the stored audio as it is, without the server changing its container or its codec. +/// The container of the audio the server delivers, when the delivery is not a direct play. for a direct play. +/// The codec of the audio the server delivers, when the delivery is not a direct play. for a direct play. +/// The shape the delivered audio is addressed and seeked by, when the delivery is not a direct play. for a direct play. +/// The duration of each segment of the delivered audio, in seconds, when the delivery is addressed as time addressed segments. otherwise. +/// Whether the delivered audio can be seeked by the player. +/// The path of the track stream, relative to the API, without a host or a scheme, so that a client never reaches the API directly. +/// +/// The opaque handle of the normalized delivery, which the segment route accepts in place of a capability list, so the delivery the +/// manifest declared cannot be recomputed from inputs that change while the track plays. for a direct play. +/// +/// +/// The path of the segment route of the normalized delivery, relative to the API and without a host or a scheme, with a {deliveryId} and a +/// {segmentIndex} placeholder. for a direct play, whose delivery is addressed by byte range. +/// +[DebuggerDisplay("TrackId: {TrackId} IsDirectPlay: {IsDirectPlay}")] +public sealed record PlaybackManifestResponse( + Guid TrackId, + int DurationInSeconds, + string? SourceContainer, + string? SourceCodec, + int SampleRate, + int Channels, + int? BitDepth, + decimal? ReplayGainTrackGain, + decimal? ReplayGainTrackPeak, + decimal? ReplayGainAlbumGain, + decimal? ReplayGainAlbumPeak, + bool IsDirectPlay, + string? DeliveryContainer, + string? DeliveryCodec, + PlaybackDeliveryShape? DeliveryShape, + int? SegmentDurationSeconds, + bool IsSeekable, + string StreamPath, + string? DeliveryId, + string? SegmentStreamPathTemplate +); diff --git a/src/Lumina.Contracts/Responses/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/ShuffleTrackResponse.cs b/src/Lumina.Contracts/Responses/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/ShuffleTrackResponse.cs new file mode 100644 index 00000000..d8a930ce --- /dev/null +++ b/src/Lumina.Contracts/Responses/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/ShuffleTrackResponse.cs @@ -0,0 +1,27 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; + +/// +/// Represents a response for a track returned by a randomized shuffle query, carrying everything the client needs to queue and play it. +/// +/// The Id of the track. +/// The title of the track. +/// The duration of the track in seconds. +/// The Id of the album the track belongs to. +/// The title of the album the track belongs to. +/// The Id of the artist the album belongs to. +/// The path of the cover of the album, if available. +[DebuggerDisplay("Title: {Title}")] +public record ShuffleTrackResponse( + Guid TrackId, + string Title, + int DurationInSeconds, + Guid AlbumId, + string AlbumTitle, + Guid ArtistId, + string? CoverPath +); diff --git a/src/Lumina.Contracts/Responses/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackResponse.cs b/src/Lumina.Contracts/Responses/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackResponse.cs index b6e64f64..160c0265 100644 --- a/src/Lumina.Contracts/Responses/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackResponse.cs +++ b/src/Lumina.Contracts/Responses/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackResponse.cs @@ -33,6 +33,7 @@ namespace Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Trac /// The list of ISRC (International Standard Recording Code) of the track. /// The list of references to the media contributors that performed on the track, each with the role they played. /// The list of ratings for this track. +/// The container of the audio file of the track, for example MP3, FLAC, OGG, AAC, MP4 or WAV, captured from the file itself. Read only, and not settable through a request. Optional. [DebuggerDisplay("Title: {Metadata.Title}")] public record TrackResponse( Guid Id, @@ -53,5 +54,6 @@ public record TrackResponse( List? Moods, List? Isrcs, List? Contributors, - List? Ratings + List? Ratings, + string? Container = null ); diff --git a/src/Lumina.Contracts/Responses/MediaLibrary/Management/LibraryResponse.cs b/src/Lumina.Contracts/Responses/MediaLibrary/Management/LibraryResponse.cs index 63e17fb0..2486f5c2 100644 --- a/src/Lumina.Contracts/Responses/MediaLibrary/Management/LibraryResponse.cs +++ b/src/Lumina.Contracts/Responses/MediaLibrary/Management/LibraryResponse.cs @@ -21,6 +21,8 @@ namespace Lumina.Contracts.Responses.MediaLibrary.Management; /// Whether the media library should update the metadata of its elements from the web, or not. /// Whether the media library should copy the downloaded metadata into the media library content locations, or not. /// Whether the media library should skip the directories whose contents have not changed since the last scan, during the scan. +/// Whether the consumption progress of the media library items is tracked. +/// The percentage of a media library item that must be consumed for its session to be considered completed, when progress tracking is enabled. /// The ordered parts of the template describing the structure of the media library on disk. /// The date and time when the library was created. /// The optional date and time when the library was updated. @@ -37,6 +39,8 @@ public record LibraryResponse( bool CanDownloadMetadataFromWeb, bool ShouldSaveMetadataInMediaDirectories, bool ShouldSkipUnchangedDirectoriesDuringScan, + bool ShouldTrackConsumptionProgress, + int? CompletionThresholdPercentage, List PathTemplateParts, DateTime CreatedOnUtc, DateTime? UpdatedOnUtc diff --git a/src/Lumina.Contracts/Responses/Playlists/PlaylistDetailsResponse.cs b/src/Lumina.Contracts/Responses/Playlists/PlaylistDetailsResponse.cs new file mode 100644 index 00000000..0f2e9838 --- /dev/null +++ b/src/Lumina.Contracts/Responses/Playlists/PlaylistDetailsResponse.cs @@ -0,0 +1,24 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.SharedKernel.Common.Enums.Playlists; +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Responses.Playlists; + +/// +/// Represents a response for the editable scalars of a playlist after a details update. +/// +/// The Id of the playlist. +/// The name of the playlist. +/// The description of the playlist, if applicable. +/// The kind of media the playlist holds. +/// The date and time when the playlist was last updated, if applicable. +[DebuggerDisplay("Id: {Id}; Name: {Name}")] +public sealed record PlaylistDetailsResponse( + Guid Id, + string Name, + string? Description, + PlaylistType Type, + DateTime? UpdatedOnUtc +); diff --git a/src/Lumina.Contracts/Responses/Playlists/PlaylistEntriesAddedResponse.cs b/src/Lumina.Contracts/Responses/Playlists/PlaylistEntriesAddedResponse.cs new file mode 100644 index 00000000..b0989579 --- /dev/null +++ b/src/Lumina.Contracts/Responses/Playlists/PlaylistEntriesAddedResponse.cs @@ -0,0 +1,19 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Responses.Playlists; + +/// +/// Represents a response for the result of appending several tracks to a playlist, without returning the whole playlist. +/// +/// The Id of the playlist the entries were added to. +/// The number of entries that were appended, including repeated tracks. +/// The date and time when the playlist was last updated, if applicable. +[DebuggerDisplay("PlaylistId: {PlaylistId}; AddedCount: {AddedCount}")] +public sealed record PlaylistEntriesAddedResponse( + Guid PlaylistId, + int AddedCount, + DateTime? UpdatedOnUtc +); diff --git a/src/Lumina.Contracts/Responses/Playlists/PlaylistEntryAddedResponse.cs b/src/Lumina.Contracts/Responses/Playlists/PlaylistEntryAddedResponse.cs new file mode 100644 index 00000000..391029d5 --- /dev/null +++ b/src/Lumina.Contracts/Responses/Playlists/PlaylistEntryAddedResponse.cs @@ -0,0 +1,19 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Responses.Playlists; + +/// +/// Represents a response for the entry that was appended to a playlist, together with its playlist and the new activity time of the playlist. +/// +/// The Id of the playlist the entry was added to. +/// The added entry, with the display details of the media item it references. +/// The date and time when the playlist was last updated, if applicable. +[DebuggerDisplay("PlaylistId: {PlaylistId}; Entry: {Entry.Id}")] +public sealed record PlaylistEntryAddedResponse( + Guid PlaylistId, + PlaylistEntryResponse Entry, + DateTime? UpdatedOnUtc +); diff --git a/src/Lumina.Contracts/Responses/Playlists/PlaylistEntryMovedResponse.cs b/src/Lumina.Contracts/Responses/Playlists/PlaylistEntryMovedResponse.cs new file mode 100644 index 00000000..c3f758c3 --- /dev/null +++ b/src/Lumina.Contracts/Responses/Playlists/PlaylistEntryMovedResponse.cs @@ -0,0 +1,21 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Responses.Playlists; + +/// +/// Represents a response for the result of moving one entry of a playlist to a new position. +/// +/// The Id of the playlist whose entry was moved. +/// The Id of the moved entry. +/// The new zero based position of the entry. +/// The date and time when the playlist was last updated, if applicable. +[DebuggerDisplay("PlaylistId: {PlaylistId}; EntryId: {EntryId}; Position: {Position}")] +public sealed record PlaylistEntryMovedResponse( + Guid PlaylistId, + Guid EntryId, + int Position, + DateTime? UpdatedOnUtc +); diff --git a/src/Lumina.Contracts/Responses/Playlists/PlaylistEntryRemovedResponse.cs b/src/Lumina.Contracts/Responses/Playlists/PlaylistEntryRemovedResponse.cs new file mode 100644 index 00000000..ca07a0d8 --- /dev/null +++ b/src/Lumina.Contracts/Responses/Playlists/PlaylistEntryRemovedResponse.cs @@ -0,0 +1,21 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Responses.Playlists; + +/// +/// Represents a response for the result of removing an entry from a playlist. +/// +/// The Id of the playlist the entry was removed from. +/// The Id of the removed entry. +/// Always zero, because sparse order keys need no remaining entries to be repositioned. +/// The date and time when the playlist was last updated, if applicable. +[DebuggerDisplay("PlaylistId: {PlaylistId}; RemovedEntryId: {RemovedEntryId}; RepositionedCount: {RepositionedCount}")] +public sealed record PlaylistEntryRemovedResponse( + Guid PlaylistId, + Guid RemovedEntryId, + int RepositionedCount, + DateTime? UpdatedOnUtc +); diff --git a/src/Lumina.Contracts/Responses/Playlists/PlaylistEntryResponse.cs b/src/Lumina.Contracts/Responses/Playlists/PlaylistEntryResponse.cs new file mode 100644 index 00000000..46f5add3 --- /dev/null +++ b/src/Lumina.Contracts/Responses/Playlists/PlaylistEntryResponse.cs @@ -0,0 +1,38 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.SharedKernel.Common.Enums.Playlists; +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Responses.Playlists; + +/// +/// Represents a response for an ordered entry of a playlist. +/// +/// The Id of the entry. +/// The Id of the media item referenced by the entry. +/// The kind of media item referenced by the entry. +/// The zero based position of the entry in the playlist. +/// The Id of the media library that contains the media item, or an empty Guid when the item no longer exists. +/// The Id of the collection that contains the media item, or an empty Guid when the item no longer exists. +/// The Id of the creator of the media item, or an empty Guid when the item no longer exists. +/// The title of the media item, or an empty string when the item no longer exists. +/// The title of the collection that contains the media item, or an empty string when the item no longer exists. +/// The name of the creator of the media item, or an empty string when the item no longer exists. +/// The duration of the media item in seconds, or zero when the item no longer exists. +/// The path of the cover art of the collection, if available. +[DebuggerDisplay("MediaItemId: {MediaItemId}; MediaItemType: {MediaItemType}; Position: {Position}")] +public sealed record PlaylistEntryResponse( + Guid Id, + Guid MediaItemId, + PlaylistMediaItemType MediaItemType, + int Position, + Guid LibraryId, + Guid CollectionId, + Guid CreatorId, + string MediaItemTitle, + string CollectionTitle, + string CreatorName, + int DurationInSeconds, + string? CoverPath +); diff --git a/src/Lumina.Contracts/Responses/Playlists/PlaylistResponse.cs b/src/Lumina.Contracts/Responses/Playlists/PlaylistResponse.cs new file mode 100644 index 00000000..91b149d5 --- /dev/null +++ b/src/Lumina.Contracts/Responses/Playlists/PlaylistResponse.cs @@ -0,0 +1,29 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Responses.Common; +using Lumina.Domain.SharedKernel.Common.Enums.Playlists; +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Responses.Playlists; + +/// +/// Represents a response for a playlist together with a page of its ordered entries. +/// +/// The Id of the playlist. +/// The name of the playlist. +/// The description of the playlist, if applicable. +/// The kind of media the playlist holds. +/// The ordered entries of the requested page of the playlist. +/// The date and time when the playlist was created. +/// The date and time when the playlist was last updated, if applicable. +[DebuggerDisplay("Id: {Id}; Name: {Name}; Entries: {Entries.Count}")] +public sealed record PlaylistResponse( + Guid Id, + string Name, + string? Description, + PlaylistType Type, + PaginatedResponse Entries, + DateTime CreatedOnUtc, + DateTime? UpdatedOnUtc +); diff --git a/src/Lumina.Contracts/Responses/Playlists/PlaylistSummaryResponse.cs b/src/Lumina.Contracts/Responses/Playlists/PlaylistSummaryResponse.cs new file mode 100644 index 00000000..d6a089f1 --- /dev/null +++ b/src/Lumina.Contracts/Responses/Playlists/PlaylistSummaryResponse.cs @@ -0,0 +1,28 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.SharedKernel.Common.Enums.Playlists; +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Responses.Playlists; + +/// +/// Represents a response for a playlist in a list, without its entries. +/// +/// The Id of the playlist. +/// The name of the playlist. +/// The description of the playlist, if applicable. +/// The kind of media the playlist holds. +/// The number of entries of the playlist. +/// The date and time when the playlist was created. +/// The date and time when the playlist was last updated, if applicable. +[DebuggerDisplay("Id: {Id}; Name: {Name}; EntryCount: {EntryCount}")] +public sealed record PlaylistSummaryResponse( + Guid Id, + string Name, + string? Description, + PlaylistType Type, + int EntryCount, + DateTime CreatedOnUtc, + DateTime? UpdatedOnUtc +); diff --git a/src/Lumina.Contracts/Responses/UsersManagement/Settings/PlaybackStateResponse.cs b/src/Lumina.Contracts/Responses/UsersManagement/Settings/PlaybackStateResponse.cs new file mode 100644 index 00000000..2884c7a7 --- /dev/null +++ b/src/Lumina.Contracts/Responses/UsersManagement/Settings/PlaybackStateResponse.cs @@ -0,0 +1,16 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Responses.UsersManagement.Settings; + +/// +/// Represents the playback state of a user, as last reported by the player. The player writes these values automatically, and they are not part of the settings the user edits. +/// +/// The last volume the player reported, as a value between 0 and 1. +/// The last mute state the player reported. +[DebuggerDisplay("Volume: {Volume}; IsMuted: {IsMuted}")] +public sealed record PlaybackStateResponse( + double Volume, + bool IsMuted +); diff --git a/src/Lumina.Contracts/Responses/UsersManagement/Settings/UserSettingsResponse.cs b/src/Lumina.Contracts/Responses/UsersManagement/Settings/UserSettingsResponse.cs index 11bdbf60..93c5da77 100644 --- a/src/Lumina.Contracts/Responses/UsersManagement/Settings/UserSettingsResponse.cs +++ b/src/Lumina.Contracts/Responses/UsersManagement/Settings/UserSettingsResponse.cs @@ -1,4 +1,5 @@ #region ========================================================================= USING ===================================================================================== +using Lumina.Domain.SharedKernel.Common.Enums.Playback; using System; using System.Diagnostics; #endregion @@ -17,6 +18,20 @@ namespace Lumina.Contracts.Responses.UsersManagement.Settings; /// Whether the artwork of the media library items is aggregated from multiple providers, when it is missing, or not. /// Whether PDF books are rendered as page images for the user, or not. /// Whether the styles of the book content are preserved when it is rendered for the user, or not. +/// Whether the player keeps downloading a track while playback is paused, or not. +/// Whether the player continues playback at the end of an album or artist, or not. +/// Whether the player transitions between consecutive tracks without a gap, or not. +/// The way ReplayGain normalization is applied to the tracks the user plays. +/// The quality cap applied to the audio the server normalizes for the user. +/// The direction in which each channel of the VU meter of the audio player grows. +/// The number of segments each channel of the VU meter is divided into. +/// The gap, in pixels, between the segments and the channels of the VU meter. +/// The level, between 0 and 1, above which a segment of the VU meter is drawn with its medium state. +/// The level, between 0 and 1, above which a segment of the VU meter is drawn with its high state. +/// Whether the VU meter holds the peak level of each channel after it falls, or not. +/// The time, in milliseconds, a peak of the VU meter is held before it starts falling. +/// The number of level units the display of the VU meter falls per second when the input level drops. +/// The number of level units the peak of the VU meter falls per second after its hold time elapsed. [DebuggerDisplay("UserId: {UserId}")] public sealed record UserSettingsResponse( Guid UserId, @@ -27,5 +42,19 @@ public sealed record UserSettingsResponse( bool ShouldAggregateMetadataWhenMissing, bool ShouldAggregateArtworkWhenMissing, bool ShouldRenderPdfAsImages, - bool ShouldPreserveBookStyles + bool ShouldPreserveBookStyles, + bool ShouldKeepDownloadingWhilePaused, + bool ShouldAutoplay, + bool IsGaplessPlaybackEnabled, + ReplayGainMode ReplayGainMode, + PlaybackStreamingQuality StreamingQuality, + VuMeterOrientation VuMeterOrientation, + int VuMeterSegmentCount, + int VuMeterSegmentGap, + double VuMeterMediumThreshold, + double VuMeterHighThreshold, + bool VuMeterShowPeak, + int VuMeterPeakHoldDurationInMilliseconds, + double VuMeterReleasePerSecond, + double VuMeterPeakReleasePerSecond ); diff --git a/src/Lumina.DataAccess/Common/Configuration/FavoriteConfiguration.cs b/src/Lumina.DataAccess/Common/Configuration/FavoriteConfiguration.cs new file mode 100644 index 00000000..6e3c4449 --- /dev/null +++ b/src/Lumina.DataAccess/Common/Configuration/FavoriteConfiguration.cs @@ -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; + +/// +/// Configures the entity mapping for the entity. +/// +public class FavoriteConfiguration : IEntityTypeConfiguration +{ + /// + /// Configures the entity. + /// + /// The builder to be used to configure the entity. + public void Configure(EntityTypeBuilder 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() + .WithMany() + .HasForeignKey(favorite => favorite.UserId) + .IsRequired() + .OnDelete(DeleteBehavior.Cascade); + + builder.Property(favorite => favorite.UserId) + .IsRequired() + .HasColumnOrder(1); + + builder.Property(favorite => favorite.MediaKind) + .IsRequired() + .HasConversion() + .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 }); + } +} diff --git a/src/Lumina.DataAccess/Common/Configuration/LibraryConfiguration.cs b/src/Lumina.DataAccess/Common/Configuration/LibraryConfiguration.cs index ae9fcc88..65e5ee8a 100644 --- a/src/Lumina.DataAccess/Common/Configuration/LibraryConfiguration.cs +++ b/src/Lumina.DataAccess/Common/Configuration/LibraryConfiguration.cs @@ -71,6 +71,14 @@ public class LibraryConfiguration : IEntityTypeConfiguration .HasDefaultValue(null) .HasColumnOrder(11); + builder.Property(library => library.ShouldTrackConsumptionProgress) + .HasDefaultValue(false) + .HasColumnOrder(16); + + builder.Property(library => library.CompletionThresholdPercentage) + .HasDefaultValue(null) + .HasColumnOrder(17); + // one user with many libraries builder.HasOne(library => library.User) .WithMany(user => user.Libraries) diff --git a/src/Lumina.DataAccess/Common/Configuration/MediaConsumptionRecordConfiguration.cs b/src/Lumina.DataAccess/Common/Configuration/MediaConsumptionRecordConfiguration.cs new file mode 100644 index 00000000..0282a73f --- /dev/null +++ b/src/Lumina.DataAccess/Common/Configuration/MediaConsumptionRecordConfiguration.cs @@ -0,0 +1,127 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaConsumption; +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata.Builders; +#endregion + +namespace Lumina.DataAccess.Common.Configuration; + +/// +/// Configures the entity mapping for the entity. +/// +public class MediaConsumptionRecordConfiguration : IEntityTypeConfiguration +{ + /// + /// Configures the entity. + /// + /// The builder to be used to configure the entity. + public void Configure(EntityTypeBuilder builder) + { + builder.ToTable("MediaConsumptionRecords"); + builder.HasKey(record => record.Id); + builder.Property(record => record.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 consumption record belongs to the user that started it, and it is removed with that user. + builder.HasOne() + .WithMany() + .HasForeignKey(record => record.UserId) + .IsRequired() + .OnDelete(DeleteBehavior.Cascade); + + builder.Property(record => record.UserId) + .IsRequired() + .HasColumnOrder(1); + + builder.Property(record => record.LibraryId) + .IsRequired() + .HasColumnOrder(2); + + builder.Property(record => record.MediaItemId) + .IsRequired() + .HasColumnOrder(3); + + builder.Property(record => record.MediaKind) + .IsRequired() + .HasConversion() + .HasMaxLength(20) + .HasColumnOrder(4); + + builder.Property(record => record.Status) + .IsRequired() + .HasConversion() + .HasMaxLength(20) + .HasColumnOrder(5); + + builder.Property(record => record.StartedOnUtc) + .IsRequired() + .HasColumnOrder(6); + + builder.Property(record => record.LastActivityOnUtc) + .IsRequired() + .HasColumnOrder(7); + + builder.Property(record => record.EndedOnUtc) + .HasColumnOrder(8); + + builder.Property(record => record.ConsumedDurationMilliseconds) + .IsRequired() + .HasColumnOrder(9); + + builder.Property(record => record.LastPositionKind) + .HasConversion() + .HasMaxLength(20) + .IsRequired(false) + .HasColumnOrder(10); + + builder.Property(record => record.LastPositionTimeOffsetMilliseconds) + .HasColumnOrder(11); + + builder.Property(record => record.LastPositionLocation) + .HasMaxLength(4096) + .HasColumnOrder(12); + + builder.Property(record => record.LastProgressFraction) + .IsRequired() + .HasColumnOrder(13); + + builder.Property(record => record.ConsecutivePagesRead) + .IsRequired() + .HasDefaultValue(0) + .HasColumnOrder(14); + + // The version is the optimistic concurrency token: every update increments it, and an update whose loaded version no longer matches + // the stored one affects no row and fails, instead of reverting a session that another report already completed or stopped. + builder.Property(record => record.Version) + .IsRequired() + .IsConcurrencyToken() + .HasColumnOrder(15); + + // Audit. + builder.Property(record => record.CreatedOnUtc) + .IsRequired() + .HasColumnOrder(16); + + builder.Property(record => record.CreatedBy) + .IsRequired() + .HasColumnOrder(17); + + builder.Property(record => record.UpdatedOnUtc) + .HasDefaultValue(null) + .HasColumnOrder(18); + + builder.Property(record => record.UpdatedBy) + .HasDefaultValue(null) + .HasColumnOrder(19); + + // 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 session survives the deletion of the item it references. + // Enables listing the history of a user from the most recent activity, optionally restricted to one media kind and item. + builder.HasIndex(record => new { record.UserId, record.MediaKind, record.MediaItemId, record.LastActivityOnUtc }); + + // Enables the statistics of a user restricted by media kind and date range. + builder.HasIndex(record => new { record.UserId, record.MediaKind, record.StartedOnUtc }); + } +} diff --git a/src/Lumina.DataAccess/Common/Configuration/MediaResumePointConfiguration.cs b/src/Lumina.DataAccess/Common/Configuration/MediaResumePointConfiguration.cs new file mode 100644 index 00000000..1a237733 --- /dev/null +++ b/src/Lumina.DataAccess/Common/Configuration/MediaResumePointConfiguration.cs @@ -0,0 +1,103 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaConsumption; +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata.Builders; +#endregion + +namespace Lumina.DataAccess.Common.Configuration; + +/// +/// Configures the entity mapping for the entity. +/// +public class MediaResumePointConfiguration : IEntityTypeConfiguration +{ + /// + /// Configures the entity. + /// + /// The builder to be used to configure the entity. + public void Configure(EntityTypeBuilder builder) + { + builder.ToTable("MediaResumePoints"); + builder.HasKey(resumePoint => resumePoint.Id); + builder.Property(resumePoint => resumePoint.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 resume point belongs to the user that owns it, and it is removed with that user. + builder.HasOne() + .WithMany() + .HasForeignKey(resumePoint => resumePoint.UserId) + .IsRequired() + .OnDelete(DeleteBehavior.Cascade); + + builder.Property(resumePoint => resumePoint.UserId) + .IsRequired() + .HasColumnOrder(1); + + builder.Property(resumePoint => resumePoint.LibraryId) + .IsRequired() + .HasColumnOrder(2); + + builder.Property(resumePoint => resumePoint.MediaKind) + .IsRequired() + .HasConversion() + .HasMaxLength(20) + .HasColumnOrder(3); + + builder.Property(resumePoint => resumePoint.MediaItemId) + .IsRequired() + .HasColumnOrder(4); + + builder.Property(resumePoint => resumePoint.LastPositionKind) + .IsRequired() + .HasConversion() + .HasMaxLength(20) + .HasColumnOrder(5); + + builder.Property(resumePoint => resumePoint.LastPositionTimeOffsetMilliseconds) + .HasColumnOrder(6); + + builder.Property(resumePoint => resumePoint.LastPositionLocation) + .HasMaxLength(4096) + .HasColumnOrder(7); + + builder.Property(resumePoint => resumePoint.LastProgressFraction) + .IsRequired() + .HasColumnOrder(8); + + builder.Property(resumePoint => resumePoint.LastConsumedOnUtc) + .IsRequired() + .HasColumnOrder(9); + + // The version is the optimistic concurrency token: every update increments it, and an update whose loaded version no longer matches + // the stored one affects no row and fails, instead of reverting a resume point that another report already advanced. + builder.Property(resumePoint => resumePoint.Version) + .IsRequired() + .IsConcurrencyToken() + .HasColumnOrder(10); + + // Audit. + builder.Property(resumePoint => resumePoint.CreatedOnUtc) + .IsRequired() + .HasColumnOrder(11); + + builder.Property(resumePoint => resumePoint.CreatedBy) + .IsRequired() + .HasColumnOrder(12); + + builder.Property(resumePoint => resumePoint.UpdatedOnUtc) + .HasDefaultValue(null) + .HasColumnOrder(13); + + builder.Property(resumePoint => resumePoint.UpdatedBy) + .HasDefaultValue(null) + .HasColumnOrder(14); + + // 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 resume point survives the deletion of the item it references. + // The unique index makes the storage medium the owner of the "one resume point per user and item" invariant. + builder.HasIndex(resumePoint => new { resumePoint.UserId, resumePoint.MediaKind, resumePoint.MediaItemId }) + .IsUnique(); + } +} diff --git a/src/Lumina.DataAccess/Common/Configuration/MusicLibraryScanItemMetadataConfiguration.cs b/src/Lumina.DataAccess/Common/Configuration/MusicLibraryScanItemMetadataConfiguration.cs index 7cc8aa53..a7d60eae 100644 --- a/src/Lumina.DataAccess/Common/Configuration/MusicLibraryScanItemMetadataConfiguration.cs +++ b/src/Lumina.DataAccess/Common/Configuration/MusicLibraryScanItemMetadataConfiguration.cs @@ -98,6 +98,9 @@ public class MusicLibraryScanItemMetadataConfiguration : IEntityTypeConfiguratio .HasColumnOrder(29); builder.PrimitiveCollection(musicMetadata => musicMetadata.Moods) .HasColumnOrder(30); + builder.Property(musicMetadata => musicMetadata.Container) + .HasMaxLength(50) + .HasColumnOrder(31); builder.HasIndex(musicMetadata => new { musicMetadata.LibraryScanId, musicMetadata.Path }) .IsUnique(); // the metadata of the same physical file cannot be staged twice during the same scan diff --git a/src/Lumina.DataAccess/Common/Configuration/PlaylistConfiguration.cs b/src/Lumina.DataAccess/Common/Configuration/PlaylistConfiguration.cs new file mode 100644 index 00000000..b9fb14eb --- /dev/null +++ b/src/Lumina.DataAccess/Common/Configuration/PlaylistConfiguration.cs @@ -0,0 +1,92 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Playlists; +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata.Builders; +#endregion + +namespace Lumina.DataAccess.Common.Configuration; + +/// +/// Configures the entity mapping for the entity. +/// +public class PlaylistConfiguration : IEntityTypeConfiguration +{ + /// + /// Configures the entity. + /// + /// The builder to be used to configure the entity. + public void Configure(EntityTypeBuilder builder) + { + builder.ToTable("Playlists"); + builder.HasKey(playlist => playlist.Id); + builder.Property(playlist => playlist.Id) + .ValueGeneratedNever() // because EF always tries to generate the value for the Id, and because we generate it as part of the aggregate root, we need to tell EF not to generate it + .HasColumnOrder(0); + + // A playlist belongs to the user that created it, and it is removed with that user. + builder.HasOne() + .WithMany() + .HasForeignKey(playlist => playlist.UserId) + .IsRequired() + .OnDelete(DeleteBehavior.Cascade); + + builder.Property(playlist => playlist.UserId) + .IsRequired() + .HasColumnOrder(1); + + builder.Property(playlist => playlist.Name) + .IsRequired() + .HasMaxLength(255) + .HasColumnOrder(2); + + builder.Property(playlist => playlist.Description) + .HasMaxLength(2000) + .HasColumnOrder(3); + + builder.Property(playlist => playlist.Type) + .IsRequired() + .HasConversion() + .HasMaxLength(20) + .HasColumnOrder(4); + + // Audit. + builder.Property(playlist => playlist.CreatedOnUtc) + .IsRequired() + .HasColumnOrder(5); + + builder.Property(playlist => playlist.CreatedBy) + .IsRequired() + .HasColumnOrder(6); + + builder.Property(playlist => playlist.UpdatedOnUtc) + .HasDefaultValue(null) + .HasColumnOrder(7); + + builder.Property(playlist => playlist.UpdatedBy) + .HasDefaultValue(null) + .HasColumnOrder(8); + + // The entry count is maintained by the set-based entry operations, so a window read never counts the entries of the whole playlist. + builder.Property(playlist => playlist.EntryCount) + .IsRequired() + .HasDefaultValue(0) + .HasColumnOrder(10); + + // The concurrency token is incremented by every details edit and by every set-based entry operation, so a concurrent writer is + // detected instead of silently overwriting the ordering work of another request. + builder.Property(playlist => playlist.Version) + .IsConcurrencyToken() + .HasDefaultValue(0L) + .HasColumnOrder(9); + + // The entries of the playlist are owned by the playlist: they are removed with it, and they are never referenced from elsewhere. + builder.HasMany(playlist => playlist.Entries) + .WithOne() + .HasForeignKey(entry => entry.PlaylistId) + .OnDelete(DeleteBehavior.Cascade); + + // Enables the list of the playlists of a user in the order of their most recent activity. + builder.HasIndex(playlist => new { playlist.UserId, playlist.UpdatedOnUtc }); + } +} diff --git a/src/Lumina.DataAccess/Common/Configuration/PlaylistEntryConfiguration.cs b/src/Lumina.DataAccess/Common/Configuration/PlaylistEntryConfiguration.cs new file mode 100644 index 00000000..0b7251e8 --- /dev/null +++ b/src/Lumina.DataAccess/Common/Configuration/PlaylistEntryConfiguration.cs @@ -0,0 +1,70 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Playlists; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata.Builders; +#endregion + +namespace Lumina.DataAccess.Common.Configuration; + +/// +/// Configures the entity mapping for the entity. +/// +public class PlaylistEntryConfiguration : IEntityTypeConfiguration +{ + /// + /// Configures the entity. + /// + /// The builder to be used to configure the entity. + public void Configure(EntityTypeBuilder builder) + { + builder.ToTable("PlaylistEntries"); + builder.HasKey(entry => entry.Id); + builder.Property(entry => entry.Id) + .ValueGeneratedNever() + .HasColumnOrder(0); + + builder.Property(entry => entry.PlaylistId) + .IsRequired() + .HasColumnOrder(1); + + builder.Property(entry => entry.MediaItemId) + .IsRequired() + .HasColumnOrder(2); + + builder.Property(entry => entry.MediaItemType) + .IsRequired() + .HasConversion() + .HasMaxLength(20) + .HasColumnOrder(3); + + builder.Property(entry => entry.Position) + .IsRequired() + .HasColumnOrder(4); + + // Audit. + builder.Property(entry => entry.CreatedOnUtc) + .IsRequired() + .HasColumnOrder(5); + + builder.Property(entry => entry.CreatedBy) + .IsRequired() + .HasColumnOrder(6); + + builder.Property(entry => entry.UpdatedOnUtc) + .HasDefaultValue(null) + .HasColumnOrder(7); + + builder.Property(entry => entry.UpdatedBy) + .HasDefaultValue(null) + .HasColumnOrder(8); + + // The referenced media item is kept by Id only, without a foreign key, so a playlist entry survives the deletion of the item it + // references and its owner can still see and remove the dangling entry. + // The unique index makes the storage medium the owner of the ordering invariant: a duplicate position is rejected even if an operation bypasses the repository. + builder.HasIndex(entry => new { entry.PlaylistId, entry.Position }) + .IsUnique(); + + // Enables finding the playlists that reference a media item, for example when a track is deleted. + builder.HasIndex(entry => entry.MediaItemId); + } +} diff --git a/src/Lumina.DataAccess/Common/Configuration/TrackConfiguration.cs b/src/Lumina.DataAccess/Common/Configuration/TrackConfiguration.cs index 733def1b..1999f0fa 100644 --- a/src/Lumina.DataAccess/Common/Configuration/TrackConfiguration.cs +++ b/src/Lumina.DataAccess/Common/Configuration/TrackConfiguration.cs @@ -152,6 +152,9 @@ public class TrackConfiguration : IEntityTypeConfiguration builder.Property(track => track.ReplayGainAlbumPeak) .HasColumnType("decimal(8,6)") .HasColumnOrder(48); + builder.Property(track => track.Container) + .HasMaxLength(50) + .HasColumnOrder(49); builder.HasOne(track => track.Album) .WithMany(album => album.Tracks) diff --git a/src/Lumina.DataAccess/Common/Configuration/UserSettingsConfiguration.cs b/src/Lumina.DataAccess/Common/Configuration/UserSettingsConfiguration.cs index d6713dc8..864b310d 100644 --- a/src/Lumina.DataAccess/Common/Configuration/UserSettingsConfiguration.cs +++ b/src/Lumina.DataAccess/Common/Configuration/UserSettingsConfiguration.cs @@ -66,6 +66,70 @@ public class UserSettingsConfiguration : IEntityTypeConfiguration settings.ShouldKeepDownloadingWhilePaused) + .IsRequired() + .HasColumnOrder(14); + + builder.Property(settings => settings.ShouldAutoplay) + .IsRequired() + .HasColumnOrder(15); + + builder.Property(settings => settings.IsGaplessPlaybackEnabled) + .IsRequired() + .HasColumnOrder(16); + + builder.Property(settings => settings.ReplayGainMode) + .IsRequired() + .HasColumnOrder(17); + + builder.Property(settings => settings.StreamingQuality) + .IsRequired() + .HasColumnOrder(18); + + builder.Property(settings => settings.VuMeterOrientation) + .IsRequired() + .HasColumnOrder(19); + + builder.Property(settings => settings.VuMeterSegmentCount) + .IsRequired() + .HasColumnOrder(20); + + builder.Property(settings => settings.VuMeterSegmentGap) + .IsRequired() + .HasColumnOrder(21); + + builder.Property(settings => settings.VuMeterMediumThreshold) + .IsRequired() + .HasColumnOrder(22); + + builder.Property(settings => settings.VuMeterHighThreshold) + .IsRequired() + .HasColumnOrder(23); + + builder.Property(settings => settings.VuMeterShowPeak) + .IsRequired() + .HasColumnOrder(24); + + builder.Property(settings => settings.VuMeterPeakHoldDurationInMilliseconds) + .IsRequired() + .HasColumnOrder(25); + + builder.Property(settings => settings.VuMeterReleasePerSecond) + .IsRequired() + .HasColumnOrder(26); + + builder.Property(settings => settings.VuMeterPeakReleasePerSecond) + .IsRequired() + .HasColumnOrder(27); + + builder.Property(settings => settings.Volume) + .IsRequired() + .HasColumnOrder(28); + + builder.Property(settings => settings.IsMuted) + .IsRequired() + .HasColumnOrder(29); + // audit builder.Property(settings => settings.CreatedOnUtc) .IsRequired() diff --git a/src/Lumina.DataAccess/Common/Dapper/SqliteGuidTypeHandler.cs b/src/Lumina.DataAccess/Common/Dapper/SqliteGuidTypeHandler.cs index 63ac7047..097367c8 100644 --- a/src/Lumina.DataAccess/Common/Dapper/SqliteGuidTypeHandler.cs +++ b/src/Lumina.DataAccess/Common/Dapper/SqliteGuidTypeHandler.cs @@ -10,20 +10,21 @@ namespace Lumina.DataAccess.Common.Dapper; /// Maps values to and from the TEXT representation used by the SQLite provider. /// /// -/// The SQLite provider stores columns as TEXT, and Dapper falls back to Convert.ChangeType when materializing such -/// columns into properties. has no string , so that conversion throws -/// an ; this handler performs the conversion explicitly instead. +/// The SQLite provider stores columns as upper case TEXT. Dapper falls back to Convert.ChangeType when materializing +/// such columns into properties. has no string , so that conversion +/// throws an ; this handler performs the conversion explicitly instead, and writes the same upper case +/// representation so raw key comparisons and foreign keys match the rows created by Entity Framework. /// internal sealed class SqliteGuidTypeHandler : SqlMapper.TypeHandler { /// - /// Sets the parameter value to the TEXT representation of the value, keeping writes consistent with reads. + /// Sets the parameter value to the upper case TEXT representation the SQLite provider uses for columns. /// /// The database parameter to set. /// The value to store. public override void SetValue(IDbDataParameter parameter, Guid value) { - parameter.Value = value.ToString(); + parameter.Value = value.ToString().ToUpperInvariant(); } /// diff --git a/src/Lumina.DataAccess/Common/Migrations/20261013195657_AddsAudioContainerToMusicMetadata.Designer.cs b/src/Lumina.DataAccess/Common/Migrations/20261013195657_AddsAudioContainerToMusicMetadata.Designer.cs new file mode 100644 index 00000000..cf1cd3a9 --- /dev/null +++ b/src/Lumina.DataAccess/Common/Migrations/20261013195657_AddsAudioContainerToMusicMetadata.Designer.cs @@ -0,0 +1,3435 @@ +// +using System; +using Lumina.DataAccess.Core.UoW; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace Lumina.DataAccess.Common.Migrations +{ + [DbContext(typeof(LuminaDbContext))] + [Migration("20261013195657_AddsAudioContainerToMusicMetadata")] + partial class AddsAudioContainerToMusicMetadata + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder.HasAnnotation("ProductVersion", "10.0.11"); + + modelBuilder.Entity("AlbumGenres", b => + { + b.Property("AlbumId") + .HasColumnType("TEXT"); + + b.Property("GenreId") + .HasColumnType("TEXT"); + + b.HasKey("AlbumId", "GenreId"); + + b.HasIndex("GenreId"); + + b.ToTable("AlbumGenres", (string)null); + }); + + modelBuilder.Entity("AlbumTags", b => + { + b.Property("AlbumId") + .HasColumnType("TEXT"); + + b.Property("TagId") + .HasColumnType("TEXT"); + + b.HasKey("AlbumId", "TagId"); + + b.HasIndex("TagId"); + + b.ToTable("AlbumTags", (string)null); + }); + + modelBuilder.Entity("ArtistGenres", b => + { + b.Property("ArtistId") + .HasColumnType("TEXT"); + + b.Property("GenreId") + .HasColumnType("TEXT"); + + b.HasKey("ArtistId", "GenreId"); + + b.HasIndex("GenreId"); + + b.ToTable("ArtistGenres", (string)null); + }); + + modelBuilder.Entity("ArtistTags", b => + { + b.Property("ArtistId") + .HasColumnType("TEXT"); + + b.Property("TagId") + .HasColumnType("TEXT"); + + b.HasKey("ArtistId", "TagId"); + + b.HasIndex("TagId"); + + b.ToTable("ArtistTags", (string)null); + }); + + modelBuilder.Entity("BookGenres", b => + { + b.Property("BookId") + .HasColumnType("TEXT"); + + b.Property("GenreId") + .HasColumnType("TEXT"); + + b.HasKey("BookId", "GenreId"); + + b.HasIndex("GenreId"); + + b.ToTable("BookGenres", (string)null); + }); + + modelBuilder.Entity("BookTags", b => + { + b.Property("BookId") + .HasColumnType("TEXT"); + + b.Property("TagId") + .HasColumnType("TEXT"); + + b.HasKey("BookId", "TagId"); + + b.HasIndex("TagId"); + + b.ToTable("BookTags", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.PermissionEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("PermissionName") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.HasKey("Id"); + + b.ToTable("Permissions", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.RoleEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("RoleName") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.HasKey("Id"); + + b.ToTable("Roles", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.RolePermissionEntity", b => + { + b.Property("RoleId") + .HasColumnType("TEXT"); + + b.Property("PermissionId") + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.HasKey("RoleId", "PermissionId"); + + b.HasIndex("PermissionId"); + + b.HasIndex("RoleId", "PermissionId") + .IsUnique(); + + b.ToTable("RolePermissions", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.UserPermissionEntity", b => + { + b.Property("UserId") + .HasColumnType("TEXT"); + + b.Property("PermissionId") + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.HasKey("UserId", "PermissionId"); + + b.HasIndex("PermissionId"); + + b.HasIndex("UserId", "PermissionId") + .IsUnique(); + + b.ToTable("UserPermissions", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.UserRoleEntity", b => + { + b.Property("UserId") + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("RoleId") + .HasColumnType("TEXT"); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.HasKey("UserId"); + + b.HasIndex("RoleId"); + + b.HasIndex("UserId", "RoleId") + .IsUnique(); + + b.ToTable("UserRoles", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Common.GenreEntity", b => + { + b.Property("Name") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b.HasKey("Name"); + + b.ToTable("Genres", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Common.TagEntity", b => + { + b.Property("Name") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b.HasKey("Name"); + + b.ToTable("Tags", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaContributors.MediaContributorEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Biography") + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("DateOfBirth") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("DateOfDeath") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("DisplayName") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1) + .UseCollation("NOCASE"); + + b.Property("LegalName") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.HasKey("Id"); + + b.HasIndex("DisplayName") + .IsUnique(); + + b.ToTable("MediaContributors", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumContributorEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("AlbumId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("MediaContributorId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("Role") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.HasKey("Id"); + + b.HasIndex("MediaContributorId"); + + b.HasIndex("AlbumId", "MediaContributorId", "Role") + .IsUnique(); + + b.ToTable("AlbumContributors", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("ASIN") + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(28); + + b.Property("ArtistId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("Barcode") + .HasMaxLength(13) + .HasColumnType("TEXT") + .HasColumnOrder(25); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(33); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(32); + + b.Property("Description") + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("Disambiguation") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("Label") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(27); + + b.Property("LanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("LanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("LanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(15); + + b.Property("LastMetadataUpdateUtc") + .HasColumnType("TEXT") + .HasColumnOrder(37); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("MediaFormat") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(23); + + b.Property("MetadataProvider") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(38); + + b.Property("MetadataStatus") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasDefaultValue("Pending") + .HasColumnOrder(36); + + b.Property("MusicBrainzReleaseArtistId") + .HasColumnType("TEXT") + .HasColumnOrder(31); + + b.Property("MusicBrainzReleaseGroupId") + .HasColumnType("TEXT") + .HasColumnOrder(30); + + b.Property("MusicBrainzReleaseId") + .HasColumnType("TEXT") + .HasColumnOrder(29); + + b.Property("OriginalLanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(16); + + b.Property("OriginalLanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(17); + + b.Property("OriginalLanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(18); + + b.Property("OriginalReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("OriginalReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(8); + + b.Property("OriginalTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("Packaging") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(24); + + b.Property("ReReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("ReReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(10); + + b.Property("ReleaseCountry") + .HasMaxLength(2) + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("ReleaseStatus") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(20); + + b.Property("ReleaseTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(26); + + b.Property("ReleaseVersion") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("Script") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(19); + + b.Property("Title") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("TotalDiscs") + .HasColumnType("INTEGER") + .HasColumnOrder(21); + + b.Property("TotalTracks") + .HasColumnType("INTEGER") + .HasColumnOrder(22); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(35); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(34); + + b.HasKey("Id"); + + b.HasIndex("ArtistId", "Title"); + + b.HasIndex("LibraryId", "Title"); + + b.ToTable("Albums", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistContributorEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("ArtistId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("MediaContributorId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("Role") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.HasKey("Id"); + + b.HasIndex("MediaContributorId"); + + b.HasIndex("ArtistId", "MediaContributorId", "Role") + .IsUnique(); + + b.ToTable("ArtistContributors", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Country") + .HasMaxLength(2) + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("Disambiguation") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("Gender") + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("IsEnded") + .HasColumnType("INTEGER") + .HasColumnOrder(10); + + b.Property("LastMetadataUpdateUtc") + .HasColumnType("TEXT") + .HasColumnOrder(18); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("LifeSpanBegin") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("LifeSpanEnd") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("MetadataProvider") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(19); + + b.Property("MetadataStatus") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasDefaultValue("Pending") + .HasColumnOrder(17); + + b.Property("MusicBrainzArtistId") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("Name") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("SortName") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("Type") + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(16); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(15); + + b.Property("Website") + .HasMaxLength(2048) + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.HasKey("Id"); + + b.HasIndex("LibraryId", "Name") + .IsUnique(); + + b.ToTable("Artists", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.MusicArtworkEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("ArtworkType") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("ContentHash") + .HasColumnType("INTEGER") + .HasColumnOrder(6); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("FileName") + .HasMaxLength(2048) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("LastUpdateUtc") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("Ordinal") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("OwnerId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("OwnerType") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("Provider") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("Status") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.HasKey("Id"); + + b.HasIndex("Status"); + + b.HasIndex("OwnerType", "OwnerId", "ArtworkType", "Ordinal") + .IsUnique(); + + b.ToTable("MusicArtwork", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.MusicLibraryScanItemMetadataEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("AcoustId") + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnOrder(25); + + b.Property("ArtistName") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("AudioCodec") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(15); + + b.Property("BitDepth") + .HasColumnType("INTEGER") + .HasColumnOrder(14); + + b.Property("Bitrate") + .HasColumnType("INTEGER") + .HasColumnOrder(16); + + b.Property("Channels") + .HasColumnType("INTEGER") + .HasColumnOrder(13); + + b.Property("Container") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(31); + + b.Property("DiscNumber") + .HasColumnType("INTEGER") + .HasColumnOrder(10); + + b.Property("DurationInSeconds") + .HasColumnType("INTEGER") + .HasColumnOrder(11); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("LibraryScanId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.PrimitiveCollection("Moods") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(30); + + b.Property("MusicBrainzArtistId") + .HasColumnType("TEXT") + .HasColumnOrder(17); + + b.Property("MusicBrainzRecordingId") + .HasColumnType("TEXT") + .HasColumnOrder(21); + + b.Property("MusicBrainzReleaseArtistId") + .HasColumnType("TEXT") + .HasColumnOrder(18); + + b.Property("MusicBrainzReleaseGroupId") + .HasColumnType("TEXT") + .HasColumnOrder(19); + + b.Property("MusicBrainzReleaseId") + .HasColumnType("TEXT") + .HasColumnOrder(20); + + b.Property("MusicBrainzTrackId") + .HasColumnType("TEXT") + .HasColumnOrder(22); + + b.Property("MusicBrainzWorkId") + .HasColumnType("TEXT") + .HasColumnOrder(23); + + b.Property("Path") + .IsRequired() + .HasMaxLength(2048) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("ReleaseName") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("ReleaseType") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("ReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(6); + + b.Property("ReplayGainAlbumGain") + .HasColumnType("decimal(8,2)") + .HasColumnOrder(28); + + b.Property("ReplayGainAlbumPeak") + .HasColumnType("decimal(8,6)") + .HasColumnOrder(29); + + b.Property("ReplayGainTrackGain") + .HasColumnType("decimal(8,2)") + .HasColumnOrder(26); + + b.Property("ReplayGainTrackPeak") + .HasColumnType("decimal(8,6)") + .HasColumnOrder(27); + + b.Property("SampleRate") + .HasColumnType("INTEGER") + .HasColumnOrder(12); + + b.Property("TrackNumber") + .HasColumnType("INTEGER") + .HasColumnOrder(9); + + b.Property("TrackTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("WorkTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(24); + + b.HasKey("Id"); + + b.HasIndex("LibraryScanId", "Path") + .IsUnique(); + + b.ToTable("MusicLibraryScanItemMetadata", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackContributorEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("MediaContributorId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("Role") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("TrackId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.HasKey("Id"); + + b.HasIndex("MediaContributorId"); + + b.HasIndex("TrackId", "MediaContributorId", "Role") + .IsUnique(); + + b.ToTable("TrackContributors", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("AcoustId") + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnOrder(44); + + b.Property("AlbumId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("AudioCodec") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(24); + + b.Property("BitDepth") + .HasColumnType("INTEGER") + .HasColumnOrder(23); + + b.Property("Bitrate") + .HasColumnType("INTEGER") + .HasColumnOrder(25); + + b.Property("Bpm") + .HasColumnType("INTEGER") + .HasColumnOrder(30); + + b.Property("Channels") + .HasColumnType("INTEGER") + .HasColumnOrder(22); + + b.Property("Container") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(49); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(38); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(37); + + b.Property("Description") + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("Disambiguation") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("DiscNumber") + .HasColumnType("INTEGER") + .HasColumnOrder(27); + + b.Property("DurationInSeconds") + .HasColumnType("INTEGER") + .HasColumnOrder(20); + + b.Property("IsVideo") + .HasColumnType("INTEGER") + .HasColumnOrder(31); + + b.Property("Key") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(29); + + b.Property("LanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("LanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(15); + + b.Property("LanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(16); + + b.Property("LastMetadataUpdateUtc") + .HasColumnType("TEXT") + .HasColumnOrder(42); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("MetadataProvider") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(43); + + b.Property("MetadataStatus") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasDefaultValue("Pending") + .HasColumnOrder(41); + + b.Property("MusicBrainzRecordingId") + .HasColumnType("TEXT") + .HasColumnOrder(34); + + b.Property("MusicBrainzTrackId") + .HasColumnType("TEXT") + .HasColumnOrder(35); + + b.Property("MusicBrainzWorkId") + .HasColumnType("TEXT") + .HasColumnOrder(36); + + b.Property("OriginalLanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(17); + + b.Property("OriginalLanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(18); + + b.Property("OriginalLanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(19); + + b.Property("OriginalReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("OriginalReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(9); + + b.Property("OriginalTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("Path") + .IsRequired() + .HasMaxLength(2048) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("ReReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("ReReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(11); + + b.Property("ReleaseCountry") + .HasMaxLength(2) + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("ReleaseVersion") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("ReplayGainAlbumGain") + .HasColumnType("decimal(8,2)") + .HasColumnOrder(47); + + b.Property("ReplayGainAlbumPeak") + .HasColumnType("decimal(8,6)") + .HasColumnOrder(48); + + b.Property("ReplayGainTrackGain") + .HasColumnType("decimal(8,2)") + .HasColumnOrder(45); + + b.Property("ReplayGainTrackPeak") + .HasColumnType("decimal(8,6)") + .HasColumnOrder(46); + + b.Property("SampleRate") + .HasColumnType("INTEGER") + .HasColumnOrder(21); + + b.Property("Script") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(28); + + b.Property("Title") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("TrackNumber") + .HasColumnType("INTEGER") + .HasColumnOrder(26); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(40); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(39); + + b.Property("WorkTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(32); + + b.Property("WorkType") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(33); + + b.HasKey("Id"); + + b.HasIndex("AlbumId", "TrackNumber"); + + b.HasIndex("LibraryId", "Path") + .IsUnique(); + + b.ToTable("Tracks", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.DirectoryScanFingerprintEntity", b => + { + b.Property("LibraryId") + .HasColumnType("TEXT"); + + b.Property("Path") + .HasMaxLength(1024) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("LastWriteTimeUtc") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.HasKey("LibraryId", "Path"); + + b.HasIndex("LibraryId"); + + b.ToTable("DirectoryScanFingerprints", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("ArtworkProvidersConfigurationFingerprint") + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("CanDownloadMetadataFromWeb") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(true) + .HasColumnOrder(6); + + b.Property("CoverImage") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("IsEnabled") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(true) + .HasColumnOrder(4); + + b.Property("IsLocked") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("LibraryType") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("MetadataProvidersConfigurationFingerprint") + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("PathTemplateFingerprint") + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("ShouldSaveMetadataInMediaDirectories") + .HasColumnType("INTEGER") + .HasColumnOrder(7); + + b.Property("ShouldSkipUnchangedDirectoriesDuringScan") + .HasColumnType("INTEGER") + .HasColumnOrder(8); + + b.Property("Title") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(15); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("UserId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("Libraries", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("LibraryId") + .HasColumnType("TEXT"); + + b.Property("Status") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UserId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.HasIndex("LibraryId", "Status", "CreatedOnUtc") + .IsDescending(true, false, true); + + b.ToTable("LibraryScans", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanResultEntity", b => + { + b.Property("LibraryScanId") + .HasColumnType("TEXT"); + + b.Property("Path") + .HasMaxLength(1024) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("ContentHash") + .HasMaxLength(24) + .HasColumnType("INTEGER") + .HasColumnOrder(2); + + b.Property("FileSize") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Status") + .IsRequired() + .HasMaxLength(10) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("Ticks") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.HasKey("LibraryScanId", "Path"); + + b.HasIndex("Path"); + + b.HasIndex("ContentHash", "FileSize", "Path"); + + b.ToTable("LibraryScanResults", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanSnapshotEntity", b => + { + b.Property("LibraryId") + .HasColumnType("TEXT"); + + b.Property("Path") + .HasMaxLength(1024) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("ContentHash") + .HasColumnType("INTEGER") + .HasColumnOrder(2); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("FileSize") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Ticks") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.HasKey("LibraryId", "Path"); + + b.HasIndex("LibraryId"); + + b.ToTable("LibraryScanSnapshots", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanStagingResultsEntity", b => + { + b.Property("LibraryScanId") + .HasColumnType("TEXT"); + + b.Property("Path") + .HasMaxLength(1024) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("ContentHash") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("IsNew") + .HasColumnType("INTEGER") + .HasColumnOrder(7); + + b.Property("NeedsRehash") + .HasColumnType("INTEGER") + .HasColumnOrder(6); + + b.Property("PreviousContentHash") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("Size") + .HasColumnType("INTEGER") + .HasColumnOrder(2); + + b.Property("Ticks") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.HasKey("LibraryScanId", "Path"); + + b.HasIndex("LibraryScanId", "NeedsRehash"); + + b.ToTable("LibraryScanStagingResults", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookArtworkEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("ArtworkType") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("BookId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("ContentHash") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("FileName") + .HasMaxLength(2048) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("LastUpdateUtc") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("Ordinal") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("Provider") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("Status") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.HasKey("Id"); + + b.HasIndex("Status"); + + b.HasIndex("BookId", "ArtworkType", "Ordinal") + .IsUnique(); + + b.ToTable("BookArtwork", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookContributorEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("BookId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("MediaContributorId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("Role") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.HasKey("Id"); + + b.HasIndex("MediaContributorId"); + + b.HasIndex("BookId", "MediaContributorId", "Role") + .IsUnique(); + + b.ToTable("BookContributors", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("ASIN") + .HasMaxLength(10) + .HasColumnType("TEXT") + .HasColumnOrder(21); + + b.Property("AppleBooksId") + .HasColumnType("TEXT") + .HasColumnOrder(29); + + b.Property("BarnesAndNobleId") + .HasMaxLength(10) + .HasColumnType("TEXT") + .HasColumnOrder(28); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(33); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(32); + + b.Property("Description") + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("Edition") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(19); + + b.Property("Format") + .HasColumnType("TEXT") + .HasColumnOrder(18); + + b.Property("GoodreadsId") + .HasColumnType("TEXT") + .HasColumnOrder(22); + + b.Property("GoogleBooksId") + .HasMaxLength(12) + .HasColumnType("TEXT") + .HasColumnOrder(27); + + b.Property("LCCN") + .HasColumnType("TEXT") + .HasColumnOrder(23); + + b.Property("LanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("LanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("LanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("LastMetadataUpdateUtc") + .HasColumnType("TEXT") + .HasColumnOrder(39); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(36); + + b.Property("LibraryThingId") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(26); + + b.Property("MetadataProvider") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(40); + + b.Property("MetadataStatus") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(38); + + b.Property("OCLCNumber") + .HasColumnType("TEXT") + .HasColumnOrder(24); + + b.Property("OpenLibraryId") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(25); + + b.Property("OriginalLanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("OriginalLanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("OriginalLanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(15); + + b.Property("OriginalReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("OriginalReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("OriginalTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("PageCount") + .HasColumnType("INTEGER") + .HasColumnOrder(17); + + b.Property("Path") + .IsRequired() + .HasMaxLength(2048) + .HasColumnType("TEXT") + .HasColumnOrder(37); + + b.Property("Publisher") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(16); + + b.Property("ReReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("ReReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(7); + + b.Property("ReleaseCountry") + .HasMaxLength(2) + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("ReleaseVersion") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("Title") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(35); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(34); + + b.Property("VolumeNumber") + .HasColumnType("REAL") + .HasColumnOrder(20); + + b.HasKey("Id"); + + b.HasIndex("LibraryId", "MetadataStatus"); + + b.HasIndex("LibraryId", "Path") + .IsUnique(); + + b.ToTable("Books", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Plugins.LibraryArtworkProviderConfigurationEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("IsEnabled") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("PluginId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("Rank") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.HasKey("Id"); + + b.HasIndex("LibraryId", "PluginId"); + + b.ToTable("LibraryArtworkProviderConfigurations", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Plugins.LibraryBookReaderConfigurationEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("IsEnabled") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("PluginId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.HasKey("Id"); + + b.HasIndex("LibraryId", "PluginId") + .IsUnique(); + + b.ToTable("LibraryBookReaderConfigurations", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Plugins.LibraryMetadataProviderConfigurationEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("IsEnabled") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("PluginId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("Rank") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.HasKey("Id"); + + b.HasIndex("LibraryId", "PluginId"); + + b.ToTable("LibraryMetadataProviderConfigurations", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Plugins.PluginEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Author") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("Description") + .IsRequired() + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("LoadError") + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("LoadStatus") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("Name") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("SettingsJson") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("Version") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.HasKey("Id"); + + b.ToTable("Plugins", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Scheduling.ScheduledJobEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("Hour") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("IntervalMinutes") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("LastCompletedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("LastStartedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("Minute") + .HasColumnType("INTEGER") + .HasColumnOrder(6); + + b.Property("Name") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("OwnerUserId") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("ScheduleType") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("Status") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("TaskType") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.HasKey("Id"); + + b.HasIndex("Status"); + + b.ToTable("ScheduledJobs", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Scheduling.ScheduledJobExecutionEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CompletedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("IsCycleRun") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("ScheduledJobId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("StartedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("TaskType") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("WasCycleActive") + .HasColumnType("INTEGER") + .HasColumnOrder(6); + + b.HasKey("Id"); + + b.HasIndex("ScheduledJobId"); + + b.HasIndex("StartedOnUtc", "ScheduledJobId"); + + b.ToTable("ScheduledJobExecutions", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Scheduling.SchedulerDisplayPreferencesEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("DisplayTimeSpan") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("DisplayTimeUnit") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("JobTypeFilter") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UserId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.HasKey("Id"); + + b.HasIndex("UserId") + .IsUnique(); + + b.ToTable("SchedulerDisplayPreferences", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Themes.ThemeEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Author") + .IsRequired() + .HasMaxLength(80) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("Description") + .IsRequired() + .HasMaxLength(300) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("InstallSource") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("InstalledAtUtc") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("IsCurrent") + .HasColumnType("INTEGER") + .HasColumnOrder(8); + + b.Property("IsDeleted") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(false) + .HasColumnOrder(9); + + b.Property("Name") + .IsRequired() + .HasMaxLength(80) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("PreviewPath") + .HasMaxLength(240) + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("ThemeId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("Version") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.HasKey("Id"); + + b.HasIndex("IsCurrent") + .IsUnique() + .HasFilter("IsCurrent = 1"); + + b.HasIndex("ThemeId") + .IsUnique(); + + b.ToTable("Themes", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("Password") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("TempPassword") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("TempPasswordCreated") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("TotpSecret") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("Username") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.HasKey("Id"); + + b.HasIndex("Username") + .IsUnique(); + + b.ToTable("Users", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserSettingsEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("IsPaginationEnabled") + .HasColumnType("INTEGER") + .HasColumnOrder(2); + + b.Property("IsThemeCachingEnabled") + .HasColumnType("INTEGER") + .HasColumnOrder(9); + + b.Property("ItemsPerPage") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("ShouldAggregateArtworkWhenMissing") + .HasColumnType("INTEGER") + .HasColumnOrder(13); + + b.Property("ShouldAggregateMetadataWhenMissing") + .HasColumnType("INTEGER") + .HasColumnOrder(10); + + b.Property("ShouldIgnoreThePrefixForAlphaPicker") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("ShouldPreserveBookStyles") + .HasColumnType("INTEGER") + .HasColumnOrder(12); + + b.Property("ShouldRenderPdfAsImages") + .HasColumnType("INTEGER") + .HasColumnOrder(11); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UserId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.HasKey("Id"); + + b.HasIndex("UserId") + .IsUnique(); + + b.ToTable("UserSettings", (string)null); + }); + + modelBuilder.Entity("TrackGenres", b => + { + b.Property("TrackId") + .HasColumnType("TEXT"); + + b.Property("GenreId") + .HasColumnType("TEXT"); + + b.HasKey("TrackId", "GenreId"); + + b.HasIndex("GenreId"); + + b.ToTable("TrackGenres", (string)null); + }); + + modelBuilder.Entity("TrackTags", b => + { + b.Property("TrackId") + .HasColumnType("TEXT"); + + b.Property("TagId") + .HasColumnType("TEXT"); + + b.HasKey("TrackId", "TagId"); + + b.HasIndex("TagId"); + + b.ToTable("TrackTags", (string)null); + }); + + modelBuilder.Entity("AlbumGenres", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumEntity", null) + .WithMany() + .HasForeignKey("AlbumId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.GenreEntity", null) + .WithMany() + .HasForeignKey("GenreId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("AlbumTags", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumEntity", null) + .WithMany() + .HasForeignKey("AlbumId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.TagEntity", null) + .WithMany() + .HasForeignKey("TagId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("ArtistGenres", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistEntity", null) + .WithMany() + .HasForeignKey("ArtistId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.GenreEntity", null) + .WithMany() + .HasForeignKey("GenreId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("ArtistTags", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistEntity", null) + .WithMany() + .HasForeignKey("ArtistId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.TagEntity", null) + .WithMany() + .HasForeignKey("TagId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BookGenres", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", null) + .WithMany() + .HasForeignKey("BookId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.GenreEntity", null) + .WithMany() + .HasForeignKey("GenreId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BookTags", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", null) + .WithMany() + .HasForeignKey("BookId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.TagEntity", null) + .WithMany() + .HasForeignKey("TagId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.RolePermissionEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Authorization.PermissionEntity", "Permission") + .WithMany("RolePermissions") + .HasForeignKey("PermissionId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Authorization.RoleEntity", "Role") + .WithMany("RolePermissions") + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Permission"); + + b.Navigation("Role"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.UserPermissionEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Authorization.PermissionEntity", "Permission") + .WithMany("UserPermissions") + .HasForeignKey("PermissionId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", "User") + .WithMany("UserPermissions") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Permission"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.UserRoleEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Authorization.RoleEntity", "Role") + .WithMany("UserRoles") + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", "User") + .WithOne("UserRole") + .HasForeignKey("Lumina.Application.Common.DataAccess.Entities.Authorization.UserRoleEntity", "UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Role"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumContributorEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumEntity", null) + .WithMany("Contributors") + .HasForeignKey("AlbumId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistEntity", "Artist") + .WithMany("Albums") + .HasForeignKey("ArtistId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumCatalogNumberEntity", "CatalogNumbers", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("AlbumId") + .HasColumnType("TEXT"); + + b1.Property("CatalogNumber") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("AlbumId"); + + b1.ToTable("AlbumCatalogNumbers", (string)null); + + b1.WithOwner() + .HasForeignKey("AlbumId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AudioRatingEntity", "Ratings", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("AlbumId") + .HasColumnType("TEXT"); + + b1.Property("MaxValue") + .HasColumnType("decimal(3,2)"); + + b1.Property("Source") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.Property("Value") + .HasColumnType("decimal(3,2)"); + + b1.Property("VoteCount") + .HasColumnType("INTEGER"); + + b1.HasKey("Id"); + + b1.HasIndex("AlbumId"); + + b1.ToTable("AlbumRatings", (string)null); + + b1.WithOwner() + .HasForeignKey("AlbumId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumReleaseTypeEntity", "ReleaseTypes", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("AlbumId") + .HasColumnType("TEXT"); + + b1.Property("ReleaseType") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("AlbumId"); + + b1.ToTable("AlbumReleaseTypes", (string)null); + + b1.WithOwner() + .HasForeignKey("AlbumId"); + }); + + b.Navigation("Artist"); + + b.Navigation("CatalogNumbers"); + + b.Navigation("Ratings"); + + b.Navigation("ReleaseTypes"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistContributorEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistEntity", null) + .WithMany("Contributors") + .HasForeignKey("ArtistId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistEntity", b => + { + b.OwnsOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.MusicAreaEntity", "Area", b1 => + { + b1.Property("ArtistEntityId"); + + b1.Property("Disambiguation"); + + b1.Property("Iso3166Code"); + + b1.Property("MusicBrainzAreaId"); + + b1.Property("Name") + .IsRequired(); + + b1.Property("SortName"); + + b1.Property("Type"); + + b1.HasKey("ArtistEntityId"); + + b1.ToTable("Artists"); + + b1 + .ToJson("Area") + .HasColumnType("TEXT"); + + b1.WithOwner() + .HasForeignKey("ArtistEntityId"); + }); + + b.OwnsOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.MusicAreaEntity", "BeginArea", b1 => + { + b1.Property("ArtistEntityId"); + + b1.Property("Disambiguation"); + + b1.Property("Iso3166Code"); + + b1.Property("MusicBrainzAreaId"); + + b1.Property("Name") + .IsRequired(); + + b1.Property("SortName"); + + b1.Property("Type"); + + b1.HasKey("ArtistEntityId"); + + b1.ToTable("Artists"); + + b1 + .ToJson("BeginArea") + .HasColumnType("TEXT"); + + b1.WithOwner() + .HasForeignKey("ArtistEntityId"); + }); + + b.OwnsOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.MusicAreaEntity", "EndArea", b1 => + { + b1.Property("ArtistEntityId"); + + b1.Property("Disambiguation"); + + b1.Property("Iso3166Code"); + + b1.Property("MusicBrainzAreaId"); + + b1.Property("Name") + .IsRequired(); + + b1.Property("SortName"); + + b1.Property("Type"); + + b1.HasKey("ArtistEntityId"); + + b1.ToTable("Artists"); + + b1 + .ToJson("EndArea") + .HasColumnType("TEXT"); + + b1.WithOwner() + .HasForeignKey("ArtistEntityId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistAliasEntity", "Aliases", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("ArtistId") + .HasColumnType("TEXT"); + + b1.Property("BeginDate") + .HasColumnType("TEXT"); + + b1.Property("EndDate") + .HasColumnType("TEXT"); + + b1.Property("IsEnded") + .HasColumnType("INTEGER"); + + b1.Property("IsPrimary") + .HasColumnType("INTEGER"); + + b1.Property("Locale") + .HasMaxLength(20) + .HasColumnType("TEXT"); + + b1.Property("Name") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT"); + + b1.Property("SortName") + .HasMaxLength(255) + .HasColumnType("TEXT"); + + b1.Property("Type") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("ArtistId"); + + b1.ToTable("ArtistAliases", (string)null); + + b1.WithOwner() + .HasForeignKey("ArtistId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AudioRatingEntity", "Ratings", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("ArtistId") + .HasColumnType("TEXT"); + + b1.Property("MaxValue") + .HasColumnType("decimal(3,2)"); + + b1.Property("Source") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.Property("Value") + .HasColumnType("decimal(3,2)"); + + b1.Property("VoteCount") + .HasColumnType("INTEGER"); + + b1.HasKey("Id"); + + b1.HasIndex("ArtistId"); + + b1.ToTable("ArtistRatings", (string)null); + + b1.WithOwner() + .HasForeignKey("ArtistId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistIpiEntity", "Ipis", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("ArtistId") + .HasColumnType("TEXT"); + + b1.Property("Value") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("ArtistId"); + + b1.ToTable("ArtistIpis", (string)null); + + b1.WithOwner() + .HasForeignKey("ArtistId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistIsniEntity", "Isnis", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("ArtistId") + .HasColumnType("TEXT"); + + b1.Property("Value") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("ArtistId"); + + b1.ToTable("ArtistIsnis", (string)null); + + b1.WithOwner() + .HasForeignKey("ArtistId"); + }); + + b.Navigation("Aliases"); + + b.Navigation("Area"); + + b.Navigation("BeginArea"); + + b.Navigation("EndArea"); + + b.Navigation("Ipis"); + + b.Navigation("Isnis"); + + b.Navigation("Ratings"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackContributorEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackEntity", null) + .WithMany("Contributors") + .HasForeignKey("TrackId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumEntity", "Album") + .WithMany("Tracks") + .HasForeignKey("AlbumId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AudioRatingEntity", "Ratings", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("MaxValue") + .HasColumnType("decimal(3,2)"); + + b1.Property("Source") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.Property("TrackId") + .HasColumnType("TEXT"); + + b1.Property("Value") + .HasColumnType("decimal(3,2)"); + + b1.Property("VoteCount") + .HasColumnType("INTEGER"); + + b1.HasKey("Id"); + + b1.HasIndex("TrackId"); + + b1.ToTable("TrackRatings", (string)null); + + b1.WithOwner() + .HasForeignKey("TrackId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackIsrcEntity", "Isrcs", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("TrackId") + .HasColumnType("TEXT"); + + b1.Property("Value") + .IsRequired() + .HasMaxLength(12) + .HasColumnType("TEXT") + .HasColumnName("ISRC"); + + b1.HasKey("Id"); + + b1.HasIndex("TrackId"); + + b1.ToTable("TrackIsrcs", (string)null); + + b1.WithOwner() + .HasForeignKey("TrackId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackMoodEntity", "Moods", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("Name") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.Property("TrackId") + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("TrackId"); + + b1.ToTable("TrackMoods", (string)null); + + b1.WithOwner() + .HasForeignKey("TrackId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackWorkIswcEntity", "WorkIswcs", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("TrackId") + .HasColumnType("TEXT"); + + b1.Property("Value") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("TrackId"); + + b1.ToTable("TrackWorkIswcs", (string)null); + + b1.WithOwner() + .HasForeignKey("TrackId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackWorkLanguageEntity", "WorkLanguages", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("LanguageCode") + .IsRequired() + .HasMaxLength(5) + .HasColumnType("TEXT"); + + b1.Property("LanguageName") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("TEXT"); + + b1.Property("NativeName") + .HasMaxLength(100) + .HasColumnType("TEXT"); + + b1.Property("TrackId") + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("TrackId"); + + b1.ToTable("TrackWorkLanguages", (string)null); + + b1.WithOwner() + .HasForeignKey("TrackId"); + }); + + b.Navigation("Album"); + + b.Navigation("Isrcs"); + + b.Navigation("Moods"); + + b.Navigation("Ratings"); + + b.Navigation("WorkIswcs"); + + b.Navigation("WorkLanguages"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.DirectoryScanFingerprintEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", null) + .WithMany() + .HasForeignKey("LibraryId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", "User") + .WithMany("Libraries") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryContentLocationEntity", "ContentLocations", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("LibraryId") + .HasColumnType("TEXT"); + + b1.Property("Path") + .IsRequired() + .HasMaxLength(260) + .HasColumnType("TEXT") + .HasColumnName("Path"); + + b1.HasKey("Id"); + + b1.HasIndex("LibraryId"); + + b1.ToTable("LibraryContentLocations", (string)null); + + b1.WithOwner() + .HasForeignKey("LibraryId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryPathTemplatePartEntity", "PathTemplateParts", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("IsOptional") + .HasColumnType("INTEGER"); + + b1.Property("Kind") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b1.Property("LibraryId") + .HasColumnType("TEXT"); + + b1.Property("Position") + .HasColumnType("INTEGER") + .HasColumnName("Position"); + + b1.Property("Representation") + .IsRequired() + .HasMaxLength(512) + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("LibraryId", "Position") + .IsUnique(); + + b1.ToTable("LibraryPathTemplateParts", (string)null); + + b1.WithOwner() + .HasForeignKey("LibraryId"); + }); + + b.Navigation("ContentLocations"); + + b.Navigation("PathTemplateParts"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", "Library") + .WithMany("LibraryScans") + .HasForeignKey("LibraryId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", "User") + .WithMany("LibraryScans") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Library"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanResultEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", "LibraryScan") + .WithMany("LibraryScanResults") + .HasForeignKey("LibraryScanId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("LibraryScan"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanSnapshotEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", "Library") + .WithMany() + .HasForeignKey("LibraryId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Library"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanStagingResultsEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", null) + .WithMany() + .HasForeignKey("LibraryScanId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookArtworkEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", null) + .WithMany("Artwork") + .HasForeignKey("BookId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookContributorEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", null) + .WithMany("Contributors") + .HasForeignKey("BookId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", b => + { + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookRatingEntity", "Ratings", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("BookId") + .HasColumnType("TEXT"); + + b1.Property("MaxValue") + .HasColumnType("decimal(3,2)"); + + b1.Property("Source") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.Property("Value") + .HasColumnType("decimal(3,2)"); + + b1.Property("VoteCount") + .HasColumnType("INTEGER"); + + b1.HasKey("Id"); + + b1.HasIndex("BookId"); + + b1.ToTable("BookRatings", (string)null); + + b1.WithOwner() + .HasForeignKey("BookId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.IsbnEntity", "ISBNs", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("BookId") + .HasColumnType("TEXT"); + + b1.Property("Format") + .IsRequired() + .HasMaxLength(6) + .HasColumnType("TEXT"); + + b1.Property("Value") + .IsRequired() + .HasMaxLength(13) + .HasColumnType("TEXT") + .HasColumnName("ISBN"); + + b1.HasKey("Id"); + + b1.HasIndex("BookId"); + + b1.ToTable("BookISBNs", (string)null); + + b1.WithOwner() + .HasForeignKey("BookId"); + }); + + b.Navigation("ISBNs"); + + b.Navigation("Ratings"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserSettingsEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", null) + .WithOne() + .HasForeignKey("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserSettingsEntity", "UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("TrackGenres", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.GenreEntity", null) + .WithMany() + .HasForeignKey("GenreId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackEntity", null) + .WithMany() + .HasForeignKey("TrackId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("TrackTags", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.TagEntity", null) + .WithMany() + .HasForeignKey("TagId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackEntity", null) + .WithMany() + .HasForeignKey("TrackId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.PermissionEntity", b => + { + b.Navigation("RolePermissions"); + + b.Navigation("UserPermissions"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.RoleEntity", b => + { + b.Navigation("RolePermissions"); + + b.Navigation("UserRoles"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumEntity", b => + { + b.Navigation("Contributors"); + + b.Navigation("Tracks"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistEntity", b => + { + b.Navigation("Albums"); + + b.Navigation("Contributors"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackEntity", b => + { + b.Navigation("Contributors"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", b => + { + b.Navigation("LibraryScans"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", b => + { + b.Navigation("LibraryScanResults"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", b => + { + b.Navigation("Artwork"); + + b.Navigation("Contributors"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", b => + { + b.Navigation("Libraries"); + + b.Navigation("LibraryScans"); + + b.Navigation("UserPermissions"); + + b.Navigation("UserRole"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/Lumina.DataAccess/Common/Migrations/20261013195657_AddsAudioContainerToMusicMetadata.cs b/src/Lumina.DataAccess/Common/Migrations/20261013195657_AddsAudioContainerToMusicMetadata.cs new file mode 100644 index 00000000..43d0edff --- /dev/null +++ b/src/Lumina.DataAccess/Common/Migrations/20261013195657_AddsAudioContainerToMusicMetadata.cs @@ -0,0 +1,42 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Lumina.DataAccess.Common.Migrations +{ + /// + public partial class AddsAudioContainerToMusicMetadata : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AddColumn( + name: "Container", + table: "Tracks", + type: "TEXT", + maxLength: 50, + nullable: true) + .Annotation("Relational:ColumnOrder", 49); + + migrationBuilder.AddColumn( + name: "Container", + table: "MusicLibraryScanItemMetadata", + type: "TEXT", + maxLength: 50, + nullable: true) + .Annotation("Relational:ColumnOrder", 31); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropColumn( + name: "Container", + table: "Tracks"); + + migrationBuilder.DropColumn( + name: "Container", + table: "MusicLibraryScanItemMetadata"); + } + } +} diff --git a/src/Lumina.DataAccess/Common/Migrations/20261015160422_AddsPlaybackPreferencesAndStateToUserSettings.Designer.cs b/src/Lumina.DataAccess/Common/Migrations/20261015160422_AddsPlaybackPreferencesAndStateToUserSettings.Designer.cs new file mode 100644 index 00000000..3188be44 --- /dev/null +++ b/src/Lumina.DataAccess/Common/Migrations/20261015160422_AddsPlaybackPreferencesAndStateToUserSettings.Designer.cs @@ -0,0 +1,3463 @@ +// +using System; +using Lumina.DataAccess.Core.UoW; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace Lumina.DataAccess.Common.Migrations +{ + [DbContext(typeof(LuminaDbContext))] + [Migration("20261015160422_AddsPlaybackPreferencesAndStateToUserSettings")] + partial class AddsPlaybackPreferencesAndStateToUserSettings + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder.HasAnnotation("ProductVersion", "10.0.11"); + + modelBuilder.Entity("AlbumGenres", b => + { + b.Property("AlbumId") + .HasColumnType("TEXT"); + + b.Property("GenreId") + .HasColumnType("TEXT"); + + b.HasKey("AlbumId", "GenreId"); + + b.HasIndex("GenreId"); + + b.ToTable("AlbumGenres", (string)null); + }); + + modelBuilder.Entity("AlbumTags", b => + { + b.Property("AlbumId") + .HasColumnType("TEXT"); + + b.Property("TagId") + .HasColumnType("TEXT"); + + b.HasKey("AlbumId", "TagId"); + + b.HasIndex("TagId"); + + b.ToTable("AlbumTags", (string)null); + }); + + modelBuilder.Entity("ArtistGenres", b => + { + b.Property("ArtistId") + .HasColumnType("TEXT"); + + b.Property("GenreId") + .HasColumnType("TEXT"); + + b.HasKey("ArtistId", "GenreId"); + + b.HasIndex("GenreId"); + + b.ToTable("ArtistGenres", (string)null); + }); + + modelBuilder.Entity("ArtistTags", b => + { + b.Property("ArtistId") + .HasColumnType("TEXT"); + + b.Property("TagId") + .HasColumnType("TEXT"); + + b.HasKey("ArtistId", "TagId"); + + b.HasIndex("TagId"); + + b.ToTable("ArtistTags", (string)null); + }); + + modelBuilder.Entity("BookGenres", b => + { + b.Property("BookId") + .HasColumnType("TEXT"); + + b.Property("GenreId") + .HasColumnType("TEXT"); + + b.HasKey("BookId", "GenreId"); + + b.HasIndex("GenreId"); + + b.ToTable("BookGenres", (string)null); + }); + + modelBuilder.Entity("BookTags", b => + { + b.Property("BookId") + .HasColumnType("TEXT"); + + b.Property("TagId") + .HasColumnType("TEXT"); + + b.HasKey("BookId", "TagId"); + + b.HasIndex("TagId"); + + b.ToTable("BookTags", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.PermissionEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("PermissionName") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.HasKey("Id"); + + b.ToTable("Permissions", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.RoleEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("RoleName") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.HasKey("Id"); + + b.ToTable("Roles", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.RolePermissionEntity", b => + { + b.Property("RoleId") + .HasColumnType("TEXT"); + + b.Property("PermissionId") + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.HasKey("RoleId", "PermissionId"); + + b.HasIndex("PermissionId"); + + b.HasIndex("RoleId", "PermissionId") + .IsUnique(); + + b.ToTable("RolePermissions", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.UserPermissionEntity", b => + { + b.Property("UserId") + .HasColumnType("TEXT"); + + b.Property("PermissionId") + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.HasKey("UserId", "PermissionId"); + + b.HasIndex("PermissionId"); + + b.HasIndex("UserId", "PermissionId") + .IsUnique(); + + b.ToTable("UserPermissions", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.UserRoleEntity", b => + { + b.Property("UserId") + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("RoleId") + .HasColumnType("TEXT"); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.HasKey("UserId"); + + b.HasIndex("RoleId"); + + b.HasIndex("UserId", "RoleId") + .IsUnique(); + + b.ToTable("UserRoles", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Common.GenreEntity", b => + { + b.Property("Name") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b.HasKey("Name"); + + b.ToTable("Genres", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Common.TagEntity", b => + { + b.Property("Name") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b.HasKey("Name"); + + b.ToTable("Tags", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaContributors.MediaContributorEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Biography") + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("DateOfBirth") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("DateOfDeath") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("DisplayName") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1) + .UseCollation("NOCASE"); + + b.Property("LegalName") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.HasKey("Id"); + + b.HasIndex("DisplayName") + .IsUnique(); + + b.ToTable("MediaContributors", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumContributorEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("AlbumId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("MediaContributorId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("Role") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.HasKey("Id"); + + b.HasIndex("MediaContributorId"); + + b.HasIndex("AlbumId", "MediaContributorId", "Role") + .IsUnique(); + + b.ToTable("AlbumContributors", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("ASIN") + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(28); + + b.Property("ArtistId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("Barcode") + .HasMaxLength(13) + .HasColumnType("TEXT") + .HasColumnOrder(25); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(33); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(32); + + b.Property("Description") + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("Disambiguation") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("Label") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(27); + + b.Property("LanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("LanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("LanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(15); + + b.Property("LastMetadataUpdateUtc") + .HasColumnType("TEXT") + .HasColumnOrder(37); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("MediaFormat") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(23); + + b.Property("MetadataProvider") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(38); + + b.Property("MetadataStatus") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasDefaultValue("Pending") + .HasColumnOrder(36); + + b.Property("MusicBrainzReleaseArtistId") + .HasColumnType("TEXT") + .HasColumnOrder(31); + + b.Property("MusicBrainzReleaseGroupId") + .HasColumnType("TEXT") + .HasColumnOrder(30); + + b.Property("MusicBrainzReleaseId") + .HasColumnType("TEXT") + .HasColumnOrder(29); + + b.Property("OriginalLanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(16); + + b.Property("OriginalLanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(17); + + b.Property("OriginalLanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(18); + + b.Property("OriginalReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("OriginalReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(8); + + b.Property("OriginalTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("Packaging") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(24); + + b.Property("ReReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("ReReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(10); + + b.Property("ReleaseCountry") + .HasMaxLength(2) + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("ReleaseStatus") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(20); + + b.Property("ReleaseTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(26); + + b.Property("ReleaseVersion") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("Script") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(19); + + b.Property("Title") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("TotalDiscs") + .HasColumnType("INTEGER") + .HasColumnOrder(21); + + b.Property("TotalTracks") + .HasColumnType("INTEGER") + .HasColumnOrder(22); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(35); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(34); + + b.HasKey("Id"); + + b.HasIndex("ArtistId", "Title"); + + b.HasIndex("LibraryId", "Title"); + + b.ToTable("Albums", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistContributorEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("ArtistId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("MediaContributorId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("Role") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.HasKey("Id"); + + b.HasIndex("MediaContributorId"); + + b.HasIndex("ArtistId", "MediaContributorId", "Role") + .IsUnique(); + + b.ToTable("ArtistContributors", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Country") + .HasMaxLength(2) + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("Disambiguation") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("Gender") + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("IsEnded") + .HasColumnType("INTEGER") + .HasColumnOrder(10); + + b.Property("LastMetadataUpdateUtc") + .HasColumnType("TEXT") + .HasColumnOrder(18); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("LifeSpanBegin") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("LifeSpanEnd") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("MetadataProvider") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(19); + + b.Property("MetadataStatus") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasDefaultValue("Pending") + .HasColumnOrder(17); + + b.Property("MusicBrainzArtistId") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("Name") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("SortName") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("Type") + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(16); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(15); + + b.Property("Website") + .HasMaxLength(2048) + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.HasKey("Id"); + + b.HasIndex("LibraryId", "Name") + .IsUnique(); + + b.ToTable("Artists", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.MusicArtworkEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("ArtworkType") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("ContentHash") + .HasColumnType("INTEGER") + .HasColumnOrder(6); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("FileName") + .HasMaxLength(2048) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("LastUpdateUtc") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("Ordinal") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("OwnerId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("OwnerType") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("Provider") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("Status") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.HasKey("Id"); + + b.HasIndex("Status"); + + b.HasIndex("OwnerType", "OwnerId", "ArtworkType", "Ordinal") + .IsUnique(); + + b.ToTable("MusicArtwork", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.MusicLibraryScanItemMetadataEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("AcoustId") + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnOrder(25); + + b.Property("ArtistName") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("AudioCodec") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(15); + + b.Property("BitDepth") + .HasColumnType("INTEGER") + .HasColumnOrder(14); + + b.Property("Bitrate") + .HasColumnType("INTEGER") + .HasColumnOrder(16); + + b.Property("Channels") + .HasColumnType("INTEGER") + .HasColumnOrder(13); + + b.Property("Container") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(31); + + b.Property("DiscNumber") + .HasColumnType("INTEGER") + .HasColumnOrder(10); + + b.Property("DurationInSeconds") + .HasColumnType("INTEGER") + .HasColumnOrder(11); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("LibraryScanId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.PrimitiveCollection("Moods") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(30); + + b.Property("MusicBrainzArtistId") + .HasColumnType("TEXT") + .HasColumnOrder(17); + + b.Property("MusicBrainzRecordingId") + .HasColumnType("TEXT") + .HasColumnOrder(21); + + b.Property("MusicBrainzReleaseArtistId") + .HasColumnType("TEXT") + .HasColumnOrder(18); + + b.Property("MusicBrainzReleaseGroupId") + .HasColumnType("TEXT") + .HasColumnOrder(19); + + b.Property("MusicBrainzReleaseId") + .HasColumnType("TEXT") + .HasColumnOrder(20); + + b.Property("MusicBrainzTrackId") + .HasColumnType("TEXT") + .HasColumnOrder(22); + + b.Property("MusicBrainzWorkId") + .HasColumnType("TEXT") + .HasColumnOrder(23); + + b.Property("Path") + .IsRequired() + .HasMaxLength(2048) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("ReleaseName") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("ReleaseType") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("ReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(6); + + b.Property("ReplayGainAlbumGain") + .HasColumnType("decimal(8,2)") + .HasColumnOrder(28); + + b.Property("ReplayGainAlbumPeak") + .HasColumnType("decimal(8,6)") + .HasColumnOrder(29); + + b.Property("ReplayGainTrackGain") + .HasColumnType("decimal(8,2)") + .HasColumnOrder(26); + + b.Property("ReplayGainTrackPeak") + .HasColumnType("decimal(8,6)") + .HasColumnOrder(27); + + b.Property("SampleRate") + .HasColumnType("INTEGER") + .HasColumnOrder(12); + + b.Property("TrackNumber") + .HasColumnType("INTEGER") + .HasColumnOrder(9); + + b.Property("TrackTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("WorkTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(24); + + b.HasKey("Id"); + + b.HasIndex("LibraryScanId", "Path") + .IsUnique(); + + b.ToTable("MusicLibraryScanItemMetadata", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackContributorEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("MediaContributorId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("Role") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("TrackId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.HasKey("Id"); + + b.HasIndex("MediaContributorId"); + + b.HasIndex("TrackId", "MediaContributorId", "Role") + .IsUnique(); + + b.ToTable("TrackContributors", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("AcoustId") + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnOrder(44); + + b.Property("AlbumId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("AudioCodec") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(24); + + b.Property("BitDepth") + .HasColumnType("INTEGER") + .HasColumnOrder(23); + + b.Property("Bitrate") + .HasColumnType("INTEGER") + .HasColumnOrder(25); + + b.Property("Bpm") + .HasColumnType("INTEGER") + .HasColumnOrder(30); + + b.Property("Channels") + .HasColumnType("INTEGER") + .HasColumnOrder(22); + + b.Property("Container") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(49); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(38); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(37); + + b.Property("Description") + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("Disambiguation") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("DiscNumber") + .HasColumnType("INTEGER") + .HasColumnOrder(27); + + b.Property("DurationInSeconds") + .HasColumnType("INTEGER") + .HasColumnOrder(20); + + b.Property("IsVideo") + .HasColumnType("INTEGER") + .HasColumnOrder(31); + + b.Property("Key") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(29); + + b.Property("LanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("LanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(15); + + b.Property("LanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(16); + + b.Property("LastMetadataUpdateUtc") + .HasColumnType("TEXT") + .HasColumnOrder(42); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("MetadataProvider") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(43); + + b.Property("MetadataStatus") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasDefaultValue("Pending") + .HasColumnOrder(41); + + b.Property("MusicBrainzRecordingId") + .HasColumnType("TEXT") + .HasColumnOrder(34); + + b.Property("MusicBrainzTrackId") + .HasColumnType("TEXT") + .HasColumnOrder(35); + + b.Property("MusicBrainzWorkId") + .HasColumnType("TEXT") + .HasColumnOrder(36); + + b.Property("OriginalLanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(17); + + b.Property("OriginalLanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(18); + + b.Property("OriginalLanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(19); + + b.Property("OriginalReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("OriginalReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(9); + + b.Property("OriginalTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("Path") + .IsRequired() + .HasMaxLength(2048) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("ReReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("ReReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(11); + + b.Property("ReleaseCountry") + .HasMaxLength(2) + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("ReleaseVersion") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("ReplayGainAlbumGain") + .HasColumnType("decimal(8,2)") + .HasColumnOrder(47); + + b.Property("ReplayGainAlbumPeak") + .HasColumnType("decimal(8,6)") + .HasColumnOrder(48); + + b.Property("ReplayGainTrackGain") + .HasColumnType("decimal(8,2)") + .HasColumnOrder(45); + + b.Property("ReplayGainTrackPeak") + .HasColumnType("decimal(8,6)") + .HasColumnOrder(46); + + b.Property("SampleRate") + .HasColumnType("INTEGER") + .HasColumnOrder(21); + + b.Property("Script") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(28); + + b.Property("Title") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("TrackNumber") + .HasColumnType("INTEGER") + .HasColumnOrder(26); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(40); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(39); + + b.Property("WorkTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(32); + + b.Property("WorkType") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(33); + + b.HasKey("Id"); + + b.HasIndex("AlbumId", "TrackNumber"); + + b.HasIndex("LibraryId", "Path") + .IsUnique(); + + b.ToTable("Tracks", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.DirectoryScanFingerprintEntity", b => + { + b.Property("LibraryId") + .HasColumnType("TEXT"); + + b.Property("Path") + .HasMaxLength(1024) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("LastWriteTimeUtc") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.HasKey("LibraryId", "Path"); + + b.HasIndex("LibraryId"); + + b.ToTable("DirectoryScanFingerprints", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("ArtworkProvidersConfigurationFingerprint") + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("CanDownloadMetadataFromWeb") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(true) + .HasColumnOrder(6); + + b.Property("CoverImage") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("IsEnabled") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(true) + .HasColumnOrder(4); + + b.Property("IsLocked") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("LibraryType") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("MetadataProvidersConfigurationFingerprint") + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("PathTemplateFingerprint") + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("ShouldSaveMetadataInMediaDirectories") + .HasColumnType("INTEGER") + .HasColumnOrder(7); + + b.Property("ShouldSkipUnchangedDirectoriesDuringScan") + .HasColumnType("INTEGER") + .HasColumnOrder(8); + + b.Property("Title") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(15); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("UserId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("Libraries", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("LibraryId") + .HasColumnType("TEXT"); + + b.Property("Status") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UserId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.HasIndex("LibraryId", "Status", "CreatedOnUtc") + .IsDescending(true, false, true); + + b.ToTable("LibraryScans", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanResultEntity", b => + { + b.Property("LibraryScanId") + .HasColumnType("TEXT"); + + b.Property("Path") + .HasMaxLength(1024) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("ContentHash") + .HasMaxLength(24) + .HasColumnType("INTEGER") + .HasColumnOrder(2); + + b.Property("FileSize") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Status") + .IsRequired() + .HasMaxLength(10) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("Ticks") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.HasKey("LibraryScanId", "Path"); + + b.HasIndex("Path"); + + b.HasIndex("ContentHash", "FileSize", "Path"); + + b.ToTable("LibraryScanResults", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanSnapshotEntity", b => + { + b.Property("LibraryId") + .HasColumnType("TEXT"); + + b.Property("Path") + .HasMaxLength(1024) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("ContentHash") + .HasColumnType("INTEGER") + .HasColumnOrder(2); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("FileSize") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Ticks") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.HasKey("LibraryId", "Path"); + + b.HasIndex("LibraryId"); + + b.ToTable("LibraryScanSnapshots", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanStagingResultsEntity", b => + { + b.Property("LibraryScanId") + .HasColumnType("TEXT"); + + b.Property("Path") + .HasMaxLength(1024) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("ContentHash") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("IsNew") + .HasColumnType("INTEGER") + .HasColumnOrder(7); + + b.Property("NeedsRehash") + .HasColumnType("INTEGER") + .HasColumnOrder(6); + + b.Property("PreviousContentHash") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("Size") + .HasColumnType("INTEGER") + .HasColumnOrder(2); + + b.Property("Ticks") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.HasKey("LibraryScanId", "Path"); + + b.HasIndex("LibraryScanId", "NeedsRehash"); + + b.ToTable("LibraryScanStagingResults", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookArtworkEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("ArtworkType") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("BookId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("ContentHash") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("FileName") + .HasMaxLength(2048) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("LastUpdateUtc") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("Ordinal") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("Provider") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("Status") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.HasKey("Id"); + + b.HasIndex("Status"); + + b.HasIndex("BookId", "ArtworkType", "Ordinal") + .IsUnique(); + + b.ToTable("BookArtwork", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookContributorEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("BookId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("MediaContributorId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("Role") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.HasKey("Id"); + + b.HasIndex("MediaContributorId"); + + b.HasIndex("BookId", "MediaContributorId", "Role") + .IsUnique(); + + b.ToTable("BookContributors", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("ASIN") + .HasMaxLength(10) + .HasColumnType("TEXT") + .HasColumnOrder(21); + + b.Property("AppleBooksId") + .HasColumnType("TEXT") + .HasColumnOrder(29); + + b.Property("BarnesAndNobleId") + .HasMaxLength(10) + .HasColumnType("TEXT") + .HasColumnOrder(28); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(33); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(32); + + b.Property("Description") + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("Edition") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(19); + + b.Property("Format") + .HasColumnType("TEXT") + .HasColumnOrder(18); + + b.Property("GoodreadsId") + .HasColumnType("TEXT") + .HasColumnOrder(22); + + b.Property("GoogleBooksId") + .HasMaxLength(12) + .HasColumnType("TEXT") + .HasColumnOrder(27); + + b.Property("LCCN") + .HasColumnType("TEXT") + .HasColumnOrder(23); + + b.Property("LanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("LanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("LanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("LastMetadataUpdateUtc") + .HasColumnType("TEXT") + .HasColumnOrder(39); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(36); + + b.Property("LibraryThingId") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(26); + + b.Property("MetadataProvider") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(40); + + b.Property("MetadataStatus") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(38); + + b.Property("OCLCNumber") + .HasColumnType("TEXT") + .HasColumnOrder(24); + + b.Property("OpenLibraryId") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(25); + + b.Property("OriginalLanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("OriginalLanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("OriginalLanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(15); + + b.Property("OriginalReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("OriginalReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("OriginalTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("PageCount") + .HasColumnType("INTEGER") + .HasColumnOrder(17); + + b.Property("Path") + .IsRequired() + .HasMaxLength(2048) + .HasColumnType("TEXT") + .HasColumnOrder(37); + + b.Property("Publisher") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(16); + + b.Property("ReReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("ReReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(7); + + b.Property("ReleaseCountry") + .HasMaxLength(2) + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("ReleaseVersion") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("Title") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(35); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(34); + + b.Property("VolumeNumber") + .HasColumnType("REAL") + .HasColumnOrder(20); + + b.HasKey("Id"); + + b.HasIndex("LibraryId", "MetadataStatus"); + + b.HasIndex("LibraryId", "Path") + .IsUnique(); + + b.ToTable("Books", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Plugins.LibraryArtworkProviderConfigurationEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("IsEnabled") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("PluginId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("Rank") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.HasKey("Id"); + + b.HasIndex("LibraryId", "PluginId"); + + b.ToTable("LibraryArtworkProviderConfigurations", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Plugins.LibraryBookReaderConfigurationEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("IsEnabled") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("PluginId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.HasKey("Id"); + + b.HasIndex("LibraryId", "PluginId") + .IsUnique(); + + b.ToTable("LibraryBookReaderConfigurations", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Plugins.LibraryMetadataProviderConfigurationEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("IsEnabled") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("PluginId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("Rank") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.HasKey("Id"); + + b.HasIndex("LibraryId", "PluginId"); + + b.ToTable("LibraryMetadataProviderConfigurations", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Plugins.PluginEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Author") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("Description") + .IsRequired() + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("LoadError") + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("LoadStatus") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("Name") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("SettingsJson") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("Version") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.HasKey("Id"); + + b.ToTable("Plugins", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Scheduling.ScheduledJobEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("Hour") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("IntervalMinutes") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("LastCompletedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("LastStartedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("Minute") + .HasColumnType("INTEGER") + .HasColumnOrder(6); + + b.Property("Name") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("OwnerUserId") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("ScheduleType") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("Status") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("TaskType") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.HasKey("Id"); + + b.HasIndex("Status"); + + b.ToTable("ScheduledJobs", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Scheduling.ScheduledJobExecutionEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CompletedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("IsCycleRun") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("ScheduledJobId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("StartedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("TaskType") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("WasCycleActive") + .HasColumnType("INTEGER") + .HasColumnOrder(6); + + b.HasKey("Id"); + + b.HasIndex("ScheduledJobId"); + + b.HasIndex("StartedOnUtc", "ScheduledJobId"); + + b.ToTable("ScheduledJobExecutions", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Scheduling.SchedulerDisplayPreferencesEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("DisplayTimeSpan") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("DisplayTimeUnit") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("JobTypeFilter") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UserId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.HasKey("Id"); + + b.HasIndex("UserId") + .IsUnique(); + + b.ToTable("SchedulerDisplayPreferences", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Themes.ThemeEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Author") + .IsRequired() + .HasMaxLength(80) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("Description") + .IsRequired() + .HasMaxLength(300) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("InstallSource") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("InstalledAtUtc") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("IsCurrent") + .HasColumnType("INTEGER") + .HasColumnOrder(8); + + b.Property("IsDeleted") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(false) + .HasColumnOrder(9); + + b.Property("Name") + .IsRequired() + .HasMaxLength(80) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("PreviewPath") + .HasMaxLength(240) + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("ThemeId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("Version") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.HasKey("Id"); + + b.HasIndex("IsCurrent") + .IsUnique() + .HasFilter("IsCurrent = 1"); + + b.HasIndex("ThemeId") + .IsUnique(); + + b.ToTable("Themes", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("Password") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("TempPassword") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("TempPasswordCreated") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("TotpSecret") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("Username") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.HasKey("Id"); + + b.HasIndex("Username") + .IsUnique(); + + b.ToTable("Users", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserSettingsEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("IsGaplessPlaybackEnabled") + .HasColumnType("INTEGER") + .HasColumnOrder(16); + + b.Property("IsMuted") + .HasColumnType("INTEGER") + .HasColumnOrder(20); + + b.Property("IsPaginationEnabled") + .HasColumnType("INTEGER") + .HasColumnOrder(2); + + b.Property("IsThemeCachingEnabled") + .HasColumnType("INTEGER") + .HasColumnOrder(9); + + b.Property("ItemsPerPage") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("ReplayGainMode") + .HasColumnType("INTEGER") + .HasColumnOrder(17); + + b.Property("ShouldAggregateArtworkWhenMissing") + .HasColumnType("INTEGER") + .HasColumnOrder(13); + + b.Property("ShouldAggregateMetadataWhenMissing") + .HasColumnType("INTEGER") + .HasColumnOrder(10); + + b.Property("ShouldAutoplay") + .HasColumnType("INTEGER") + .HasColumnOrder(15); + + b.Property("ShouldIgnoreThePrefixForAlphaPicker") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("ShouldKeepDownloadingWhilePaused") + .HasColumnType("INTEGER") + .HasColumnOrder(14); + + b.Property("ShouldPreserveBookStyles") + .HasColumnType("INTEGER") + .HasColumnOrder(12); + + b.Property("ShouldRenderPdfAsImages") + .HasColumnType("INTEGER") + .HasColumnOrder(11); + + b.Property("StreamingQuality") + .HasColumnType("INTEGER") + .HasColumnOrder(18); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UserId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("Volume") + .HasColumnType("REAL") + .HasColumnOrder(19); + + b.HasKey("Id"); + + b.HasIndex("UserId") + .IsUnique(); + + b.ToTable("UserSettings", (string)null); + }); + + modelBuilder.Entity("TrackGenres", b => + { + b.Property("TrackId") + .HasColumnType("TEXT"); + + b.Property("GenreId") + .HasColumnType("TEXT"); + + b.HasKey("TrackId", "GenreId"); + + b.HasIndex("GenreId"); + + b.ToTable("TrackGenres", (string)null); + }); + + modelBuilder.Entity("TrackTags", b => + { + b.Property("TrackId") + .HasColumnType("TEXT"); + + b.Property("TagId") + .HasColumnType("TEXT"); + + b.HasKey("TrackId", "TagId"); + + b.HasIndex("TagId"); + + b.ToTable("TrackTags", (string)null); + }); + + modelBuilder.Entity("AlbumGenres", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumEntity", null) + .WithMany() + .HasForeignKey("AlbumId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.GenreEntity", null) + .WithMany() + .HasForeignKey("GenreId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("AlbumTags", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumEntity", null) + .WithMany() + .HasForeignKey("AlbumId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.TagEntity", null) + .WithMany() + .HasForeignKey("TagId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("ArtistGenres", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistEntity", null) + .WithMany() + .HasForeignKey("ArtistId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.GenreEntity", null) + .WithMany() + .HasForeignKey("GenreId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("ArtistTags", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistEntity", null) + .WithMany() + .HasForeignKey("ArtistId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.TagEntity", null) + .WithMany() + .HasForeignKey("TagId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BookGenres", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", null) + .WithMany() + .HasForeignKey("BookId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.GenreEntity", null) + .WithMany() + .HasForeignKey("GenreId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BookTags", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", null) + .WithMany() + .HasForeignKey("BookId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.TagEntity", null) + .WithMany() + .HasForeignKey("TagId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.RolePermissionEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Authorization.PermissionEntity", "Permission") + .WithMany("RolePermissions") + .HasForeignKey("PermissionId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Authorization.RoleEntity", "Role") + .WithMany("RolePermissions") + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Permission"); + + b.Navigation("Role"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.UserPermissionEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Authorization.PermissionEntity", "Permission") + .WithMany("UserPermissions") + .HasForeignKey("PermissionId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", "User") + .WithMany("UserPermissions") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Permission"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.UserRoleEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Authorization.RoleEntity", "Role") + .WithMany("UserRoles") + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", "User") + .WithOne("UserRole") + .HasForeignKey("Lumina.Application.Common.DataAccess.Entities.Authorization.UserRoleEntity", "UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Role"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumContributorEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumEntity", null) + .WithMany("Contributors") + .HasForeignKey("AlbumId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistEntity", "Artist") + .WithMany("Albums") + .HasForeignKey("ArtistId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumCatalogNumberEntity", "CatalogNumbers", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("AlbumId") + .HasColumnType("TEXT"); + + b1.Property("CatalogNumber") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("AlbumId"); + + b1.ToTable("AlbumCatalogNumbers", (string)null); + + b1.WithOwner() + .HasForeignKey("AlbumId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AudioRatingEntity", "Ratings", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("AlbumId") + .HasColumnType("TEXT"); + + b1.Property("MaxValue") + .HasColumnType("decimal(3,2)"); + + b1.Property("Source") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.Property("Value") + .HasColumnType("decimal(3,2)"); + + b1.Property("VoteCount") + .HasColumnType("INTEGER"); + + b1.HasKey("Id"); + + b1.HasIndex("AlbumId"); + + b1.ToTable("AlbumRatings", (string)null); + + b1.WithOwner() + .HasForeignKey("AlbumId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumReleaseTypeEntity", "ReleaseTypes", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("AlbumId") + .HasColumnType("TEXT"); + + b1.Property("ReleaseType") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("AlbumId"); + + b1.ToTable("AlbumReleaseTypes", (string)null); + + b1.WithOwner() + .HasForeignKey("AlbumId"); + }); + + b.Navigation("Artist"); + + b.Navigation("CatalogNumbers"); + + b.Navigation("Ratings"); + + b.Navigation("ReleaseTypes"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistContributorEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistEntity", null) + .WithMany("Contributors") + .HasForeignKey("ArtistId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistEntity", b => + { + b.OwnsOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.MusicAreaEntity", "Area", b1 => + { + b1.Property("ArtistEntityId"); + + b1.Property("Disambiguation"); + + b1.Property("Iso3166Code"); + + b1.Property("MusicBrainzAreaId"); + + b1.Property("Name") + .IsRequired(); + + b1.Property("SortName"); + + b1.Property("Type"); + + b1.HasKey("ArtistEntityId"); + + b1.ToTable("Artists"); + + b1 + .ToJson("Area") + .HasColumnType("TEXT"); + + b1.WithOwner() + .HasForeignKey("ArtistEntityId"); + }); + + b.OwnsOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.MusicAreaEntity", "BeginArea", b1 => + { + b1.Property("ArtistEntityId"); + + b1.Property("Disambiguation"); + + b1.Property("Iso3166Code"); + + b1.Property("MusicBrainzAreaId"); + + b1.Property("Name") + .IsRequired(); + + b1.Property("SortName"); + + b1.Property("Type"); + + b1.HasKey("ArtistEntityId"); + + b1.ToTable("Artists"); + + b1 + .ToJson("BeginArea") + .HasColumnType("TEXT"); + + b1.WithOwner() + .HasForeignKey("ArtistEntityId"); + }); + + b.OwnsOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.MusicAreaEntity", "EndArea", b1 => + { + b1.Property("ArtistEntityId"); + + b1.Property("Disambiguation"); + + b1.Property("Iso3166Code"); + + b1.Property("MusicBrainzAreaId"); + + b1.Property("Name") + .IsRequired(); + + b1.Property("SortName"); + + b1.Property("Type"); + + b1.HasKey("ArtistEntityId"); + + b1.ToTable("Artists"); + + b1 + .ToJson("EndArea") + .HasColumnType("TEXT"); + + b1.WithOwner() + .HasForeignKey("ArtistEntityId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistAliasEntity", "Aliases", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("ArtistId") + .HasColumnType("TEXT"); + + b1.Property("BeginDate") + .HasColumnType("TEXT"); + + b1.Property("EndDate") + .HasColumnType("TEXT"); + + b1.Property("IsEnded") + .HasColumnType("INTEGER"); + + b1.Property("IsPrimary") + .HasColumnType("INTEGER"); + + b1.Property("Locale") + .HasMaxLength(20) + .HasColumnType("TEXT"); + + b1.Property("Name") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT"); + + b1.Property("SortName") + .HasMaxLength(255) + .HasColumnType("TEXT"); + + b1.Property("Type") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("ArtistId"); + + b1.ToTable("ArtistAliases", (string)null); + + b1.WithOwner() + .HasForeignKey("ArtistId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AudioRatingEntity", "Ratings", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("ArtistId") + .HasColumnType("TEXT"); + + b1.Property("MaxValue") + .HasColumnType("decimal(3,2)"); + + b1.Property("Source") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.Property("Value") + .HasColumnType("decimal(3,2)"); + + b1.Property("VoteCount") + .HasColumnType("INTEGER"); + + b1.HasKey("Id"); + + b1.HasIndex("ArtistId"); + + b1.ToTable("ArtistRatings", (string)null); + + b1.WithOwner() + .HasForeignKey("ArtistId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistIpiEntity", "Ipis", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("ArtistId") + .HasColumnType("TEXT"); + + b1.Property("Value") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("ArtistId"); + + b1.ToTable("ArtistIpis", (string)null); + + b1.WithOwner() + .HasForeignKey("ArtistId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistIsniEntity", "Isnis", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("ArtistId") + .HasColumnType("TEXT"); + + b1.Property("Value") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("ArtistId"); + + b1.ToTable("ArtistIsnis", (string)null); + + b1.WithOwner() + .HasForeignKey("ArtistId"); + }); + + b.Navigation("Aliases"); + + b.Navigation("Area"); + + b.Navigation("BeginArea"); + + b.Navigation("EndArea"); + + b.Navigation("Ipis"); + + b.Navigation("Isnis"); + + b.Navigation("Ratings"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackContributorEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackEntity", null) + .WithMany("Contributors") + .HasForeignKey("TrackId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumEntity", "Album") + .WithMany("Tracks") + .HasForeignKey("AlbumId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AudioRatingEntity", "Ratings", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("MaxValue") + .HasColumnType("decimal(3,2)"); + + b1.Property("Source") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.Property("TrackId") + .HasColumnType("TEXT"); + + b1.Property("Value") + .HasColumnType("decimal(3,2)"); + + b1.Property("VoteCount") + .HasColumnType("INTEGER"); + + b1.HasKey("Id"); + + b1.HasIndex("TrackId"); + + b1.ToTable("TrackRatings", (string)null); + + b1.WithOwner() + .HasForeignKey("TrackId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackIsrcEntity", "Isrcs", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("TrackId") + .HasColumnType("TEXT"); + + b1.Property("Value") + .IsRequired() + .HasMaxLength(12) + .HasColumnType("TEXT") + .HasColumnName("ISRC"); + + b1.HasKey("Id"); + + b1.HasIndex("TrackId"); + + b1.ToTable("TrackIsrcs", (string)null); + + b1.WithOwner() + .HasForeignKey("TrackId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackMoodEntity", "Moods", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("Name") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.Property("TrackId") + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("TrackId"); + + b1.ToTable("TrackMoods", (string)null); + + b1.WithOwner() + .HasForeignKey("TrackId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackWorkIswcEntity", "WorkIswcs", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("TrackId") + .HasColumnType("TEXT"); + + b1.Property("Value") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("TrackId"); + + b1.ToTable("TrackWorkIswcs", (string)null); + + b1.WithOwner() + .HasForeignKey("TrackId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackWorkLanguageEntity", "WorkLanguages", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("LanguageCode") + .IsRequired() + .HasMaxLength(5) + .HasColumnType("TEXT"); + + b1.Property("LanguageName") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("TEXT"); + + b1.Property("NativeName") + .HasMaxLength(100) + .HasColumnType("TEXT"); + + b1.Property("TrackId") + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("TrackId"); + + b1.ToTable("TrackWorkLanguages", (string)null); + + b1.WithOwner() + .HasForeignKey("TrackId"); + }); + + b.Navigation("Album"); + + b.Navigation("Isrcs"); + + b.Navigation("Moods"); + + b.Navigation("Ratings"); + + b.Navigation("WorkIswcs"); + + b.Navigation("WorkLanguages"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.DirectoryScanFingerprintEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", null) + .WithMany() + .HasForeignKey("LibraryId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", "User") + .WithMany("Libraries") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryContentLocationEntity", "ContentLocations", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("LibraryId") + .HasColumnType("TEXT"); + + b1.Property("Path") + .IsRequired() + .HasMaxLength(260) + .HasColumnType("TEXT") + .HasColumnName("Path"); + + b1.HasKey("Id"); + + b1.HasIndex("LibraryId"); + + b1.ToTable("LibraryContentLocations", (string)null); + + b1.WithOwner() + .HasForeignKey("LibraryId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryPathTemplatePartEntity", "PathTemplateParts", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("IsOptional") + .HasColumnType("INTEGER"); + + b1.Property("Kind") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b1.Property("LibraryId") + .HasColumnType("TEXT"); + + b1.Property("Position") + .HasColumnType("INTEGER") + .HasColumnName("Position"); + + b1.Property("Representation") + .IsRequired() + .HasMaxLength(512) + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("LibraryId", "Position") + .IsUnique(); + + b1.ToTable("LibraryPathTemplateParts", (string)null); + + b1.WithOwner() + .HasForeignKey("LibraryId"); + }); + + b.Navigation("ContentLocations"); + + b.Navigation("PathTemplateParts"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", "Library") + .WithMany("LibraryScans") + .HasForeignKey("LibraryId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", "User") + .WithMany("LibraryScans") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Library"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanResultEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", "LibraryScan") + .WithMany("LibraryScanResults") + .HasForeignKey("LibraryScanId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("LibraryScan"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanSnapshotEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", "Library") + .WithMany() + .HasForeignKey("LibraryId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Library"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanStagingResultsEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", null) + .WithMany() + .HasForeignKey("LibraryScanId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookArtworkEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", null) + .WithMany("Artwork") + .HasForeignKey("BookId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookContributorEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", null) + .WithMany("Contributors") + .HasForeignKey("BookId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", b => + { + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookRatingEntity", "Ratings", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("BookId") + .HasColumnType("TEXT"); + + b1.Property("MaxValue") + .HasColumnType("decimal(3,2)"); + + b1.Property("Source") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.Property("Value") + .HasColumnType("decimal(3,2)"); + + b1.Property("VoteCount") + .HasColumnType("INTEGER"); + + b1.HasKey("Id"); + + b1.HasIndex("BookId"); + + b1.ToTable("BookRatings", (string)null); + + b1.WithOwner() + .HasForeignKey("BookId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.IsbnEntity", "ISBNs", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("BookId") + .HasColumnType("TEXT"); + + b1.Property("Format") + .IsRequired() + .HasMaxLength(6) + .HasColumnType("TEXT"); + + b1.Property("Value") + .IsRequired() + .HasMaxLength(13) + .HasColumnType("TEXT") + .HasColumnName("ISBN"); + + b1.HasKey("Id"); + + b1.HasIndex("BookId"); + + b1.ToTable("BookISBNs", (string)null); + + b1.WithOwner() + .HasForeignKey("BookId"); + }); + + b.Navigation("ISBNs"); + + b.Navigation("Ratings"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserSettingsEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", null) + .WithOne() + .HasForeignKey("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserSettingsEntity", "UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("TrackGenres", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.GenreEntity", null) + .WithMany() + .HasForeignKey("GenreId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackEntity", null) + .WithMany() + .HasForeignKey("TrackId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("TrackTags", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.TagEntity", null) + .WithMany() + .HasForeignKey("TagId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackEntity", null) + .WithMany() + .HasForeignKey("TrackId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.PermissionEntity", b => + { + b.Navigation("RolePermissions"); + + b.Navigation("UserPermissions"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.RoleEntity", b => + { + b.Navigation("RolePermissions"); + + b.Navigation("UserRoles"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumEntity", b => + { + b.Navigation("Contributors"); + + b.Navigation("Tracks"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistEntity", b => + { + b.Navigation("Albums"); + + b.Navigation("Contributors"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackEntity", b => + { + b.Navigation("Contributors"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", b => + { + b.Navigation("LibraryScans"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", b => + { + b.Navigation("LibraryScanResults"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", b => + { + b.Navigation("Artwork"); + + b.Navigation("Contributors"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", b => + { + b.Navigation("Libraries"); + + b.Navigation("LibraryScans"); + + b.Navigation("UserPermissions"); + + b.Navigation("UserRole"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/Lumina.DataAccess/Common/Migrations/20261015160422_AddsPlaybackPreferencesAndStateToUserSettings.cs b/src/Lumina.DataAccess/Common/Migrations/20261015160422_AddsPlaybackPreferencesAndStateToUserSettings.cs new file mode 100644 index 00000000..9b74da5d --- /dev/null +++ b/src/Lumina.DataAccess/Common/Migrations/20261015160422_AddsPlaybackPreferencesAndStateToUserSettings.cs @@ -0,0 +1,102 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Lumina.DataAccess.Common.Migrations +{ + /// + public partial class AddsPlaybackPreferencesAndStateToUserSettings : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AddColumn( + name: "IsGaplessPlaybackEnabled", + table: "UserSettings", + type: "INTEGER", + nullable: false, + defaultValue: true) + .Annotation("Relational:ColumnOrder", 16); + + migrationBuilder.AddColumn( + name: "IsMuted", + table: "UserSettings", + type: "INTEGER", + nullable: false, + defaultValue: false) + .Annotation("Relational:ColumnOrder", 20); + + migrationBuilder.AddColumn( + name: "ReplayGainMode", + table: "UserSettings", + type: "INTEGER", + nullable: false, + defaultValue: 0) + .Annotation("Relational:ColumnOrder", 17); + + migrationBuilder.AddColumn( + name: "ShouldAutoplay", + table: "UserSettings", + type: "INTEGER", + nullable: false, + defaultValue: true) + .Annotation("Relational:ColumnOrder", 15); + + migrationBuilder.AddColumn( + name: "ShouldKeepDownloadingWhilePaused", + table: "UserSettings", + type: "INTEGER", + nullable: false, + defaultValue: true) + .Annotation("Relational:ColumnOrder", 14); + + migrationBuilder.AddColumn( + name: "StreamingQuality", + table: "UserSettings", + type: "INTEGER", + nullable: false, + defaultValue: 0) + .Annotation("Relational:ColumnOrder", 18); + + migrationBuilder.AddColumn( + name: "Volume", + table: "UserSettings", + type: "REAL", + nullable: false, + defaultValue: 1.0) + .Annotation("Relational:ColumnOrder", 19); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropColumn( + name: "IsGaplessPlaybackEnabled", + table: "UserSettings"); + + migrationBuilder.DropColumn( + name: "IsMuted", + table: "UserSettings"); + + migrationBuilder.DropColumn( + name: "ReplayGainMode", + table: "UserSettings"); + + migrationBuilder.DropColumn( + name: "ShouldAutoplay", + table: "UserSettings"); + + migrationBuilder.DropColumn( + name: "ShouldKeepDownloadingWhilePaused", + table: "UserSettings"); + + migrationBuilder.DropColumn( + name: "StreamingQuality", + table: "UserSettings"); + + migrationBuilder.DropColumn( + name: "Volume", + table: "UserSettings"); + } + } +} diff --git a/src/Lumina.DataAccess/Common/Migrations/20261019182431_AddsMusicPlayHistory.Designer.cs b/src/Lumina.DataAccess/Common/Migrations/20261019182431_AddsMusicPlayHistory.Designer.cs new file mode 100644 index 00000000..cc35b814 --- /dev/null +++ b/src/Lumina.DataAccess/Common/Migrations/20261019182431_AddsMusicPlayHistory.Designer.cs @@ -0,0 +1,3537 @@ +// +using System; +using Lumina.DataAccess.Core.UoW; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace Lumina.DataAccess.Common.Migrations +{ + [DbContext(typeof(LuminaDbContext))] + [Migration("20261019182431_AddsMusicPlayHistory")] + partial class AddsMusicPlayHistory + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder.HasAnnotation("ProductVersion", "10.0.11"); + + modelBuilder.Entity("AlbumGenres", b => + { + b.Property("AlbumId") + .HasColumnType("TEXT"); + + b.Property("GenreId") + .HasColumnType("TEXT"); + + b.HasKey("AlbumId", "GenreId"); + + b.HasIndex("GenreId"); + + b.ToTable("AlbumGenres", (string)null); + }); + + modelBuilder.Entity("AlbumTags", b => + { + b.Property("AlbumId") + .HasColumnType("TEXT"); + + b.Property("TagId") + .HasColumnType("TEXT"); + + b.HasKey("AlbumId", "TagId"); + + b.HasIndex("TagId"); + + b.ToTable("AlbumTags", (string)null); + }); + + modelBuilder.Entity("ArtistGenres", b => + { + b.Property("ArtistId") + .HasColumnType("TEXT"); + + b.Property("GenreId") + .HasColumnType("TEXT"); + + b.HasKey("ArtistId", "GenreId"); + + b.HasIndex("GenreId"); + + b.ToTable("ArtistGenres", (string)null); + }); + + modelBuilder.Entity("ArtistTags", b => + { + b.Property("ArtistId") + .HasColumnType("TEXT"); + + b.Property("TagId") + .HasColumnType("TEXT"); + + b.HasKey("ArtistId", "TagId"); + + b.HasIndex("TagId"); + + b.ToTable("ArtistTags", (string)null); + }); + + modelBuilder.Entity("BookGenres", b => + { + b.Property("BookId") + .HasColumnType("TEXT"); + + b.Property("GenreId") + .HasColumnType("TEXT"); + + b.HasKey("BookId", "GenreId"); + + b.HasIndex("GenreId"); + + b.ToTable("BookGenres", (string)null); + }); + + modelBuilder.Entity("BookTags", b => + { + b.Property("BookId") + .HasColumnType("TEXT"); + + b.Property("TagId") + .HasColumnType("TEXT"); + + b.HasKey("BookId", "TagId"); + + b.HasIndex("TagId"); + + b.ToTable("BookTags", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.PermissionEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("PermissionName") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.HasKey("Id"); + + b.ToTable("Permissions", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.RoleEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("RoleName") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.HasKey("Id"); + + b.ToTable("Roles", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.RolePermissionEntity", b => + { + b.Property("RoleId") + .HasColumnType("TEXT"); + + b.Property("PermissionId") + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.HasKey("RoleId", "PermissionId"); + + b.HasIndex("PermissionId"); + + b.HasIndex("RoleId", "PermissionId") + .IsUnique(); + + b.ToTable("RolePermissions", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.UserPermissionEntity", b => + { + b.Property("UserId") + .HasColumnType("TEXT"); + + b.Property("PermissionId") + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.HasKey("UserId", "PermissionId"); + + b.HasIndex("PermissionId"); + + b.HasIndex("UserId", "PermissionId") + .IsUnique(); + + b.ToTable("UserPermissions", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.UserRoleEntity", b => + { + b.Property("UserId") + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("RoleId") + .HasColumnType("TEXT"); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.HasKey("UserId"); + + b.HasIndex("RoleId"); + + b.HasIndex("UserId", "RoleId") + .IsUnique(); + + b.ToTable("UserRoles", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Common.GenreEntity", b => + { + b.Property("Name") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b.HasKey("Name"); + + b.ToTable("Genres", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Common.TagEntity", b => + { + b.Property("Name") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b.HasKey("Name"); + + b.ToTable("Tags", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaContributors.MediaContributorEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Biography") + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("DateOfBirth") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("DateOfDeath") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("DisplayName") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1) + .UseCollation("NOCASE"); + + b.Property("LegalName") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.HasKey("Id"); + + b.HasIndex("DisplayName") + .IsUnique(); + + b.ToTable("MediaContributors", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumContributorEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("AlbumId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("MediaContributorId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("Role") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.HasKey("Id"); + + b.HasIndex("MediaContributorId"); + + b.HasIndex("AlbumId", "MediaContributorId", "Role") + .IsUnique(); + + b.ToTable("AlbumContributors", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("ASIN") + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(28); + + b.Property("ArtistId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("Barcode") + .HasMaxLength(13) + .HasColumnType("TEXT") + .HasColumnOrder(25); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(33); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(32); + + b.Property("Description") + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("Disambiguation") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("Label") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(27); + + b.Property("LanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("LanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("LanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(15); + + b.Property("LastMetadataUpdateUtc") + .HasColumnType("TEXT") + .HasColumnOrder(37); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("MediaFormat") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(23); + + b.Property("MetadataProvider") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(38); + + b.Property("MetadataStatus") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasDefaultValue("Pending") + .HasColumnOrder(36); + + b.Property("MusicBrainzReleaseArtistId") + .HasColumnType("TEXT") + .HasColumnOrder(31); + + b.Property("MusicBrainzReleaseGroupId") + .HasColumnType("TEXT") + .HasColumnOrder(30); + + b.Property("MusicBrainzReleaseId") + .HasColumnType("TEXT") + .HasColumnOrder(29); + + b.Property("OriginalLanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(16); + + b.Property("OriginalLanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(17); + + b.Property("OriginalLanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(18); + + b.Property("OriginalReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("OriginalReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(8); + + b.Property("OriginalTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("Packaging") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(24); + + b.Property("ReReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("ReReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(10); + + b.Property("ReleaseCountry") + .HasMaxLength(2) + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("ReleaseStatus") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(20); + + b.Property("ReleaseTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(26); + + b.Property("ReleaseVersion") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("Script") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(19); + + b.Property("Title") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("TotalDiscs") + .HasColumnType("INTEGER") + .HasColumnOrder(21); + + b.Property("TotalTracks") + .HasColumnType("INTEGER") + .HasColumnOrder(22); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(35); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(34); + + b.HasKey("Id"); + + b.HasIndex("ArtistId", "Title"); + + b.HasIndex("LibraryId", "Title"); + + b.ToTable("Albums", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistContributorEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("ArtistId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("MediaContributorId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("Role") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.HasKey("Id"); + + b.HasIndex("MediaContributorId"); + + b.HasIndex("ArtistId", "MediaContributorId", "Role") + .IsUnique(); + + b.ToTable("ArtistContributors", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Country") + .HasMaxLength(2) + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("Disambiguation") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("Gender") + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("IsEnded") + .HasColumnType("INTEGER") + .HasColumnOrder(10); + + b.Property("LastMetadataUpdateUtc") + .HasColumnType("TEXT") + .HasColumnOrder(18); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("LifeSpanBegin") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("LifeSpanEnd") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("MetadataProvider") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(19); + + b.Property("MetadataStatus") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasDefaultValue("Pending") + .HasColumnOrder(17); + + b.Property("MusicBrainzArtistId") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("Name") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("SortName") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("Type") + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(16); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(15); + + b.Property("Website") + .HasMaxLength(2048) + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.HasKey("Id"); + + b.HasIndex("LibraryId", "Name") + .IsUnique(); + + b.ToTable("Artists", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.MusicArtworkEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("ArtworkType") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("ContentHash") + .HasColumnType("INTEGER") + .HasColumnOrder(6); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("FileName") + .HasMaxLength(2048) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("LastUpdateUtc") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("Ordinal") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("OwnerId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("OwnerType") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("Provider") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("Status") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.HasKey("Id"); + + b.HasIndex("Status"); + + b.HasIndex("OwnerType", "OwnerId", "ArtworkType", "Ordinal") + .IsUnique(); + + b.ToTable("MusicArtwork", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.MusicLibraryScanItemMetadataEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("AcoustId") + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnOrder(25); + + b.Property("ArtistName") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("AudioCodec") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(15); + + b.Property("BitDepth") + .HasColumnType("INTEGER") + .HasColumnOrder(14); + + b.Property("Bitrate") + .HasColumnType("INTEGER") + .HasColumnOrder(16); + + b.Property("Channels") + .HasColumnType("INTEGER") + .HasColumnOrder(13); + + b.Property("Container") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(31); + + b.Property("DiscNumber") + .HasColumnType("INTEGER") + .HasColumnOrder(10); + + b.Property("DurationInSeconds") + .HasColumnType("INTEGER") + .HasColumnOrder(11); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("LibraryScanId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.PrimitiveCollection("Moods") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(30); + + b.Property("MusicBrainzArtistId") + .HasColumnType("TEXT") + .HasColumnOrder(17); + + b.Property("MusicBrainzRecordingId") + .HasColumnType("TEXT") + .HasColumnOrder(21); + + b.Property("MusicBrainzReleaseArtistId") + .HasColumnType("TEXT") + .HasColumnOrder(18); + + b.Property("MusicBrainzReleaseGroupId") + .HasColumnType("TEXT") + .HasColumnOrder(19); + + b.Property("MusicBrainzReleaseId") + .HasColumnType("TEXT") + .HasColumnOrder(20); + + b.Property("MusicBrainzTrackId") + .HasColumnType("TEXT") + .HasColumnOrder(22); + + b.Property("MusicBrainzWorkId") + .HasColumnType("TEXT") + .HasColumnOrder(23); + + b.Property("Path") + .IsRequired() + .HasMaxLength(2048) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("ReleaseName") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("ReleaseType") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("ReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(6); + + b.Property("ReplayGainAlbumGain") + .HasColumnType("decimal(8,2)") + .HasColumnOrder(28); + + b.Property("ReplayGainAlbumPeak") + .HasColumnType("decimal(8,6)") + .HasColumnOrder(29); + + b.Property("ReplayGainTrackGain") + .HasColumnType("decimal(8,2)") + .HasColumnOrder(26); + + b.Property("ReplayGainTrackPeak") + .HasColumnType("decimal(8,6)") + .HasColumnOrder(27); + + b.Property("SampleRate") + .HasColumnType("INTEGER") + .HasColumnOrder(12); + + b.Property("TrackNumber") + .HasColumnType("INTEGER") + .HasColumnOrder(9); + + b.Property("TrackTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("WorkTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(24); + + b.HasKey("Id"); + + b.HasIndex("LibraryScanId", "Path") + .IsUnique(); + + b.ToTable("MusicLibraryScanItemMetadata", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.MusicPlayRecordEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("AlbumId") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("ArtistId") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("EndedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("LastPositionMilliseconds") + .HasColumnType("INTEGER") + .HasColumnOrder(7); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("ListenedDurationMilliseconds") + .HasColumnType("INTEGER") + .HasColumnOrder(8); + + b.Property("Status") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("TrackId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("UserId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("Version") + .IsConcurrencyToken() + .HasColumnType("INTEGER") + .HasColumnOrder(10); + + b.HasKey("Id"); + + b.HasIndex("TrackId"); + + b.HasIndex("UserId", "CreatedOnUtc"); + + b.ToTable("MusicPlayRecords", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackContributorEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("MediaContributorId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("Role") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("TrackId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.HasKey("Id"); + + b.HasIndex("MediaContributorId"); + + b.HasIndex("TrackId", "MediaContributorId", "Role") + .IsUnique(); + + b.ToTable("TrackContributors", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("AcoustId") + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnOrder(44); + + b.Property("AlbumId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("AudioCodec") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(24); + + b.Property("BitDepth") + .HasColumnType("INTEGER") + .HasColumnOrder(23); + + b.Property("Bitrate") + .HasColumnType("INTEGER") + .HasColumnOrder(25); + + b.Property("Bpm") + .HasColumnType("INTEGER") + .HasColumnOrder(30); + + b.Property("Channels") + .HasColumnType("INTEGER") + .HasColumnOrder(22); + + b.Property("Container") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(49); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(38); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(37); + + b.Property("Description") + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("Disambiguation") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("DiscNumber") + .HasColumnType("INTEGER") + .HasColumnOrder(27); + + b.Property("DurationInSeconds") + .HasColumnType("INTEGER") + .HasColumnOrder(20); + + b.Property("IsVideo") + .HasColumnType("INTEGER") + .HasColumnOrder(31); + + b.Property("Key") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(29); + + b.Property("LanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("LanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(15); + + b.Property("LanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(16); + + b.Property("LastMetadataUpdateUtc") + .HasColumnType("TEXT") + .HasColumnOrder(42); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("MetadataProvider") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(43); + + b.Property("MetadataStatus") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasDefaultValue("Pending") + .HasColumnOrder(41); + + b.Property("MusicBrainzRecordingId") + .HasColumnType("TEXT") + .HasColumnOrder(34); + + b.Property("MusicBrainzTrackId") + .HasColumnType("TEXT") + .HasColumnOrder(35); + + b.Property("MusicBrainzWorkId") + .HasColumnType("TEXT") + .HasColumnOrder(36); + + b.Property("OriginalLanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(17); + + b.Property("OriginalLanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(18); + + b.Property("OriginalLanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(19); + + b.Property("OriginalReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("OriginalReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(9); + + b.Property("OriginalTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("Path") + .IsRequired() + .HasMaxLength(2048) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("ReReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("ReReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(11); + + b.Property("ReleaseCountry") + .HasMaxLength(2) + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("ReleaseVersion") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("ReplayGainAlbumGain") + .HasColumnType("decimal(8,2)") + .HasColumnOrder(47); + + b.Property("ReplayGainAlbumPeak") + .HasColumnType("decimal(8,6)") + .HasColumnOrder(48); + + b.Property("ReplayGainTrackGain") + .HasColumnType("decimal(8,2)") + .HasColumnOrder(45); + + b.Property("ReplayGainTrackPeak") + .HasColumnType("decimal(8,6)") + .HasColumnOrder(46); + + b.Property("SampleRate") + .HasColumnType("INTEGER") + .HasColumnOrder(21); + + b.Property("Script") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(28); + + b.Property("Title") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("TrackNumber") + .HasColumnType("INTEGER") + .HasColumnOrder(26); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(40); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(39); + + b.Property("WorkTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(32); + + b.Property("WorkType") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(33); + + b.HasKey("Id"); + + b.HasIndex("AlbumId", "TrackNumber"); + + b.HasIndex("LibraryId", "Path") + .IsUnique(); + + b.ToTable("Tracks", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.DirectoryScanFingerprintEntity", b => + { + b.Property("LibraryId") + .HasColumnType("TEXT"); + + b.Property("Path") + .HasMaxLength(1024) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("LastWriteTimeUtc") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.HasKey("LibraryId", "Path"); + + b.HasIndex("LibraryId"); + + b.ToTable("DirectoryScanFingerprints", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("ArtworkProvidersConfigurationFingerprint") + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("CanDownloadMetadataFromWeb") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(true) + .HasColumnOrder(6); + + b.Property("CoverImage") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("IsEnabled") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(true) + .HasColumnOrder(4); + + b.Property("IsLocked") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("LibraryType") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("MetadataProvidersConfigurationFingerprint") + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("PathTemplateFingerprint") + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("ShouldSaveMetadataInMediaDirectories") + .HasColumnType("INTEGER") + .HasColumnOrder(7); + + b.Property("ShouldSkipUnchangedDirectoriesDuringScan") + .HasColumnType("INTEGER") + .HasColumnOrder(8); + + b.Property("Title") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(15); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("UserId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("Libraries", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("LibraryId") + .HasColumnType("TEXT"); + + b.Property("Status") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UserId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.HasIndex("LibraryId", "Status", "CreatedOnUtc") + .IsDescending(true, false, true); + + b.ToTable("LibraryScans", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanResultEntity", b => + { + b.Property("LibraryScanId") + .HasColumnType("TEXT"); + + b.Property("Path") + .HasMaxLength(1024) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("ContentHash") + .HasMaxLength(24) + .HasColumnType("INTEGER") + .HasColumnOrder(2); + + b.Property("FileSize") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Status") + .IsRequired() + .HasMaxLength(10) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("Ticks") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.HasKey("LibraryScanId", "Path"); + + b.HasIndex("Path"); + + b.HasIndex("ContentHash", "FileSize", "Path"); + + b.ToTable("LibraryScanResults", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanSnapshotEntity", b => + { + b.Property("LibraryId") + .HasColumnType("TEXT"); + + b.Property("Path") + .HasMaxLength(1024) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("ContentHash") + .HasColumnType("INTEGER") + .HasColumnOrder(2); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("FileSize") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Ticks") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.HasKey("LibraryId", "Path"); + + b.HasIndex("LibraryId"); + + b.ToTable("LibraryScanSnapshots", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanStagingResultsEntity", b => + { + b.Property("LibraryScanId") + .HasColumnType("TEXT"); + + b.Property("Path") + .HasMaxLength(1024) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("ContentHash") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("IsNew") + .HasColumnType("INTEGER") + .HasColumnOrder(7); + + b.Property("NeedsRehash") + .HasColumnType("INTEGER") + .HasColumnOrder(6); + + b.Property("PreviousContentHash") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("Size") + .HasColumnType("INTEGER") + .HasColumnOrder(2); + + b.Property("Ticks") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.HasKey("LibraryScanId", "Path"); + + b.HasIndex("LibraryScanId", "NeedsRehash"); + + b.ToTable("LibraryScanStagingResults", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookArtworkEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("ArtworkType") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("BookId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("ContentHash") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("FileName") + .HasMaxLength(2048) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("LastUpdateUtc") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("Ordinal") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("Provider") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("Status") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.HasKey("Id"); + + b.HasIndex("Status"); + + b.HasIndex("BookId", "ArtworkType", "Ordinal") + .IsUnique(); + + b.ToTable("BookArtwork", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookContributorEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("BookId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("MediaContributorId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("Role") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.HasKey("Id"); + + b.HasIndex("MediaContributorId"); + + b.HasIndex("BookId", "MediaContributorId", "Role") + .IsUnique(); + + b.ToTable("BookContributors", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("ASIN") + .HasMaxLength(10) + .HasColumnType("TEXT") + .HasColumnOrder(21); + + b.Property("AppleBooksId") + .HasColumnType("TEXT") + .HasColumnOrder(29); + + b.Property("BarnesAndNobleId") + .HasMaxLength(10) + .HasColumnType("TEXT") + .HasColumnOrder(28); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(33); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(32); + + b.Property("Description") + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("Edition") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(19); + + b.Property("Format") + .HasColumnType("TEXT") + .HasColumnOrder(18); + + b.Property("GoodreadsId") + .HasColumnType("TEXT") + .HasColumnOrder(22); + + b.Property("GoogleBooksId") + .HasMaxLength(12) + .HasColumnType("TEXT") + .HasColumnOrder(27); + + b.Property("LCCN") + .HasColumnType("TEXT") + .HasColumnOrder(23); + + b.Property("LanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("LanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("LanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("LastMetadataUpdateUtc") + .HasColumnType("TEXT") + .HasColumnOrder(39); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(36); + + b.Property("LibraryThingId") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(26); + + b.Property("MetadataProvider") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(40); + + b.Property("MetadataStatus") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(38); + + b.Property("OCLCNumber") + .HasColumnType("TEXT") + .HasColumnOrder(24); + + b.Property("OpenLibraryId") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(25); + + b.Property("OriginalLanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("OriginalLanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("OriginalLanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(15); + + b.Property("OriginalReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("OriginalReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("OriginalTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("PageCount") + .HasColumnType("INTEGER") + .HasColumnOrder(17); + + b.Property("Path") + .IsRequired() + .HasMaxLength(2048) + .HasColumnType("TEXT") + .HasColumnOrder(37); + + b.Property("Publisher") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(16); + + b.Property("ReReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("ReReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(7); + + b.Property("ReleaseCountry") + .HasMaxLength(2) + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("ReleaseVersion") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("Title") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(35); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(34); + + b.Property("VolumeNumber") + .HasColumnType("REAL") + .HasColumnOrder(20); + + b.HasKey("Id"); + + b.HasIndex("LibraryId", "MetadataStatus"); + + b.HasIndex("LibraryId", "Path") + .IsUnique(); + + b.ToTable("Books", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Plugins.LibraryArtworkProviderConfigurationEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("IsEnabled") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("PluginId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("Rank") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.HasKey("Id"); + + b.HasIndex("LibraryId", "PluginId"); + + b.ToTable("LibraryArtworkProviderConfigurations", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Plugins.LibraryBookReaderConfigurationEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("IsEnabled") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("PluginId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.HasKey("Id"); + + b.HasIndex("LibraryId", "PluginId") + .IsUnique(); + + b.ToTable("LibraryBookReaderConfigurations", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Plugins.LibraryMetadataProviderConfigurationEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("IsEnabled") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("PluginId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("Rank") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.HasKey("Id"); + + b.HasIndex("LibraryId", "PluginId"); + + b.ToTable("LibraryMetadataProviderConfigurations", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Plugins.PluginEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Author") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("Description") + .IsRequired() + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("LoadError") + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("LoadStatus") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("Name") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("SettingsJson") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("Version") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.HasKey("Id"); + + b.ToTable("Plugins", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Scheduling.ScheduledJobEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("Hour") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("IntervalMinutes") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("LastCompletedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("LastStartedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("Minute") + .HasColumnType("INTEGER") + .HasColumnOrder(6); + + b.Property("Name") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("OwnerUserId") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("ScheduleType") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("Status") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("TaskType") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.HasKey("Id"); + + b.HasIndex("Status"); + + b.ToTable("ScheduledJobs", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Scheduling.ScheduledJobExecutionEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CompletedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("IsCycleRun") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("ScheduledJobId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("StartedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("TaskType") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("WasCycleActive") + .HasColumnType("INTEGER") + .HasColumnOrder(6); + + b.HasKey("Id"); + + b.HasIndex("ScheduledJobId"); + + b.HasIndex("StartedOnUtc", "ScheduledJobId"); + + b.ToTable("ScheduledJobExecutions", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Scheduling.SchedulerDisplayPreferencesEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("DisplayTimeSpan") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("DisplayTimeUnit") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("JobTypeFilter") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UserId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.HasKey("Id"); + + b.HasIndex("UserId") + .IsUnique(); + + b.ToTable("SchedulerDisplayPreferences", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Themes.ThemeEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Author") + .IsRequired() + .HasMaxLength(80) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("Description") + .IsRequired() + .HasMaxLength(300) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("InstallSource") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("InstalledAtUtc") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("IsCurrent") + .HasColumnType("INTEGER") + .HasColumnOrder(8); + + b.Property("IsDeleted") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(false) + .HasColumnOrder(9); + + b.Property("Name") + .IsRequired() + .HasMaxLength(80) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("PreviewPath") + .HasMaxLength(240) + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("ThemeId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("Version") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.HasKey("Id"); + + b.HasIndex("IsCurrent") + .IsUnique() + .HasFilter("IsCurrent = 1"); + + b.HasIndex("ThemeId") + .IsUnique(); + + b.ToTable("Themes", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("Password") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("TempPassword") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("TempPasswordCreated") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("TotpSecret") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("Username") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.HasKey("Id"); + + b.HasIndex("Username") + .IsUnique(); + + b.ToTable("Users", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserSettingsEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("IsGaplessPlaybackEnabled") + .HasColumnType("INTEGER") + .HasColumnOrder(16); + + b.Property("IsMuted") + .HasColumnType("INTEGER") + .HasColumnOrder(20); + + b.Property("IsPaginationEnabled") + .HasColumnType("INTEGER") + .HasColumnOrder(2); + + b.Property("IsThemeCachingEnabled") + .HasColumnType("INTEGER") + .HasColumnOrder(9); + + b.Property("ItemsPerPage") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("ReplayGainMode") + .HasColumnType("INTEGER") + .HasColumnOrder(17); + + b.Property("ShouldAggregateArtworkWhenMissing") + .HasColumnType("INTEGER") + .HasColumnOrder(13); + + b.Property("ShouldAggregateMetadataWhenMissing") + .HasColumnType("INTEGER") + .HasColumnOrder(10); + + b.Property("ShouldAutoplay") + .HasColumnType("INTEGER") + .HasColumnOrder(15); + + b.Property("ShouldIgnoreThePrefixForAlphaPicker") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("ShouldKeepDownloadingWhilePaused") + .HasColumnType("INTEGER") + .HasColumnOrder(14); + + b.Property("ShouldPreserveBookStyles") + .HasColumnType("INTEGER") + .HasColumnOrder(12); + + b.Property("ShouldRenderPdfAsImages") + .HasColumnType("INTEGER") + .HasColumnOrder(11); + + b.Property("StreamingQuality") + .HasColumnType("INTEGER") + .HasColumnOrder(18); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UserId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("Volume") + .HasColumnType("REAL") + .HasColumnOrder(19); + + b.HasKey("Id"); + + b.HasIndex("UserId") + .IsUnique(); + + b.ToTable("UserSettings", (string)null); + }); + + modelBuilder.Entity("TrackGenres", b => + { + b.Property("TrackId") + .HasColumnType("TEXT"); + + b.Property("GenreId") + .HasColumnType("TEXT"); + + b.HasKey("TrackId", "GenreId"); + + b.HasIndex("GenreId"); + + b.ToTable("TrackGenres", (string)null); + }); + + modelBuilder.Entity("TrackTags", b => + { + b.Property("TrackId") + .HasColumnType("TEXT"); + + b.Property("TagId") + .HasColumnType("TEXT"); + + b.HasKey("TrackId", "TagId"); + + b.HasIndex("TagId"); + + b.ToTable("TrackTags", (string)null); + }); + + modelBuilder.Entity("AlbumGenres", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumEntity", null) + .WithMany() + .HasForeignKey("AlbumId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.GenreEntity", null) + .WithMany() + .HasForeignKey("GenreId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("AlbumTags", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumEntity", null) + .WithMany() + .HasForeignKey("AlbumId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.TagEntity", null) + .WithMany() + .HasForeignKey("TagId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("ArtistGenres", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistEntity", null) + .WithMany() + .HasForeignKey("ArtistId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.GenreEntity", null) + .WithMany() + .HasForeignKey("GenreId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("ArtistTags", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistEntity", null) + .WithMany() + .HasForeignKey("ArtistId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.TagEntity", null) + .WithMany() + .HasForeignKey("TagId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BookGenres", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", null) + .WithMany() + .HasForeignKey("BookId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.GenreEntity", null) + .WithMany() + .HasForeignKey("GenreId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BookTags", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", null) + .WithMany() + .HasForeignKey("BookId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.TagEntity", null) + .WithMany() + .HasForeignKey("TagId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.RolePermissionEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Authorization.PermissionEntity", "Permission") + .WithMany("RolePermissions") + .HasForeignKey("PermissionId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Authorization.RoleEntity", "Role") + .WithMany("RolePermissions") + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Permission"); + + b.Navigation("Role"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.UserPermissionEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Authorization.PermissionEntity", "Permission") + .WithMany("UserPermissions") + .HasForeignKey("PermissionId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", "User") + .WithMany("UserPermissions") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Permission"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.UserRoleEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Authorization.RoleEntity", "Role") + .WithMany("UserRoles") + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", "User") + .WithOne("UserRole") + .HasForeignKey("Lumina.Application.Common.DataAccess.Entities.Authorization.UserRoleEntity", "UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Role"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumContributorEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumEntity", null) + .WithMany("Contributors") + .HasForeignKey("AlbumId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistEntity", "Artist") + .WithMany("Albums") + .HasForeignKey("ArtistId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumCatalogNumberEntity", "CatalogNumbers", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("AlbumId") + .HasColumnType("TEXT"); + + b1.Property("CatalogNumber") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("AlbumId"); + + b1.ToTable("AlbumCatalogNumbers", (string)null); + + b1.WithOwner() + .HasForeignKey("AlbumId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AudioRatingEntity", "Ratings", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("AlbumId") + .HasColumnType("TEXT"); + + b1.Property("MaxValue") + .HasColumnType("decimal(3,2)"); + + b1.Property("Source") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.Property("Value") + .HasColumnType("decimal(3,2)"); + + b1.Property("VoteCount") + .HasColumnType("INTEGER"); + + b1.HasKey("Id"); + + b1.HasIndex("AlbumId"); + + b1.ToTable("AlbumRatings", (string)null); + + b1.WithOwner() + .HasForeignKey("AlbumId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumReleaseTypeEntity", "ReleaseTypes", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("AlbumId") + .HasColumnType("TEXT"); + + b1.Property("ReleaseType") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("AlbumId"); + + b1.ToTable("AlbumReleaseTypes", (string)null); + + b1.WithOwner() + .HasForeignKey("AlbumId"); + }); + + b.Navigation("Artist"); + + b.Navigation("CatalogNumbers"); + + b.Navigation("Ratings"); + + b.Navigation("ReleaseTypes"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistContributorEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistEntity", null) + .WithMany("Contributors") + .HasForeignKey("ArtistId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistEntity", b => + { + b.OwnsOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.MusicAreaEntity", "Area", b1 => + { + b1.Property("ArtistEntityId"); + + b1.Property("Disambiguation"); + + b1.Property("Iso3166Code"); + + b1.Property("MusicBrainzAreaId"); + + b1.Property("Name") + .IsRequired(); + + b1.Property("SortName"); + + b1.Property("Type"); + + b1.HasKey("ArtistEntityId"); + + b1.ToTable("Artists"); + + b1 + .ToJson("Area") + .HasColumnType("TEXT"); + + b1.WithOwner() + .HasForeignKey("ArtistEntityId"); + }); + + b.OwnsOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.MusicAreaEntity", "BeginArea", b1 => + { + b1.Property("ArtistEntityId"); + + b1.Property("Disambiguation"); + + b1.Property("Iso3166Code"); + + b1.Property("MusicBrainzAreaId"); + + b1.Property("Name") + .IsRequired(); + + b1.Property("SortName"); + + b1.Property("Type"); + + b1.HasKey("ArtistEntityId"); + + b1.ToTable("Artists"); + + b1 + .ToJson("BeginArea") + .HasColumnType("TEXT"); + + b1.WithOwner() + .HasForeignKey("ArtistEntityId"); + }); + + b.OwnsOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.MusicAreaEntity", "EndArea", b1 => + { + b1.Property("ArtistEntityId"); + + b1.Property("Disambiguation"); + + b1.Property("Iso3166Code"); + + b1.Property("MusicBrainzAreaId"); + + b1.Property("Name") + .IsRequired(); + + b1.Property("SortName"); + + b1.Property("Type"); + + b1.HasKey("ArtistEntityId"); + + b1.ToTable("Artists"); + + b1 + .ToJson("EndArea") + .HasColumnType("TEXT"); + + b1.WithOwner() + .HasForeignKey("ArtistEntityId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistAliasEntity", "Aliases", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("ArtistId") + .HasColumnType("TEXT"); + + b1.Property("BeginDate") + .HasColumnType("TEXT"); + + b1.Property("EndDate") + .HasColumnType("TEXT"); + + b1.Property("IsEnded") + .HasColumnType("INTEGER"); + + b1.Property("IsPrimary") + .HasColumnType("INTEGER"); + + b1.Property("Locale") + .HasMaxLength(20) + .HasColumnType("TEXT"); + + b1.Property("Name") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT"); + + b1.Property("SortName") + .HasMaxLength(255) + .HasColumnType("TEXT"); + + b1.Property("Type") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("ArtistId"); + + b1.ToTable("ArtistAliases", (string)null); + + b1.WithOwner() + .HasForeignKey("ArtistId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AudioRatingEntity", "Ratings", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("ArtistId") + .HasColumnType("TEXT"); + + b1.Property("MaxValue") + .HasColumnType("decimal(3,2)"); + + b1.Property("Source") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.Property("Value") + .HasColumnType("decimal(3,2)"); + + b1.Property("VoteCount") + .HasColumnType("INTEGER"); + + b1.HasKey("Id"); + + b1.HasIndex("ArtistId"); + + b1.ToTable("ArtistRatings", (string)null); + + b1.WithOwner() + .HasForeignKey("ArtistId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistIpiEntity", "Ipis", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("ArtistId") + .HasColumnType("TEXT"); + + b1.Property("Value") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("ArtistId"); + + b1.ToTable("ArtistIpis", (string)null); + + b1.WithOwner() + .HasForeignKey("ArtistId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistIsniEntity", "Isnis", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("ArtistId") + .HasColumnType("TEXT"); + + b1.Property("Value") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("ArtistId"); + + b1.ToTable("ArtistIsnis", (string)null); + + b1.WithOwner() + .HasForeignKey("ArtistId"); + }); + + b.Navigation("Aliases"); + + b.Navigation("Area"); + + b.Navigation("BeginArea"); + + b.Navigation("EndArea"); + + b.Navigation("Ipis"); + + b.Navigation("Isnis"); + + b.Navigation("Ratings"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackContributorEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackEntity", null) + .WithMany("Contributors") + .HasForeignKey("TrackId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumEntity", "Album") + .WithMany("Tracks") + .HasForeignKey("AlbumId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AudioRatingEntity", "Ratings", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("MaxValue") + .HasColumnType("decimal(3,2)"); + + b1.Property("Source") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.Property("TrackId") + .HasColumnType("TEXT"); + + b1.Property("Value") + .HasColumnType("decimal(3,2)"); + + b1.Property("VoteCount") + .HasColumnType("INTEGER"); + + b1.HasKey("Id"); + + b1.HasIndex("TrackId"); + + b1.ToTable("TrackRatings", (string)null); + + b1.WithOwner() + .HasForeignKey("TrackId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackIsrcEntity", "Isrcs", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("TrackId") + .HasColumnType("TEXT"); + + b1.Property("Value") + .IsRequired() + .HasMaxLength(12) + .HasColumnType("TEXT") + .HasColumnName("ISRC"); + + b1.HasKey("Id"); + + b1.HasIndex("TrackId"); + + b1.ToTable("TrackIsrcs", (string)null); + + b1.WithOwner() + .HasForeignKey("TrackId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackMoodEntity", "Moods", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("Name") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.Property("TrackId") + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("TrackId"); + + b1.ToTable("TrackMoods", (string)null); + + b1.WithOwner() + .HasForeignKey("TrackId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackWorkIswcEntity", "WorkIswcs", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("TrackId") + .HasColumnType("TEXT"); + + b1.Property("Value") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("TrackId"); + + b1.ToTable("TrackWorkIswcs", (string)null); + + b1.WithOwner() + .HasForeignKey("TrackId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackWorkLanguageEntity", "WorkLanguages", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("LanguageCode") + .IsRequired() + .HasMaxLength(5) + .HasColumnType("TEXT"); + + b1.Property("LanguageName") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("TEXT"); + + b1.Property("NativeName") + .HasMaxLength(100) + .HasColumnType("TEXT"); + + b1.Property("TrackId") + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("TrackId"); + + b1.ToTable("TrackWorkLanguages", (string)null); + + b1.WithOwner() + .HasForeignKey("TrackId"); + }); + + b.Navigation("Album"); + + b.Navigation("Isrcs"); + + b.Navigation("Moods"); + + b.Navigation("Ratings"); + + b.Navigation("WorkIswcs"); + + b.Navigation("WorkLanguages"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.DirectoryScanFingerprintEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", null) + .WithMany() + .HasForeignKey("LibraryId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", "User") + .WithMany("Libraries") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryContentLocationEntity", "ContentLocations", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("LibraryId") + .HasColumnType("TEXT"); + + b1.Property("Path") + .IsRequired() + .HasMaxLength(260) + .HasColumnType("TEXT") + .HasColumnName("Path"); + + b1.HasKey("Id"); + + b1.HasIndex("LibraryId"); + + b1.ToTable("LibraryContentLocations", (string)null); + + b1.WithOwner() + .HasForeignKey("LibraryId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryPathTemplatePartEntity", "PathTemplateParts", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("IsOptional") + .HasColumnType("INTEGER"); + + b1.Property("Kind") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b1.Property("LibraryId") + .HasColumnType("TEXT"); + + b1.Property("Position") + .HasColumnType("INTEGER") + .HasColumnName("Position"); + + b1.Property("Representation") + .IsRequired() + .HasMaxLength(512) + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("LibraryId", "Position") + .IsUnique(); + + b1.ToTable("LibraryPathTemplateParts", (string)null); + + b1.WithOwner() + .HasForeignKey("LibraryId"); + }); + + b.Navigation("ContentLocations"); + + b.Navigation("PathTemplateParts"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", "Library") + .WithMany("LibraryScans") + .HasForeignKey("LibraryId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", "User") + .WithMany("LibraryScans") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Library"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanResultEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", "LibraryScan") + .WithMany("LibraryScanResults") + .HasForeignKey("LibraryScanId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("LibraryScan"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanSnapshotEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", "Library") + .WithMany() + .HasForeignKey("LibraryId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Library"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanStagingResultsEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", null) + .WithMany() + .HasForeignKey("LibraryScanId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookArtworkEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", null) + .WithMany("Artwork") + .HasForeignKey("BookId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookContributorEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", null) + .WithMany("Contributors") + .HasForeignKey("BookId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", b => + { + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookRatingEntity", "Ratings", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("BookId") + .HasColumnType("TEXT"); + + b1.Property("MaxValue") + .HasColumnType("decimal(3,2)"); + + b1.Property("Source") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.Property("Value") + .HasColumnType("decimal(3,2)"); + + b1.Property("VoteCount") + .HasColumnType("INTEGER"); + + b1.HasKey("Id"); + + b1.HasIndex("BookId"); + + b1.ToTable("BookRatings", (string)null); + + b1.WithOwner() + .HasForeignKey("BookId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.IsbnEntity", "ISBNs", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("BookId") + .HasColumnType("TEXT"); + + b1.Property("Format") + .IsRequired() + .HasMaxLength(6) + .HasColumnType("TEXT"); + + b1.Property("Value") + .IsRequired() + .HasMaxLength(13) + .HasColumnType("TEXT") + .HasColumnName("ISBN"); + + b1.HasKey("Id"); + + b1.HasIndex("BookId"); + + b1.ToTable("BookISBNs", (string)null); + + b1.WithOwner() + .HasForeignKey("BookId"); + }); + + b.Navigation("ISBNs"); + + b.Navigation("Ratings"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserSettingsEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", null) + .WithOne() + .HasForeignKey("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserSettingsEntity", "UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("TrackGenres", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.GenreEntity", null) + .WithMany() + .HasForeignKey("GenreId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackEntity", null) + .WithMany() + .HasForeignKey("TrackId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("TrackTags", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.TagEntity", null) + .WithMany() + .HasForeignKey("TagId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackEntity", null) + .WithMany() + .HasForeignKey("TrackId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.PermissionEntity", b => + { + b.Navigation("RolePermissions"); + + b.Navigation("UserPermissions"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.RoleEntity", b => + { + b.Navigation("RolePermissions"); + + b.Navigation("UserRoles"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumEntity", b => + { + b.Navigation("Contributors"); + + b.Navigation("Tracks"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistEntity", b => + { + b.Navigation("Albums"); + + b.Navigation("Contributors"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackEntity", b => + { + b.Navigation("Contributors"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", b => + { + b.Navigation("LibraryScans"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", b => + { + b.Navigation("LibraryScanResults"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", b => + { + b.Navigation("Artwork"); + + b.Navigation("Contributors"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", b => + { + b.Navigation("Libraries"); + + b.Navigation("LibraryScans"); + + b.Navigation("UserPermissions"); + + b.Navigation("UserRole"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/Lumina.DataAccess/Common/Migrations/20261019182431_AddsMusicPlayHistory.cs b/src/Lumina.DataAccess/Common/Migrations/20261019182431_AddsMusicPlayHistory.cs new file mode 100644 index 00000000..3122c9a3 --- /dev/null +++ b/src/Lumina.DataAccess/Common/Migrations/20261019182431_AddsMusicPlayHistory.cs @@ -0,0 +1,57 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Lumina.DataAccess.Common.Migrations +{ + /// + public partial class AddsMusicPlayHistory : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "MusicPlayRecords", + columns: table => new + { + Id = table.Column(type: "TEXT", nullable: false), + UserId = table.Column(type: "TEXT", nullable: false), + TrackId = table.Column(type: "TEXT", nullable: false), + LibraryId = table.Column(type: "TEXT", nullable: false), + AlbumId = table.Column(type: "TEXT", nullable: false), + ArtistId = table.Column(type: "TEXT", nullable: false), + Status = table.Column(type: "TEXT", maxLength: 20, nullable: false), + LastPositionMilliseconds = table.Column(type: "INTEGER", nullable: false), + ListenedDurationMilliseconds = table.Column(type: "INTEGER", nullable: false), + EndedOnUtc = table.Column(type: "TEXT", nullable: true), + Version = table.Column(type: "INTEGER", nullable: false), + CreatedOnUtc = table.Column(type: "TEXT", nullable: false), + CreatedBy = table.Column(type: "TEXT", nullable: false), + UpdatedOnUtc = table.Column(type: "TEXT", nullable: true), + UpdatedBy = table.Column(type: "TEXT", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_MusicPlayRecords", x => x.Id); + }); + + migrationBuilder.CreateIndex( + name: "IX_MusicPlayRecords_TrackId", + table: "MusicPlayRecords", + column: "TrackId"); + + migrationBuilder.CreateIndex( + name: "IX_MusicPlayRecords_UserId_CreatedOnUtc", + table: "MusicPlayRecords", + columns: new[] { "UserId", "CreatedOnUtc" }); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "MusicPlayRecords"); + } + } +} diff --git a/src/Lumina.DataAccess/Common/Migrations/20261021090430_AddsPlaylists.Designer.cs b/src/Lumina.DataAccess/Common/Migrations/20261021090430_AddsPlaylists.Designer.cs new file mode 100644 index 00000000..fba99e07 --- /dev/null +++ b/src/Lumina.DataAccess/Common/Migrations/20261021090430_AddsPlaylists.Designer.cs @@ -0,0 +1,3673 @@ +// +using System; +using Lumina.DataAccess.Core.UoW; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace Lumina.DataAccess.Common.Migrations +{ + [DbContext(typeof(LuminaDbContext))] + [Migration("20261021090430_AddsPlaylists")] + partial class AddsPlaylists + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder.HasAnnotation("ProductVersion", "10.0.11"); + + modelBuilder.Entity("AlbumGenres", b => + { + b.Property("AlbumId") + .HasColumnType("TEXT"); + + b.Property("GenreId") + .HasColumnType("TEXT"); + + b.HasKey("AlbumId", "GenreId"); + + b.HasIndex("GenreId"); + + b.ToTable("AlbumGenres", (string)null); + }); + + modelBuilder.Entity("AlbumTags", b => + { + b.Property("AlbumId") + .HasColumnType("TEXT"); + + b.Property("TagId") + .HasColumnType("TEXT"); + + b.HasKey("AlbumId", "TagId"); + + b.HasIndex("TagId"); + + b.ToTable("AlbumTags", (string)null); + }); + + modelBuilder.Entity("ArtistGenres", b => + { + b.Property("ArtistId") + .HasColumnType("TEXT"); + + b.Property("GenreId") + .HasColumnType("TEXT"); + + b.HasKey("ArtistId", "GenreId"); + + b.HasIndex("GenreId"); + + b.ToTable("ArtistGenres", (string)null); + }); + + modelBuilder.Entity("ArtistTags", b => + { + b.Property("ArtistId") + .HasColumnType("TEXT"); + + b.Property("TagId") + .HasColumnType("TEXT"); + + b.HasKey("ArtistId", "TagId"); + + b.HasIndex("TagId"); + + b.ToTable("ArtistTags", (string)null); + }); + + modelBuilder.Entity("BookGenres", b => + { + b.Property("BookId") + .HasColumnType("TEXT"); + + b.Property("GenreId") + .HasColumnType("TEXT"); + + b.HasKey("BookId", "GenreId"); + + b.HasIndex("GenreId"); + + b.ToTable("BookGenres", (string)null); + }); + + modelBuilder.Entity("BookTags", b => + { + b.Property("BookId") + .HasColumnType("TEXT"); + + b.Property("TagId") + .HasColumnType("TEXT"); + + b.HasKey("BookId", "TagId"); + + b.HasIndex("TagId"); + + b.ToTable("BookTags", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.PermissionEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("PermissionName") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.HasKey("Id"); + + b.ToTable("Permissions", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.RoleEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("RoleName") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.HasKey("Id"); + + b.ToTable("Roles", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.RolePermissionEntity", b => + { + b.Property("RoleId") + .HasColumnType("TEXT"); + + b.Property("PermissionId") + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.HasKey("RoleId", "PermissionId"); + + b.HasIndex("PermissionId"); + + b.HasIndex("RoleId", "PermissionId") + .IsUnique(); + + b.ToTable("RolePermissions", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.UserPermissionEntity", b => + { + b.Property("UserId") + .HasColumnType("TEXT"); + + b.Property("PermissionId") + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.HasKey("UserId", "PermissionId"); + + b.HasIndex("PermissionId"); + + b.HasIndex("UserId", "PermissionId") + .IsUnique(); + + b.ToTable("UserPermissions", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.UserRoleEntity", b => + { + b.Property("UserId") + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("RoleId") + .HasColumnType("TEXT"); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.HasKey("UserId"); + + b.HasIndex("RoleId"); + + b.HasIndex("UserId", "RoleId") + .IsUnique(); + + b.ToTable("UserRoles", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Common.GenreEntity", b => + { + b.Property("Name") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b.HasKey("Name"); + + b.ToTable("Genres", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Common.TagEntity", b => + { + b.Property("Name") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b.HasKey("Name"); + + b.ToTable("Tags", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaContributors.MediaContributorEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Biography") + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("DateOfBirth") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("DateOfDeath") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("DisplayName") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1) + .UseCollation("NOCASE"); + + b.Property("LegalName") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.HasKey("Id"); + + b.HasIndex("DisplayName") + .IsUnique(); + + b.ToTable("MediaContributors", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumContributorEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("AlbumId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("MediaContributorId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("Role") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.HasKey("Id"); + + b.HasIndex("MediaContributorId"); + + b.HasIndex("AlbumId", "MediaContributorId", "Role") + .IsUnique(); + + b.ToTable("AlbumContributors", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("ASIN") + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(28); + + b.Property("ArtistId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("Barcode") + .HasMaxLength(13) + .HasColumnType("TEXT") + .HasColumnOrder(25); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(33); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(32); + + b.Property("Description") + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("Disambiguation") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("Label") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(27); + + b.Property("LanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("LanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("LanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(15); + + b.Property("LastMetadataUpdateUtc") + .HasColumnType("TEXT") + .HasColumnOrder(37); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("MediaFormat") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(23); + + b.Property("MetadataProvider") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(38); + + b.Property("MetadataStatus") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasDefaultValue("Pending") + .HasColumnOrder(36); + + b.Property("MusicBrainzReleaseArtistId") + .HasColumnType("TEXT") + .HasColumnOrder(31); + + b.Property("MusicBrainzReleaseGroupId") + .HasColumnType("TEXT") + .HasColumnOrder(30); + + b.Property("MusicBrainzReleaseId") + .HasColumnType("TEXT") + .HasColumnOrder(29); + + b.Property("OriginalLanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(16); + + b.Property("OriginalLanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(17); + + b.Property("OriginalLanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(18); + + b.Property("OriginalReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("OriginalReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(8); + + b.Property("OriginalTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("Packaging") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(24); + + b.Property("ReReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("ReReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(10); + + b.Property("ReleaseCountry") + .HasMaxLength(2) + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("ReleaseStatus") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(20); + + b.Property("ReleaseTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(26); + + b.Property("ReleaseVersion") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("Script") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(19); + + b.Property("Title") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("TotalDiscs") + .HasColumnType("INTEGER") + .HasColumnOrder(21); + + b.Property("TotalTracks") + .HasColumnType("INTEGER") + .HasColumnOrder(22); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(35); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(34); + + b.HasKey("Id"); + + b.HasIndex("ArtistId", "Title"); + + b.HasIndex("LibraryId", "Title"); + + b.ToTable("Albums", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistContributorEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("ArtistId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("MediaContributorId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("Role") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.HasKey("Id"); + + b.HasIndex("MediaContributorId"); + + b.HasIndex("ArtistId", "MediaContributorId", "Role") + .IsUnique(); + + b.ToTable("ArtistContributors", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Country") + .HasMaxLength(2) + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("Disambiguation") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("Gender") + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("IsEnded") + .HasColumnType("INTEGER") + .HasColumnOrder(10); + + b.Property("LastMetadataUpdateUtc") + .HasColumnType("TEXT") + .HasColumnOrder(18); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("LifeSpanBegin") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("LifeSpanEnd") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("MetadataProvider") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(19); + + b.Property("MetadataStatus") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasDefaultValue("Pending") + .HasColumnOrder(17); + + b.Property("MusicBrainzArtistId") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("Name") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("SortName") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("Type") + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(16); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(15); + + b.Property("Website") + .HasMaxLength(2048) + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.HasKey("Id"); + + b.HasIndex("LibraryId", "Name") + .IsUnique(); + + b.ToTable("Artists", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.MusicArtworkEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("ArtworkType") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("ContentHash") + .HasColumnType("INTEGER") + .HasColumnOrder(6); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("FileName") + .HasMaxLength(2048) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("LastUpdateUtc") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("Ordinal") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("OwnerId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("OwnerType") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("Provider") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("Status") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.HasKey("Id"); + + b.HasIndex("Status"); + + b.HasIndex("OwnerType", "OwnerId", "ArtworkType", "Ordinal") + .IsUnique(); + + b.ToTable("MusicArtwork", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.MusicLibraryScanItemMetadataEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("AcoustId") + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnOrder(25); + + b.Property("ArtistName") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("AudioCodec") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(15); + + b.Property("BitDepth") + .HasColumnType("INTEGER") + .HasColumnOrder(14); + + b.Property("Bitrate") + .HasColumnType("INTEGER") + .HasColumnOrder(16); + + b.Property("Channels") + .HasColumnType("INTEGER") + .HasColumnOrder(13); + + b.Property("Container") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(31); + + b.Property("DiscNumber") + .HasColumnType("INTEGER") + .HasColumnOrder(10); + + b.Property("DurationInSeconds") + .HasColumnType("INTEGER") + .HasColumnOrder(11); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("LibraryScanId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.PrimitiveCollection("Moods") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(30); + + b.Property("MusicBrainzArtistId") + .HasColumnType("TEXT") + .HasColumnOrder(17); + + b.Property("MusicBrainzRecordingId") + .HasColumnType("TEXT") + .HasColumnOrder(21); + + b.Property("MusicBrainzReleaseArtistId") + .HasColumnType("TEXT") + .HasColumnOrder(18); + + b.Property("MusicBrainzReleaseGroupId") + .HasColumnType("TEXT") + .HasColumnOrder(19); + + b.Property("MusicBrainzReleaseId") + .HasColumnType("TEXT") + .HasColumnOrder(20); + + b.Property("MusicBrainzTrackId") + .HasColumnType("TEXT") + .HasColumnOrder(22); + + b.Property("MusicBrainzWorkId") + .HasColumnType("TEXT") + .HasColumnOrder(23); + + b.Property("Path") + .IsRequired() + .HasMaxLength(2048) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("ReleaseName") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("ReleaseType") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("ReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(6); + + b.Property("ReplayGainAlbumGain") + .HasColumnType("decimal(8,2)") + .HasColumnOrder(28); + + b.Property("ReplayGainAlbumPeak") + .HasColumnType("decimal(8,6)") + .HasColumnOrder(29); + + b.Property("ReplayGainTrackGain") + .HasColumnType("decimal(8,2)") + .HasColumnOrder(26); + + b.Property("ReplayGainTrackPeak") + .HasColumnType("decimal(8,6)") + .HasColumnOrder(27); + + b.Property("SampleRate") + .HasColumnType("INTEGER") + .HasColumnOrder(12); + + b.Property("TrackNumber") + .HasColumnType("INTEGER") + .HasColumnOrder(9); + + b.Property("TrackTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("WorkTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(24); + + b.HasKey("Id"); + + b.HasIndex("LibraryScanId", "Path") + .IsUnique(); + + b.ToTable("MusicLibraryScanItemMetadata", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.MusicPlayRecordEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("AlbumId") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("ArtistId") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("EndedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("LastPositionMilliseconds") + .HasColumnType("INTEGER") + .HasColumnOrder(7); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("ListenedDurationMilliseconds") + .HasColumnType("INTEGER") + .HasColumnOrder(8); + + b.Property("Status") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("TrackId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("UserId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("Version") + .IsConcurrencyToken() + .HasColumnType("INTEGER") + .HasColumnOrder(10); + + b.HasKey("Id"); + + b.HasIndex("TrackId"); + + b.HasIndex("UserId", "CreatedOnUtc"); + + b.ToTable("MusicPlayRecords", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackContributorEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("MediaContributorId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("Role") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("TrackId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.HasKey("Id"); + + b.HasIndex("MediaContributorId"); + + b.HasIndex("TrackId", "MediaContributorId", "Role") + .IsUnique(); + + b.ToTable("TrackContributors", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("AcoustId") + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnOrder(44); + + b.Property("AlbumId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("AudioCodec") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(24); + + b.Property("BitDepth") + .HasColumnType("INTEGER") + .HasColumnOrder(23); + + b.Property("Bitrate") + .HasColumnType("INTEGER") + .HasColumnOrder(25); + + b.Property("Bpm") + .HasColumnType("INTEGER") + .HasColumnOrder(30); + + b.Property("Channels") + .HasColumnType("INTEGER") + .HasColumnOrder(22); + + b.Property("Container") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(49); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(38); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(37); + + b.Property("Description") + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("Disambiguation") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("DiscNumber") + .HasColumnType("INTEGER") + .HasColumnOrder(27); + + b.Property("DurationInSeconds") + .HasColumnType("INTEGER") + .HasColumnOrder(20); + + b.Property("IsVideo") + .HasColumnType("INTEGER") + .HasColumnOrder(31); + + b.Property("Key") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(29); + + b.Property("LanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("LanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(15); + + b.Property("LanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(16); + + b.Property("LastMetadataUpdateUtc") + .HasColumnType("TEXT") + .HasColumnOrder(42); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("MetadataProvider") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(43); + + b.Property("MetadataStatus") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasDefaultValue("Pending") + .HasColumnOrder(41); + + b.Property("MusicBrainzRecordingId") + .HasColumnType("TEXT") + .HasColumnOrder(34); + + b.Property("MusicBrainzTrackId") + .HasColumnType("TEXT") + .HasColumnOrder(35); + + b.Property("MusicBrainzWorkId") + .HasColumnType("TEXT") + .HasColumnOrder(36); + + b.Property("OriginalLanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(17); + + b.Property("OriginalLanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(18); + + b.Property("OriginalLanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(19); + + b.Property("OriginalReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("OriginalReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(9); + + b.Property("OriginalTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("Path") + .IsRequired() + .HasMaxLength(2048) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("ReReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("ReReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(11); + + b.Property("ReleaseCountry") + .HasMaxLength(2) + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("ReleaseVersion") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("ReplayGainAlbumGain") + .HasColumnType("decimal(8,2)") + .HasColumnOrder(47); + + b.Property("ReplayGainAlbumPeak") + .HasColumnType("decimal(8,6)") + .HasColumnOrder(48); + + b.Property("ReplayGainTrackGain") + .HasColumnType("decimal(8,2)") + .HasColumnOrder(45); + + b.Property("ReplayGainTrackPeak") + .HasColumnType("decimal(8,6)") + .HasColumnOrder(46); + + b.Property("SampleRate") + .HasColumnType("INTEGER") + .HasColumnOrder(21); + + b.Property("Script") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(28); + + b.Property("Title") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("TrackNumber") + .HasColumnType("INTEGER") + .HasColumnOrder(26); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(40); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(39); + + b.Property("WorkTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(32); + + b.Property("WorkType") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(33); + + b.HasKey("Id"); + + b.HasIndex("AlbumId", "TrackNumber"); + + b.HasIndex("LibraryId", "Path") + .IsUnique(); + + b.ToTable("Tracks", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.DirectoryScanFingerprintEntity", b => + { + b.Property("LibraryId") + .HasColumnType("TEXT"); + + b.Property("Path") + .HasMaxLength(1024) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("LastWriteTimeUtc") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.HasKey("LibraryId", "Path"); + + b.HasIndex("LibraryId"); + + b.ToTable("DirectoryScanFingerprints", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("ArtworkProvidersConfigurationFingerprint") + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("CanDownloadMetadataFromWeb") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(true) + .HasColumnOrder(6); + + b.Property("CoverImage") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("IsEnabled") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(true) + .HasColumnOrder(4); + + b.Property("IsLocked") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("LibraryType") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("MetadataProvidersConfigurationFingerprint") + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("PathTemplateFingerprint") + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("ShouldSaveMetadataInMediaDirectories") + .HasColumnType("INTEGER") + .HasColumnOrder(7); + + b.Property("ShouldSkipUnchangedDirectoriesDuringScan") + .HasColumnType("INTEGER") + .HasColumnOrder(8); + + b.Property("Title") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(15); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("UserId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("Libraries", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("LibraryId") + .HasColumnType("TEXT"); + + b.Property("Status") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UserId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.HasIndex("LibraryId", "Status", "CreatedOnUtc") + .IsDescending(true, false, true); + + b.ToTable("LibraryScans", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanResultEntity", b => + { + b.Property("LibraryScanId") + .HasColumnType("TEXT"); + + b.Property("Path") + .HasMaxLength(1024) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("ContentHash") + .HasMaxLength(24) + .HasColumnType("INTEGER") + .HasColumnOrder(2); + + b.Property("FileSize") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Status") + .IsRequired() + .HasMaxLength(10) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("Ticks") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.HasKey("LibraryScanId", "Path"); + + b.HasIndex("Path"); + + b.HasIndex("ContentHash", "FileSize", "Path"); + + b.ToTable("LibraryScanResults", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanSnapshotEntity", b => + { + b.Property("LibraryId") + .HasColumnType("TEXT"); + + b.Property("Path") + .HasMaxLength(1024) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("ContentHash") + .HasColumnType("INTEGER") + .HasColumnOrder(2); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("FileSize") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Ticks") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.HasKey("LibraryId", "Path"); + + b.HasIndex("LibraryId"); + + b.ToTable("LibraryScanSnapshots", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanStagingResultsEntity", b => + { + b.Property("LibraryScanId") + .HasColumnType("TEXT"); + + b.Property("Path") + .HasMaxLength(1024) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("ContentHash") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("IsNew") + .HasColumnType("INTEGER") + .HasColumnOrder(7); + + b.Property("NeedsRehash") + .HasColumnType("INTEGER") + .HasColumnOrder(6); + + b.Property("PreviousContentHash") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("Size") + .HasColumnType("INTEGER") + .HasColumnOrder(2); + + b.Property("Ticks") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.HasKey("LibraryScanId", "Path"); + + b.HasIndex("LibraryScanId", "NeedsRehash"); + + b.ToTable("LibraryScanStagingResults", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookArtworkEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("ArtworkType") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("BookId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("ContentHash") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("FileName") + .HasMaxLength(2048) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("LastUpdateUtc") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("Ordinal") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("Provider") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("Status") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.HasKey("Id"); + + b.HasIndex("Status"); + + b.HasIndex("BookId", "ArtworkType", "Ordinal") + .IsUnique(); + + b.ToTable("BookArtwork", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookContributorEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("BookId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("MediaContributorId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("Role") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.HasKey("Id"); + + b.HasIndex("MediaContributorId"); + + b.HasIndex("BookId", "MediaContributorId", "Role") + .IsUnique(); + + b.ToTable("BookContributors", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("ASIN") + .HasMaxLength(10) + .HasColumnType("TEXT") + .HasColumnOrder(21); + + b.Property("AppleBooksId") + .HasColumnType("TEXT") + .HasColumnOrder(29); + + b.Property("BarnesAndNobleId") + .HasMaxLength(10) + .HasColumnType("TEXT") + .HasColumnOrder(28); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(33); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(32); + + b.Property("Description") + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("Edition") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(19); + + b.Property("Format") + .HasColumnType("TEXT") + .HasColumnOrder(18); + + b.Property("GoodreadsId") + .HasColumnType("TEXT") + .HasColumnOrder(22); + + b.Property("GoogleBooksId") + .HasMaxLength(12) + .HasColumnType("TEXT") + .HasColumnOrder(27); + + b.Property("LCCN") + .HasColumnType("TEXT") + .HasColumnOrder(23); + + b.Property("LanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("LanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("LanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("LastMetadataUpdateUtc") + .HasColumnType("TEXT") + .HasColumnOrder(39); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(36); + + b.Property("LibraryThingId") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(26); + + b.Property("MetadataProvider") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(40); + + b.Property("MetadataStatus") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(38); + + b.Property("OCLCNumber") + .HasColumnType("TEXT") + .HasColumnOrder(24); + + b.Property("OpenLibraryId") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(25); + + b.Property("OriginalLanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("OriginalLanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("OriginalLanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(15); + + b.Property("OriginalReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("OriginalReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("OriginalTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("PageCount") + .HasColumnType("INTEGER") + .HasColumnOrder(17); + + b.Property("Path") + .IsRequired() + .HasMaxLength(2048) + .HasColumnType("TEXT") + .HasColumnOrder(37); + + b.Property("Publisher") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(16); + + b.Property("ReReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("ReReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(7); + + b.Property("ReleaseCountry") + .HasMaxLength(2) + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("ReleaseVersion") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("Title") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(35); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(34); + + b.Property("VolumeNumber") + .HasColumnType("REAL") + .HasColumnOrder(20); + + b.HasKey("Id"); + + b.HasIndex("LibraryId", "MetadataStatus"); + + b.HasIndex("LibraryId", "Path") + .IsUnique(); + + b.ToTable("Books", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Playlists.PlaylistEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("Description") + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("EntryCount") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(0) + .HasColumnOrder(10); + + b.Property("Name") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("Type") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UserId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("Version") + .IsConcurrencyToken() + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(0L) + .HasColumnOrder(9); + + b.HasKey("Id"); + + b.HasIndex("UserId", "UpdatedOnUtc"); + + b.ToTable("Playlists", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Playlists.PlaylistEntryEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("MediaItemId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("MediaItemType") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("PlaylistId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("Position") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.HasKey("Id"); + + b.HasIndex("MediaItemId"); + + b.HasIndex("PlaylistId", "Position") + .IsUnique(); + + b.ToTable("PlaylistEntries", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Plugins.LibraryArtworkProviderConfigurationEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("IsEnabled") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("PluginId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("Rank") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.HasKey("Id"); + + b.HasIndex("LibraryId", "PluginId"); + + b.ToTable("LibraryArtworkProviderConfigurations", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Plugins.LibraryBookReaderConfigurationEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("IsEnabled") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("PluginId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.HasKey("Id"); + + b.HasIndex("LibraryId", "PluginId") + .IsUnique(); + + b.ToTable("LibraryBookReaderConfigurations", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Plugins.LibraryMetadataProviderConfigurationEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("IsEnabled") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("PluginId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("Rank") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.HasKey("Id"); + + b.HasIndex("LibraryId", "PluginId"); + + b.ToTable("LibraryMetadataProviderConfigurations", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Plugins.PluginEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Author") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("Description") + .IsRequired() + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("LoadError") + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("LoadStatus") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("Name") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("SettingsJson") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("Version") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.HasKey("Id"); + + b.ToTable("Plugins", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Scheduling.ScheduledJobEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("Hour") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("IntervalMinutes") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("LastCompletedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("LastStartedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("Minute") + .HasColumnType("INTEGER") + .HasColumnOrder(6); + + b.Property("Name") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("OwnerUserId") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("ScheduleType") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("Status") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("TaskType") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.HasKey("Id"); + + b.HasIndex("Status"); + + b.ToTable("ScheduledJobs", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Scheduling.ScheduledJobExecutionEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CompletedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("IsCycleRun") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("ScheduledJobId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("StartedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("TaskType") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("WasCycleActive") + .HasColumnType("INTEGER") + .HasColumnOrder(6); + + b.HasKey("Id"); + + b.HasIndex("ScheduledJobId"); + + b.HasIndex("StartedOnUtc", "ScheduledJobId"); + + b.ToTable("ScheduledJobExecutions", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Scheduling.SchedulerDisplayPreferencesEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("DisplayTimeSpan") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("DisplayTimeUnit") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("JobTypeFilter") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UserId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.HasKey("Id"); + + b.HasIndex("UserId") + .IsUnique(); + + b.ToTable("SchedulerDisplayPreferences", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Themes.ThemeEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Author") + .IsRequired() + .HasMaxLength(80) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("Description") + .IsRequired() + .HasMaxLength(300) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("InstallSource") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("InstalledAtUtc") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("IsCurrent") + .HasColumnType("INTEGER") + .HasColumnOrder(8); + + b.Property("IsDeleted") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(false) + .HasColumnOrder(9); + + b.Property("Name") + .IsRequired() + .HasMaxLength(80) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("PreviewPath") + .HasMaxLength(240) + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("ThemeId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("Version") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.HasKey("Id"); + + b.HasIndex("IsCurrent") + .IsUnique() + .HasFilter("IsCurrent = 1"); + + b.HasIndex("ThemeId") + .IsUnique(); + + b.ToTable("Themes", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("Password") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("TempPassword") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("TempPasswordCreated") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("TotpSecret") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("Username") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.HasKey("Id"); + + b.HasIndex("Username") + .IsUnique(); + + b.ToTable("Users", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserSettingsEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("IsGaplessPlaybackEnabled") + .HasColumnType("INTEGER") + .HasColumnOrder(16); + + b.Property("IsMuted") + .HasColumnType("INTEGER") + .HasColumnOrder(20); + + b.Property("IsPaginationEnabled") + .HasColumnType("INTEGER") + .HasColumnOrder(2); + + b.Property("IsThemeCachingEnabled") + .HasColumnType("INTEGER") + .HasColumnOrder(9); + + b.Property("ItemsPerPage") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("ReplayGainMode") + .HasColumnType("INTEGER") + .HasColumnOrder(17); + + b.Property("ShouldAggregateArtworkWhenMissing") + .HasColumnType("INTEGER") + .HasColumnOrder(13); + + b.Property("ShouldAggregateMetadataWhenMissing") + .HasColumnType("INTEGER") + .HasColumnOrder(10); + + b.Property("ShouldAutoplay") + .HasColumnType("INTEGER") + .HasColumnOrder(15); + + b.Property("ShouldIgnoreThePrefixForAlphaPicker") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("ShouldKeepDownloadingWhilePaused") + .HasColumnType("INTEGER") + .HasColumnOrder(14); + + b.Property("ShouldPreserveBookStyles") + .HasColumnType("INTEGER") + .HasColumnOrder(12); + + b.Property("ShouldRenderPdfAsImages") + .HasColumnType("INTEGER") + .HasColumnOrder(11); + + b.Property("StreamingQuality") + .HasColumnType("INTEGER") + .HasColumnOrder(18); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UserId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("Volume") + .HasColumnType("REAL") + .HasColumnOrder(19); + + b.HasKey("Id"); + + b.HasIndex("UserId") + .IsUnique(); + + b.ToTable("UserSettings", (string)null); + }); + + modelBuilder.Entity("TrackGenres", b => + { + b.Property("TrackId") + .HasColumnType("TEXT"); + + b.Property("GenreId") + .HasColumnType("TEXT"); + + b.HasKey("TrackId", "GenreId"); + + b.HasIndex("GenreId"); + + b.ToTable("TrackGenres", (string)null); + }); + + modelBuilder.Entity("TrackTags", b => + { + b.Property("TrackId") + .HasColumnType("TEXT"); + + b.Property("TagId") + .HasColumnType("TEXT"); + + b.HasKey("TrackId", "TagId"); + + b.HasIndex("TagId"); + + b.ToTable("TrackTags", (string)null); + }); + + modelBuilder.Entity("AlbumGenres", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumEntity", null) + .WithMany() + .HasForeignKey("AlbumId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.GenreEntity", null) + .WithMany() + .HasForeignKey("GenreId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("AlbumTags", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumEntity", null) + .WithMany() + .HasForeignKey("AlbumId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.TagEntity", null) + .WithMany() + .HasForeignKey("TagId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("ArtistGenres", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistEntity", null) + .WithMany() + .HasForeignKey("ArtistId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.GenreEntity", null) + .WithMany() + .HasForeignKey("GenreId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("ArtistTags", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistEntity", null) + .WithMany() + .HasForeignKey("ArtistId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.TagEntity", null) + .WithMany() + .HasForeignKey("TagId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BookGenres", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", null) + .WithMany() + .HasForeignKey("BookId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.GenreEntity", null) + .WithMany() + .HasForeignKey("GenreId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BookTags", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", null) + .WithMany() + .HasForeignKey("BookId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.TagEntity", null) + .WithMany() + .HasForeignKey("TagId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.RolePermissionEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Authorization.PermissionEntity", "Permission") + .WithMany("RolePermissions") + .HasForeignKey("PermissionId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Authorization.RoleEntity", "Role") + .WithMany("RolePermissions") + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Permission"); + + b.Navigation("Role"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.UserPermissionEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Authorization.PermissionEntity", "Permission") + .WithMany("UserPermissions") + .HasForeignKey("PermissionId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", "User") + .WithMany("UserPermissions") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Permission"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.UserRoleEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Authorization.RoleEntity", "Role") + .WithMany("UserRoles") + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", "User") + .WithOne("UserRole") + .HasForeignKey("Lumina.Application.Common.DataAccess.Entities.Authorization.UserRoleEntity", "UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Role"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumContributorEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumEntity", null) + .WithMany("Contributors") + .HasForeignKey("AlbumId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistEntity", "Artist") + .WithMany("Albums") + .HasForeignKey("ArtistId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumCatalogNumberEntity", "CatalogNumbers", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("AlbumId") + .HasColumnType("TEXT"); + + b1.Property("CatalogNumber") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("AlbumId"); + + b1.ToTable("AlbumCatalogNumbers", (string)null); + + b1.WithOwner() + .HasForeignKey("AlbumId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AudioRatingEntity", "Ratings", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("AlbumId") + .HasColumnType("TEXT"); + + b1.Property("MaxValue") + .HasColumnType("decimal(3,2)"); + + b1.Property("Source") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.Property("Value") + .HasColumnType("decimal(3,2)"); + + b1.Property("VoteCount") + .HasColumnType("INTEGER"); + + b1.HasKey("Id"); + + b1.HasIndex("AlbumId"); + + b1.ToTable("AlbumRatings", (string)null); + + b1.WithOwner() + .HasForeignKey("AlbumId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumReleaseTypeEntity", "ReleaseTypes", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("AlbumId") + .HasColumnType("TEXT"); + + b1.Property("ReleaseType") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("AlbumId"); + + b1.ToTable("AlbumReleaseTypes", (string)null); + + b1.WithOwner() + .HasForeignKey("AlbumId"); + }); + + b.Navigation("Artist"); + + b.Navigation("CatalogNumbers"); + + b.Navigation("Ratings"); + + b.Navigation("ReleaseTypes"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistContributorEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistEntity", null) + .WithMany("Contributors") + .HasForeignKey("ArtistId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistEntity", b => + { + b.OwnsOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.MusicAreaEntity", "Area", b1 => + { + b1.Property("ArtistEntityId"); + + b1.Property("Disambiguation"); + + b1.Property("Iso3166Code"); + + b1.Property("MusicBrainzAreaId"); + + b1.Property("Name") + .IsRequired(); + + b1.Property("SortName"); + + b1.Property("Type"); + + b1.HasKey("ArtistEntityId"); + + b1.ToTable("Artists"); + + b1 + .ToJson("Area") + .HasColumnType("TEXT"); + + b1.WithOwner() + .HasForeignKey("ArtistEntityId"); + }); + + b.OwnsOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.MusicAreaEntity", "BeginArea", b1 => + { + b1.Property("ArtistEntityId"); + + b1.Property("Disambiguation"); + + b1.Property("Iso3166Code"); + + b1.Property("MusicBrainzAreaId"); + + b1.Property("Name") + .IsRequired(); + + b1.Property("SortName"); + + b1.Property("Type"); + + b1.HasKey("ArtistEntityId"); + + b1.ToTable("Artists"); + + b1 + .ToJson("BeginArea") + .HasColumnType("TEXT"); + + b1.WithOwner() + .HasForeignKey("ArtistEntityId"); + }); + + b.OwnsOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.MusicAreaEntity", "EndArea", b1 => + { + b1.Property("ArtistEntityId"); + + b1.Property("Disambiguation"); + + b1.Property("Iso3166Code"); + + b1.Property("MusicBrainzAreaId"); + + b1.Property("Name") + .IsRequired(); + + b1.Property("SortName"); + + b1.Property("Type"); + + b1.HasKey("ArtistEntityId"); + + b1.ToTable("Artists"); + + b1 + .ToJson("EndArea") + .HasColumnType("TEXT"); + + b1.WithOwner() + .HasForeignKey("ArtistEntityId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistAliasEntity", "Aliases", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("ArtistId") + .HasColumnType("TEXT"); + + b1.Property("BeginDate") + .HasColumnType("TEXT"); + + b1.Property("EndDate") + .HasColumnType("TEXT"); + + b1.Property("IsEnded") + .HasColumnType("INTEGER"); + + b1.Property("IsPrimary") + .HasColumnType("INTEGER"); + + b1.Property("Locale") + .HasMaxLength(20) + .HasColumnType("TEXT"); + + b1.Property("Name") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT"); + + b1.Property("SortName") + .HasMaxLength(255) + .HasColumnType("TEXT"); + + b1.Property("Type") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("ArtistId"); + + b1.ToTable("ArtistAliases", (string)null); + + b1.WithOwner() + .HasForeignKey("ArtistId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AudioRatingEntity", "Ratings", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("ArtistId") + .HasColumnType("TEXT"); + + b1.Property("MaxValue") + .HasColumnType("decimal(3,2)"); + + b1.Property("Source") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.Property("Value") + .HasColumnType("decimal(3,2)"); + + b1.Property("VoteCount") + .HasColumnType("INTEGER"); + + b1.HasKey("Id"); + + b1.HasIndex("ArtistId"); + + b1.ToTable("ArtistRatings", (string)null); + + b1.WithOwner() + .HasForeignKey("ArtistId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistIpiEntity", "Ipis", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("ArtistId") + .HasColumnType("TEXT"); + + b1.Property("Value") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("ArtistId"); + + b1.ToTable("ArtistIpis", (string)null); + + b1.WithOwner() + .HasForeignKey("ArtistId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistIsniEntity", "Isnis", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("ArtistId") + .HasColumnType("TEXT"); + + b1.Property("Value") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("ArtistId"); + + b1.ToTable("ArtistIsnis", (string)null); + + b1.WithOwner() + .HasForeignKey("ArtistId"); + }); + + b.Navigation("Aliases"); + + b.Navigation("Area"); + + b.Navigation("BeginArea"); + + b.Navigation("EndArea"); + + b.Navigation("Ipis"); + + b.Navigation("Isnis"); + + b.Navigation("Ratings"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackContributorEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackEntity", null) + .WithMany("Contributors") + .HasForeignKey("TrackId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumEntity", "Album") + .WithMany("Tracks") + .HasForeignKey("AlbumId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AudioRatingEntity", "Ratings", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("MaxValue") + .HasColumnType("decimal(3,2)"); + + b1.Property("Source") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.Property("TrackId") + .HasColumnType("TEXT"); + + b1.Property("Value") + .HasColumnType("decimal(3,2)"); + + b1.Property("VoteCount") + .HasColumnType("INTEGER"); + + b1.HasKey("Id"); + + b1.HasIndex("TrackId"); + + b1.ToTable("TrackRatings", (string)null); + + b1.WithOwner() + .HasForeignKey("TrackId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackIsrcEntity", "Isrcs", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("TrackId") + .HasColumnType("TEXT"); + + b1.Property("Value") + .IsRequired() + .HasMaxLength(12) + .HasColumnType("TEXT") + .HasColumnName("ISRC"); + + b1.HasKey("Id"); + + b1.HasIndex("TrackId"); + + b1.ToTable("TrackIsrcs", (string)null); + + b1.WithOwner() + .HasForeignKey("TrackId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackMoodEntity", "Moods", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("Name") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.Property("TrackId") + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("TrackId"); + + b1.ToTable("TrackMoods", (string)null); + + b1.WithOwner() + .HasForeignKey("TrackId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackWorkIswcEntity", "WorkIswcs", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("TrackId") + .HasColumnType("TEXT"); + + b1.Property("Value") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("TrackId"); + + b1.ToTable("TrackWorkIswcs", (string)null); + + b1.WithOwner() + .HasForeignKey("TrackId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackWorkLanguageEntity", "WorkLanguages", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("LanguageCode") + .IsRequired() + .HasMaxLength(5) + .HasColumnType("TEXT"); + + b1.Property("LanguageName") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("TEXT"); + + b1.Property("NativeName") + .HasMaxLength(100) + .HasColumnType("TEXT"); + + b1.Property("TrackId") + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("TrackId"); + + b1.ToTable("TrackWorkLanguages", (string)null); + + b1.WithOwner() + .HasForeignKey("TrackId"); + }); + + b.Navigation("Album"); + + b.Navigation("Isrcs"); + + b.Navigation("Moods"); + + b.Navigation("Ratings"); + + b.Navigation("WorkIswcs"); + + b.Navigation("WorkLanguages"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.DirectoryScanFingerprintEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", null) + .WithMany() + .HasForeignKey("LibraryId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", "User") + .WithMany("Libraries") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryContentLocationEntity", "ContentLocations", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("LibraryId") + .HasColumnType("TEXT"); + + b1.Property("Path") + .IsRequired() + .HasMaxLength(260) + .HasColumnType("TEXT") + .HasColumnName("Path"); + + b1.HasKey("Id"); + + b1.HasIndex("LibraryId"); + + b1.ToTable("LibraryContentLocations", (string)null); + + b1.WithOwner() + .HasForeignKey("LibraryId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryPathTemplatePartEntity", "PathTemplateParts", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("IsOptional") + .HasColumnType("INTEGER"); + + b1.Property("Kind") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b1.Property("LibraryId") + .HasColumnType("TEXT"); + + b1.Property("Position") + .HasColumnType("INTEGER") + .HasColumnName("Position"); + + b1.Property("Representation") + .IsRequired() + .HasMaxLength(512) + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("LibraryId", "Position") + .IsUnique(); + + b1.ToTable("LibraryPathTemplateParts", (string)null); + + b1.WithOwner() + .HasForeignKey("LibraryId"); + }); + + b.Navigation("ContentLocations"); + + b.Navigation("PathTemplateParts"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", "Library") + .WithMany("LibraryScans") + .HasForeignKey("LibraryId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", "User") + .WithMany("LibraryScans") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Library"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanResultEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", "LibraryScan") + .WithMany("LibraryScanResults") + .HasForeignKey("LibraryScanId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("LibraryScan"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanSnapshotEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", "Library") + .WithMany() + .HasForeignKey("LibraryId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Library"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanStagingResultsEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", null) + .WithMany() + .HasForeignKey("LibraryScanId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookArtworkEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", null) + .WithMany("Artwork") + .HasForeignKey("BookId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookContributorEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", null) + .WithMany("Contributors") + .HasForeignKey("BookId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", b => + { + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookRatingEntity", "Ratings", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("BookId") + .HasColumnType("TEXT"); + + b1.Property("MaxValue") + .HasColumnType("decimal(3,2)"); + + b1.Property("Source") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.Property("Value") + .HasColumnType("decimal(3,2)"); + + b1.Property("VoteCount") + .HasColumnType("INTEGER"); + + b1.HasKey("Id"); + + b1.HasIndex("BookId"); + + b1.ToTable("BookRatings", (string)null); + + b1.WithOwner() + .HasForeignKey("BookId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.IsbnEntity", "ISBNs", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("BookId") + .HasColumnType("TEXT"); + + b1.Property("Format") + .IsRequired() + .HasMaxLength(6) + .HasColumnType("TEXT"); + + b1.Property("Value") + .IsRequired() + .HasMaxLength(13) + .HasColumnType("TEXT") + .HasColumnName("ISBN"); + + b1.HasKey("Id"); + + b1.HasIndex("BookId"); + + b1.ToTable("BookISBNs", (string)null); + + b1.WithOwner() + .HasForeignKey("BookId"); + }); + + b.Navigation("ISBNs"); + + b.Navigation("Ratings"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Playlists.PlaylistEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Playlists.PlaylistEntryEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Playlists.PlaylistEntity", null) + .WithMany("Entries") + .HasForeignKey("PlaylistId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserSettingsEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", null) + .WithOne() + .HasForeignKey("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserSettingsEntity", "UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("TrackGenres", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.GenreEntity", null) + .WithMany() + .HasForeignKey("GenreId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackEntity", null) + .WithMany() + .HasForeignKey("TrackId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("TrackTags", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.TagEntity", null) + .WithMany() + .HasForeignKey("TagId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackEntity", null) + .WithMany() + .HasForeignKey("TrackId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.PermissionEntity", b => + { + b.Navigation("RolePermissions"); + + b.Navigation("UserPermissions"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.RoleEntity", b => + { + b.Navigation("RolePermissions"); + + b.Navigation("UserRoles"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumEntity", b => + { + b.Navigation("Contributors"); + + b.Navigation("Tracks"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistEntity", b => + { + b.Navigation("Albums"); + + b.Navigation("Contributors"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackEntity", b => + { + b.Navigation("Contributors"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", b => + { + b.Navigation("LibraryScans"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", b => + { + b.Navigation("LibraryScanResults"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", b => + { + b.Navigation("Artwork"); + + b.Navigation("Contributors"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Playlists.PlaylistEntity", b => + { + b.Navigation("Entries"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", b => + { + b.Navigation("Libraries"); + + b.Navigation("LibraryScans"); + + b.Navigation("UserPermissions"); + + b.Navigation("UserRole"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/Lumina.DataAccess/Common/Migrations/20261021090430_AddsPlaylists.cs b/src/Lumina.DataAccess/Common/Migrations/20261021090430_AddsPlaylists.cs new file mode 100644 index 00000000..42ad1c87 --- /dev/null +++ b/src/Lumina.DataAccess/Common/Migrations/20261021090430_AddsPlaylists.cs @@ -0,0 +1,93 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Lumina.DataAccess.Common.Migrations +{ + /// + public partial class AddsPlaylists : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "Playlists", + columns: table => new + { + Id = table.Column(type: "TEXT", nullable: false), + UserId = table.Column(type: "TEXT", nullable: false), + Name = table.Column(type: "TEXT", maxLength: 255, nullable: false), + Description = table.Column(type: "TEXT", maxLength: 2000, nullable: true), + Type = table.Column(type: "TEXT", maxLength: 20, nullable: false), + CreatedOnUtc = table.Column(type: "TEXT", nullable: false), + CreatedBy = table.Column(type: "TEXT", nullable: false), + UpdatedOnUtc = table.Column(type: "TEXT", nullable: true), + UpdatedBy = table.Column(type: "TEXT", nullable: true), + Version = table.Column(type: "INTEGER", nullable: false, defaultValue: 0L), + EntryCount = table.Column(type: "INTEGER", nullable: false, defaultValue: 0) + }, + constraints: table => + { + table.PrimaryKey("PK_Playlists", x => x.Id); + table.ForeignKey( + name: "FK_Playlists_Users_UserId", + column: x => x.UserId, + principalTable: "Users", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateTable( + name: "PlaylistEntries", + columns: table => new + { + Id = table.Column(type: "TEXT", nullable: false), + PlaylistId = table.Column(type: "TEXT", nullable: false), + MediaItemId = table.Column(type: "TEXT", nullable: false), + MediaItemType = table.Column(type: "TEXT", maxLength: 20, nullable: false), + Position = table.Column(type: "INTEGER", nullable: false), + CreatedOnUtc = table.Column(type: "TEXT", nullable: false), + CreatedBy = table.Column(type: "TEXT", nullable: false), + UpdatedOnUtc = table.Column(type: "TEXT", nullable: true), + UpdatedBy = table.Column(type: "TEXT", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_PlaylistEntries", x => x.Id); + table.ForeignKey( + name: "FK_PlaylistEntries_Playlists_PlaylistId", + column: x => x.PlaylistId, + principalTable: "Playlists", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateIndex( + name: "IX_PlaylistEntries_MediaItemId", + table: "PlaylistEntries", + column: "MediaItemId"); + + migrationBuilder.CreateIndex( + name: "IX_PlaylistEntries_PlaylistId_Position", + table: "PlaylistEntries", + columns: new[] { "PlaylistId", "Position" }, + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_Playlists_UserId_UpdatedOnUtc", + table: "Playlists", + columns: new[] { "UserId", "UpdatedOnUtc" }); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "PlaylistEntries"); + + migrationBuilder.DropTable( + name: "Playlists"); + } + } +} diff --git a/src/Lumina.DataAccess/Common/Migrations/20261021134714_AddsVuMeterSettingsToUserSettings.Designer.cs b/src/Lumina.DataAccess/Common/Migrations/20261021134714_AddsVuMeterSettingsToUserSettings.Designer.cs new file mode 100644 index 00000000..d2cbd08c --- /dev/null +++ b/src/Lumina.DataAccess/Common/Migrations/20261021134714_AddsVuMeterSettingsToUserSettings.Designer.cs @@ -0,0 +1,3709 @@ +// +using System; +using Lumina.DataAccess.Core.UoW; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace Lumina.DataAccess.Common.Migrations +{ + [DbContext(typeof(LuminaDbContext))] + [Migration("20261021134714_AddsVuMeterSettingsToUserSettings")] + partial class AddsVuMeterSettingsToUserSettings + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder.HasAnnotation("ProductVersion", "10.0.11"); + + modelBuilder.Entity("AlbumGenres", b => + { + b.Property("AlbumId") + .HasColumnType("TEXT"); + + b.Property("GenreId") + .HasColumnType("TEXT"); + + b.HasKey("AlbumId", "GenreId"); + + b.HasIndex("GenreId"); + + b.ToTable("AlbumGenres", (string)null); + }); + + modelBuilder.Entity("AlbumTags", b => + { + b.Property("AlbumId") + .HasColumnType("TEXT"); + + b.Property("TagId") + .HasColumnType("TEXT"); + + b.HasKey("AlbumId", "TagId"); + + b.HasIndex("TagId"); + + b.ToTable("AlbumTags", (string)null); + }); + + modelBuilder.Entity("ArtistGenres", b => + { + b.Property("ArtistId") + .HasColumnType("TEXT"); + + b.Property("GenreId") + .HasColumnType("TEXT"); + + b.HasKey("ArtistId", "GenreId"); + + b.HasIndex("GenreId"); + + b.ToTable("ArtistGenres", (string)null); + }); + + modelBuilder.Entity("ArtistTags", b => + { + b.Property("ArtistId") + .HasColumnType("TEXT"); + + b.Property("TagId") + .HasColumnType("TEXT"); + + b.HasKey("ArtistId", "TagId"); + + b.HasIndex("TagId"); + + b.ToTable("ArtistTags", (string)null); + }); + + modelBuilder.Entity("BookGenres", b => + { + b.Property("BookId") + .HasColumnType("TEXT"); + + b.Property("GenreId") + .HasColumnType("TEXT"); + + b.HasKey("BookId", "GenreId"); + + b.HasIndex("GenreId"); + + b.ToTable("BookGenres", (string)null); + }); + + modelBuilder.Entity("BookTags", b => + { + b.Property("BookId") + .HasColumnType("TEXT"); + + b.Property("TagId") + .HasColumnType("TEXT"); + + b.HasKey("BookId", "TagId"); + + b.HasIndex("TagId"); + + b.ToTable("BookTags", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.PermissionEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("PermissionName") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.HasKey("Id"); + + b.ToTable("Permissions", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.RoleEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("RoleName") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.HasKey("Id"); + + b.ToTable("Roles", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.RolePermissionEntity", b => + { + b.Property("RoleId") + .HasColumnType("TEXT"); + + b.Property("PermissionId") + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.HasKey("RoleId", "PermissionId"); + + b.HasIndex("PermissionId"); + + b.HasIndex("RoleId", "PermissionId") + .IsUnique(); + + b.ToTable("RolePermissions", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.UserPermissionEntity", b => + { + b.Property("UserId") + .HasColumnType("TEXT"); + + b.Property("PermissionId") + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.HasKey("UserId", "PermissionId"); + + b.HasIndex("PermissionId"); + + b.HasIndex("UserId", "PermissionId") + .IsUnique(); + + b.ToTable("UserPermissions", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.UserRoleEntity", b => + { + b.Property("UserId") + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("RoleId") + .HasColumnType("TEXT"); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.HasKey("UserId"); + + b.HasIndex("RoleId"); + + b.HasIndex("UserId", "RoleId") + .IsUnique(); + + b.ToTable("UserRoles", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Common.GenreEntity", b => + { + b.Property("Name") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b.HasKey("Name"); + + b.ToTable("Genres", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Common.TagEntity", b => + { + b.Property("Name") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b.HasKey("Name"); + + b.ToTable("Tags", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaContributors.MediaContributorEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Biography") + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("DateOfBirth") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("DateOfDeath") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("DisplayName") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1) + .UseCollation("NOCASE"); + + b.Property("LegalName") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.HasKey("Id"); + + b.HasIndex("DisplayName") + .IsUnique(); + + b.ToTable("MediaContributors", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumContributorEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("AlbumId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("MediaContributorId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("Role") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.HasKey("Id"); + + b.HasIndex("MediaContributorId"); + + b.HasIndex("AlbumId", "MediaContributorId", "Role") + .IsUnique(); + + b.ToTable("AlbumContributors", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("ASIN") + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(28); + + b.Property("ArtistId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("Barcode") + .HasMaxLength(13) + .HasColumnType("TEXT") + .HasColumnOrder(25); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(33); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(32); + + b.Property("Description") + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("Disambiguation") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("Label") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(27); + + b.Property("LanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("LanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("LanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(15); + + b.Property("LastMetadataUpdateUtc") + .HasColumnType("TEXT") + .HasColumnOrder(37); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("MediaFormat") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(23); + + b.Property("MetadataProvider") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(38); + + b.Property("MetadataStatus") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasDefaultValue("Pending") + .HasColumnOrder(36); + + b.Property("MusicBrainzReleaseArtistId") + .HasColumnType("TEXT") + .HasColumnOrder(31); + + b.Property("MusicBrainzReleaseGroupId") + .HasColumnType("TEXT") + .HasColumnOrder(30); + + b.Property("MusicBrainzReleaseId") + .HasColumnType("TEXT") + .HasColumnOrder(29); + + b.Property("OriginalLanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(16); + + b.Property("OriginalLanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(17); + + b.Property("OriginalLanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(18); + + b.Property("OriginalReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("OriginalReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(8); + + b.Property("OriginalTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("Packaging") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(24); + + b.Property("ReReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("ReReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(10); + + b.Property("ReleaseCountry") + .HasMaxLength(2) + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("ReleaseStatus") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(20); + + b.Property("ReleaseTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(26); + + b.Property("ReleaseVersion") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("Script") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(19); + + b.Property("Title") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("TotalDiscs") + .HasColumnType("INTEGER") + .HasColumnOrder(21); + + b.Property("TotalTracks") + .HasColumnType("INTEGER") + .HasColumnOrder(22); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(35); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(34); + + b.HasKey("Id"); + + b.HasIndex("ArtistId", "Title"); + + b.HasIndex("LibraryId", "Title"); + + b.ToTable("Albums", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistContributorEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("ArtistId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("MediaContributorId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("Role") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.HasKey("Id"); + + b.HasIndex("MediaContributorId"); + + b.HasIndex("ArtistId", "MediaContributorId", "Role") + .IsUnique(); + + b.ToTable("ArtistContributors", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Country") + .HasMaxLength(2) + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("Disambiguation") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("Gender") + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("IsEnded") + .HasColumnType("INTEGER") + .HasColumnOrder(10); + + b.Property("LastMetadataUpdateUtc") + .HasColumnType("TEXT") + .HasColumnOrder(18); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("LifeSpanBegin") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("LifeSpanEnd") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("MetadataProvider") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(19); + + b.Property("MetadataStatus") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasDefaultValue("Pending") + .HasColumnOrder(17); + + b.Property("MusicBrainzArtistId") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("Name") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("SortName") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("Type") + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(16); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(15); + + b.Property("Website") + .HasMaxLength(2048) + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.HasKey("Id"); + + b.HasIndex("LibraryId", "Name") + .IsUnique(); + + b.ToTable("Artists", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.MusicArtworkEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("ArtworkType") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("ContentHash") + .HasColumnType("INTEGER") + .HasColumnOrder(6); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("FileName") + .HasMaxLength(2048) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("LastUpdateUtc") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("Ordinal") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("OwnerId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("OwnerType") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("Provider") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("Status") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.HasKey("Id"); + + b.HasIndex("Status"); + + b.HasIndex("OwnerType", "OwnerId", "ArtworkType", "Ordinal") + .IsUnique(); + + b.ToTable("MusicArtwork", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.MusicLibraryScanItemMetadataEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("AcoustId") + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnOrder(25); + + b.Property("ArtistName") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("AudioCodec") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(15); + + b.Property("BitDepth") + .HasColumnType("INTEGER") + .HasColumnOrder(14); + + b.Property("Bitrate") + .HasColumnType("INTEGER") + .HasColumnOrder(16); + + b.Property("Channels") + .HasColumnType("INTEGER") + .HasColumnOrder(13); + + b.Property("Container") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(31); + + b.Property("DiscNumber") + .HasColumnType("INTEGER") + .HasColumnOrder(10); + + b.Property("DurationInSeconds") + .HasColumnType("INTEGER") + .HasColumnOrder(11); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("LibraryScanId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.PrimitiveCollection("Moods") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(30); + + b.Property("MusicBrainzArtistId") + .HasColumnType("TEXT") + .HasColumnOrder(17); + + b.Property("MusicBrainzRecordingId") + .HasColumnType("TEXT") + .HasColumnOrder(21); + + b.Property("MusicBrainzReleaseArtistId") + .HasColumnType("TEXT") + .HasColumnOrder(18); + + b.Property("MusicBrainzReleaseGroupId") + .HasColumnType("TEXT") + .HasColumnOrder(19); + + b.Property("MusicBrainzReleaseId") + .HasColumnType("TEXT") + .HasColumnOrder(20); + + b.Property("MusicBrainzTrackId") + .HasColumnType("TEXT") + .HasColumnOrder(22); + + b.Property("MusicBrainzWorkId") + .HasColumnType("TEXT") + .HasColumnOrder(23); + + b.Property("Path") + .IsRequired() + .HasMaxLength(2048) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("ReleaseName") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("ReleaseType") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("ReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(6); + + b.Property("ReplayGainAlbumGain") + .HasColumnType("decimal(8,2)") + .HasColumnOrder(28); + + b.Property("ReplayGainAlbumPeak") + .HasColumnType("decimal(8,6)") + .HasColumnOrder(29); + + b.Property("ReplayGainTrackGain") + .HasColumnType("decimal(8,2)") + .HasColumnOrder(26); + + b.Property("ReplayGainTrackPeak") + .HasColumnType("decimal(8,6)") + .HasColumnOrder(27); + + b.Property("SampleRate") + .HasColumnType("INTEGER") + .HasColumnOrder(12); + + b.Property("TrackNumber") + .HasColumnType("INTEGER") + .HasColumnOrder(9); + + b.Property("TrackTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("WorkTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(24); + + b.HasKey("Id"); + + b.HasIndex("LibraryScanId", "Path") + .IsUnique(); + + b.ToTable("MusicLibraryScanItemMetadata", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.MusicPlayRecordEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("AlbumId") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("ArtistId") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("EndedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("LastPositionMilliseconds") + .HasColumnType("INTEGER") + .HasColumnOrder(7); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("ListenedDurationMilliseconds") + .HasColumnType("INTEGER") + .HasColumnOrder(8); + + b.Property("Status") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("TrackId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("UserId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("Version") + .IsConcurrencyToken() + .HasColumnType("INTEGER") + .HasColumnOrder(10); + + b.HasKey("Id"); + + b.HasIndex("TrackId"); + + b.HasIndex("UserId", "CreatedOnUtc"); + + b.ToTable("MusicPlayRecords", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackContributorEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("MediaContributorId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("Role") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("TrackId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.HasKey("Id"); + + b.HasIndex("MediaContributorId"); + + b.HasIndex("TrackId", "MediaContributorId", "Role") + .IsUnique(); + + b.ToTable("TrackContributors", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("AcoustId") + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnOrder(44); + + b.Property("AlbumId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("AudioCodec") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(24); + + b.Property("BitDepth") + .HasColumnType("INTEGER") + .HasColumnOrder(23); + + b.Property("Bitrate") + .HasColumnType("INTEGER") + .HasColumnOrder(25); + + b.Property("Bpm") + .HasColumnType("INTEGER") + .HasColumnOrder(30); + + b.Property("Channels") + .HasColumnType("INTEGER") + .HasColumnOrder(22); + + b.Property("Container") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(49); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(38); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(37); + + b.Property("Description") + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("Disambiguation") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("DiscNumber") + .HasColumnType("INTEGER") + .HasColumnOrder(27); + + b.Property("DurationInSeconds") + .HasColumnType("INTEGER") + .HasColumnOrder(20); + + b.Property("IsVideo") + .HasColumnType("INTEGER") + .HasColumnOrder(31); + + b.Property("Key") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(29); + + b.Property("LanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("LanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(15); + + b.Property("LanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(16); + + b.Property("LastMetadataUpdateUtc") + .HasColumnType("TEXT") + .HasColumnOrder(42); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("MetadataProvider") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(43); + + b.Property("MetadataStatus") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasDefaultValue("Pending") + .HasColumnOrder(41); + + b.Property("MusicBrainzRecordingId") + .HasColumnType("TEXT") + .HasColumnOrder(34); + + b.Property("MusicBrainzTrackId") + .HasColumnType("TEXT") + .HasColumnOrder(35); + + b.Property("MusicBrainzWorkId") + .HasColumnType("TEXT") + .HasColumnOrder(36); + + b.Property("OriginalLanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(17); + + b.Property("OriginalLanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(18); + + b.Property("OriginalLanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(19); + + b.Property("OriginalReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("OriginalReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(9); + + b.Property("OriginalTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("Path") + .IsRequired() + .HasMaxLength(2048) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("ReReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("ReReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(11); + + b.Property("ReleaseCountry") + .HasMaxLength(2) + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("ReleaseVersion") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("ReplayGainAlbumGain") + .HasColumnType("decimal(8,2)") + .HasColumnOrder(47); + + b.Property("ReplayGainAlbumPeak") + .HasColumnType("decimal(8,6)") + .HasColumnOrder(48); + + b.Property("ReplayGainTrackGain") + .HasColumnType("decimal(8,2)") + .HasColumnOrder(45); + + b.Property("ReplayGainTrackPeak") + .HasColumnType("decimal(8,6)") + .HasColumnOrder(46); + + b.Property("SampleRate") + .HasColumnType("INTEGER") + .HasColumnOrder(21); + + b.Property("Script") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(28); + + b.Property("Title") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("TrackNumber") + .HasColumnType("INTEGER") + .HasColumnOrder(26); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(40); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(39); + + b.Property("WorkTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(32); + + b.Property("WorkType") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(33); + + b.HasKey("Id"); + + b.HasIndex("AlbumId", "TrackNumber"); + + b.HasIndex("LibraryId", "Path") + .IsUnique(); + + b.ToTable("Tracks", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.DirectoryScanFingerprintEntity", b => + { + b.Property("LibraryId") + .HasColumnType("TEXT"); + + b.Property("Path") + .HasMaxLength(1024) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("LastWriteTimeUtc") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.HasKey("LibraryId", "Path"); + + b.HasIndex("LibraryId"); + + b.ToTable("DirectoryScanFingerprints", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("ArtworkProvidersConfigurationFingerprint") + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("CanDownloadMetadataFromWeb") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(true) + .HasColumnOrder(6); + + b.Property("CoverImage") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("IsEnabled") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(true) + .HasColumnOrder(4); + + b.Property("IsLocked") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("LibraryType") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("MetadataProvidersConfigurationFingerprint") + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("PathTemplateFingerprint") + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("ShouldSaveMetadataInMediaDirectories") + .HasColumnType("INTEGER") + .HasColumnOrder(7); + + b.Property("ShouldSkipUnchangedDirectoriesDuringScan") + .HasColumnType("INTEGER") + .HasColumnOrder(8); + + b.Property("Title") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(15); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("UserId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("Libraries", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("LibraryId") + .HasColumnType("TEXT"); + + b.Property("Status") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UserId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.HasIndex("LibraryId", "Status", "CreatedOnUtc") + .IsDescending(true, false, true); + + b.ToTable("LibraryScans", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanResultEntity", b => + { + b.Property("LibraryScanId") + .HasColumnType("TEXT"); + + b.Property("Path") + .HasMaxLength(1024) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("ContentHash") + .HasMaxLength(24) + .HasColumnType("INTEGER") + .HasColumnOrder(2); + + b.Property("FileSize") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Status") + .IsRequired() + .HasMaxLength(10) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("Ticks") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.HasKey("LibraryScanId", "Path"); + + b.HasIndex("Path"); + + b.HasIndex("ContentHash", "FileSize", "Path"); + + b.ToTable("LibraryScanResults", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanSnapshotEntity", b => + { + b.Property("LibraryId") + .HasColumnType("TEXT"); + + b.Property("Path") + .HasMaxLength(1024) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("ContentHash") + .HasColumnType("INTEGER") + .HasColumnOrder(2); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("FileSize") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Ticks") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.HasKey("LibraryId", "Path"); + + b.HasIndex("LibraryId"); + + b.ToTable("LibraryScanSnapshots", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanStagingResultsEntity", b => + { + b.Property("LibraryScanId") + .HasColumnType("TEXT"); + + b.Property("Path") + .HasMaxLength(1024) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("ContentHash") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("IsNew") + .HasColumnType("INTEGER") + .HasColumnOrder(7); + + b.Property("NeedsRehash") + .HasColumnType("INTEGER") + .HasColumnOrder(6); + + b.Property("PreviousContentHash") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("Size") + .HasColumnType("INTEGER") + .HasColumnOrder(2); + + b.Property("Ticks") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.HasKey("LibraryScanId", "Path"); + + b.HasIndex("LibraryScanId", "NeedsRehash"); + + b.ToTable("LibraryScanStagingResults", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookArtworkEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("ArtworkType") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("BookId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("ContentHash") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("FileName") + .HasMaxLength(2048) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("LastUpdateUtc") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("Ordinal") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("Provider") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("Status") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.HasKey("Id"); + + b.HasIndex("Status"); + + b.HasIndex("BookId", "ArtworkType", "Ordinal") + .IsUnique(); + + b.ToTable("BookArtwork", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookContributorEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("BookId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("MediaContributorId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("Role") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.HasKey("Id"); + + b.HasIndex("MediaContributorId"); + + b.HasIndex("BookId", "MediaContributorId", "Role") + .IsUnique(); + + b.ToTable("BookContributors", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("ASIN") + .HasMaxLength(10) + .HasColumnType("TEXT") + .HasColumnOrder(21); + + b.Property("AppleBooksId") + .HasColumnType("TEXT") + .HasColumnOrder(29); + + b.Property("BarnesAndNobleId") + .HasMaxLength(10) + .HasColumnType("TEXT") + .HasColumnOrder(28); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(33); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(32); + + b.Property("Description") + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("Edition") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(19); + + b.Property("Format") + .HasColumnType("TEXT") + .HasColumnOrder(18); + + b.Property("GoodreadsId") + .HasColumnType("TEXT") + .HasColumnOrder(22); + + b.Property("GoogleBooksId") + .HasMaxLength(12) + .HasColumnType("TEXT") + .HasColumnOrder(27); + + b.Property("LCCN") + .HasColumnType("TEXT") + .HasColumnOrder(23); + + b.Property("LanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("LanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("LanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("LastMetadataUpdateUtc") + .HasColumnType("TEXT") + .HasColumnOrder(39); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(36); + + b.Property("LibraryThingId") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(26); + + b.Property("MetadataProvider") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(40); + + b.Property("MetadataStatus") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(38); + + b.Property("OCLCNumber") + .HasColumnType("TEXT") + .HasColumnOrder(24); + + b.Property("OpenLibraryId") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(25); + + b.Property("OriginalLanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("OriginalLanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("OriginalLanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(15); + + b.Property("OriginalReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("OriginalReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("OriginalTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("PageCount") + .HasColumnType("INTEGER") + .HasColumnOrder(17); + + b.Property("Path") + .IsRequired() + .HasMaxLength(2048) + .HasColumnType("TEXT") + .HasColumnOrder(37); + + b.Property("Publisher") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(16); + + b.Property("ReReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("ReReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(7); + + b.Property("ReleaseCountry") + .HasMaxLength(2) + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("ReleaseVersion") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("Title") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(35); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(34); + + b.Property("VolumeNumber") + .HasColumnType("REAL") + .HasColumnOrder(20); + + b.HasKey("Id"); + + b.HasIndex("LibraryId", "MetadataStatus"); + + b.HasIndex("LibraryId", "Path") + .IsUnique(); + + b.ToTable("Books", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Playlists.PlaylistEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("Description") + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("EntryCount") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(0) + .HasColumnOrder(10); + + b.Property("Name") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("Type") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UserId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("Version") + .IsConcurrencyToken() + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(0L) + .HasColumnOrder(9); + + b.HasKey("Id"); + + b.HasIndex("UserId", "UpdatedOnUtc"); + + b.ToTable("Playlists", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Playlists.PlaylistEntryEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("MediaItemId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("MediaItemType") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("PlaylistId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("Position") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.HasKey("Id"); + + b.HasIndex("MediaItemId"); + + b.HasIndex("PlaylistId", "Position") + .IsUnique(); + + b.ToTable("PlaylistEntries", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Plugins.LibraryArtworkProviderConfigurationEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("IsEnabled") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("PluginId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("Rank") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.HasKey("Id"); + + b.HasIndex("LibraryId", "PluginId"); + + b.ToTable("LibraryArtworkProviderConfigurations", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Plugins.LibraryBookReaderConfigurationEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("IsEnabled") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("PluginId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.HasKey("Id"); + + b.HasIndex("LibraryId", "PluginId") + .IsUnique(); + + b.ToTable("LibraryBookReaderConfigurations", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Plugins.LibraryMetadataProviderConfigurationEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("IsEnabled") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("PluginId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("Rank") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.HasKey("Id"); + + b.HasIndex("LibraryId", "PluginId"); + + b.ToTable("LibraryMetadataProviderConfigurations", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Plugins.PluginEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Author") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("Description") + .IsRequired() + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("LoadError") + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("LoadStatus") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("Name") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("SettingsJson") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("Version") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.HasKey("Id"); + + b.ToTable("Plugins", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Scheduling.ScheduledJobEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("Hour") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("IntervalMinutes") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("LastCompletedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("LastStartedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("Minute") + .HasColumnType("INTEGER") + .HasColumnOrder(6); + + b.Property("Name") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("OwnerUserId") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("ScheduleType") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("Status") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("TaskType") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.HasKey("Id"); + + b.HasIndex("Status"); + + b.ToTable("ScheduledJobs", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Scheduling.ScheduledJobExecutionEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CompletedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("IsCycleRun") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("ScheduledJobId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("StartedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("TaskType") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("WasCycleActive") + .HasColumnType("INTEGER") + .HasColumnOrder(6); + + b.HasKey("Id"); + + b.HasIndex("ScheduledJobId"); + + b.HasIndex("StartedOnUtc", "ScheduledJobId"); + + b.ToTable("ScheduledJobExecutions", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Scheduling.SchedulerDisplayPreferencesEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("DisplayTimeSpan") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("DisplayTimeUnit") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("JobTypeFilter") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UserId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.HasKey("Id"); + + b.HasIndex("UserId") + .IsUnique(); + + b.ToTable("SchedulerDisplayPreferences", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Themes.ThemeEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Author") + .IsRequired() + .HasMaxLength(80) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("Description") + .IsRequired() + .HasMaxLength(300) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("InstallSource") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("InstalledAtUtc") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("IsCurrent") + .HasColumnType("INTEGER") + .HasColumnOrder(8); + + b.Property("IsDeleted") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(false) + .HasColumnOrder(9); + + b.Property("Name") + .IsRequired() + .HasMaxLength(80) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("PreviewPath") + .HasMaxLength(240) + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("ThemeId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("Version") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.HasKey("Id"); + + b.HasIndex("IsCurrent") + .IsUnique() + .HasFilter("IsCurrent = 1"); + + b.HasIndex("ThemeId") + .IsUnique(); + + b.ToTable("Themes", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("Password") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("TempPassword") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("TempPasswordCreated") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("TotpSecret") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("Username") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.HasKey("Id"); + + b.HasIndex("Username") + .IsUnique(); + + b.ToTable("Users", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserSettingsEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("IsGaplessPlaybackEnabled") + .HasColumnType("INTEGER") + .HasColumnOrder(16); + + b.Property("IsMuted") + .HasColumnType("INTEGER") + .HasColumnOrder(29); + + b.Property("IsPaginationEnabled") + .HasColumnType("INTEGER") + .HasColumnOrder(2); + + b.Property("IsThemeCachingEnabled") + .HasColumnType("INTEGER") + .HasColumnOrder(9); + + b.Property("ItemsPerPage") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("ReplayGainMode") + .HasColumnType("INTEGER") + .HasColumnOrder(17); + + b.Property("ShouldAggregateArtworkWhenMissing") + .HasColumnType("INTEGER") + .HasColumnOrder(13); + + b.Property("ShouldAggregateMetadataWhenMissing") + .HasColumnType("INTEGER") + .HasColumnOrder(10); + + b.Property("ShouldAutoplay") + .HasColumnType("INTEGER") + .HasColumnOrder(15); + + b.Property("ShouldIgnoreThePrefixForAlphaPicker") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("ShouldKeepDownloadingWhilePaused") + .HasColumnType("INTEGER") + .HasColumnOrder(14); + + b.Property("ShouldPreserveBookStyles") + .HasColumnType("INTEGER") + .HasColumnOrder(12); + + b.Property("ShouldRenderPdfAsImages") + .HasColumnType("INTEGER") + .HasColumnOrder(11); + + b.Property("StreamingQuality") + .HasColumnType("INTEGER") + .HasColumnOrder(18); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UserId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("Volume") + .HasColumnType("REAL") + .HasColumnOrder(28); + + b.Property("VuMeterHighThreshold") + .HasColumnType("REAL") + .HasColumnOrder(23); + + b.Property("VuMeterMediumThreshold") + .HasColumnType("REAL") + .HasColumnOrder(22); + + b.Property("VuMeterOrientation") + .HasColumnType("INTEGER") + .HasColumnOrder(19); + + b.Property("VuMeterPeakHoldDurationInMilliseconds") + .HasColumnType("INTEGER") + .HasColumnOrder(25); + + b.Property("VuMeterPeakReleasePerSecond") + .HasColumnType("REAL") + .HasColumnOrder(27); + + b.Property("VuMeterReleasePerSecond") + .HasColumnType("REAL") + .HasColumnOrder(26); + + b.Property("VuMeterSegmentCount") + .HasColumnType("INTEGER") + .HasColumnOrder(20); + + b.Property("VuMeterSegmentGap") + .HasColumnType("INTEGER") + .HasColumnOrder(21); + + b.Property("VuMeterShowPeak") + .HasColumnType("INTEGER") + .HasColumnOrder(24); + + b.HasKey("Id"); + + b.HasIndex("UserId") + .IsUnique(); + + b.ToTable("UserSettings", (string)null); + }); + + modelBuilder.Entity("TrackGenres", b => + { + b.Property("TrackId") + .HasColumnType("TEXT"); + + b.Property("GenreId") + .HasColumnType("TEXT"); + + b.HasKey("TrackId", "GenreId"); + + b.HasIndex("GenreId"); + + b.ToTable("TrackGenres", (string)null); + }); + + modelBuilder.Entity("TrackTags", b => + { + b.Property("TrackId") + .HasColumnType("TEXT"); + + b.Property("TagId") + .HasColumnType("TEXT"); + + b.HasKey("TrackId", "TagId"); + + b.HasIndex("TagId"); + + b.ToTable("TrackTags", (string)null); + }); + + modelBuilder.Entity("AlbumGenres", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumEntity", null) + .WithMany() + .HasForeignKey("AlbumId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.GenreEntity", null) + .WithMany() + .HasForeignKey("GenreId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("AlbumTags", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumEntity", null) + .WithMany() + .HasForeignKey("AlbumId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.TagEntity", null) + .WithMany() + .HasForeignKey("TagId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("ArtistGenres", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistEntity", null) + .WithMany() + .HasForeignKey("ArtistId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.GenreEntity", null) + .WithMany() + .HasForeignKey("GenreId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("ArtistTags", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistEntity", null) + .WithMany() + .HasForeignKey("ArtistId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.TagEntity", null) + .WithMany() + .HasForeignKey("TagId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BookGenres", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", null) + .WithMany() + .HasForeignKey("BookId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.GenreEntity", null) + .WithMany() + .HasForeignKey("GenreId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BookTags", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", null) + .WithMany() + .HasForeignKey("BookId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.TagEntity", null) + .WithMany() + .HasForeignKey("TagId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.RolePermissionEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Authorization.PermissionEntity", "Permission") + .WithMany("RolePermissions") + .HasForeignKey("PermissionId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Authorization.RoleEntity", "Role") + .WithMany("RolePermissions") + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Permission"); + + b.Navigation("Role"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.UserPermissionEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Authorization.PermissionEntity", "Permission") + .WithMany("UserPermissions") + .HasForeignKey("PermissionId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", "User") + .WithMany("UserPermissions") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Permission"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.UserRoleEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Authorization.RoleEntity", "Role") + .WithMany("UserRoles") + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", "User") + .WithOne("UserRole") + .HasForeignKey("Lumina.Application.Common.DataAccess.Entities.Authorization.UserRoleEntity", "UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Role"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumContributorEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumEntity", null) + .WithMany("Contributors") + .HasForeignKey("AlbumId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistEntity", "Artist") + .WithMany("Albums") + .HasForeignKey("ArtistId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumCatalogNumberEntity", "CatalogNumbers", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("AlbumId") + .HasColumnType("TEXT"); + + b1.Property("CatalogNumber") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("AlbumId"); + + b1.ToTable("AlbumCatalogNumbers", (string)null); + + b1.WithOwner() + .HasForeignKey("AlbumId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AudioRatingEntity", "Ratings", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("AlbumId") + .HasColumnType("TEXT"); + + b1.Property("MaxValue") + .HasColumnType("decimal(3,2)"); + + b1.Property("Source") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.Property("Value") + .HasColumnType("decimal(3,2)"); + + b1.Property("VoteCount") + .HasColumnType("INTEGER"); + + b1.HasKey("Id"); + + b1.HasIndex("AlbumId"); + + b1.ToTable("AlbumRatings", (string)null); + + b1.WithOwner() + .HasForeignKey("AlbumId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumReleaseTypeEntity", "ReleaseTypes", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("AlbumId") + .HasColumnType("TEXT"); + + b1.Property("ReleaseType") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("AlbumId"); + + b1.ToTable("AlbumReleaseTypes", (string)null); + + b1.WithOwner() + .HasForeignKey("AlbumId"); + }); + + b.Navigation("Artist"); + + b.Navigation("CatalogNumbers"); + + b.Navigation("Ratings"); + + b.Navigation("ReleaseTypes"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistContributorEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistEntity", null) + .WithMany("Contributors") + .HasForeignKey("ArtistId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistEntity", b => + { + b.OwnsOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.MusicAreaEntity", "Area", b1 => + { + b1.Property("ArtistEntityId"); + + b1.Property("Disambiguation"); + + b1.Property("Iso3166Code"); + + b1.Property("MusicBrainzAreaId"); + + b1.Property("Name") + .IsRequired(); + + b1.Property("SortName"); + + b1.Property("Type"); + + b1.HasKey("ArtistEntityId"); + + b1.ToTable("Artists"); + + b1 + .ToJson("Area") + .HasColumnType("TEXT"); + + b1.WithOwner() + .HasForeignKey("ArtistEntityId"); + }); + + b.OwnsOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.MusicAreaEntity", "BeginArea", b1 => + { + b1.Property("ArtistEntityId"); + + b1.Property("Disambiguation"); + + b1.Property("Iso3166Code"); + + b1.Property("MusicBrainzAreaId"); + + b1.Property("Name") + .IsRequired(); + + b1.Property("SortName"); + + b1.Property("Type"); + + b1.HasKey("ArtistEntityId"); + + b1.ToTable("Artists"); + + b1 + .ToJson("BeginArea") + .HasColumnType("TEXT"); + + b1.WithOwner() + .HasForeignKey("ArtistEntityId"); + }); + + b.OwnsOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.MusicAreaEntity", "EndArea", b1 => + { + b1.Property("ArtistEntityId"); + + b1.Property("Disambiguation"); + + b1.Property("Iso3166Code"); + + b1.Property("MusicBrainzAreaId"); + + b1.Property("Name") + .IsRequired(); + + b1.Property("SortName"); + + b1.Property("Type"); + + b1.HasKey("ArtistEntityId"); + + b1.ToTable("Artists"); + + b1 + .ToJson("EndArea") + .HasColumnType("TEXT"); + + b1.WithOwner() + .HasForeignKey("ArtistEntityId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistAliasEntity", "Aliases", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("ArtistId") + .HasColumnType("TEXT"); + + b1.Property("BeginDate") + .HasColumnType("TEXT"); + + b1.Property("EndDate") + .HasColumnType("TEXT"); + + b1.Property("IsEnded") + .HasColumnType("INTEGER"); + + b1.Property("IsPrimary") + .HasColumnType("INTEGER"); + + b1.Property("Locale") + .HasMaxLength(20) + .HasColumnType("TEXT"); + + b1.Property("Name") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT"); + + b1.Property("SortName") + .HasMaxLength(255) + .HasColumnType("TEXT"); + + b1.Property("Type") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("ArtistId"); + + b1.ToTable("ArtistAliases", (string)null); + + b1.WithOwner() + .HasForeignKey("ArtistId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AudioRatingEntity", "Ratings", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("ArtistId") + .HasColumnType("TEXT"); + + b1.Property("MaxValue") + .HasColumnType("decimal(3,2)"); + + b1.Property("Source") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.Property("Value") + .HasColumnType("decimal(3,2)"); + + b1.Property("VoteCount") + .HasColumnType("INTEGER"); + + b1.HasKey("Id"); + + b1.HasIndex("ArtistId"); + + b1.ToTable("ArtistRatings", (string)null); + + b1.WithOwner() + .HasForeignKey("ArtistId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistIpiEntity", "Ipis", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("ArtistId") + .HasColumnType("TEXT"); + + b1.Property("Value") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("ArtistId"); + + b1.ToTable("ArtistIpis", (string)null); + + b1.WithOwner() + .HasForeignKey("ArtistId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistIsniEntity", "Isnis", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("ArtistId") + .HasColumnType("TEXT"); + + b1.Property("Value") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("ArtistId"); + + b1.ToTable("ArtistIsnis", (string)null); + + b1.WithOwner() + .HasForeignKey("ArtistId"); + }); + + b.Navigation("Aliases"); + + b.Navigation("Area"); + + b.Navigation("BeginArea"); + + b.Navigation("EndArea"); + + b.Navigation("Ipis"); + + b.Navigation("Isnis"); + + b.Navigation("Ratings"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackContributorEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackEntity", null) + .WithMany("Contributors") + .HasForeignKey("TrackId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumEntity", "Album") + .WithMany("Tracks") + .HasForeignKey("AlbumId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AudioRatingEntity", "Ratings", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("MaxValue") + .HasColumnType("decimal(3,2)"); + + b1.Property("Source") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.Property("TrackId") + .HasColumnType("TEXT"); + + b1.Property("Value") + .HasColumnType("decimal(3,2)"); + + b1.Property("VoteCount") + .HasColumnType("INTEGER"); + + b1.HasKey("Id"); + + b1.HasIndex("TrackId"); + + b1.ToTable("TrackRatings", (string)null); + + b1.WithOwner() + .HasForeignKey("TrackId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackIsrcEntity", "Isrcs", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("TrackId") + .HasColumnType("TEXT"); + + b1.Property("Value") + .IsRequired() + .HasMaxLength(12) + .HasColumnType("TEXT") + .HasColumnName("ISRC"); + + b1.HasKey("Id"); + + b1.HasIndex("TrackId"); + + b1.ToTable("TrackIsrcs", (string)null); + + b1.WithOwner() + .HasForeignKey("TrackId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackMoodEntity", "Moods", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("Name") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.Property("TrackId") + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("TrackId"); + + b1.ToTable("TrackMoods", (string)null); + + b1.WithOwner() + .HasForeignKey("TrackId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackWorkIswcEntity", "WorkIswcs", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("TrackId") + .HasColumnType("TEXT"); + + b1.Property("Value") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("TrackId"); + + b1.ToTable("TrackWorkIswcs", (string)null); + + b1.WithOwner() + .HasForeignKey("TrackId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackWorkLanguageEntity", "WorkLanguages", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("LanguageCode") + .IsRequired() + .HasMaxLength(5) + .HasColumnType("TEXT"); + + b1.Property("LanguageName") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("TEXT"); + + b1.Property("NativeName") + .HasMaxLength(100) + .HasColumnType("TEXT"); + + b1.Property("TrackId") + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("TrackId"); + + b1.ToTable("TrackWorkLanguages", (string)null); + + b1.WithOwner() + .HasForeignKey("TrackId"); + }); + + b.Navigation("Album"); + + b.Navigation("Isrcs"); + + b.Navigation("Moods"); + + b.Navigation("Ratings"); + + b.Navigation("WorkIswcs"); + + b.Navigation("WorkLanguages"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.DirectoryScanFingerprintEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", null) + .WithMany() + .HasForeignKey("LibraryId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", "User") + .WithMany("Libraries") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryContentLocationEntity", "ContentLocations", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("LibraryId") + .HasColumnType("TEXT"); + + b1.Property("Path") + .IsRequired() + .HasMaxLength(260) + .HasColumnType("TEXT") + .HasColumnName("Path"); + + b1.HasKey("Id"); + + b1.HasIndex("LibraryId"); + + b1.ToTable("LibraryContentLocations", (string)null); + + b1.WithOwner() + .HasForeignKey("LibraryId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryPathTemplatePartEntity", "PathTemplateParts", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("IsOptional") + .HasColumnType("INTEGER"); + + b1.Property("Kind") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b1.Property("LibraryId") + .HasColumnType("TEXT"); + + b1.Property("Position") + .HasColumnType("INTEGER") + .HasColumnName("Position"); + + b1.Property("Representation") + .IsRequired() + .HasMaxLength(512) + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("LibraryId", "Position") + .IsUnique(); + + b1.ToTable("LibraryPathTemplateParts", (string)null); + + b1.WithOwner() + .HasForeignKey("LibraryId"); + }); + + b.Navigation("ContentLocations"); + + b.Navigation("PathTemplateParts"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", "Library") + .WithMany("LibraryScans") + .HasForeignKey("LibraryId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", "User") + .WithMany("LibraryScans") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Library"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanResultEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", "LibraryScan") + .WithMany("LibraryScanResults") + .HasForeignKey("LibraryScanId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("LibraryScan"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanSnapshotEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", "Library") + .WithMany() + .HasForeignKey("LibraryId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Library"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanStagingResultsEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", null) + .WithMany() + .HasForeignKey("LibraryScanId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookArtworkEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", null) + .WithMany("Artwork") + .HasForeignKey("BookId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookContributorEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", null) + .WithMany("Contributors") + .HasForeignKey("BookId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", b => + { + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookRatingEntity", "Ratings", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("BookId") + .HasColumnType("TEXT"); + + b1.Property("MaxValue") + .HasColumnType("decimal(3,2)"); + + b1.Property("Source") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.Property("Value") + .HasColumnType("decimal(3,2)"); + + b1.Property("VoteCount") + .HasColumnType("INTEGER"); + + b1.HasKey("Id"); + + b1.HasIndex("BookId"); + + b1.ToTable("BookRatings", (string)null); + + b1.WithOwner() + .HasForeignKey("BookId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.IsbnEntity", "ISBNs", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("BookId") + .HasColumnType("TEXT"); + + b1.Property("Format") + .IsRequired() + .HasMaxLength(6) + .HasColumnType("TEXT"); + + b1.Property("Value") + .IsRequired() + .HasMaxLength(13) + .HasColumnType("TEXT") + .HasColumnName("ISBN"); + + b1.HasKey("Id"); + + b1.HasIndex("BookId"); + + b1.ToTable("BookISBNs", (string)null); + + b1.WithOwner() + .HasForeignKey("BookId"); + }); + + b.Navigation("ISBNs"); + + b.Navigation("Ratings"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Playlists.PlaylistEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Playlists.PlaylistEntryEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Playlists.PlaylistEntity", null) + .WithMany("Entries") + .HasForeignKey("PlaylistId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserSettingsEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", null) + .WithOne() + .HasForeignKey("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserSettingsEntity", "UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("TrackGenres", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.GenreEntity", null) + .WithMany() + .HasForeignKey("GenreId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackEntity", null) + .WithMany() + .HasForeignKey("TrackId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("TrackTags", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.TagEntity", null) + .WithMany() + .HasForeignKey("TagId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackEntity", null) + .WithMany() + .HasForeignKey("TrackId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.PermissionEntity", b => + { + b.Navigation("RolePermissions"); + + b.Navigation("UserPermissions"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.RoleEntity", b => + { + b.Navigation("RolePermissions"); + + b.Navigation("UserRoles"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumEntity", b => + { + b.Navigation("Contributors"); + + b.Navigation("Tracks"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistEntity", b => + { + b.Navigation("Albums"); + + b.Navigation("Contributors"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackEntity", b => + { + b.Navigation("Contributors"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", b => + { + b.Navigation("LibraryScans"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", b => + { + b.Navigation("LibraryScanResults"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", b => + { + b.Navigation("Artwork"); + + b.Navigation("Contributors"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Playlists.PlaylistEntity", b => + { + b.Navigation("Entries"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", b => + { + b.Navigation("Libraries"); + + b.Navigation("LibraryScans"); + + b.Navigation("UserPermissions"); + + b.Navigation("UserRole"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/Lumina.DataAccess/Common/Migrations/20261021134714_AddsVuMeterSettingsToUserSettings.cs b/src/Lumina.DataAccess/Common/Migrations/20261021134714_AddsVuMeterSettingsToUserSettings.cs new file mode 100644 index 00000000..08b32733 --- /dev/null +++ b/src/Lumina.DataAccess/Common/Migrations/20261021134714_AddsVuMeterSettingsToUserSettings.cs @@ -0,0 +1,166 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Lumina.DataAccess.Common.Migrations +{ + /// + public partial class AddsVuMeterSettingsToUserSettings : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AlterColumn( + name: "Volume", + table: "UserSettings", + type: "REAL", + nullable: false, + oldClrType: typeof(double), + oldType: "REAL") + .Annotation("Relational:ColumnOrder", 28) + .OldAnnotation("Relational:ColumnOrder", 19); + + migrationBuilder.AlterColumn( + name: "IsMuted", + table: "UserSettings", + type: "INTEGER", + nullable: false, + oldClrType: typeof(bool), + oldType: "INTEGER") + .Annotation("Relational:ColumnOrder", 29) + .OldAnnotation("Relational:ColumnOrder", 20); + + migrationBuilder.AddColumn( + name: "VuMeterHighThreshold", + table: "UserSettings", + type: "REAL", + nullable: false, + defaultValue: 0.8) + .Annotation("Relational:ColumnOrder", 23); + + migrationBuilder.AddColumn( + name: "VuMeterMediumThreshold", + table: "UserSettings", + type: "REAL", + nullable: false, + defaultValue: 0.6) + .Annotation("Relational:ColumnOrder", 22); + + migrationBuilder.AddColumn( + name: "VuMeterOrientation", + table: "UserSettings", + type: "INTEGER", + nullable: false, + defaultValue: 0) + .Annotation("Relational:ColumnOrder", 19); + + migrationBuilder.AddColumn( + name: "VuMeterPeakHoldDurationInMilliseconds", + table: "UserSettings", + type: "INTEGER", + nullable: false, + defaultValue: 650) + .Annotation("Relational:ColumnOrder", 25); + + migrationBuilder.AddColumn( + name: "VuMeterPeakReleasePerSecond", + table: "UserSettings", + type: "REAL", + nullable: false, + defaultValue: 0.65) + .Annotation("Relational:ColumnOrder", 27); + + migrationBuilder.AddColumn( + name: "VuMeterReleasePerSecond", + table: "UserSettings", + type: "REAL", + nullable: false, + defaultValue: 3.0) + .Annotation("Relational:ColumnOrder", 26); + + migrationBuilder.AddColumn( + name: "VuMeterSegmentCount", + table: "UserSettings", + type: "INTEGER", + nullable: false, + defaultValue: 12) + .Annotation("Relational:ColumnOrder", 20); + + migrationBuilder.AddColumn( + name: "VuMeterSegmentGap", + table: "UserSettings", + type: "INTEGER", + nullable: false, + defaultValue: 1) + .Annotation("Relational:ColumnOrder", 21); + + migrationBuilder.AddColumn( + name: "VuMeterShowPeak", + table: "UserSettings", + type: "INTEGER", + nullable: false, + defaultValue: true) + .Annotation("Relational:ColumnOrder", 24); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropColumn( + name: "VuMeterHighThreshold", + table: "UserSettings"); + + migrationBuilder.DropColumn( + name: "VuMeterMediumThreshold", + table: "UserSettings"); + + migrationBuilder.DropColumn( + name: "VuMeterOrientation", + table: "UserSettings"); + + migrationBuilder.DropColumn( + name: "VuMeterPeakHoldDurationInMilliseconds", + table: "UserSettings"); + + migrationBuilder.DropColumn( + name: "VuMeterPeakReleasePerSecond", + table: "UserSettings"); + + migrationBuilder.DropColumn( + name: "VuMeterReleasePerSecond", + table: "UserSettings"); + + migrationBuilder.DropColumn( + name: "VuMeterSegmentCount", + table: "UserSettings"); + + migrationBuilder.DropColumn( + name: "VuMeterSegmentGap", + table: "UserSettings"); + + migrationBuilder.DropColumn( + name: "VuMeterShowPeak", + table: "UserSettings"); + + migrationBuilder.AlterColumn( + name: "Volume", + table: "UserSettings", + type: "REAL", + nullable: false, + oldClrType: typeof(double), + oldType: "REAL") + .Annotation("Relational:ColumnOrder", 19) + .OldAnnotation("Relational:ColumnOrder", 28); + + migrationBuilder.AlterColumn( + name: "IsMuted", + table: "UserSettings", + type: "INTEGER", + nullable: false, + oldClrType: typeof(bool), + oldType: "INTEGER") + .Annotation("Relational:ColumnOrder", 20) + .OldAnnotation("Relational:ColumnOrder", 29); + } + } +} diff --git a/src/Lumina.DataAccess/Common/Migrations/20261021184608_AddsFavorites.Designer.cs b/src/Lumina.DataAccess/Common/Migrations/20261021184608_AddsFavorites.Designer.cs new file mode 100644 index 00000000..d02201cb --- /dev/null +++ b/src/Lumina.DataAccess/Common/Migrations/20261021184608_AddsFavorites.Designer.cs @@ -0,0 +1,3766 @@ +// +using System; +using Lumina.DataAccess.Core.UoW; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace Lumina.DataAccess.Common.Migrations +{ + [DbContext(typeof(LuminaDbContext))] + [Migration("20261021184608_AddsFavorites")] + partial class AddsFavorites + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder.HasAnnotation("ProductVersion", "10.0.11"); + + modelBuilder.Entity("AlbumGenres", b => + { + b.Property("AlbumId") + .HasColumnType("TEXT"); + + b.Property("GenreId") + .HasColumnType("TEXT"); + + b.HasKey("AlbumId", "GenreId"); + + b.HasIndex("GenreId"); + + b.ToTable("AlbumGenres", (string)null); + }); + + modelBuilder.Entity("AlbumTags", b => + { + b.Property("AlbumId") + .HasColumnType("TEXT"); + + b.Property("TagId") + .HasColumnType("TEXT"); + + b.HasKey("AlbumId", "TagId"); + + b.HasIndex("TagId"); + + b.ToTable("AlbumTags", (string)null); + }); + + modelBuilder.Entity("ArtistGenres", b => + { + b.Property("ArtistId") + .HasColumnType("TEXT"); + + b.Property("GenreId") + .HasColumnType("TEXT"); + + b.HasKey("ArtistId", "GenreId"); + + b.HasIndex("GenreId"); + + b.ToTable("ArtistGenres", (string)null); + }); + + modelBuilder.Entity("ArtistTags", b => + { + b.Property("ArtistId") + .HasColumnType("TEXT"); + + b.Property("TagId") + .HasColumnType("TEXT"); + + b.HasKey("ArtistId", "TagId"); + + b.HasIndex("TagId"); + + b.ToTable("ArtistTags", (string)null); + }); + + modelBuilder.Entity("BookGenres", b => + { + b.Property("BookId") + .HasColumnType("TEXT"); + + b.Property("GenreId") + .HasColumnType("TEXT"); + + b.HasKey("BookId", "GenreId"); + + b.HasIndex("GenreId"); + + b.ToTable("BookGenres", (string)null); + }); + + modelBuilder.Entity("BookTags", b => + { + b.Property("BookId") + .HasColumnType("TEXT"); + + b.Property("TagId") + .HasColumnType("TEXT"); + + b.HasKey("BookId", "TagId"); + + b.HasIndex("TagId"); + + b.ToTable("BookTags", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.PermissionEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("PermissionName") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.HasKey("Id"); + + b.ToTable("Permissions", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.RoleEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("RoleName") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.HasKey("Id"); + + b.ToTable("Roles", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.RolePermissionEntity", b => + { + b.Property("RoleId") + .HasColumnType("TEXT"); + + b.Property("PermissionId") + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.HasKey("RoleId", "PermissionId"); + + b.HasIndex("PermissionId"); + + b.HasIndex("RoleId", "PermissionId") + .IsUnique(); + + b.ToTable("RolePermissions", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.UserPermissionEntity", b => + { + b.Property("UserId") + .HasColumnType("TEXT"); + + b.Property("PermissionId") + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.HasKey("UserId", "PermissionId"); + + b.HasIndex("PermissionId"); + + b.HasIndex("UserId", "PermissionId") + .IsUnique(); + + b.ToTable("UserPermissions", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.UserRoleEntity", b => + { + b.Property("UserId") + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("RoleId") + .HasColumnType("TEXT"); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.HasKey("UserId"); + + b.HasIndex("RoleId"); + + b.HasIndex("UserId", "RoleId") + .IsUnique(); + + b.ToTable("UserRoles", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Common.GenreEntity", b => + { + b.Property("Name") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b.HasKey("Name"); + + b.ToTable("Genres", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Common.TagEntity", b => + { + b.Property("Name") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b.HasKey("Name"); + + b.ToTable("Tags", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Favorites.FavoriteEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("MediaItemId") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("MediaKind") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("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("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Biography") + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("DateOfBirth") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("DateOfDeath") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("DisplayName") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1) + .UseCollation("NOCASE"); + + b.Property("LegalName") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.HasKey("Id"); + + b.HasIndex("DisplayName") + .IsUnique(); + + b.ToTable("MediaContributors", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumContributorEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("AlbumId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("MediaContributorId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("Role") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.HasKey("Id"); + + b.HasIndex("MediaContributorId"); + + b.HasIndex("AlbumId", "MediaContributorId", "Role") + .IsUnique(); + + b.ToTable("AlbumContributors", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("ASIN") + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(28); + + b.Property("ArtistId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("Barcode") + .HasMaxLength(13) + .HasColumnType("TEXT") + .HasColumnOrder(25); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(33); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(32); + + b.Property("Description") + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("Disambiguation") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("Label") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(27); + + b.Property("LanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("LanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("LanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(15); + + b.Property("LastMetadataUpdateUtc") + .HasColumnType("TEXT") + .HasColumnOrder(37); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("MediaFormat") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(23); + + b.Property("MetadataProvider") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(38); + + b.Property("MetadataStatus") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasDefaultValue("Pending") + .HasColumnOrder(36); + + b.Property("MusicBrainzReleaseArtistId") + .HasColumnType("TEXT") + .HasColumnOrder(31); + + b.Property("MusicBrainzReleaseGroupId") + .HasColumnType("TEXT") + .HasColumnOrder(30); + + b.Property("MusicBrainzReleaseId") + .HasColumnType("TEXT") + .HasColumnOrder(29); + + b.Property("OriginalLanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(16); + + b.Property("OriginalLanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(17); + + b.Property("OriginalLanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(18); + + b.Property("OriginalReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("OriginalReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(8); + + b.Property("OriginalTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("Packaging") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(24); + + b.Property("ReReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("ReReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(10); + + b.Property("ReleaseCountry") + .HasMaxLength(2) + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("ReleaseStatus") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(20); + + b.Property("ReleaseTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(26); + + b.Property("ReleaseVersion") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("Script") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(19); + + b.Property("Title") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("TotalDiscs") + .HasColumnType("INTEGER") + .HasColumnOrder(21); + + b.Property("TotalTracks") + .HasColumnType("INTEGER") + .HasColumnOrder(22); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(35); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(34); + + b.HasKey("Id"); + + b.HasIndex("ArtistId", "Title"); + + b.HasIndex("LibraryId", "Title"); + + b.ToTable("Albums", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistContributorEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("ArtistId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("MediaContributorId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("Role") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.HasKey("Id"); + + b.HasIndex("MediaContributorId"); + + b.HasIndex("ArtistId", "MediaContributorId", "Role") + .IsUnique(); + + b.ToTable("ArtistContributors", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Country") + .HasMaxLength(2) + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("Disambiguation") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("Gender") + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("IsEnded") + .HasColumnType("INTEGER") + .HasColumnOrder(10); + + b.Property("LastMetadataUpdateUtc") + .HasColumnType("TEXT") + .HasColumnOrder(18); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("LifeSpanBegin") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("LifeSpanEnd") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("MetadataProvider") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(19); + + b.Property("MetadataStatus") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasDefaultValue("Pending") + .HasColumnOrder(17); + + b.Property("MusicBrainzArtistId") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("Name") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("SortName") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("Type") + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(16); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(15); + + b.Property("Website") + .HasMaxLength(2048) + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.HasKey("Id"); + + b.HasIndex("LibraryId", "Name") + .IsUnique(); + + b.ToTable("Artists", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.MusicArtworkEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("ArtworkType") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("ContentHash") + .HasColumnType("INTEGER") + .HasColumnOrder(6); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("FileName") + .HasMaxLength(2048) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("LastUpdateUtc") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("Ordinal") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("OwnerId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("OwnerType") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("Provider") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("Status") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.HasKey("Id"); + + b.HasIndex("Status"); + + b.HasIndex("OwnerType", "OwnerId", "ArtworkType", "Ordinal") + .IsUnique(); + + b.ToTable("MusicArtwork", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.MusicLibraryScanItemMetadataEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("AcoustId") + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnOrder(25); + + b.Property("ArtistName") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("AudioCodec") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(15); + + b.Property("BitDepth") + .HasColumnType("INTEGER") + .HasColumnOrder(14); + + b.Property("Bitrate") + .HasColumnType("INTEGER") + .HasColumnOrder(16); + + b.Property("Channels") + .HasColumnType("INTEGER") + .HasColumnOrder(13); + + b.Property("Container") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(31); + + b.Property("DiscNumber") + .HasColumnType("INTEGER") + .HasColumnOrder(10); + + b.Property("DurationInSeconds") + .HasColumnType("INTEGER") + .HasColumnOrder(11); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("LibraryScanId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.PrimitiveCollection("Moods") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(30); + + b.Property("MusicBrainzArtistId") + .HasColumnType("TEXT") + .HasColumnOrder(17); + + b.Property("MusicBrainzRecordingId") + .HasColumnType("TEXT") + .HasColumnOrder(21); + + b.Property("MusicBrainzReleaseArtistId") + .HasColumnType("TEXT") + .HasColumnOrder(18); + + b.Property("MusicBrainzReleaseGroupId") + .HasColumnType("TEXT") + .HasColumnOrder(19); + + b.Property("MusicBrainzReleaseId") + .HasColumnType("TEXT") + .HasColumnOrder(20); + + b.Property("MusicBrainzTrackId") + .HasColumnType("TEXT") + .HasColumnOrder(22); + + b.Property("MusicBrainzWorkId") + .HasColumnType("TEXT") + .HasColumnOrder(23); + + b.Property("Path") + .IsRequired() + .HasMaxLength(2048) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("ReleaseName") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("ReleaseType") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("ReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(6); + + b.Property("ReplayGainAlbumGain") + .HasColumnType("decimal(8,2)") + .HasColumnOrder(28); + + b.Property("ReplayGainAlbumPeak") + .HasColumnType("decimal(8,6)") + .HasColumnOrder(29); + + b.Property("ReplayGainTrackGain") + .HasColumnType("decimal(8,2)") + .HasColumnOrder(26); + + b.Property("ReplayGainTrackPeak") + .HasColumnType("decimal(8,6)") + .HasColumnOrder(27); + + b.Property("SampleRate") + .HasColumnType("INTEGER") + .HasColumnOrder(12); + + b.Property("TrackNumber") + .HasColumnType("INTEGER") + .HasColumnOrder(9); + + b.Property("TrackTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("WorkTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(24); + + b.HasKey("Id"); + + b.HasIndex("LibraryScanId", "Path") + .IsUnique(); + + b.ToTable("MusicLibraryScanItemMetadata", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.MusicPlayRecordEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("AlbumId") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("ArtistId") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("EndedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("LastPositionMilliseconds") + .HasColumnType("INTEGER") + .HasColumnOrder(7); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("ListenedDurationMilliseconds") + .HasColumnType("INTEGER") + .HasColumnOrder(8); + + b.Property("Status") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("TrackId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("UserId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("Version") + .IsConcurrencyToken() + .HasColumnType("INTEGER") + .HasColumnOrder(10); + + b.HasKey("Id"); + + b.HasIndex("TrackId"); + + b.HasIndex("UserId", "CreatedOnUtc"); + + b.ToTable("MusicPlayRecords", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackContributorEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("MediaContributorId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("Role") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("TrackId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.HasKey("Id"); + + b.HasIndex("MediaContributorId"); + + b.HasIndex("TrackId", "MediaContributorId", "Role") + .IsUnique(); + + b.ToTable("TrackContributors", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("AcoustId") + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnOrder(44); + + b.Property("AlbumId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("AudioCodec") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(24); + + b.Property("BitDepth") + .HasColumnType("INTEGER") + .HasColumnOrder(23); + + b.Property("Bitrate") + .HasColumnType("INTEGER") + .HasColumnOrder(25); + + b.Property("Bpm") + .HasColumnType("INTEGER") + .HasColumnOrder(30); + + b.Property("Channels") + .HasColumnType("INTEGER") + .HasColumnOrder(22); + + b.Property("Container") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(49); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(38); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(37); + + b.Property("Description") + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("Disambiguation") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("DiscNumber") + .HasColumnType("INTEGER") + .HasColumnOrder(27); + + b.Property("DurationInSeconds") + .HasColumnType("INTEGER") + .HasColumnOrder(20); + + b.Property("IsVideo") + .HasColumnType("INTEGER") + .HasColumnOrder(31); + + b.Property("Key") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(29); + + b.Property("LanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("LanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(15); + + b.Property("LanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(16); + + b.Property("LastMetadataUpdateUtc") + .HasColumnType("TEXT") + .HasColumnOrder(42); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("MetadataProvider") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(43); + + b.Property("MetadataStatus") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasDefaultValue("Pending") + .HasColumnOrder(41); + + b.Property("MusicBrainzRecordingId") + .HasColumnType("TEXT") + .HasColumnOrder(34); + + b.Property("MusicBrainzTrackId") + .HasColumnType("TEXT") + .HasColumnOrder(35); + + b.Property("MusicBrainzWorkId") + .HasColumnType("TEXT") + .HasColumnOrder(36); + + b.Property("OriginalLanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(17); + + b.Property("OriginalLanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(18); + + b.Property("OriginalLanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(19); + + b.Property("OriginalReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("OriginalReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(9); + + b.Property("OriginalTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("Path") + .IsRequired() + .HasMaxLength(2048) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("ReReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("ReReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(11); + + b.Property("ReleaseCountry") + .HasMaxLength(2) + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("ReleaseVersion") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("ReplayGainAlbumGain") + .HasColumnType("decimal(8,2)") + .HasColumnOrder(47); + + b.Property("ReplayGainAlbumPeak") + .HasColumnType("decimal(8,6)") + .HasColumnOrder(48); + + b.Property("ReplayGainTrackGain") + .HasColumnType("decimal(8,2)") + .HasColumnOrder(45); + + b.Property("ReplayGainTrackPeak") + .HasColumnType("decimal(8,6)") + .HasColumnOrder(46); + + b.Property("SampleRate") + .HasColumnType("INTEGER") + .HasColumnOrder(21); + + b.Property("Script") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(28); + + b.Property("Title") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("TrackNumber") + .HasColumnType("INTEGER") + .HasColumnOrder(26); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(40); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(39); + + b.Property("WorkTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(32); + + b.Property("WorkType") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(33); + + b.HasKey("Id"); + + b.HasIndex("AlbumId", "TrackNumber"); + + b.HasIndex("LibraryId", "Path") + .IsUnique(); + + b.ToTable("Tracks", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.DirectoryScanFingerprintEntity", b => + { + b.Property("LibraryId") + .HasColumnType("TEXT"); + + b.Property("Path") + .HasMaxLength(1024) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("LastWriteTimeUtc") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.HasKey("LibraryId", "Path"); + + b.HasIndex("LibraryId"); + + b.ToTable("DirectoryScanFingerprints", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("ArtworkProvidersConfigurationFingerprint") + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("CanDownloadMetadataFromWeb") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(true) + .HasColumnOrder(6); + + b.Property("CoverImage") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("IsEnabled") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(true) + .HasColumnOrder(4); + + b.Property("IsLocked") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("LibraryType") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("MetadataProvidersConfigurationFingerprint") + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("PathTemplateFingerprint") + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("ShouldSaveMetadataInMediaDirectories") + .HasColumnType("INTEGER") + .HasColumnOrder(7); + + b.Property("ShouldSkipUnchangedDirectoriesDuringScan") + .HasColumnType("INTEGER") + .HasColumnOrder(8); + + b.Property("Title") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(15); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("UserId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("Libraries", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("LibraryId") + .HasColumnType("TEXT"); + + b.Property("Status") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UserId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.HasIndex("LibraryId", "Status", "CreatedOnUtc") + .IsDescending(true, false, true); + + b.ToTable("LibraryScans", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanResultEntity", b => + { + b.Property("LibraryScanId") + .HasColumnType("TEXT"); + + b.Property("Path") + .HasMaxLength(1024) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("ContentHash") + .HasMaxLength(24) + .HasColumnType("INTEGER") + .HasColumnOrder(2); + + b.Property("FileSize") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Status") + .IsRequired() + .HasMaxLength(10) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("Ticks") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.HasKey("LibraryScanId", "Path"); + + b.HasIndex("Path"); + + b.HasIndex("ContentHash", "FileSize", "Path"); + + b.ToTable("LibraryScanResults", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanSnapshotEntity", b => + { + b.Property("LibraryId") + .HasColumnType("TEXT"); + + b.Property("Path") + .HasMaxLength(1024) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("ContentHash") + .HasColumnType("INTEGER") + .HasColumnOrder(2); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("FileSize") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Ticks") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.HasKey("LibraryId", "Path"); + + b.HasIndex("LibraryId"); + + b.ToTable("LibraryScanSnapshots", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanStagingResultsEntity", b => + { + b.Property("LibraryScanId") + .HasColumnType("TEXT"); + + b.Property("Path") + .HasMaxLength(1024) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("ContentHash") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("IsNew") + .HasColumnType("INTEGER") + .HasColumnOrder(7); + + b.Property("NeedsRehash") + .HasColumnType("INTEGER") + .HasColumnOrder(6); + + b.Property("PreviousContentHash") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("Size") + .HasColumnType("INTEGER") + .HasColumnOrder(2); + + b.Property("Ticks") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.HasKey("LibraryScanId", "Path"); + + b.HasIndex("LibraryScanId", "NeedsRehash"); + + b.ToTable("LibraryScanStagingResults", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookArtworkEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("ArtworkType") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("BookId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("ContentHash") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("FileName") + .HasMaxLength(2048) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("LastUpdateUtc") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("Ordinal") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("Provider") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("Status") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.HasKey("Id"); + + b.HasIndex("Status"); + + b.HasIndex("BookId", "ArtworkType", "Ordinal") + .IsUnique(); + + b.ToTable("BookArtwork", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookContributorEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("BookId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("MediaContributorId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("Role") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.HasKey("Id"); + + b.HasIndex("MediaContributorId"); + + b.HasIndex("BookId", "MediaContributorId", "Role") + .IsUnique(); + + b.ToTable("BookContributors", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("ASIN") + .HasMaxLength(10) + .HasColumnType("TEXT") + .HasColumnOrder(21); + + b.Property("AppleBooksId") + .HasColumnType("TEXT") + .HasColumnOrder(29); + + b.Property("BarnesAndNobleId") + .HasMaxLength(10) + .HasColumnType("TEXT") + .HasColumnOrder(28); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(33); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(32); + + b.Property("Description") + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("Edition") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(19); + + b.Property("Format") + .HasColumnType("TEXT") + .HasColumnOrder(18); + + b.Property("GoodreadsId") + .HasColumnType("TEXT") + .HasColumnOrder(22); + + b.Property("GoogleBooksId") + .HasMaxLength(12) + .HasColumnType("TEXT") + .HasColumnOrder(27); + + b.Property("LCCN") + .HasColumnType("TEXT") + .HasColumnOrder(23); + + b.Property("LanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("LanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("LanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("LastMetadataUpdateUtc") + .HasColumnType("TEXT") + .HasColumnOrder(39); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(36); + + b.Property("LibraryThingId") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(26); + + b.Property("MetadataProvider") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(40); + + b.Property("MetadataStatus") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(38); + + b.Property("OCLCNumber") + .HasColumnType("TEXT") + .HasColumnOrder(24); + + b.Property("OpenLibraryId") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(25); + + b.Property("OriginalLanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("OriginalLanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("OriginalLanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(15); + + b.Property("OriginalReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("OriginalReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("OriginalTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("PageCount") + .HasColumnType("INTEGER") + .HasColumnOrder(17); + + b.Property("Path") + .IsRequired() + .HasMaxLength(2048) + .HasColumnType("TEXT") + .HasColumnOrder(37); + + b.Property("Publisher") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(16); + + b.Property("ReReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("ReReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(7); + + b.Property("ReleaseCountry") + .HasMaxLength(2) + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("ReleaseVersion") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("Title") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(35); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(34); + + b.Property("VolumeNumber") + .HasColumnType("REAL") + .HasColumnOrder(20); + + b.HasKey("Id"); + + b.HasIndex("LibraryId", "MetadataStatus"); + + b.HasIndex("LibraryId", "Path") + .IsUnique(); + + b.ToTable("Books", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Playlists.PlaylistEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("Description") + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("EntryCount") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(0) + .HasColumnOrder(10); + + b.Property("Name") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("Type") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UserId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("Version") + .IsConcurrencyToken() + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(0L) + .HasColumnOrder(9); + + b.HasKey("Id"); + + b.HasIndex("UserId", "UpdatedOnUtc"); + + b.ToTable("Playlists", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Playlists.PlaylistEntryEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("MediaItemId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("MediaItemType") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("PlaylistId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("Position") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.HasKey("Id"); + + b.HasIndex("MediaItemId"); + + b.HasIndex("PlaylistId", "Position") + .IsUnique(); + + b.ToTable("PlaylistEntries", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Plugins.LibraryArtworkProviderConfigurationEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("IsEnabled") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("PluginId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("Rank") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.HasKey("Id"); + + b.HasIndex("LibraryId", "PluginId"); + + b.ToTable("LibraryArtworkProviderConfigurations", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Plugins.LibraryBookReaderConfigurationEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("IsEnabled") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("PluginId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.HasKey("Id"); + + b.HasIndex("LibraryId", "PluginId") + .IsUnique(); + + b.ToTable("LibraryBookReaderConfigurations", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Plugins.LibraryMetadataProviderConfigurationEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("IsEnabled") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("PluginId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("Rank") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.HasKey("Id"); + + b.HasIndex("LibraryId", "PluginId"); + + b.ToTable("LibraryMetadataProviderConfigurations", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Plugins.PluginEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Author") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("Description") + .IsRequired() + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("LoadError") + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("LoadStatus") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("Name") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("SettingsJson") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("Version") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.HasKey("Id"); + + b.ToTable("Plugins", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Scheduling.ScheduledJobEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("Hour") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("IntervalMinutes") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("LastCompletedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("LastStartedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("Minute") + .HasColumnType("INTEGER") + .HasColumnOrder(6); + + b.Property("Name") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("OwnerUserId") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("ScheduleType") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("Status") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("TaskType") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.HasKey("Id"); + + b.HasIndex("Status"); + + b.ToTable("ScheduledJobs", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Scheduling.ScheduledJobExecutionEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CompletedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("IsCycleRun") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("ScheduledJobId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("StartedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("TaskType") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("WasCycleActive") + .HasColumnType("INTEGER") + .HasColumnOrder(6); + + b.HasKey("Id"); + + b.HasIndex("ScheduledJobId"); + + b.HasIndex("StartedOnUtc", "ScheduledJobId"); + + b.ToTable("ScheduledJobExecutions", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Scheduling.SchedulerDisplayPreferencesEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("DisplayTimeSpan") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("DisplayTimeUnit") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("JobTypeFilter") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UserId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.HasKey("Id"); + + b.HasIndex("UserId") + .IsUnique(); + + b.ToTable("SchedulerDisplayPreferences", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Themes.ThemeEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Author") + .IsRequired() + .HasMaxLength(80) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("Description") + .IsRequired() + .HasMaxLength(300) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("InstallSource") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("InstalledAtUtc") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("IsCurrent") + .HasColumnType("INTEGER") + .HasColumnOrder(8); + + b.Property("IsDeleted") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(false) + .HasColumnOrder(9); + + b.Property("Name") + .IsRequired() + .HasMaxLength(80) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("PreviewPath") + .HasMaxLength(240) + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("ThemeId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("Version") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.HasKey("Id"); + + b.HasIndex("IsCurrent") + .IsUnique() + .HasFilter("IsCurrent = 1"); + + b.HasIndex("ThemeId") + .IsUnique(); + + b.ToTable("Themes", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("Password") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("TempPassword") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("TempPasswordCreated") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("TotpSecret") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("Username") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.HasKey("Id"); + + b.HasIndex("Username") + .IsUnique(); + + b.ToTable("Users", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserSettingsEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("IsGaplessPlaybackEnabled") + .HasColumnType("INTEGER") + .HasColumnOrder(16); + + b.Property("IsMuted") + .HasColumnType("INTEGER") + .HasColumnOrder(29); + + b.Property("IsPaginationEnabled") + .HasColumnType("INTEGER") + .HasColumnOrder(2); + + b.Property("IsThemeCachingEnabled") + .HasColumnType("INTEGER") + .HasColumnOrder(9); + + b.Property("ItemsPerPage") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("ReplayGainMode") + .HasColumnType("INTEGER") + .HasColumnOrder(17); + + b.Property("ShouldAggregateArtworkWhenMissing") + .HasColumnType("INTEGER") + .HasColumnOrder(13); + + b.Property("ShouldAggregateMetadataWhenMissing") + .HasColumnType("INTEGER") + .HasColumnOrder(10); + + b.Property("ShouldAutoplay") + .HasColumnType("INTEGER") + .HasColumnOrder(15); + + b.Property("ShouldIgnoreThePrefixForAlphaPicker") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("ShouldKeepDownloadingWhilePaused") + .HasColumnType("INTEGER") + .HasColumnOrder(14); + + b.Property("ShouldPreserveBookStyles") + .HasColumnType("INTEGER") + .HasColumnOrder(12); + + b.Property("ShouldRenderPdfAsImages") + .HasColumnType("INTEGER") + .HasColumnOrder(11); + + b.Property("StreamingQuality") + .HasColumnType("INTEGER") + .HasColumnOrder(18); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UserId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("Volume") + .HasColumnType("REAL") + .HasColumnOrder(28); + + b.Property("VuMeterHighThreshold") + .HasColumnType("REAL") + .HasColumnOrder(23); + + b.Property("VuMeterMediumThreshold") + .HasColumnType("REAL") + .HasColumnOrder(22); + + b.Property("VuMeterOrientation") + .HasColumnType("INTEGER") + .HasColumnOrder(19); + + b.Property("VuMeterPeakHoldDurationInMilliseconds") + .HasColumnType("INTEGER") + .HasColumnOrder(25); + + b.Property("VuMeterPeakReleasePerSecond") + .HasColumnType("REAL") + .HasColumnOrder(27); + + b.Property("VuMeterReleasePerSecond") + .HasColumnType("REAL") + .HasColumnOrder(26); + + b.Property("VuMeterSegmentCount") + .HasColumnType("INTEGER") + .HasColumnOrder(20); + + b.Property("VuMeterSegmentGap") + .HasColumnType("INTEGER") + .HasColumnOrder(21); + + b.Property("VuMeterShowPeak") + .HasColumnType("INTEGER") + .HasColumnOrder(24); + + b.HasKey("Id"); + + b.HasIndex("UserId") + .IsUnique(); + + b.ToTable("UserSettings", (string)null); + }); + + modelBuilder.Entity("TrackGenres", b => + { + b.Property("TrackId") + .HasColumnType("TEXT"); + + b.Property("GenreId") + .HasColumnType("TEXT"); + + b.HasKey("TrackId", "GenreId"); + + b.HasIndex("GenreId"); + + b.ToTable("TrackGenres", (string)null); + }); + + modelBuilder.Entity("TrackTags", b => + { + b.Property("TrackId") + .HasColumnType("TEXT"); + + b.Property("TagId") + .HasColumnType("TEXT"); + + b.HasKey("TrackId", "TagId"); + + b.HasIndex("TagId"); + + b.ToTable("TrackTags", (string)null); + }); + + modelBuilder.Entity("AlbumGenres", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumEntity", null) + .WithMany() + .HasForeignKey("AlbumId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.GenreEntity", null) + .WithMany() + .HasForeignKey("GenreId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("AlbumTags", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumEntity", null) + .WithMany() + .HasForeignKey("AlbumId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.TagEntity", null) + .WithMany() + .HasForeignKey("TagId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("ArtistGenres", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistEntity", null) + .WithMany() + .HasForeignKey("ArtistId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.GenreEntity", null) + .WithMany() + .HasForeignKey("GenreId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("ArtistTags", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistEntity", null) + .WithMany() + .HasForeignKey("ArtistId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.TagEntity", null) + .WithMany() + .HasForeignKey("TagId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BookGenres", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", null) + .WithMany() + .HasForeignKey("BookId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.GenreEntity", null) + .WithMany() + .HasForeignKey("GenreId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BookTags", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", null) + .WithMany() + .HasForeignKey("BookId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.TagEntity", null) + .WithMany() + .HasForeignKey("TagId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.RolePermissionEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Authorization.PermissionEntity", "Permission") + .WithMany("RolePermissions") + .HasForeignKey("PermissionId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Authorization.RoleEntity", "Role") + .WithMany("RolePermissions") + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Permission"); + + b.Navigation("Role"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.UserPermissionEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Authorization.PermissionEntity", "Permission") + .WithMany("UserPermissions") + .HasForeignKey("PermissionId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", "User") + .WithMany("UserPermissions") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Permission"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.UserRoleEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Authorization.RoleEntity", "Role") + .WithMany("UserRoles") + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", "User") + .WithOne("UserRole") + .HasForeignKey("Lumina.Application.Common.DataAccess.Entities.Authorization.UserRoleEntity", "UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Role"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.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) + .WithMany("Contributors") + .HasForeignKey("AlbumId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistEntity", "Artist") + .WithMany("Albums") + .HasForeignKey("ArtistId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumCatalogNumberEntity", "CatalogNumbers", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("AlbumId") + .HasColumnType("TEXT"); + + b1.Property("CatalogNumber") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("AlbumId"); + + b1.ToTable("AlbumCatalogNumbers", (string)null); + + b1.WithOwner() + .HasForeignKey("AlbumId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AudioRatingEntity", "Ratings", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("AlbumId") + .HasColumnType("TEXT"); + + b1.Property("MaxValue") + .HasColumnType("decimal(3,2)"); + + b1.Property("Source") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.Property("Value") + .HasColumnType("decimal(3,2)"); + + b1.Property("VoteCount") + .HasColumnType("INTEGER"); + + b1.HasKey("Id"); + + b1.HasIndex("AlbumId"); + + b1.ToTable("AlbumRatings", (string)null); + + b1.WithOwner() + .HasForeignKey("AlbumId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumReleaseTypeEntity", "ReleaseTypes", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("AlbumId") + .HasColumnType("TEXT"); + + b1.Property("ReleaseType") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("AlbumId"); + + b1.ToTable("AlbumReleaseTypes", (string)null); + + b1.WithOwner() + .HasForeignKey("AlbumId"); + }); + + b.Navigation("Artist"); + + b.Navigation("CatalogNumbers"); + + b.Navigation("Ratings"); + + b.Navigation("ReleaseTypes"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistContributorEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistEntity", null) + .WithMany("Contributors") + .HasForeignKey("ArtistId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistEntity", b => + { + b.OwnsOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.MusicAreaEntity", "Area", b1 => + { + b1.Property("ArtistEntityId"); + + b1.Property("Disambiguation"); + + b1.Property("Iso3166Code"); + + b1.Property("MusicBrainzAreaId"); + + b1.Property("Name") + .IsRequired(); + + b1.Property("SortName"); + + b1.Property("Type"); + + b1.HasKey("ArtistEntityId"); + + b1.ToTable("Artists"); + + b1 + .ToJson("Area") + .HasColumnType("TEXT"); + + b1.WithOwner() + .HasForeignKey("ArtistEntityId"); + }); + + b.OwnsOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.MusicAreaEntity", "BeginArea", b1 => + { + b1.Property("ArtistEntityId"); + + b1.Property("Disambiguation"); + + b1.Property("Iso3166Code"); + + b1.Property("MusicBrainzAreaId"); + + b1.Property("Name") + .IsRequired(); + + b1.Property("SortName"); + + b1.Property("Type"); + + b1.HasKey("ArtistEntityId"); + + b1.ToTable("Artists"); + + b1 + .ToJson("BeginArea") + .HasColumnType("TEXT"); + + b1.WithOwner() + .HasForeignKey("ArtistEntityId"); + }); + + b.OwnsOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.MusicAreaEntity", "EndArea", b1 => + { + b1.Property("ArtistEntityId"); + + b1.Property("Disambiguation"); + + b1.Property("Iso3166Code"); + + b1.Property("MusicBrainzAreaId"); + + b1.Property("Name") + .IsRequired(); + + b1.Property("SortName"); + + b1.Property("Type"); + + b1.HasKey("ArtistEntityId"); + + b1.ToTable("Artists"); + + b1 + .ToJson("EndArea") + .HasColumnType("TEXT"); + + b1.WithOwner() + .HasForeignKey("ArtistEntityId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistAliasEntity", "Aliases", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("ArtistId") + .HasColumnType("TEXT"); + + b1.Property("BeginDate") + .HasColumnType("TEXT"); + + b1.Property("EndDate") + .HasColumnType("TEXT"); + + b1.Property("IsEnded") + .HasColumnType("INTEGER"); + + b1.Property("IsPrimary") + .HasColumnType("INTEGER"); + + b1.Property("Locale") + .HasMaxLength(20) + .HasColumnType("TEXT"); + + b1.Property("Name") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT"); + + b1.Property("SortName") + .HasMaxLength(255) + .HasColumnType("TEXT"); + + b1.Property("Type") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("ArtistId"); + + b1.ToTable("ArtistAliases", (string)null); + + b1.WithOwner() + .HasForeignKey("ArtistId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AudioRatingEntity", "Ratings", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("ArtistId") + .HasColumnType("TEXT"); + + b1.Property("MaxValue") + .HasColumnType("decimal(3,2)"); + + b1.Property("Source") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.Property("Value") + .HasColumnType("decimal(3,2)"); + + b1.Property("VoteCount") + .HasColumnType("INTEGER"); + + b1.HasKey("Id"); + + b1.HasIndex("ArtistId"); + + b1.ToTable("ArtistRatings", (string)null); + + b1.WithOwner() + .HasForeignKey("ArtistId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistIpiEntity", "Ipis", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("ArtistId") + .HasColumnType("TEXT"); + + b1.Property("Value") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("ArtistId"); + + b1.ToTable("ArtistIpis", (string)null); + + b1.WithOwner() + .HasForeignKey("ArtistId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistIsniEntity", "Isnis", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("ArtistId") + .HasColumnType("TEXT"); + + b1.Property("Value") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("ArtistId"); + + b1.ToTable("ArtistIsnis", (string)null); + + b1.WithOwner() + .HasForeignKey("ArtistId"); + }); + + b.Navigation("Aliases"); + + b.Navigation("Area"); + + b.Navigation("BeginArea"); + + b.Navigation("EndArea"); + + b.Navigation("Ipis"); + + b.Navigation("Isnis"); + + b.Navigation("Ratings"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackContributorEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackEntity", null) + .WithMany("Contributors") + .HasForeignKey("TrackId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumEntity", "Album") + .WithMany("Tracks") + .HasForeignKey("AlbumId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AudioRatingEntity", "Ratings", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("MaxValue") + .HasColumnType("decimal(3,2)"); + + b1.Property("Source") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.Property("TrackId") + .HasColumnType("TEXT"); + + b1.Property("Value") + .HasColumnType("decimal(3,2)"); + + b1.Property("VoteCount") + .HasColumnType("INTEGER"); + + b1.HasKey("Id"); + + b1.HasIndex("TrackId"); + + b1.ToTable("TrackRatings", (string)null); + + b1.WithOwner() + .HasForeignKey("TrackId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackIsrcEntity", "Isrcs", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("TrackId") + .HasColumnType("TEXT"); + + b1.Property("Value") + .IsRequired() + .HasMaxLength(12) + .HasColumnType("TEXT") + .HasColumnName("ISRC"); + + b1.HasKey("Id"); + + b1.HasIndex("TrackId"); + + b1.ToTable("TrackIsrcs", (string)null); + + b1.WithOwner() + .HasForeignKey("TrackId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackMoodEntity", "Moods", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("Name") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.Property("TrackId") + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("TrackId"); + + b1.ToTable("TrackMoods", (string)null); + + b1.WithOwner() + .HasForeignKey("TrackId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackWorkIswcEntity", "WorkIswcs", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("TrackId") + .HasColumnType("TEXT"); + + b1.Property("Value") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("TrackId"); + + b1.ToTable("TrackWorkIswcs", (string)null); + + b1.WithOwner() + .HasForeignKey("TrackId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackWorkLanguageEntity", "WorkLanguages", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("LanguageCode") + .IsRequired() + .HasMaxLength(5) + .HasColumnType("TEXT"); + + b1.Property("LanguageName") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("TEXT"); + + b1.Property("NativeName") + .HasMaxLength(100) + .HasColumnType("TEXT"); + + b1.Property("TrackId") + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("TrackId"); + + b1.ToTable("TrackWorkLanguages", (string)null); + + b1.WithOwner() + .HasForeignKey("TrackId"); + }); + + b.Navigation("Album"); + + b.Navigation("Isrcs"); + + b.Navigation("Moods"); + + b.Navigation("Ratings"); + + b.Navigation("WorkIswcs"); + + b.Navigation("WorkLanguages"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.DirectoryScanFingerprintEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", null) + .WithMany() + .HasForeignKey("LibraryId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", "User") + .WithMany("Libraries") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryContentLocationEntity", "ContentLocations", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("LibraryId") + .HasColumnType("TEXT"); + + b1.Property("Path") + .IsRequired() + .HasMaxLength(260) + .HasColumnType("TEXT") + .HasColumnName("Path"); + + b1.HasKey("Id"); + + b1.HasIndex("LibraryId"); + + b1.ToTable("LibraryContentLocations", (string)null); + + b1.WithOwner() + .HasForeignKey("LibraryId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryPathTemplatePartEntity", "PathTemplateParts", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("IsOptional") + .HasColumnType("INTEGER"); + + b1.Property("Kind") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b1.Property("LibraryId") + .HasColumnType("TEXT"); + + b1.Property("Position") + .HasColumnType("INTEGER") + .HasColumnName("Position"); + + b1.Property("Representation") + .IsRequired() + .HasMaxLength(512) + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("LibraryId", "Position") + .IsUnique(); + + b1.ToTable("LibraryPathTemplateParts", (string)null); + + b1.WithOwner() + .HasForeignKey("LibraryId"); + }); + + b.Navigation("ContentLocations"); + + b.Navigation("PathTemplateParts"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", "Library") + .WithMany("LibraryScans") + .HasForeignKey("LibraryId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", "User") + .WithMany("LibraryScans") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Library"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanResultEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", "LibraryScan") + .WithMany("LibraryScanResults") + .HasForeignKey("LibraryScanId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("LibraryScan"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanSnapshotEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", "Library") + .WithMany() + .HasForeignKey("LibraryId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Library"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanStagingResultsEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", null) + .WithMany() + .HasForeignKey("LibraryScanId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookArtworkEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", null) + .WithMany("Artwork") + .HasForeignKey("BookId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookContributorEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", null) + .WithMany("Contributors") + .HasForeignKey("BookId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", b => + { + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookRatingEntity", "Ratings", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("BookId") + .HasColumnType("TEXT"); + + b1.Property("MaxValue") + .HasColumnType("decimal(3,2)"); + + b1.Property("Source") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.Property("Value") + .HasColumnType("decimal(3,2)"); + + b1.Property("VoteCount") + .HasColumnType("INTEGER"); + + b1.HasKey("Id"); + + b1.HasIndex("BookId"); + + b1.ToTable("BookRatings", (string)null); + + b1.WithOwner() + .HasForeignKey("BookId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.IsbnEntity", "ISBNs", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("BookId") + .HasColumnType("TEXT"); + + b1.Property("Format") + .IsRequired() + .HasMaxLength(6) + .HasColumnType("TEXT"); + + b1.Property("Value") + .IsRequired() + .HasMaxLength(13) + .HasColumnType("TEXT") + .HasColumnName("ISBN"); + + b1.HasKey("Id"); + + b1.HasIndex("BookId"); + + b1.ToTable("BookISBNs", (string)null); + + b1.WithOwner() + .HasForeignKey("BookId"); + }); + + b.Navigation("ISBNs"); + + b.Navigation("Ratings"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Playlists.PlaylistEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Playlists.PlaylistEntryEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Playlists.PlaylistEntity", null) + .WithMany("Entries") + .HasForeignKey("PlaylistId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserSettingsEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", null) + .WithOne() + .HasForeignKey("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserSettingsEntity", "UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("TrackGenres", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.GenreEntity", null) + .WithMany() + .HasForeignKey("GenreId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackEntity", null) + .WithMany() + .HasForeignKey("TrackId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("TrackTags", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.TagEntity", null) + .WithMany() + .HasForeignKey("TagId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackEntity", null) + .WithMany() + .HasForeignKey("TrackId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.PermissionEntity", b => + { + b.Navigation("RolePermissions"); + + b.Navigation("UserPermissions"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.RoleEntity", b => + { + b.Navigation("RolePermissions"); + + b.Navigation("UserRoles"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumEntity", b => + { + b.Navigation("Contributors"); + + b.Navigation("Tracks"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistEntity", b => + { + b.Navigation("Albums"); + + b.Navigation("Contributors"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackEntity", b => + { + b.Navigation("Contributors"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", b => + { + b.Navigation("LibraryScans"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", b => + { + b.Navigation("LibraryScanResults"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", b => + { + b.Navigation("Artwork"); + + b.Navigation("Contributors"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Playlists.PlaylistEntity", b => + { + b.Navigation("Entries"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", b => + { + b.Navigation("Libraries"); + + b.Navigation("LibraryScans"); + + b.Navigation("UserPermissions"); + + b.Navigation("UserRole"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/Lumina.DataAccess/Common/Migrations/20261021184608_AddsFavorites.cs b/src/Lumina.DataAccess/Common/Migrations/20261021184608_AddsFavorites.cs new file mode 100644 index 00000000..697baf0b --- /dev/null +++ b/src/Lumina.DataAccess/Common/Migrations/20261021184608_AddsFavorites.cs @@ -0,0 +1,62 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Lumina.DataAccess.Common.Migrations +{ + /// + public partial class AddsFavorites : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "Favorites", + columns: table => new + { + Id = table.Column(type: "TEXT", nullable: false), + UserId = table.Column(type: "TEXT", nullable: false), + MediaKind = table.Column(type: "TEXT", maxLength: 20, nullable: false), + MediaItemId = table.Column(type: "TEXT", nullable: false), + CreatedOnUtc = table.Column(type: "TEXT", nullable: false), + CreatedBy = table.Column(type: "TEXT", nullable: false), + UpdatedOnUtc = table.Column(type: "TEXT", nullable: true), + UpdatedBy = table.Column(type: "TEXT", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_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); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "Favorites"); + } + } +} diff --git a/src/Lumina.DataAccess/Common/Migrations/20261023180439_NormalizesTagAndGenreNames.Designer.cs b/src/Lumina.DataAccess/Common/Migrations/20261023180439_NormalizesTagAndGenreNames.Designer.cs new file mode 100644 index 00000000..82d0c3ef --- /dev/null +++ b/src/Lumina.DataAccess/Common/Migrations/20261023180439_NormalizesTagAndGenreNames.Designer.cs @@ -0,0 +1,3766 @@ +// +using System; +using Lumina.DataAccess.Core.UoW; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace Lumina.DataAccess.Common.Migrations +{ + [DbContext(typeof(LuminaDbContext))] + [Migration("20261023180439_NormalizesTagAndGenreNames")] + partial class NormalizesTagAndGenreNames + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder.HasAnnotation("ProductVersion", "10.0.11"); + + modelBuilder.Entity("AlbumGenres", b => + { + b.Property("AlbumId") + .HasColumnType("TEXT"); + + b.Property("GenreId") + .HasColumnType("TEXT"); + + b.HasKey("AlbumId", "GenreId"); + + b.HasIndex("GenreId"); + + b.ToTable("AlbumGenres", (string)null); + }); + + modelBuilder.Entity("AlbumTags", b => + { + b.Property("AlbumId") + .HasColumnType("TEXT"); + + b.Property("TagId") + .HasColumnType("TEXT"); + + b.HasKey("AlbumId", "TagId"); + + b.HasIndex("TagId"); + + b.ToTable("AlbumTags", (string)null); + }); + + modelBuilder.Entity("ArtistGenres", b => + { + b.Property("ArtistId") + .HasColumnType("TEXT"); + + b.Property("GenreId") + .HasColumnType("TEXT"); + + b.HasKey("ArtistId", "GenreId"); + + b.HasIndex("GenreId"); + + b.ToTable("ArtistGenres", (string)null); + }); + + modelBuilder.Entity("ArtistTags", b => + { + b.Property("ArtistId") + .HasColumnType("TEXT"); + + b.Property("TagId") + .HasColumnType("TEXT"); + + b.HasKey("ArtistId", "TagId"); + + b.HasIndex("TagId"); + + b.ToTable("ArtistTags", (string)null); + }); + + modelBuilder.Entity("BookGenres", b => + { + b.Property("BookId") + .HasColumnType("TEXT"); + + b.Property("GenreId") + .HasColumnType("TEXT"); + + b.HasKey("BookId", "GenreId"); + + b.HasIndex("GenreId"); + + b.ToTable("BookGenres", (string)null); + }); + + modelBuilder.Entity("BookTags", b => + { + b.Property("BookId") + .HasColumnType("TEXT"); + + b.Property("TagId") + .HasColumnType("TEXT"); + + b.HasKey("BookId", "TagId"); + + b.HasIndex("TagId"); + + b.ToTable("BookTags", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.PermissionEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("PermissionName") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.HasKey("Id"); + + b.ToTable("Permissions", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.RoleEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("RoleName") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.HasKey("Id"); + + b.ToTable("Roles", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.RolePermissionEntity", b => + { + b.Property("RoleId") + .HasColumnType("TEXT"); + + b.Property("PermissionId") + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.HasKey("RoleId", "PermissionId"); + + b.HasIndex("PermissionId"); + + b.HasIndex("RoleId", "PermissionId") + .IsUnique(); + + b.ToTable("RolePermissions", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.UserPermissionEntity", b => + { + b.Property("UserId") + .HasColumnType("TEXT"); + + b.Property("PermissionId") + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.HasKey("UserId", "PermissionId"); + + b.HasIndex("PermissionId"); + + b.HasIndex("UserId", "PermissionId") + .IsUnique(); + + b.ToTable("UserPermissions", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.UserRoleEntity", b => + { + b.Property("UserId") + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("RoleId") + .HasColumnType("TEXT"); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.HasKey("UserId"); + + b.HasIndex("RoleId"); + + b.HasIndex("UserId", "RoleId") + .IsUnique(); + + b.ToTable("UserRoles", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Common.GenreEntity", b => + { + b.Property("Name") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b.HasKey("Name"); + + b.ToTable("Genres", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Common.TagEntity", b => + { + b.Property("Name") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b.HasKey("Name"); + + b.ToTable("Tags", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Favorites.FavoriteEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("MediaItemId") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("MediaKind") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("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("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Biography") + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("DateOfBirth") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("DateOfDeath") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("DisplayName") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1) + .UseCollation("NOCASE"); + + b.Property("LegalName") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.HasKey("Id"); + + b.HasIndex("DisplayName") + .IsUnique(); + + b.ToTable("MediaContributors", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumContributorEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("AlbumId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("MediaContributorId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("Role") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.HasKey("Id"); + + b.HasIndex("MediaContributorId"); + + b.HasIndex("AlbumId", "MediaContributorId", "Role") + .IsUnique(); + + b.ToTable("AlbumContributors", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("ASIN") + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(28); + + b.Property("ArtistId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("Barcode") + .HasMaxLength(13) + .HasColumnType("TEXT") + .HasColumnOrder(25); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(33); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(32); + + b.Property("Description") + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("Disambiguation") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("Label") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(27); + + b.Property("LanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("LanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("LanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(15); + + b.Property("LastMetadataUpdateUtc") + .HasColumnType("TEXT") + .HasColumnOrder(37); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("MediaFormat") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(23); + + b.Property("MetadataProvider") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(38); + + b.Property("MetadataStatus") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasDefaultValue("Pending") + .HasColumnOrder(36); + + b.Property("MusicBrainzReleaseArtistId") + .HasColumnType("TEXT") + .HasColumnOrder(31); + + b.Property("MusicBrainzReleaseGroupId") + .HasColumnType("TEXT") + .HasColumnOrder(30); + + b.Property("MusicBrainzReleaseId") + .HasColumnType("TEXT") + .HasColumnOrder(29); + + b.Property("OriginalLanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(16); + + b.Property("OriginalLanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(17); + + b.Property("OriginalLanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(18); + + b.Property("OriginalReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("OriginalReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(8); + + b.Property("OriginalTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("Packaging") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(24); + + b.Property("ReReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("ReReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(10); + + b.Property("ReleaseCountry") + .HasMaxLength(2) + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("ReleaseStatus") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(20); + + b.Property("ReleaseTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(26); + + b.Property("ReleaseVersion") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("Script") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(19); + + b.Property("Title") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("TotalDiscs") + .HasColumnType("INTEGER") + .HasColumnOrder(21); + + b.Property("TotalTracks") + .HasColumnType("INTEGER") + .HasColumnOrder(22); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(35); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(34); + + b.HasKey("Id"); + + b.HasIndex("ArtistId", "Title"); + + b.HasIndex("LibraryId", "Title"); + + b.ToTable("Albums", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistContributorEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("ArtistId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("MediaContributorId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("Role") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.HasKey("Id"); + + b.HasIndex("MediaContributorId"); + + b.HasIndex("ArtistId", "MediaContributorId", "Role") + .IsUnique(); + + b.ToTable("ArtistContributors", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Country") + .HasMaxLength(2) + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("Disambiguation") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("Gender") + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("IsEnded") + .HasColumnType("INTEGER") + .HasColumnOrder(10); + + b.Property("LastMetadataUpdateUtc") + .HasColumnType("TEXT") + .HasColumnOrder(18); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("LifeSpanBegin") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("LifeSpanEnd") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("MetadataProvider") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(19); + + b.Property("MetadataStatus") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasDefaultValue("Pending") + .HasColumnOrder(17); + + b.Property("MusicBrainzArtistId") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("Name") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("SortName") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("Type") + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(16); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(15); + + b.Property("Website") + .HasMaxLength(2048) + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.HasKey("Id"); + + b.HasIndex("LibraryId", "Name") + .IsUnique(); + + b.ToTable("Artists", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.MusicArtworkEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("ArtworkType") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("ContentHash") + .HasColumnType("INTEGER") + .HasColumnOrder(6); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("FileName") + .HasMaxLength(2048) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("LastUpdateUtc") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("Ordinal") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("OwnerId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("OwnerType") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("Provider") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("Status") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.HasKey("Id"); + + b.HasIndex("Status"); + + b.HasIndex("OwnerType", "OwnerId", "ArtworkType", "Ordinal") + .IsUnique(); + + b.ToTable("MusicArtwork", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.MusicLibraryScanItemMetadataEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("AcoustId") + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnOrder(25); + + b.Property("ArtistName") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("AudioCodec") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(15); + + b.Property("BitDepth") + .HasColumnType("INTEGER") + .HasColumnOrder(14); + + b.Property("Bitrate") + .HasColumnType("INTEGER") + .HasColumnOrder(16); + + b.Property("Channels") + .HasColumnType("INTEGER") + .HasColumnOrder(13); + + b.Property("Container") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(31); + + b.Property("DiscNumber") + .HasColumnType("INTEGER") + .HasColumnOrder(10); + + b.Property("DurationInSeconds") + .HasColumnType("INTEGER") + .HasColumnOrder(11); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("LibraryScanId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.PrimitiveCollection("Moods") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(30); + + b.Property("MusicBrainzArtistId") + .HasColumnType("TEXT") + .HasColumnOrder(17); + + b.Property("MusicBrainzRecordingId") + .HasColumnType("TEXT") + .HasColumnOrder(21); + + b.Property("MusicBrainzReleaseArtistId") + .HasColumnType("TEXT") + .HasColumnOrder(18); + + b.Property("MusicBrainzReleaseGroupId") + .HasColumnType("TEXT") + .HasColumnOrder(19); + + b.Property("MusicBrainzReleaseId") + .HasColumnType("TEXT") + .HasColumnOrder(20); + + b.Property("MusicBrainzTrackId") + .HasColumnType("TEXT") + .HasColumnOrder(22); + + b.Property("MusicBrainzWorkId") + .HasColumnType("TEXT") + .HasColumnOrder(23); + + b.Property("Path") + .IsRequired() + .HasMaxLength(2048) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("ReleaseName") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("ReleaseType") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("ReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(6); + + b.Property("ReplayGainAlbumGain") + .HasColumnType("decimal(8,2)") + .HasColumnOrder(28); + + b.Property("ReplayGainAlbumPeak") + .HasColumnType("decimal(8,6)") + .HasColumnOrder(29); + + b.Property("ReplayGainTrackGain") + .HasColumnType("decimal(8,2)") + .HasColumnOrder(26); + + b.Property("ReplayGainTrackPeak") + .HasColumnType("decimal(8,6)") + .HasColumnOrder(27); + + b.Property("SampleRate") + .HasColumnType("INTEGER") + .HasColumnOrder(12); + + b.Property("TrackNumber") + .HasColumnType("INTEGER") + .HasColumnOrder(9); + + b.Property("TrackTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("WorkTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(24); + + b.HasKey("Id"); + + b.HasIndex("LibraryScanId", "Path") + .IsUnique(); + + b.ToTable("MusicLibraryScanItemMetadata", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.MusicPlayRecordEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("AlbumId") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("ArtistId") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("EndedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("LastPositionMilliseconds") + .HasColumnType("INTEGER") + .HasColumnOrder(7); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("ListenedDurationMilliseconds") + .HasColumnType("INTEGER") + .HasColumnOrder(8); + + b.Property("Status") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("TrackId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("UserId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("Version") + .IsConcurrencyToken() + .HasColumnType("INTEGER") + .HasColumnOrder(10); + + b.HasKey("Id"); + + b.HasIndex("TrackId"); + + b.HasIndex("UserId", "CreatedOnUtc"); + + b.ToTable("MusicPlayRecords", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackContributorEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("MediaContributorId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("Role") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("TrackId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.HasKey("Id"); + + b.HasIndex("MediaContributorId"); + + b.HasIndex("TrackId", "MediaContributorId", "Role") + .IsUnique(); + + b.ToTable("TrackContributors", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("AcoustId") + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnOrder(44); + + b.Property("AlbumId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("AudioCodec") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(24); + + b.Property("BitDepth") + .HasColumnType("INTEGER") + .HasColumnOrder(23); + + b.Property("Bitrate") + .HasColumnType("INTEGER") + .HasColumnOrder(25); + + b.Property("Bpm") + .HasColumnType("INTEGER") + .HasColumnOrder(30); + + b.Property("Channels") + .HasColumnType("INTEGER") + .HasColumnOrder(22); + + b.Property("Container") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(49); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(38); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(37); + + b.Property("Description") + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("Disambiguation") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("DiscNumber") + .HasColumnType("INTEGER") + .HasColumnOrder(27); + + b.Property("DurationInSeconds") + .HasColumnType("INTEGER") + .HasColumnOrder(20); + + b.Property("IsVideo") + .HasColumnType("INTEGER") + .HasColumnOrder(31); + + b.Property("Key") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(29); + + b.Property("LanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("LanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(15); + + b.Property("LanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(16); + + b.Property("LastMetadataUpdateUtc") + .HasColumnType("TEXT") + .HasColumnOrder(42); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("MetadataProvider") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(43); + + b.Property("MetadataStatus") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasDefaultValue("Pending") + .HasColumnOrder(41); + + b.Property("MusicBrainzRecordingId") + .HasColumnType("TEXT") + .HasColumnOrder(34); + + b.Property("MusicBrainzTrackId") + .HasColumnType("TEXT") + .HasColumnOrder(35); + + b.Property("MusicBrainzWorkId") + .HasColumnType("TEXT") + .HasColumnOrder(36); + + b.Property("OriginalLanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(17); + + b.Property("OriginalLanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(18); + + b.Property("OriginalLanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(19); + + b.Property("OriginalReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("OriginalReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(9); + + b.Property("OriginalTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("Path") + .IsRequired() + .HasMaxLength(2048) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("ReReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("ReReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(11); + + b.Property("ReleaseCountry") + .HasMaxLength(2) + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("ReleaseVersion") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("ReplayGainAlbumGain") + .HasColumnType("decimal(8,2)") + .HasColumnOrder(47); + + b.Property("ReplayGainAlbumPeak") + .HasColumnType("decimal(8,6)") + .HasColumnOrder(48); + + b.Property("ReplayGainTrackGain") + .HasColumnType("decimal(8,2)") + .HasColumnOrder(45); + + b.Property("ReplayGainTrackPeak") + .HasColumnType("decimal(8,6)") + .HasColumnOrder(46); + + b.Property("SampleRate") + .HasColumnType("INTEGER") + .HasColumnOrder(21); + + b.Property("Script") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(28); + + b.Property("Title") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("TrackNumber") + .HasColumnType("INTEGER") + .HasColumnOrder(26); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(40); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(39); + + b.Property("WorkTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(32); + + b.Property("WorkType") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(33); + + b.HasKey("Id"); + + b.HasIndex("AlbumId", "TrackNumber"); + + b.HasIndex("LibraryId", "Path") + .IsUnique(); + + b.ToTable("Tracks", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.DirectoryScanFingerprintEntity", b => + { + b.Property("LibraryId") + .HasColumnType("TEXT"); + + b.Property("Path") + .HasMaxLength(1024) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("LastWriteTimeUtc") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.HasKey("LibraryId", "Path"); + + b.HasIndex("LibraryId"); + + b.ToTable("DirectoryScanFingerprints", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("ArtworkProvidersConfigurationFingerprint") + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("CanDownloadMetadataFromWeb") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(true) + .HasColumnOrder(6); + + b.Property("CoverImage") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("IsEnabled") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(true) + .HasColumnOrder(4); + + b.Property("IsLocked") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("LibraryType") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("MetadataProvidersConfigurationFingerprint") + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("PathTemplateFingerprint") + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("ShouldSaveMetadataInMediaDirectories") + .HasColumnType("INTEGER") + .HasColumnOrder(7); + + b.Property("ShouldSkipUnchangedDirectoriesDuringScan") + .HasColumnType("INTEGER") + .HasColumnOrder(8); + + b.Property("Title") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(15); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("UserId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("Libraries", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("LibraryId") + .HasColumnType("TEXT"); + + b.Property("Status") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UserId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.HasIndex("LibraryId", "Status", "CreatedOnUtc") + .IsDescending(true, false, true); + + b.ToTable("LibraryScans", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanResultEntity", b => + { + b.Property("LibraryScanId") + .HasColumnType("TEXT"); + + b.Property("Path") + .HasMaxLength(1024) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("ContentHash") + .HasMaxLength(24) + .HasColumnType("INTEGER") + .HasColumnOrder(2); + + b.Property("FileSize") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Status") + .IsRequired() + .HasMaxLength(10) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("Ticks") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.HasKey("LibraryScanId", "Path"); + + b.HasIndex("Path"); + + b.HasIndex("ContentHash", "FileSize", "Path"); + + b.ToTable("LibraryScanResults", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanSnapshotEntity", b => + { + b.Property("LibraryId") + .HasColumnType("TEXT"); + + b.Property("Path") + .HasMaxLength(1024) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("ContentHash") + .HasColumnType("INTEGER") + .HasColumnOrder(2); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("FileSize") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Ticks") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.HasKey("LibraryId", "Path"); + + b.HasIndex("LibraryId"); + + b.ToTable("LibraryScanSnapshots", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanStagingResultsEntity", b => + { + b.Property("LibraryScanId") + .HasColumnType("TEXT"); + + b.Property("Path") + .HasMaxLength(1024) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("ContentHash") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("IsNew") + .HasColumnType("INTEGER") + .HasColumnOrder(7); + + b.Property("NeedsRehash") + .HasColumnType("INTEGER") + .HasColumnOrder(6); + + b.Property("PreviousContentHash") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("Size") + .HasColumnType("INTEGER") + .HasColumnOrder(2); + + b.Property("Ticks") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.HasKey("LibraryScanId", "Path"); + + b.HasIndex("LibraryScanId", "NeedsRehash"); + + b.ToTable("LibraryScanStagingResults", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookArtworkEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("ArtworkType") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("BookId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("ContentHash") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("FileName") + .HasMaxLength(2048) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("LastUpdateUtc") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("Ordinal") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("Provider") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("Status") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.HasKey("Id"); + + b.HasIndex("Status"); + + b.HasIndex("BookId", "ArtworkType", "Ordinal") + .IsUnique(); + + b.ToTable("BookArtwork", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookContributorEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("BookId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("MediaContributorId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("Role") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.HasKey("Id"); + + b.HasIndex("MediaContributorId"); + + b.HasIndex("BookId", "MediaContributorId", "Role") + .IsUnique(); + + b.ToTable("BookContributors", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("ASIN") + .HasMaxLength(10) + .HasColumnType("TEXT") + .HasColumnOrder(21); + + b.Property("AppleBooksId") + .HasColumnType("TEXT") + .HasColumnOrder(29); + + b.Property("BarnesAndNobleId") + .HasMaxLength(10) + .HasColumnType("TEXT") + .HasColumnOrder(28); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(33); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(32); + + b.Property("Description") + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("Edition") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(19); + + b.Property("Format") + .HasColumnType("TEXT") + .HasColumnOrder(18); + + b.Property("GoodreadsId") + .HasColumnType("TEXT") + .HasColumnOrder(22); + + b.Property("GoogleBooksId") + .HasMaxLength(12) + .HasColumnType("TEXT") + .HasColumnOrder(27); + + b.Property("LCCN") + .HasColumnType("TEXT") + .HasColumnOrder(23); + + b.Property("LanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("LanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("LanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("LastMetadataUpdateUtc") + .HasColumnType("TEXT") + .HasColumnOrder(39); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(36); + + b.Property("LibraryThingId") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(26); + + b.Property("MetadataProvider") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(40); + + b.Property("MetadataStatus") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(38); + + b.Property("OCLCNumber") + .HasColumnType("TEXT") + .HasColumnOrder(24); + + b.Property("OpenLibraryId") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(25); + + b.Property("OriginalLanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("OriginalLanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("OriginalLanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(15); + + b.Property("OriginalReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("OriginalReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("OriginalTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("PageCount") + .HasColumnType("INTEGER") + .HasColumnOrder(17); + + b.Property("Path") + .IsRequired() + .HasMaxLength(2048) + .HasColumnType("TEXT") + .HasColumnOrder(37); + + b.Property("Publisher") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(16); + + b.Property("ReReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("ReReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(7); + + b.Property("ReleaseCountry") + .HasMaxLength(2) + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("ReleaseVersion") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("Title") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(35); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(34); + + b.Property("VolumeNumber") + .HasColumnType("REAL") + .HasColumnOrder(20); + + b.HasKey("Id"); + + b.HasIndex("LibraryId", "MetadataStatus"); + + b.HasIndex("LibraryId", "Path") + .IsUnique(); + + b.ToTable("Books", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Playlists.PlaylistEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("Description") + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("EntryCount") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(0) + .HasColumnOrder(10); + + b.Property("Name") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("Type") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UserId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("Version") + .IsConcurrencyToken() + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(0L) + .HasColumnOrder(9); + + b.HasKey("Id"); + + b.HasIndex("UserId", "UpdatedOnUtc"); + + b.ToTable("Playlists", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Playlists.PlaylistEntryEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("MediaItemId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("MediaItemType") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("PlaylistId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("Position") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.HasKey("Id"); + + b.HasIndex("MediaItemId"); + + b.HasIndex("PlaylistId", "Position") + .IsUnique(); + + b.ToTable("PlaylistEntries", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Plugins.LibraryArtworkProviderConfigurationEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("IsEnabled") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("PluginId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("Rank") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.HasKey("Id"); + + b.HasIndex("LibraryId", "PluginId"); + + b.ToTable("LibraryArtworkProviderConfigurations", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Plugins.LibraryBookReaderConfigurationEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("IsEnabled") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("PluginId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.HasKey("Id"); + + b.HasIndex("LibraryId", "PluginId") + .IsUnique(); + + b.ToTable("LibraryBookReaderConfigurations", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Plugins.LibraryMetadataProviderConfigurationEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("IsEnabled") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("PluginId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("Rank") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.HasKey("Id"); + + b.HasIndex("LibraryId", "PluginId"); + + b.ToTable("LibraryMetadataProviderConfigurations", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Plugins.PluginEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Author") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("Description") + .IsRequired() + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("LoadError") + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("LoadStatus") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("Name") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("SettingsJson") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("Version") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.HasKey("Id"); + + b.ToTable("Plugins", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Scheduling.ScheduledJobEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("Hour") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("IntervalMinutes") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("LastCompletedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("LastStartedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("Minute") + .HasColumnType("INTEGER") + .HasColumnOrder(6); + + b.Property("Name") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("OwnerUserId") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("ScheduleType") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("Status") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("TaskType") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.HasKey("Id"); + + b.HasIndex("Status"); + + b.ToTable("ScheduledJobs", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Scheduling.ScheduledJobExecutionEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CompletedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("IsCycleRun") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("ScheduledJobId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("StartedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("TaskType") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("WasCycleActive") + .HasColumnType("INTEGER") + .HasColumnOrder(6); + + b.HasKey("Id"); + + b.HasIndex("ScheduledJobId"); + + b.HasIndex("StartedOnUtc", "ScheduledJobId"); + + b.ToTable("ScheduledJobExecutions", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Scheduling.SchedulerDisplayPreferencesEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("DisplayTimeSpan") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("DisplayTimeUnit") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("JobTypeFilter") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UserId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.HasKey("Id"); + + b.HasIndex("UserId") + .IsUnique(); + + b.ToTable("SchedulerDisplayPreferences", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Themes.ThemeEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Author") + .IsRequired() + .HasMaxLength(80) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("Description") + .IsRequired() + .HasMaxLength(300) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("InstallSource") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("InstalledAtUtc") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("IsCurrent") + .HasColumnType("INTEGER") + .HasColumnOrder(8); + + b.Property("IsDeleted") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(false) + .HasColumnOrder(9); + + b.Property("Name") + .IsRequired() + .HasMaxLength(80) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("PreviewPath") + .HasMaxLength(240) + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("ThemeId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("Version") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.HasKey("Id"); + + b.HasIndex("IsCurrent") + .IsUnique() + .HasFilter("IsCurrent = 1"); + + b.HasIndex("ThemeId") + .IsUnique(); + + b.ToTable("Themes", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("Password") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("TempPassword") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("TempPasswordCreated") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("TotpSecret") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("Username") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.HasKey("Id"); + + b.HasIndex("Username") + .IsUnique(); + + b.ToTable("Users", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserSettingsEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("IsGaplessPlaybackEnabled") + .HasColumnType("INTEGER") + .HasColumnOrder(16); + + b.Property("IsMuted") + .HasColumnType("INTEGER") + .HasColumnOrder(29); + + b.Property("IsPaginationEnabled") + .HasColumnType("INTEGER") + .HasColumnOrder(2); + + b.Property("IsThemeCachingEnabled") + .HasColumnType("INTEGER") + .HasColumnOrder(9); + + b.Property("ItemsPerPage") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("ReplayGainMode") + .HasColumnType("INTEGER") + .HasColumnOrder(17); + + b.Property("ShouldAggregateArtworkWhenMissing") + .HasColumnType("INTEGER") + .HasColumnOrder(13); + + b.Property("ShouldAggregateMetadataWhenMissing") + .HasColumnType("INTEGER") + .HasColumnOrder(10); + + b.Property("ShouldAutoplay") + .HasColumnType("INTEGER") + .HasColumnOrder(15); + + b.Property("ShouldIgnoreThePrefixForAlphaPicker") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("ShouldKeepDownloadingWhilePaused") + .HasColumnType("INTEGER") + .HasColumnOrder(14); + + b.Property("ShouldPreserveBookStyles") + .HasColumnType("INTEGER") + .HasColumnOrder(12); + + b.Property("ShouldRenderPdfAsImages") + .HasColumnType("INTEGER") + .HasColumnOrder(11); + + b.Property("StreamingQuality") + .HasColumnType("INTEGER") + .HasColumnOrder(18); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UserId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("Volume") + .HasColumnType("REAL") + .HasColumnOrder(28); + + b.Property("VuMeterHighThreshold") + .HasColumnType("REAL") + .HasColumnOrder(23); + + b.Property("VuMeterMediumThreshold") + .HasColumnType("REAL") + .HasColumnOrder(22); + + b.Property("VuMeterOrientation") + .HasColumnType("INTEGER") + .HasColumnOrder(19); + + b.Property("VuMeterPeakHoldDurationInMilliseconds") + .HasColumnType("INTEGER") + .HasColumnOrder(25); + + b.Property("VuMeterPeakReleasePerSecond") + .HasColumnType("REAL") + .HasColumnOrder(27); + + b.Property("VuMeterReleasePerSecond") + .HasColumnType("REAL") + .HasColumnOrder(26); + + b.Property("VuMeterSegmentCount") + .HasColumnType("INTEGER") + .HasColumnOrder(20); + + b.Property("VuMeterSegmentGap") + .HasColumnType("INTEGER") + .HasColumnOrder(21); + + b.Property("VuMeterShowPeak") + .HasColumnType("INTEGER") + .HasColumnOrder(24); + + b.HasKey("Id"); + + b.HasIndex("UserId") + .IsUnique(); + + b.ToTable("UserSettings", (string)null); + }); + + modelBuilder.Entity("TrackGenres", b => + { + b.Property("TrackId") + .HasColumnType("TEXT"); + + b.Property("GenreId") + .HasColumnType("TEXT"); + + b.HasKey("TrackId", "GenreId"); + + b.HasIndex("GenreId"); + + b.ToTable("TrackGenres", (string)null); + }); + + modelBuilder.Entity("TrackTags", b => + { + b.Property("TrackId") + .HasColumnType("TEXT"); + + b.Property("TagId") + .HasColumnType("TEXT"); + + b.HasKey("TrackId", "TagId"); + + b.HasIndex("TagId"); + + b.ToTable("TrackTags", (string)null); + }); + + modelBuilder.Entity("AlbumGenres", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumEntity", null) + .WithMany() + .HasForeignKey("AlbumId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.GenreEntity", null) + .WithMany() + .HasForeignKey("GenreId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("AlbumTags", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumEntity", null) + .WithMany() + .HasForeignKey("AlbumId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.TagEntity", null) + .WithMany() + .HasForeignKey("TagId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("ArtistGenres", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistEntity", null) + .WithMany() + .HasForeignKey("ArtistId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.GenreEntity", null) + .WithMany() + .HasForeignKey("GenreId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("ArtistTags", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistEntity", null) + .WithMany() + .HasForeignKey("ArtistId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.TagEntity", null) + .WithMany() + .HasForeignKey("TagId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BookGenres", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", null) + .WithMany() + .HasForeignKey("BookId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.GenreEntity", null) + .WithMany() + .HasForeignKey("GenreId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BookTags", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", null) + .WithMany() + .HasForeignKey("BookId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.TagEntity", null) + .WithMany() + .HasForeignKey("TagId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.RolePermissionEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Authorization.PermissionEntity", "Permission") + .WithMany("RolePermissions") + .HasForeignKey("PermissionId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Authorization.RoleEntity", "Role") + .WithMany("RolePermissions") + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Permission"); + + b.Navigation("Role"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.UserPermissionEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Authorization.PermissionEntity", "Permission") + .WithMany("UserPermissions") + .HasForeignKey("PermissionId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", "User") + .WithMany("UserPermissions") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Permission"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.UserRoleEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Authorization.RoleEntity", "Role") + .WithMany("UserRoles") + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", "User") + .WithOne("UserRole") + .HasForeignKey("Lumina.Application.Common.DataAccess.Entities.Authorization.UserRoleEntity", "UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Role"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.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) + .WithMany("Contributors") + .HasForeignKey("AlbumId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistEntity", "Artist") + .WithMany("Albums") + .HasForeignKey("ArtistId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumCatalogNumberEntity", "CatalogNumbers", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("AlbumId") + .HasColumnType("TEXT"); + + b1.Property("CatalogNumber") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("AlbumId"); + + b1.ToTable("AlbumCatalogNumbers", (string)null); + + b1.WithOwner() + .HasForeignKey("AlbumId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AudioRatingEntity", "Ratings", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("AlbumId") + .HasColumnType("TEXT"); + + b1.Property("MaxValue") + .HasColumnType("decimal(3,2)"); + + b1.Property("Source") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.Property("Value") + .HasColumnType("decimal(3,2)"); + + b1.Property("VoteCount") + .HasColumnType("INTEGER"); + + b1.HasKey("Id"); + + b1.HasIndex("AlbumId"); + + b1.ToTable("AlbumRatings", (string)null); + + b1.WithOwner() + .HasForeignKey("AlbumId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumReleaseTypeEntity", "ReleaseTypes", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("AlbumId") + .HasColumnType("TEXT"); + + b1.Property("ReleaseType") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("AlbumId"); + + b1.ToTable("AlbumReleaseTypes", (string)null); + + b1.WithOwner() + .HasForeignKey("AlbumId"); + }); + + b.Navigation("Artist"); + + b.Navigation("CatalogNumbers"); + + b.Navigation("Ratings"); + + b.Navigation("ReleaseTypes"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistContributorEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistEntity", null) + .WithMany("Contributors") + .HasForeignKey("ArtistId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistEntity", b => + { + b.OwnsOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.MusicAreaEntity", "Area", b1 => + { + b1.Property("ArtistEntityId"); + + b1.Property("Disambiguation"); + + b1.Property("Iso3166Code"); + + b1.Property("MusicBrainzAreaId"); + + b1.Property("Name") + .IsRequired(); + + b1.Property("SortName"); + + b1.Property("Type"); + + b1.HasKey("ArtistEntityId"); + + b1.ToTable("Artists"); + + b1 + .ToJson("Area") + .HasColumnType("TEXT"); + + b1.WithOwner() + .HasForeignKey("ArtistEntityId"); + }); + + b.OwnsOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.MusicAreaEntity", "BeginArea", b1 => + { + b1.Property("ArtistEntityId"); + + b1.Property("Disambiguation"); + + b1.Property("Iso3166Code"); + + b1.Property("MusicBrainzAreaId"); + + b1.Property("Name") + .IsRequired(); + + b1.Property("SortName"); + + b1.Property("Type"); + + b1.HasKey("ArtistEntityId"); + + b1.ToTable("Artists"); + + b1 + .ToJson("BeginArea") + .HasColumnType("TEXT"); + + b1.WithOwner() + .HasForeignKey("ArtistEntityId"); + }); + + b.OwnsOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.MusicAreaEntity", "EndArea", b1 => + { + b1.Property("ArtistEntityId"); + + b1.Property("Disambiguation"); + + b1.Property("Iso3166Code"); + + b1.Property("MusicBrainzAreaId"); + + b1.Property("Name") + .IsRequired(); + + b1.Property("SortName"); + + b1.Property("Type"); + + b1.HasKey("ArtistEntityId"); + + b1.ToTable("Artists"); + + b1 + .ToJson("EndArea") + .HasColumnType("TEXT"); + + b1.WithOwner() + .HasForeignKey("ArtistEntityId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistAliasEntity", "Aliases", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("ArtistId") + .HasColumnType("TEXT"); + + b1.Property("BeginDate") + .HasColumnType("TEXT"); + + b1.Property("EndDate") + .HasColumnType("TEXT"); + + b1.Property("IsEnded") + .HasColumnType("INTEGER"); + + b1.Property("IsPrimary") + .HasColumnType("INTEGER"); + + b1.Property("Locale") + .HasMaxLength(20) + .HasColumnType("TEXT"); + + b1.Property("Name") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT"); + + b1.Property("SortName") + .HasMaxLength(255) + .HasColumnType("TEXT"); + + b1.Property("Type") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("ArtistId"); + + b1.ToTable("ArtistAliases", (string)null); + + b1.WithOwner() + .HasForeignKey("ArtistId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AudioRatingEntity", "Ratings", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("ArtistId") + .HasColumnType("TEXT"); + + b1.Property("MaxValue") + .HasColumnType("decimal(3,2)"); + + b1.Property("Source") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.Property("Value") + .HasColumnType("decimal(3,2)"); + + b1.Property("VoteCount") + .HasColumnType("INTEGER"); + + b1.HasKey("Id"); + + b1.HasIndex("ArtistId"); + + b1.ToTable("ArtistRatings", (string)null); + + b1.WithOwner() + .HasForeignKey("ArtistId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistIpiEntity", "Ipis", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("ArtistId") + .HasColumnType("TEXT"); + + b1.Property("Value") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("ArtistId"); + + b1.ToTable("ArtistIpis", (string)null); + + b1.WithOwner() + .HasForeignKey("ArtistId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistIsniEntity", "Isnis", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("ArtistId") + .HasColumnType("TEXT"); + + b1.Property("Value") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("ArtistId"); + + b1.ToTable("ArtistIsnis", (string)null); + + b1.WithOwner() + .HasForeignKey("ArtistId"); + }); + + b.Navigation("Aliases"); + + b.Navigation("Area"); + + b.Navigation("BeginArea"); + + b.Navigation("EndArea"); + + b.Navigation("Ipis"); + + b.Navigation("Isnis"); + + b.Navigation("Ratings"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackContributorEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackEntity", null) + .WithMany("Contributors") + .HasForeignKey("TrackId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumEntity", "Album") + .WithMany("Tracks") + .HasForeignKey("AlbumId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AudioRatingEntity", "Ratings", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("MaxValue") + .HasColumnType("decimal(3,2)"); + + b1.Property("Source") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.Property("TrackId") + .HasColumnType("TEXT"); + + b1.Property("Value") + .HasColumnType("decimal(3,2)"); + + b1.Property("VoteCount") + .HasColumnType("INTEGER"); + + b1.HasKey("Id"); + + b1.HasIndex("TrackId"); + + b1.ToTable("TrackRatings", (string)null); + + b1.WithOwner() + .HasForeignKey("TrackId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackIsrcEntity", "Isrcs", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("TrackId") + .HasColumnType("TEXT"); + + b1.Property("Value") + .IsRequired() + .HasMaxLength(12) + .HasColumnType("TEXT") + .HasColumnName("ISRC"); + + b1.HasKey("Id"); + + b1.HasIndex("TrackId"); + + b1.ToTable("TrackIsrcs", (string)null); + + b1.WithOwner() + .HasForeignKey("TrackId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackMoodEntity", "Moods", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("Name") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.Property("TrackId") + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("TrackId"); + + b1.ToTable("TrackMoods", (string)null); + + b1.WithOwner() + .HasForeignKey("TrackId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackWorkIswcEntity", "WorkIswcs", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("TrackId") + .HasColumnType("TEXT"); + + b1.Property("Value") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("TrackId"); + + b1.ToTable("TrackWorkIswcs", (string)null); + + b1.WithOwner() + .HasForeignKey("TrackId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackWorkLanguageEntity", "WorkLanguages", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("LanguageCode") + .IsRequired() + .HasMaxLength(5) + .HasColumnType("TEXT"); + + b1.Property("LanguageName") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("TEXT"); + + b1.Property("NativeName") + .HasMaxLength(100) + .HasColumnType("TEXT"); + + b1.Property("TrackId") + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("TrackId"); + + b1.ToTable("TrackWorkLanguages", (string)null); + + b1.WithOwner() + .HasForeignKey("TrackId"); + }); + + b.Navigation("Album"); + + b.Navigation("Isrcs"); + + b.Navigation("Moods"); + + b.Navigation("Ratings"); + + b.Navigation("WorkIswcs"); + + b.Navigation("WorkLanguages"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.DirectoryScanFingerprintEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", null) + .WithMany() + .HasForeignKey("LibraryId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", "User") + .WithMany("Libraries") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryContentLocationEntity", "ContentLocations", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("LibraryId") + .HasColumnType("TEXT"); + + b1.Property("Path") + .IsRequired() + .HasMaxLength(260) + .HasColumnType("TEXT") + .HasColumnName("Path"); + + b1.HasKey("Id"); + + b1.HasIndex("LibraryId"); + + b1.ToTable("LibraryContentLocations", (string)null); + + b1.WithOwner() + .HasForeignKey("LibraryId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryPathTemplatePartEntity", "PathTemplateParts", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("IsOptional") + .HasColumnType("INTEGER"); + + b1.Property("Kind") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b1.Property("LibraryId") + .HasColumnType("TEXT"); + + b1.Property("Position") + .HasColumnType("INTEGER") + .HasColumnName("Position"); + + b1.Property("Representation") + .IsRequired() + .HasMaxLength(512) + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("LibraryId", "Position") + .IsUnique(); + + b1.ToTable("LibraryPathTemplateParts", (string)null); + + b1.WithOwner() + .HasForeignKey("LibraryId"); + }); + + b.Navigation("ContentLocations"); + + b.Navigation("PathTemplateParts"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", "Library") + .WithMany("LibraryScans") + .HasForeignKey("LibraryId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", "User") + .WithMany("LibraryScans") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Library"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanResultEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", "LibraryScan") + .WithMany("LibraryScanResults") + .HasForeignKey("LibraryScanId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("LibraryScan"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanSnapshotEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", "Library") + .WithMany() + .HasForeignKey("LibraryId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Library"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanStagingResultsEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", null) + .WithMany() + .HasForeignKey("LibraryScanId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookArtworkEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", null) + .WithMany("Artwork") + .HasForeignKey("BookId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookContributorEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", null) + .WithMany("Contributors") + .HasForeignKey("BookId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", b => + { + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookRatingEntity", "Ratings", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("BookId") + .HasColumnType("TEXT"); + + b1.Property("MaxValue") + .HasColumnType("decimal(3,2)"); + + b1.Property("Source") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.Property("Value") + .HasColumnType("decimal(3,2)"); + + b1.Property("VoteCount") + .HasColumnType("INTEGER"); + + b1.HasKey("Id"); + + b1.HasIndex("BookId"); + + b1.ToTable("BookRatings", (string)null); + + b1.WithOwner() + .HasForeignKey("BookId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.IsbnEntity", "ISBNs", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("BookId") + .HasColumnType("TEXT"); + + b1.Property("Format") + .IsRequired() + .HasMaxLength(6) + .HasColumnType("TEXT"); + + b1.Property("Value") + .IsRequired() + .HasMaxLength(13) + .HasColumnType("TEXT") + .HasColumnName("ISBN"); + + b1.HasKey("Id"); + + b1.HasIndex("BookId"); + + b1.ToTable("BookISBNs", (string)null); + + b1.WithOwner() + .HasForeignKey("BookId"); + }); + + b.Navigation("ISBNs"); + + b.Navigation("Ratings"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Playlists.PlaylistEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Playlists.PlaylistEntryEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Playlists.PlaylistEntity", null) + .WithMany("Entries") + .HasForeignKey("PlaylistId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserSettingsEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", null) + .WithOne() + .HasForeignKey("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserSettingsEntity", "UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("TrackGenres", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.GenreEntity", null) + .WithMany() + .HasForeignKey("GenreId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackEntity", null) + .WithMany() + .HasForeignKey("TrackId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("TrackTags", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.TagEntity", null) + .WithMany() + .HasForeignKey("TagId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackEntity", null) + .WithMany() + .HasForeignKey("TrackId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.PermissionEntity", b => + { + b.Navigation("RolePermissions"); + + b.Navigation("UserPermissions"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.RoleEntity", b => + { + b.Navigation("RolePermissions"); + + b.Navigation("UserRoles"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumEntity", b => + { + b.Navigation("Contributors"); + + b.Navigation("Tracks"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistEntity", b => + { + b.Navigation("Albums"); + + b.Navigation("Contributors"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackEntity", b => + { + b.Navigation("Contributors"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", b => + { + b.Navigation("LibraryScans"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", b => + { + b.Navigation("LibraryScanResults"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", b => + { + b.Navigation("Artwork"); + + b.Navigation("Contributors"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Playlists.PlaylistEntity", b => + { + b.Navigation("Entries"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", b => + { + b.Navigation("Libraries"); + + b.Navigation("LibraryScans"); + + b.Navigation("UserPermissions"); + + b.Navigation("UserRole"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/Lumina.DataAccess/Common/Migrations/20261023180439_NormalizesTagAndGenreNames.cs b/src/Lumina.DataAccess/Common/Migrations/20261023180439_NormalizesTagAndGenreNames.cs new file mode 100644 index 00000000..c2a47ecb --- /dev/null +++ b/src/Lumina.DataAccess/Common/Migrations/20261023180439_NormalizesTagAndGenreNames.cs @@ -0,0 +1,64 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Lumina.DataAccess.Common.Migrations +{ + /// + /// Normalizes the existing tag and genre names to their trimmed lowercase form, and merges the rows that differ only by casing. + /// + public partial class NormalizesTagAndGenreNames : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + // The value objects now store names trimmed and lowercased, so the existing rows must be normalized before new scans start reusing them + // by their normalized name. SQLite's built-in lower() folds ASCII letters only, so a legacy name whose uppercase letters are outside + // ASCII is not fully folded and is not merged with its lowercase counterpart. The lowercase rows are inserted first, so that the join + // rows can always be repointed. + migrationBuilder.Sql(""" + INSERT OR IGNORE INTO Tags (Name) + SELECT DISTINCT trim(lower(Name)) FROM Tags; + + INSERT OR IGNORE INTO Genres (Name) + SELECT DISTINCT trim(lower(Name)) FROM Genres; + """); + + // A repointed join row that would collide with an existing lowercase join row is left in its old form by OR IGNORE, and is removed below. + migrationBuilder.Sql(""" + UPDATE OR IGNORE TrackTags SET TagId = trim(lower(TagId)) WHERE TagId <> trim(lower(TagId)); + UPDATE OR IGNORE AlbumTags SET TagId = trim(lower(TagId)) WHERE TagId <> trim(lower(TagId)); + UPDATE OR IGNORE ArtistTags SET TagId = trim(lower(TagId)) WHERE TagId <> trim(lower(TagId)); + UPDATE OR IGNORE BookTags SET TagId = trim(lower(TagId)) WHERE TagId <> trim(lower(TagId)); + + UPDATE OR IGNORE TrackGenres SET GenreId = trim(lower(GenreId)) WHERE GenreId <> trim(lower(GenreId)); + UPDATE OR IGNORE AlbumGenres SET GenreId = trim(lower(GenreId)) WHERE GenreId <> trim(lower(GenreId)); + UPDATE OR IGNORE ArtistGenres SET GenreId = trim(lower(GenreId)) WHERE GenreId <> trim(lower(GenreId)); + UPDATE OR IGNORE BookGenres SET GenreId = trim(lower(GenreId)) WHERE GenreId <> trim(lower(GenreId)); + """); + + // The rows still carrying a mixed-case or untrimmed name are the duplicates that could not be repointed, because the lowercase join row + // was already present. They are removed before the old tag and genre rows, so that no foreign key is left pointing at a deleted row. + migrationBuilder.Sql(""" + DELETE FROM TrackTags WHERE TagId <> trim(lower(TagId)); + DELETE FROM AlbumTags WHERE TagId <> trim(lower(TagId)); + DELETE FROM ArtistTags WHERE TagId <> trim(lower(TagId)); + DELETE FROM BookTags WHERE TagId <> trim(lower(TagId)); + + DELETE FROM TrackGenres WHERE GenreId <> trim(lower(GenreId)); + DELETE FROM AlbumGenres WHERE GenreId <> trim(lower(GenreId)); + DELETE FROM ArtistGenres WHERE GenreId <> trim(lower(GenreId)); + DELETE FROM BookGenres WHERE GenreId <> trim(lower(GenreId)); + + DELETE FROM Tags WHERE Name <> trim(lower(Name)); + DELETE FROM Genres WHERE Name <> trim(lower(Name)); + """); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + // Normalization is irreversible: the original letter casing of the names is not retained, so there is nothing to restore. + } + } +} diff --git a/src/Lumina.DataAccess/Common/Migrations/20261024065622_AddsLibraryConsumptionSettings.Designer.cs b/src/Lumina.DataAccess/Common/Migrations/20261024065622_AddsLibraryConsumptionSettings.Designer.cs new file mode 100644 index 00000000..a0094eaa --- /dev/null +++ b/src/Lumina.DataAccess/Common/Migrations/20261024065622_AddsLibraryConsumptionSettings.Designer.cs @@ -0,0 +1,3776 @@ +// +using System; +using Lumina.DataAccess.Core.UoW; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace Lumina.DataAccess.Common.Migrations +{ + [DbContext(typeof(LuminaDbContext))] + [Migration("20261024065622_AddsLibraryConsumptionSettings")] + partial class AddsLibraryConsumptionSettings + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder.HasAnnotation("ProductVersion", "10.0.11"); + + modelBuilder.Entity("AlbumGenres", b => + { + b.Property("AlbumId") + .HasColumnType("TEXT"); + + b.Property("GenreId") + .HasColumnType("TEXT"); + + b.HasKey("AlbumId", "GenreId"); + + b.HasIndex("GenreId"); + + b.ToTable("AlbumGenres", (string)null); + }); + + modelBuilder.Entity("AlbumTags", b => + { + b.Property("AlbumId") + .HasColumnType("TEXT"); + + b.Property("TagId") + .HasColumnType("TEXT"); + + b.HasKey("AlbumId", "TagId"); + + b.HasIndex("TagId"); + + b.ToTable("AlbumTags", (string)null); + }); + + modelBuilder.Entity("ArtistGenres", b => + { + b.Property("ArtistId") + .HasColumnType("TEXT"); + + b.Property("GenreId") + .HasColumnType("TEXT"); + + b.HasKey("ArtistId", "GenreId"); + + b.HasIndex("GenreId"); + + b.ToTable("ArtistGenres", (string)null); + }); + + modelBuilder.Entity("ArtistTags", b => + { + b.Property("ArtistId") + .HasColumnType("TEXT"); + + b.Property("TagId") + .HasColumnType("TEXT"); + + b.HasKey("ArtistId", "TagId"); + + b.HasIndex("TagId"); + + b.ToTable("ArtistTags", (string)null); + }); + + modelBuilder.Entity("BookGenres", b => + { + b.Property("BookId") + .HasColumnType("TEXT"); + + b.Property("GenreId") + .HasColumnType("TEXT"); + + b.HasKey("BookId", "GenreId"); + + b.HasIndex("GenreId"); + + b.ToTable("BookGenres", (string)null); + }); + + modelBuilder.Entity("BookTags", b => + { + b.Property("BookId") + .HasColumnType("TEXT"); + + b.Property("TagId") + .HasColumnType("TEXT"); + + b.HasKey("BookId", "TagId"); + + b.HasIndex("TagId"); + + b.ToTable("BookTags", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.PermissionEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("PermissionName") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.HasKey("Id"); + + b.ToTable("Permissions", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.RoleEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("RoleName") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.HasKey("Id"); + + b.ToTable("Roles", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.RolePermissionEntity", b => + { + b.Property("RoleId") + .HasColumnType("TEXT"); + + b.Property("PermissionId") + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.HasKey("RoleId", "PermissionId"); + + b.HasIndex("PermissionId"); + + b.HasIndex("RoleId", "PermissionId") + .IsUnique(); + + b.ToTable("RolePermissions", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.UserPermissionEntity", b => + { + b.Property("UserId") + .HasColumnType("TEXT"); + + b.Property("PermissionId") + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.HasKey("UserId", "PermissionId"); + + b.HasIndex("PermissionId"); + + b.HasIndex("UserId", "PermissionId") + .IsUnique(); + + b.ToTable("UserPermissions", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.UserRoleEntity", b => + { + b.Property("UserId") + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("RoleId") + .HasColumnType("TEXT"); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.HasKey("UserId"); + + b.HasIndex("RoleId"); + + b.HasIndex("UserId", "RoleId") + .IsUnique(); + + b.ToTable("UserRoles", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Common.GenreEntity", b => + { + b.Property("Name") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b.HasKey("Name"); + + b.ToTable("Genres", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Common.TagEntity", b => + { + b.Property("Name") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b.HasKey("Name"); + + b.ToTable("Tags", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Favorites.FavoriteEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("MediaItemId") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("MediaKind") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("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("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Biography") + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("DateOfBirth") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("DateOfDeath") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("DisplayName") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1) + .UseCollation("NOCASE"); + + b.Property("LegalName") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.HasKey("Id"); + + b.HasIndex("DisplayName") + .IsUnique(); + + b.ToTable("MediaContributors", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumContributorEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("AlbumId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("MediaContributorId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("Role") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.HasKey("Id"); + + b.HasIndex("MediaContributorId"); + + b.HasIndex("AlbumId", "MediaContributorId", "Role") + .IsUnique(); + + b.ToTable("AlbumContributors", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("ASIN") + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(28); + + b.Property("ArtistId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("Barcode") + .HasMaxLength(13) + .HasColumnType("TEXT") + .HasColumnOrder(25); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(33); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(32); + + b.Property("Description") + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("Disambiguation") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("Label") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(27); + + b.Property("LanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("LanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("LanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(15); + + b.Property("LastMetadataUpdateUtc") + .HasColumnType("TEXT") + .HasColumnOrder(37); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("MediaFormat") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(23); + + b.Property("MetadataProvider") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(38); + + b.Property("MetadataStatus") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasDefaultValue("Pending") + .HasColumnOrder(36); + + b.Property("MusicBrainzReleaseArtistId") + .HasColumnType("TEXT") + .HasColumnOrder(31); + + b.Property("MusicBrainzReleaseGroupId") + .HasColumnType("TEXT") + .HasColumnOrder(30); + + b.Property("MusicBrainzReleaseId") + .HasColumnType("TEXT") + .HasColumnOrder(29); + + b.Property("OriginalLanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(16); + + b.Property("OriginalLanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(17); + + b.Property("OriginalLanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(18); + + b.Property("OriginalReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("OriginalReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(8); + + b.Property("OriginalTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("Packaging") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(24); + + b.Property("ReReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("ReReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(10); + + b.Property("ReleaseCountry") + .HasMaxLength(2) + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("ReleaseStatus") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(20); + + b.Property("ReleaseTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(26); + + b.Property("ReleaseVersion") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("Script") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(19); + + b.Property("Title") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("TotalDiscs") + .HasColumnType("INTEGER") + .HasColumnOrder(21); + + b.Property("TotalTracks") + .HasColumnType("INTEGER") + .HasColumnOrder(22); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(35); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(34); + + b.HasKey("Id"); + + b.HasIndex("ArtistId", "Title"); + + b.HasIndex("LibraryId", "Title"); + + b.ToTable("Albums", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistContributorEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("ArtistId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("MediaContributorId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("Role") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.HasKey("Id"); + + b.HasIndex("MediaContributorId"); + + b.HasIndex("ArtistId", "MediaContributorId", "Role") + .IsUnique(); + + b.ToTable("ArtistContributors", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Country") + .HasMaxLength(2) + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("Disambiguation") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("Gender") + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("IsEnded") + .HasColumnType("INTEGER") + .HasColumnOrder(10); + + b.Property("LastMetadataUpdateUtc") + .HasColumnType("TEXT") + .HasColumnOrder(18); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("LifeSpanBegin") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("LifeSpanEnd") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("MetadataProvider") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(19); + + b.Property("MetadataStatus") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasDefaultValue("Pending") + .HasColumnOrder(17); + + b.Property("MusicBrainzArtistId") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("Name") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("SortName") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("Type") + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(16); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(15); + + b.Property("Website") + .HasMaxLength(2048) + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.HasKey("Id"); + + b.HasIndex("LibraryId", "Name") + .IsUnique(); + + b.ToTable("Artists", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.MusicArtworkEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("ArtworkType") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("ContentHash") + .HasColumnType("INTEGER") + .HasColumnOrder(6); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("FileName") + .HasMaxLength(2048) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("LastUpdateUtc") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("Ordinal") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("OwnerId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("OwnerType") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("Provider") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("Status") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.HasKey("Id"); + + b.HasIndex("Status"); + + b.HasIndex("OwnerType", "OwnerId", "ArtworkType", "Ordinal") + .IsUnique(); + + b.ToTable("MusicArtwork", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.MusicLibraryScanItemMetadataEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("AcoustId") + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnOrder(25); + + b.Property("ArtistName") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("AudioCodec") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(15); + + b.Property("BitDepth") + .HasColumnType("INTEGER") + .HasColumnOrder(14); + + b.Property("Bitrate") + .HasColumnType("INTEGER") + .HasColumnOrder(16); + + b.Property("Channels") + .HasColumnType("INTEGER") + .HasColumnOrder(13); + + b.Property("Container") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(31); + + b.Property("DiscNumber") + .HasColumnType("INTEGER") + .HasColumnOrder(10); + + b.Property("DurationInSeconds") + .HasColumnType("INTEGER") + .HasColumnOrder(11); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("LibraryScanId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.PrimitiveCollection("Moods") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(30); + + b.Property("MusicBrainzArtistId") + .HasColumnType("TEXT") + .HasColumnOrder(17); + + b.Property("MusicBrainzRecordingId") + .HasColumnType("TEXT") + .HasColumnOrder(21); + + b.Property("MusicBrainzReleaseArtistId") + .HasColumnType("TEXT") + .HasColumnOrder(18); + + b.Property("MusicBrainzReleaseGroupId") + .HasColumnType("TEXT") + .HasColumnOrder(19); + + b.Property("MusicBrainzReleaseId") + .HasColumnType("TEXT") + .HasColumnOrder(20); + + b.Property("MusicBrainzTrackId") + .HasColumnType("TEXT") + .HasColumnOrder(22); + + b.Property("MusicBrainzWorkId") + .HasColumnType("TEXT") + .HasColumnOrder(23); + + b.Property("Path") + .IsRequired() + .HasMaxLength(2048) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("ReleaseName") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("ReleaseType") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("ReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(6); + + b.Property("ReplayGainAlbumGain") + .HasColumnType("decimal(8,2)") + .HasColumnOrder(28); + + b.Property("ReplayGainAlbumPeak") + .HasColumnType("decimal(8,6)") + .HasColumnOrder(29); + + b.Property("ReplayGainTrackGain") + .HasColumnType("decimal(8,2)") + .HasColumnOrder(26); + + b.Property("ReplayGainTrackPeak") + .HasColumnType("decimal(8,6)") + .HasColumnOrder(27); + + b.Property("SampleRate") + .HasColumnType("INTEGER") + .HasColumnOrder(12); + + b.Property("TrackNumber") + .HasColumnType("INTEGER") + .HasColumnOrder(9); + + b.Property("TrackTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("WorkTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(24); + + b.HasKey("Id"); + + b.HasIndex("LibraryScanId", "Path") + .IsUnique(); + + b.ToTable("MusicLibraryScanItemMetadata", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.MusicPlayRecordEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("AlbumId") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("ArtistId") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("EndedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("LastPositionMilliseconds") + .HasColumnType("INTEGER") + .HasColumnOrder(7); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("ListenedDurationMilliseconds") + .HasColumnType("INTEGER") + .HasColumnOrder(8); + + b.Property("Status") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("TrackId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("UserId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("Version") + .IsConcurrencyToken() + .HasColumnType("INTEGER") + .HasColumnOrder(10); + + b.HasKey("Id"); + + b.HasIndex("TrackId"); + + b.HasIndex("UserId", "CreatedOnUtc"); + + b.ToTable("MusicPlayRecords", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackContributorEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("MediaContributorId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("Role") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("TrackId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.HasKey("Id"); + + b.HasIndex("MediaContributorId"); + + b.HasIndex("TrackId", "MediaContributorId", "Role") + .IsUnique(); + + b.ToTable("TrackContributors", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("AcoustId") + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnOrder(44); + + b.Property("AlbumId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("AudioCodec") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(24); + + b.Property("BitDepth") + .HasColumnType("INTEGER") + .HasColumnOrder(23); + + b.Property("Bitrate") + .HasColumnType("INTEGER") + .HasColumnOrder(25); + + b.Property("Bpm") + .HasColumnType("INTEGER") + .HasColumnOrder(30); + + b.Property("Channels") + .HasColumnType("INTEGER") + .HasColumnOrder(22); + + b.Property("Container") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(49); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(38); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(37); + + b.Property("Description") + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("Disambiguation") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("DiscNumber") + .HasColumnType("INTEGER") + .HasColumnOrder(27); + + b.Property("DurationInSeconds") + .HasColumnType("INTEGER") + .HasColumnOrder(20); + + b.Property("IsVideo") + .HasColumnType("INTEGER") + .HasColumnOrder(31); + + b.Property("Key") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(29); + + b.Property("LanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("LanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(15); + + b.Property("LanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(16); + + b.Property("LastMetadataUpdateUtc") + .HasColumnType("TEXT") + .HasColumnOrder(42); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("MetadataProvider") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(43); + + b.Property("MetadataStatus") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasDefaultValue("Pending") + .HasColumnOrder(41); + + b.Property("MusicBrainzRecordingId") + .HasColumnType("TEXT") + .HasColumnOrder(34); + + b.Property("MusicBrainzTrackId") + .HasColumnType("TEXT") + .HasColumnOrder(35); + + b.Property("MusicBrainzWorkId") + .HasColumnType("TEXT") + .HasColumnOrder(36); + + b.Property("OriginalLanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(17); + + b.Property("OriginalLanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(18); + + b.Property("OriginalLanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(19); + + b.Property("OriginalReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("OriginalReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(9); + + b.Property("OriginalTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("Path") + .IsRequired() + .HasMaxLength(2048) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("ReReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("ReReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(11); + + b.Property("ReleaseCountry") + .HasMaxLength(2) + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("ReleaseVersion") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("ReplayGainAlbumGain") + .HasColumnType("decimal(8,2)") + .HasColumnOrder(47); + + b.Property("ReplayGainAlbumPeak") + .HasColumnType("decimal(8,6)") + .HasColumnOrder(48); + + b.Property("ReplayGainTrackGain") + .HasColumnType("decimal(8,2)") + .HasColumnOrder(45); + + b.Property("ReplayGainTrackPeak") + .HasColumnType("decimal(8,6)") + .HasColumnOrder(46); + + b.Property("SampleRate") + .HasColumnType("INTEGER") + .HasColumnOrder(21); + + b.Property("Script") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(28); + + b.Property("Title") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("TrackNumber") + .HasColumnType("INTEGER") + .HasColumnOrder(26); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(40); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(39); + + b.Property("WorkTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(32); + + b.Property("WorkType") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(33); + + b.HasKey("Id"); + + b.HasIndex("AlbumId", "TrackNumber"); + + b.HasIndex("LibraryId", "Path") + .IsUnique(); + + b.ToTable("Tracks", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.DirectoryScanFingerprintEntity", b => + { + b.Property("LibraryId") + .HasColumnType("TEXT"); + + b.Property("Path") + .HasMaxLength(1024) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("LastWriteTimeUtc") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.HasKey("LibraryId", "Path"); + + b.HasIndex("LibraryId"); + + b.ToTable("DirectoryScanFingerprints", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("ArtworkProvidersConfigurationFingerprint") + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("CanDownloadMetadataFromWeb") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(true) + .HasColumnOrder(6); + + b.Property("CompletionThresholdPercentage") + .HasColumnType("INTEGER") + .HasColumnOrder(17); + + b.Property("CoverImage") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("IsEnabled") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(true) + .HasColumnOrder(4); + + b.Property("IsLocked") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("LibraryType") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("MetadataProvidersConfigurationFingerprint") + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("PathTemplateFingerprint") + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("ShouldSaveMetadataInMediaDirectories") + .HasColumnType("INTEGER") + .HasColumnOrder(7); + + b.Property("ShouldSkipUnchangedDirectoriesDuringScan") + .HasColumnType("INTEGER") + .HasColumnOrder(8); + + b.Property("ShouldTrackConsumptionProgress") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(false) + .HasColumnOrder(16); + + b.Property("Title") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(15); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("UserId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("Libraries", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("LibraryId") + .HasColumnType("TEXT"); + + b.Property("Status") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UserId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.HasIndex("LibraryId", "Status", "CreatedOnUtc") + .IsDescending(true, false, true); + + b.ToTable("LibraryScans", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanResultEntity", b => + { + b.Property("LibraryScanId") + .HasColumnType("TEXT"); + + b.Property("Path") + .HasMaxLength(1024) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("ContentHash") + .HasMaxLength(24) + .HasColumnType("INTEGER") + .HasColumnOrder(2); + + b.Property("FileSize") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Status") + .IsRequired() + .HasMaxLength(10) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("Ticks") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.HasKey("LibraryScanId", "Path"); + + b.HasIndex("Path"); + + b.HasIndex("ContentHash", "FileSize", "Path"); + + b.ToTable("LibraryScanResults", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanSnapshotEntity", b => + { + b.Property("LibraryId") + .HasColumnType("TEXT"); + + b.Property("Path") + .HasMaxLength(1024) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("ContentHash") + .HasColumnType("INTEGER") + .HasColumnOrder(2); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("FileSize") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Ticks") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.HasKey("LibraryId", "Path"); + + b.HasIndex("LibraryId"); + + b.ToTable("LibraryScanSnapshots", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanStagingResultsEntity", b => + { + b.Property("LibraryScanId") + .HasColumnType("TEXT"); + + b.Property("Path") + .HasMaxLength(1024) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("ContentHash") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("IsNew") + .HasColumnType("INTEGER") + .HasColumnOrder(7); + + b.Property("NeedsRehash") + .HasColumnType("INTEGER") + .HasColumnOrder(6); + + b.Property("PreviousContentHash") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("Size") + .HasColumnType("INTEGER") + .HasColumnOrder(2); + + b.Property("Ticks") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.HasKey("LibraryScanId", "Path"); + + b.HasIndex("LibraryScanId", "NeedsRehash"); + + b.ToTable("LibraryScanStagingResults", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookArtworkEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("ArtworkType") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("BookId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("ContentHash") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("FileName") + .HasMaxLength(2048) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("LastUpdateUtc") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("Ordinal") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("Provider") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("Status") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.HasKey("Id"); + + b.HasIndex("Status"); + + b.HasIndex("BookId", "ArtworkType", "Ordinal") + .IsUnique(); + + b.ToTable("BookArtwork", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookContributorEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("BookId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("MediaContributorId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("Role") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.HasKey("Id"); + + b.HasIndex("MediaContributorId"); + + b.HasIndex("BookId", "MediaContributorId", "Role") + .IsUnique(); + + b.ToTable("BookContributors", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("ASIN") + .HasMaxLength(10) + .HasColumnType("TEXT") + .HasColumnOrder(21); + + b.Property("AppleBooksId") + .HasColumnType("TEXT") + .HasColumnOrder(29); + + b.Property("BarnesAndNobleId") + .HasMaxLength(10) + .HasColumnType("TEXT") + .HasColumnOrder(28); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(33); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(32); + + b.Property("Description") + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("Edition") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(19); + + b.Property("Format") + .HasColumnType("TEXT") + .HasColumnOrder(18); + + b.Property("GoodreadsId") + .HasColumnType("TEXT") + .HasColumnOrder(22); + + b.Property("GoogleBooksId") + .HasMaxLength(12) + .HasColumnType("TEXT") + .HasColumnOrder(27); + + b.Property("LCCN") + .HasColumnType("TEXT") + .HasColumnOrder(23); + + b.Property("LanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("LanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("LanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("LastMetadataUpdateUtc") + .HasColumnType("TEXT") + .HasColumnOrder(39); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(36); + + b.Property("LibraryThingId") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(26); + + b.Property("MetadataProvider") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(40); + + b.Property("MetadataStatus") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(38); + + b.Property("OCLCNumber") + .HasColumnType("TEXT") + .HasColumnOrder(24); + + b.Property("OpenLibraryId") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(25); + + b.Property("OriginalLanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("OriginalLanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("OriginalLanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(15); + + b.Property("OriginalReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("OriginalReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("OriginalTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("PageCount") + .HasColumnType("INTEGER") + .HasColumnOrder(17); + + b.Property("Path") + .IsRequired() + .HasMaxLength(2048) + .HasColumnType("TEXT") + .HasColumnOrder(37); + + b.Property("Publisher") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(16); + + b.Property("ReReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("ReReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(7); + + b.Property("ReleaseCountry") + .HasMaxLength(2) + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("ReleaseVersion") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("Title") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(35); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(34); + + b.Property("VolumeNumber") + .HasColumnType("REAL") + .HasColumnOrder(20); + + b.HasKey("Id"); + + b.HasIndex("LibraryId", "MetadataStatus"); + + b.HasIndex("LibraryId", "Path") + .IsUnique(); + + b.ToTable("Books", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Playlists.PlaylistEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("Description") + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("EntryCount") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(0) + .HasColumnOrder(10); + + b.Property("Name") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("Type") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UserId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("Version") + .IsConcurrencyToken() + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(0L) + .HasColumnOrder(9); + + b.HasKey("Id"); + + b.HasIndex("UserId", "UpdatedOnUtc"); + + b.ToTable("Playlists", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Playlists.PlaylistEntryEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("MediaItemId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("MediaItemType") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("PlaylistId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("Position") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.HasKey("Id"); + + b.HasIndex("MediaItemId"); + + b.HasIndex("PlaylistId", "Position") + .IsUnique(); + + b.ToTable("PlaylistEntries", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Plugins.LibraryArtworkProviderConfigurationEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("IsEnabled") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("PluginId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("Rank") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.HasKey("Id"); + + b.HasIndex("LibraryId", "PluginId"); + + b.ToTable("LibraryArtworkProviderConfigurations", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Plugins.LibraryBookReaderConfigurationEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("IsEnabled") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("PluginId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.HasKey("Id"); + + b.HasIndex("LibraryId", "PluginId") + .IsUnique(); + + b.ToTable("LibraryBookReaderConfigurations", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Plugins.LibraryMetadataProviderConfigurationEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("IsEnabled") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("PluginId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("Rank") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.HasKey("Id"); + + b.HasIndex("LibraryId", "PluginId"); + + b.ToTable("LibraryMetadataProviderConfigurations", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Plugins.PluginEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Author") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("Description") + .IsRequired() + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("LoadError") + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("LoadStatus") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("Name") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("SettingsJson") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("Version") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.HasKey("Id"); + + b.ToTable("Plugins", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Scheduling.ScheduledJobEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("Hour") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("IntervalMinutes") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("LastCompletedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("LastStartedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("Minute") + .HasColumnType("INTEGER") + .HasColumnOrder(6); + + b.Property("Name") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("OwnerUserId") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("ScheduleType") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("Status") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("TaskType") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.HasKey("Id"); + + b.HasIndex("Status"); + + b.ToTable("ScheduledJobs", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Scheduling.ScheduledJobExecutionEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CompletedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("IsCycleRun") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("ScheduledJobId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("StartedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("TaskType") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("WasCycleActive") + .HasColumnType("INTEGER") + .HasColumnOrder(6); + + b.HasKey("Id"); + + b.HasIndex("ScheduledJobId"); + + b.HasIndex("StartedOnUtc", "ScheduledJobId"); + + b.ToTable("ScheduledJobExecutions", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Scheduling.SchedulerDisplayPreferencesEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("DisplayTimeSpan") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("DisplayTimeUnit") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("JobTypeFilter") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UserId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.HasKey("Id"); + + b.HasIndex("UserId") + .IsUnique(); + + b.ToTable("SchedulerDisplayPreferences", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Themes.ThemeEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Author") + .IsRequired() + .HasMaxLength(80) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("Description") + .IsRequired() + .HasMaxLength(300) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("InstallSource") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("InstalledAtUtc") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("IsCurrent") + .HasColumnType("INTEGER") + .HasColumnOrder(8); + + b.Property("IsDeleted") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(false) + .HasColumnOrder(9); + + b.Property("Name") + .IsRequired() + .HasMaxLength(80) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("PreviewPath") + .HasMaxLength(240) + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("ThemeId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("Version") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.HasKey("Id"); + + b.HasIndex("IsCurrent") + .IsUnique() + .HasFilter("IsCurrent = 1"); + + b.HasIndex("ThemeId") + .IsUnique(); + + b.ToTable("Themes", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("Password") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("TempPassword") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("TempPasswordCreated") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("TotpSecret") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("Username") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.HasKey("Id"); + + b.HasIndex("Username") + .IsUnique(); + + b.ToTable("Users", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserSettingsEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("IsGaplessPlaybackEnabled") + .HasColumnType("INTEGER") + .HasColumnOrder(16); + + b.Property("IsMuted") + .HasColumnType("INTEGER") + .HasColumnOrder(29); + + b.Property("IsPaginationEnabled") + .HasColumnType("INTEGER") + .HasColumnOrder(2); + + b.Property("IsThemeCachingEnabled") + .HasColumnType("INTEGER") + .HasColumnOrder(9); + + b.Property("ItemsPerPage") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("ReplayGainMode") + .HasColumnType("INTEGER") + .HasColumnOrder(17); + + b.Property("ShouldAggregateArtworkWhenMissing") + .HasColumnType("INTEGER") + .HasColumnOrder(13); + + b.Property("ShouldAggregateMetadataWhenMissing") + .HasColumnType("INTEGER") + .HasColumnOrder(10); + + b.Property("ShouldAutoplay") + .HasColumnType("INTEGER") + .HasColumnOrder(15); + + b.Property("ShouldIgnoreThePrefixForAlphaPicker") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("ShouldKeepDownloadingWhilePaused") + .HasColumnType("INTEGER") + .HasColumnOrder(14); + + b.Property("ShouldPreserveBookStyles") + .HasColumnType("INTEGER") + .HasColumnOrder(12); + + b.Property("ShouldRenderPdfAsImages") + .HasColumnType("INTEGER") + .HasColumnOrder(11); + + b.Property("StreamingQuality") + .HasColumnType("INTEGER") + .HasColumnOrder(18); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UserId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("Volume") + .HasColumnType("REAL") + .HasColumnOrder(28); + + b.Property("VuMeterHighThreshold") + .HasColumnType("REAL") + .HasColumnOrder(23); + + b.Property("VuMeterMediumThreshold") + .HasColumnType("REAL") + .HasColumnOrder(22); + + b.Property("VuMeterOrientation") + .HasColumnType("INTEGER") + .HasColumnOrder(19); + + b.Property("VuMeterPeakHoldDurationInMilliseconds") + .HasColumnType("INTEGER") + .HasColumnOrder(25); + + b.Property("VuMeterPeakReleasePerSecond") + .HasColumnType("REAL") + .HasColumnOrder(27); + + b.Property("VuMeterReleasePerSecond") + .HasColumnType("REAL") + .HasColumnOrder(26); + + b.Property("VuMeterSegmentCount") + .HasColumnType("INTEGER") + .HasColumnOrder(20); + + b.Property("VuMeterSegmentGap") + .HasColumnType("INTEGER") + .HasColumnOrder(21); + + b.Property("VuMeterShowPeak") + .HasColumnType("INTEGER") + .HasColumnOrder(24); + + b.HasKey("Id"); + + b.HasIndex("UserId") + .IsUnique(); + + b.ToTable("UserSettings", (string)null); + }); + + modelBuilder.Entity("TrackGenres", b => + { + b.Property("TrackId") + .HasColumnType("TEXT"); + + b.Property("GenreId") + .HasColumnType("TEXT"); + + b.HasKey("TrackId", "GenreId"); + + b.HasIndex("GenreId"); + + b.ToTable("TrackGenres", (string)null); + }); + + modelBuilder.Entity("TrackTags", b => + { + b.Property("TrackId") + .HasColumnType("TEXT"); + + b.Property("TagId") + .HasColumnType("TEXT"); + + b.HasKey("TrackId", "TagId"); + + b.HasIndex("TagId"); + + b.ToTable("TrackTags", (string)null); + }); + + modelBuilder.Entity("AlbumGenres", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumEntity", null) + .WithMany() + .HasForeignKey("AlbumId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.GenreEntity", null) + .WithMany() + .HasForeignKey("GenreId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("AlbumTags", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumEntity", null) + .WithMany() + .HasForeignKey("AlbumId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.TagEntity", null) + .WithMany() + .HasForeignKey("TagId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("ArtistGenres", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistEntity", null) + .WithMany() + .HasForeignKey("ArtistId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.GenreEntity", null) + .WithMany() + .HasForeignKey("GenreId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("ArtistTags", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistEntity", null) + .WithMany() + .HasForeignKey("ArtistId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.TagEntity", null) + .WithMany() + .HasForeignKey("TagId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BookGenres", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", null) + .WithMany() + .HasForeignKey("BookId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.GenreEntity", null) + .WithMany() + .HasForeignKey("GenreId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BookTags", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", null) + .WithMany() + .HasForeignKey("BookId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.TagEntity", null) + .WithMany() + .HasForeignKey("TagId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.RolePermissionEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Authorization.PermissionEntity", "Permission") + .WithMany("RolePermissions") + .HasForeignKey("PermissionId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Authorization.RoleEntity", "Role") + .WithMany("RolePermissions") + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Permission"); + + b.Navigation("Role"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.UserPermissionEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Authorization.PermissionEntity", "Permission") + .WithMany("UserPermissions") + .HasForeignKey("PermissionId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", "User") + .WithMany("UserPermissions") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Permission"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.UserRoleEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Authorization.RoleEntity", "Role") + .WithMany("UserRoles") + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", "User") + .WithOne("UserRole") + .HasForeignKey("Lumina.Application.Common.DataAccess.Entities.Authorization.UserRoleEntity", "UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Role"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.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) + .WithMany("Contributors") + .HasForeignKey("AlbumId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistEntity", "Artist") + .WithMany("Albums") + .HasForeignKey("ArtistId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumCatalogNumberEntity", "CatalogNumbers", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("AlbumId") + .HasColumnType("TEXT"); + + b1.Property("CatalogNumber") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("AlbumId"); + + b1.ToTable("AlbumCatalogNumbers", (string)null); + + b1.WithOwner() + .HasForeignKey("AlbumId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AudioRatingEntity", "Ratings", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("AlbumId") + .HasColumnType("TEXT"); + + b1.Property("MaxValue") + .HasColumnType("decimal(3,2)"); + + b1.Property("Source") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.Property("Value") + .HasColumnType("decimal(3,2)"); + + b1.Property("VoteCount") + .HasColumnType("INTEGER"); + + b1.HasKey("Id"); + + b1.HasIndex("AlbumId"); + + b1.ToTable("AlbumRatings", (string)null); + + b1.WithOwner() + .HasForeignKey("AlbumId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumReleaseTypeEntity", "ReleaseTypes", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("AlbumId") + .HasColumnType("TEXT"); + + b1.Property("ReleaseType") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("AlbumId"); + + b1.ToTable("AlbumReleaseTypes", (string)null); + + b1.WithOwner() + .HasForeignKey("AlbumId"); + }); + + b.Navigation("Artist"); + + b.Navigation("CatalogNumbers"); + + b.Navigation("Ratings"); + + b.Navigation("ReleaseTypes"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistContributorEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistEntity", null) + .WithMany("Contributors") + .HasForeignKey("ArtistId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistEntity", b => + { + b.OwnsOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.MusicAreaEntity", "Area", b1 => + { + b1.Property("ArtistEntityId"); + + b1.Property("Disambiguation"); + + b1.Property("Iso3166Code"); + + b1.Property("MusicBrainzAreaId"); + + b1.Property("Name") + .IsRequired(); + + b1.Property("SortName"); + + b1.Property("Type"); + + b1.HasKey("ArtistEntityId"); + + b1.ToTable("Artists"); + + b1 + .ToJson("Area") + .HasColumnType("TEXT"); + + b1.WithOwner() + .HasForeignKey("ArtistEntityId"); + }); + + b.OwnsOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.MusicAreaEntity", "BeginArea", b1 => + { + b1.Property("ArtistEntityId"); + + b1.Property("Disambiguation"); + + b1.Property("Iso3166Code"); + + b1.Property("MusicBrainzAreaId"); + + b1.Property("Name") + .IsRequired(); + + b1.Property("SortName"); + + b1.Property("Type"); + + b1.HasKey("ArtistEntityId"); + + b1.ToTable("Artists"); + + b1 + .ToJson("BeginArea") + .HasColumnType("TEXT"); + + b1.WithOwner() + .HasForeignKey("ArtistEntityId"); + }); + + b.OwnsOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.MusicAreaEntity", "EndArea", b1 => + { + b1.Property("ArtistEntityId"); + + b1.Property("Disambiguation"); + + b1.Property("Iso3166Code"); + + b1.Property("MusicBrainzAreaId"); + + b1.Property("Name") + .IsRequired(); + + b1.Property("SortName"); + + b1.Property("Type"); + + b1.HasKey("ArtistEntityId"); + + b1.ToTable("Artists"); + + b1 + .ToJson("EndArea") + .HasColumnType("TEXT"); + + b1.WithOwner() + .HasForeignKey("ArtistEntityId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistAliasEntity", "Aliases", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("ArtistId") + .HasColumnType("TEXT"); + + b1.Property("BeginDate") + .HasColumnType("TEXT"); + + b1.Property("EndDate") + .HasColumnType("TEXT"); + + b1.Property("IsEnded") + .HasColumnType("INTEGER"); + + b1.Property("IsPrimary") + .HasColumnType("INTEGER"); + + b1.Property("Locale") + .HasMaxLength(20) + .HasColumnType("TEXT"); + + b1.Property("Name") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT"); + + b1.Property("SortName") + .HasMaxLength(255) + .HasColumnType("TEXT"); + + b1.Property("Type") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("ArtistId"); + + b1.ToTable("ArtistAliases", (string)null); + + b1.WithOwner() + .HasForeignKey("ArtistId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AudioRatingEntity", "Ratings", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("ArtistId") + .HasColumnType("TEXT"); + + b1.Property("MaxValue") + .HasColumnType("decimal(3,2)"); + + b1.Property("Source") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.Property("Value") + .HasColumnType("decimal(3,2)"); + + b1.Property("VoteCount") + .HasColumnType("INTEGER"); + + b1.HasKey("Id"); + + b1.HasIndex("ArtistId"); + + b1.ToTable("ArtistRatings", (string)null); + + b1.WithOwner() + .HasForeignKey("ArtistId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistIpiEntity", "Ipis", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("ArtistId") + .HasColumnType("TEXT"); + + b1.Property("Value") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("ArtistId"); + + b1.ToTable("ArtistIpis", (string)null); + + b1.WithOwner() + .HasForeignKey("ArtistId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistIsniEntity", "Isnis", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("ArtistId") + .HasColumnType("TEXT"); + + b1.Property("Value") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("ArtistId"); + + b1.ToTable("ArtistIsnis", (string)null); + + b1.WithOwner() + .HasForeignKey("ArtistId"); + }); + + b.Navigation("Aliases"); + + b.Navigation("Area"); + + b.Navigation("BeginArea"); + + b.Navigation("EndArea"); + + b.Navigation("Ipis"); + + b.Navigation("Isnis"); + + b.Navigation("Ratings"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackContributorEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackEntity", null) + .WithMany("Contributors") + .HasForeignKey("TrackId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumEntity", "Album") + .WithMany("Tracks") + .HasForeignKey("AlbumId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AudioRatingEntity", "Ratings", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("MaxValue") + .HasColumnType("decimal(3,2)"); + + b1.Property("Source") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.Property("TrackId") + .HasColumnType("TEXT"); + + b1.Property("Value") + .HasColumnType("decimal(3,2)"); + + b1.Property("VoteCount") + .HasColumnType("INTEGER"); + + b1.HasKey("Id"); + + b1.HasIndex("TrackId"); + + b1.ToTable("TrackRatings", (string)null); + + b1.WithOwner() + .HasForeignKey("TrackId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackIsrcEntity", "Isrcs", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("TrackId") + .HasColumnType("TEXT"); + + b1.Property("Value") + .IsRequired() + .HasMaxLength(12) + .HasColumnType("TEXT") + .HasColumnName("ISRC"); + + b1.HasKey("Id"); + + b1.HasIndex("TrackId"); + + b1.ToTable("TrackIsrcs", (string)null); + + b1.WithOwner() + .HasForeignKey("TrackId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackMoodEntity", "Moods", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("Name") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.Property("TrackId") + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("TrackId"); + + b1.ToTable("TrackMoods", (string)null); + + b1.WithOwner() + .HasForeignKey("TrackId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackWorkIswcEntity", "WorkIswcs", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("TrackId") + .HasColumnType("TEXT"); + + b1.Property("Value") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("TrackId"); + + b1.ToTable("TrackWorkIswcs", (string)null); + + b1.WithOwner() + .HasForeignKey("TrackId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackWorkLanguageEntity", "WorkLanguages", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("LanguageCode") + .IsRequired() + .HasMaxLength(5) + .HasColumnType("TEXT"); + + b1.Property("LanguageName") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("TEXT"); + + b1.Property("NativeName") + .HasMaxLength(100) + .HasColumnType("TEXT"); + + b1.Property("TrackId") + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("TrackId"); + + b1.ToTable("TrackWorkLanguages", (string)null); + + b1.WithOwner() + .HasForeignKey("TrackId"); + }); + + b.Navigation("Album"); + + b.Navigation("Isrcs"); + + b.Navigation("Moods"); + + b.Navigation("Ratings"); + + b.Navigation("WorkIswcs"); + + b.Navigation("WorkLanguages"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.DirectoryScanFingerprintEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", null) + .WithMany() + .HasForeignKey("LibraryId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", "User") + .WithMany("Libraries") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryContentLocationEntity", "ContentLocations", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("LibraryId") + .HasColumnType("TEXT"); + + b1.Property("Path") + .IsRequired() + .HasMaxLength(260) + .HasColumnType("TEXT") + .HasColumnName("Path"); + + b1.HasKey("Id"); + + b1.HasIndex("LibraryId"); + + b1.ToTable("LibraryContentLocations", (string)null); + + b1.WithOwner() + .HasForeignKey("LibraryId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryPathTemplatePartEntity", "PathTemplateParts", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("IsOptional") + .HasColumnType("INTEGER"); + + b1.Property("Kind") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b1.Property("LibraryId") + .HasColumnType("TEXT"); + + b1.Property("Position") + .HasColumnType("INTEGER") + .HasColumnName("Position"); + + b1.Property("Representation") + .IsRequired() + .HasMaxLength(512) + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("LibraryId", "Position") + .IsUnique(); + + b1.ToTable("LibraryPathTemplateParts", (string)null); + + b1.WithOwner() + .HasForeignKey("LibraryId"); + }); + + b.Navigation("ContentLocations"); + + b.Navigation("PathTemplateParts"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", "Library") + .WithMany("LibraryScans") + .HasForeignKey("LibraryId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", "User") + .WithMany("LibraryScans") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Library"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanResultEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", "LibraryScan") + .WithMany("LibraryScanResults") + .HasForeignKey("LibraryScanId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("LibraryScan"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanSnapshotEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", "Library") + .WithMany() + .HasForeignKey("LibraryId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Library"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanStagingResultsEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", null) + .WithMany() + .HasForeignKey("LibraryScanId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookArtworkEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", null) + .WithMany("Artwork") + .HasForeignKey("BookId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookContributorEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", null) + .WithMany("Contributors") + .HasForeignKey("BookId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", b => + { + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookRatingEntity", "Ratings", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("BookId") + .HasColumnType("TEXT"); + + b1.Property("MaxValue") + .HasColumnType("decimal(3,2)"); + + b1.Property("Source") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.Property("Value") + .HasColumnType("decimal(3,2)"); + + b1.Property("VoteCount") + .HasColumnType("INTEGER"); + + b1.HasKey("Id"); + + b1.HasIndex("BookId"); + + b1.ToTable("BookRatings", (string)null); + + b1.WithOwner() + .HasForeignKey("BookId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.IsbnEntity", "ISBNs", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("BookId") + .HasColumnType("TEXT"); + + b1.Property("Format") + .IsRequired() + .HasMaxLength(6) + .HasColumnType("TEXT"); + + b1.Property("Value") + .IsRequired() + .HasMaxLength(13) + .HasColumnType("TEXT") + .HasColumnName("ISBN"); + + b1.HasKey("Id"); + + b1.HasIndex("BookId"); + + b1.ToTable("BookISBNs", (string)null); + + b1.WithOwner() + .HasForeignKey("BookId"); + }); + + b.Navigation("ISBNs"); + + b.Navigation("Ratings"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Playlists.PlaylistEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Playlists.PlaylistEntryEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Playlists.PlaylistEntity", null) + .WithMany("Entries") + .HasForeignKey("PlaylistId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserSettingsEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", null) + .WithOne() + .HasForeignKey("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserSettingsEntity", "UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("TrackGenres", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.GenreEntity", null) + .WithMany() + .HasForeignKey("GenreId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackEntity", null) + .WithMany() + .HasForeignKey("TrackId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("TrackTags", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.TagEntity", null) + .WithMany() + .HasForeignKey("TagId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackEntity", null) + .WithMany() + .HasForeignKey("TrackId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.PermissionEntity", b => + { + b.Navigation("RolePermissions"); + + b.Navigation("UserPermissions"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.RoleEntity", b => + { + b.Navigation("RolePermissions"); + + b.Navigation("UserRoles"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumEntity", b => + { + b.Navigation("Contributors"); + + b.Navigation("Tracks"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistEntity", b => + { + b.Navigation("Albums"); + + b.Navigation("Contributors"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackEntity", b => + { + b.Navigation("Contributors"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", b => + { + b.Navigation("LibraryScans"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", b => + { + b.Navigation("LibraryScanResults"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", b => + { + b.Navigation("Artwork"); + + b.Navigation("Contributors"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Playlists.PlaylistEntity", b => + { + b.Navigation("Entries"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", b => + { + b.Navigation("Libraries"); + + b.Navigation("LibraryScans"); + + b.Navigation("UserPermissions"); + + b.Navigation("UserRole"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/Lumina.DataAccess/Common/Migrations/20261024065622_AddsLibraryConsumptionSettings.cs b/src/Lumina.DataAccess/Common/Migrations/20261024065622_AddsLibraryConsumptionSettings.cs new file mode 100644 index 00000000..283250b9 --- /dev/null +++ b/src/Lumina.DataAccess/Common/Migrations/20261024065622_AddsLibraryConsumptionSettings.cs @@ -0,0 +1,41 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Lumina.DataAccess.Common.Migrations +{ + /// + public partial class AddsLibraryConsumptionSettings : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AddColumn( + name: "CompletionThresholdPercentage", + table: "Libraries", + type: "INTEGER", + nullable: true) + .Annotation("Relational:ColumnOrder", 17); + + migrationBuilder.AddColumn( + name: "ShouldTrackConsumptionProgress", + table: "Libraries", + type: "INTEGER", + nullable: false, + defaultValue: false) + .Annotation("Relational:ColumnOrder", 16); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropColumn( + name: "CompletionThresholdPercentage", + table: "Libraries"); + + migrationBuilder.DropColumn( + name: "ShouldTrackConsumptionProgress", + table: "Libraries"); + } + } +} diff --git a/src/Lumina.DataAccess/Common/Migrations/20261024161715_AddsMediaConsumptionHistory.Designer.cs b/src/Lumina.DataAccess/Common/Migrations/20261024161715_AddsMediaConsumptionHistory.Designer.cs new file mode 100644 index 00000000..7ab99488 --- /dev/null +++ b/src/Lumina.DataAccess/Common/Migrations/20261024161715_AddsMediaConsumptionHistory.Designer.cs @@ -0,0 +1,3970 @@ +// +using System; +using Lumina.DataAccess.Core.UoW; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace Lumina.DataAccess.Common.Migrations +{ + [DbContext(typeof(LuminaDbContext))] + [Migration("20261024161715_AddsMediaConsumptionHistory")] + partial class AddsMediaConsumptionHistory + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder.HasAnnotation("ProductVersion", "10.0.11"); + + modelBuilder.Entity("AlbumGenres", b => + { + b.Property("AlbumId") + .HasColumnType("TEXT"); + + b.Property("GenreId") + .HasColumnType("TEXT"); + + b.HasKey("AlbumId", "GenreId"); + + b.HasIndex("GenreId"); + + b.ToTable("AlbumGenres", (string)null); + }); + + modelBuilder.Entity("AlbumTags", b => + { + b.Property("AlbumId") + .HasColumnType("TEXT"); + + b.Property("TagId") + .HasColumnType("TEXT"); + + b.HasKey("AlbumId", "TagId"); + + b.HasIndex("TagId"); + + b.ToTable("AlbumTags", (string)null); + }); + + modelBuilder.Entity("ArtistGenres", b => + { + b.Property("ArtistId") + .HasColumnType("TEXT"); + + b.Property("GenreId") + .HasColumnType("TEXT"); + + b.HasKey("ArtistId", "GenreId"); + + b.HasIndex("GenreId"); + + b.ToTable("ArtistGenres", (string)null); + }); + + modelBuilder.Entity("ArtistTags", b => + { + b.Property("ArtistId") + .HasColumnType("TEXT"); + + b.Property("TagId") + .HasColumnType("TEXT"); + + b.HasKey("ArtistId", "TagId"); + + b.HasIndex("TagId"); + + b.ToTable("ArtistTags", (string)null); + }); + + modelBuilder.Entity("BookGenres", b => + { + b.Property("BookId") + .HasColumnType("TEXT"); + + b.Property("GenreId") + .HasColumnType("TEXT"); + + b.HasKey("BookId", "GenreId"); + + b.HasIndex("GenreId"); + + b.ToTable("BookGenres", (string)null); + }); + + modelBuilder.Entity("BookTags", b => + { + b.Property("BookId") + .HasColumnType("TEXT"); + + b.Property("TagId") + .HasColumnType("TEXT"); + + b.HasKey("BookId", "TagId"); + + b.HasIndex("TagId"); + + b.ToTable("BookTags", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.PermissionEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("PermissionName") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.HasKey("Id"); + + b.ToTable("Permissions", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.RoleEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("RoleName") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.HasKey("Id"); + + b.ToTable("Roles", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.RolePermissionEntity", b => + { + b.Property("RoleId") + .HasColumnType("TEXT"); + + b.Property("PermissionId") + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.HasKey("RoleId", "PermissionId"); + + b.HasIndex("PermissionId"); + + b.HasIndex("RoleId", "PermissionId") + .IsUnique(); + + b.ToTable("RolePermissions", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.UserPermissionEntity", b => + { + b.Property("UserId") + .HasColumnType("TEXT"); + + b.Property("PermissionId") + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.HasKey("UserId", "PermissionId"); + + b.HasIndex("PermissionId"); + + b.HasIndex("UserId", "PermissionId") + .IsUnique(); + + b.ToTable("UserPermissions", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.UserRoleEntity", b => + { + b.Property("UserId") + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("RoleId") + .HasColumnType("TEXT"); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.HasKey("UserId"); + + b.HasIndex("RoleId"); + + b.HasIndex("UserId", "RoleId") + .IsUnique(); + + b.ToTable("UserRoles", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Common.GenreEntity", b => + { + b.Property("Name") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b.HasKey("Name"); + + b.ToTable("Genres", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Common.TagEntity", b => + { + b.Property("Name") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b.HasKey("Name"); + + b.ToTable("Tags", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Favorites.FavoriteEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("MediaItemId") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("MediaKind") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("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.MediaConsumption.MediaConsumptionRecordEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("ConsecutivePagesRead") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(0) + .HasColumnOrder(14); + + b.Property("ConsumedDurationMilliseconds") + .HasColumnType("INTEGER") + .HasColumnOrder(9); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(17); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(16); + + b.Property("EndedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("LastActivityOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("LastPositionKind") + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("LastPositionLocation") + .HasMaxLength(4096) + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("LastPositionTimeOffsetMilliseconds") + .HasColumnType("INTEGER") + .HasColumnOrder(11); + + b.Property("LastProgressFraction") + .HasColumnType("REAL") + .HasColumnOrder(13); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("MediaItemId") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("MediaKind") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("StartedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("Status") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(19); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(18); + + b.Property("UserId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("Version") + .IsConcurrencyToken() + .HasColumnType("INTEGER") + .HasColumnOrder(15); + + b.HasKey("Id"); + + b.HasIndex("UserId", "MediaKind", "StartedOnUtc"); + + b.HasIndex("UserId", "MediaKind", "MediaItemId", "LastActivityOnUtc"); + + b.ToTable("MediaConsumptionRecords", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaConsumption.MediaResumePointEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("LastConsumedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("LastPositionKind") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("LastPositionLocation") + .HasMaxLength(4096) + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("LastPositionTimeOffsetMilliseconds") + .HasColumnType("INTEGER") + .HasColumnOrder(6); + + b.Property("LastProgressFraction") + .HasColumnType("REAL") + .HasColumnOrder(8); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("MediaItemId") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("MediaKind") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("UserId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("Version") + .IsConcurrencyToken() + .HasColumnType("INTEGER") + .HasColumnOrder(10); + + b.HasKey("Id"); + + b.HasIndex("UserId", "MediaKind", "MediaItemId") + .IsUnique(); + + b.ToTable("MediaResumePoints", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaContributors.MediaContributorEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Biography") + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("DateOfBirth") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("DateOfDeath") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("DisplayName") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1) + .UseCollation("NOCASE"); + + b.Property("LegalName") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.HasKey("Id"); + + b.HasIndex("DisplayName") + .IsUnique(); + + b.ToTable("MediaContributors", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumContributorEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("AlbumId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("MediaContributorId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("Role") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.HasKey("Id"); + + b.HasIndex("MediaContributorId"); + + b.HasIndex("AlbumId", "MediaContributorId", "Role") + .IsUnique(); + + b.ToTable("AlbumContributors", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("ASIN") + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(28); + + b.Property("ArtistId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("Barcode") + .HasMaxLength(13) + .HasColumnType("TEXT") + .HasColumnOrder(25); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(33); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(32); + + b.Property("Description") + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("Disambiguation") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("Label") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(27); + + b.Property("LanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("LanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("LanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(15); + + b.Property("LastMetadataUpdateUtc") + .HasColumnType("TEXT") + .HasColumnOrder(37); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("MediaFormat") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(23); + + b.Property("MetadataProvider") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(38); + + b.Property("MetadataStatus") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasDefaultValue("Pending") + .HasColumnOrder(36); + + b.Property("MusicBrainzReleaseArtistId") + .HasColumnType("TEXT") + .HasColumnOrder(31); + + b.Property("MusicBrainzReleaseGroupId") + .HasColumnType("TEXT") + .HasColumnOrder(30); + + b.Property("MusicBrainzReleaseId") + .HasColumnType("TEXT") + .HasColumnOrder(29); + + b.Property("OriginalLanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(16); + + b.Property("OriginalLanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(17); + + b.Property("OriginalLanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(18); + + b.Property("OriginalReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("OriginalReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(8); + + b.Property("OriginalTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("Packaging") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(24); + + b.Property("ReReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("ReReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(10); + + b.Property("ReleaseCountry") + .HasMaxLength(2) + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("ReleaseStatus") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(20); + + b.Property("ReleaseTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(26); + + b.Property("ReleaseVersion") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("Script") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(19); + + b.Property("Title") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("TotalDiscs") + .HasColumnType("INTEGER") + .HasColumnOrder(21); + + b.Property("TotalTracks") + .HasColumnType("INTEGER") + .HasColumnOrder(22); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(35); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(34); + + b.HasKey("Id"); + + b.HasIndex("ArtistId", "Title"); + + b.HasIndex("LibraryId", "Title"); + + b.ToTable("Albums", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistContributorEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("ArtistId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("MediaContributorId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("Role") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.HasKey("Id"); + + b.HasIndex("MediaContributorId"); + + b.HasIndex("ArtistId", "MediaContributorId", "Role") + .IsUnique(); + + b.ToTable("ArtistContributors", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Country") + .HasMaxLength(2) + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("Disambiguation") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("Gender") + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("IsEnded") + .HasColumnType("INTEGER") + .HasColumnOrder(10); + + b.Property("LastMetadataUpdateUtc") + .HasColumnType("TEXT") + .HasColumnOrder(18); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("LifeSpanBegin") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("LifeSpanEnd") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("MetadataProvider") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(19); + + b.Property("MetadataStatus") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasDefaultValue("Pending") + .HasColumnOrder(17); + + b.Property("MusicBrainzArtistId") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("Name") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("SortName") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("Type") + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(16); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(15); + + b.Property("Website") + .HasMaxLength(2048) + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.HasKey("Id"); + + b.HasIndex("LibraryId", "Name") + .IsUnique(); + + b.ToTable("Artists", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.MusicArtworkEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("ArtworkType") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("ContentHash") + .HasColumnType("INTEGER") + .HasColumnOrder(6); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("FileName") + .HasMaxLength(2048) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("LastUpdateUtc") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("Ordinal") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("OwnerId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("OwnerType") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("Provider") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("Status") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.HasKey("Id"); + + b.HasIndex("Status"); + + b.HasIndex("OwnerType", "OwnerId", "ArtworkType", "Ordinal") + .IsUnique(); + + b.ToTable("MusicArtwork", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.MusicLibraryScanItemMetadataEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("AcoustId") + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnOrder(25); + + b.Property("ArtistName") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("AudioCodec") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(15); + + b.Property("BitDepth") + .HasColumnType("INTEGER") + .HasColumnOrder(14); + + b.Property("Bitrate") + .HasColumnType("INTEGER") + .HasColumnOrder(16); + + b.Property("Channels") + .HasColumnType("INTEGER") + .HasColumnOrder(13); + + b.Property("Container") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(31); + + b.Property("DiscNumber") + .HasColumnType("INTEGER") + .HasColumnOrder(10); + + b.Property("DurationInSeconds") + .HasColumnType("INTEGER") + .HasColumnOrder(11); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("LibraryScanId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.PrimitiveCollection("Moods") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(30); + + b.Property("MusicBrainzArtistId") + .HasColumnType("TEXT") + .HasColumnOrder(17); + + b.Property("MusicBrainzRecordingId") + .HasColumnType("TEXT") + .HasColumnOrder(21); + + b.Property("MusicBrainzReleaseArtistId") + .HasColumnType("TEXT") + .HasColumnOrder(18); + + b.Property("MusicBrainzReleaseGroupId") + .HasColumnType("TEXT") + .HasColumnOrder(19); + + b.Property("MusicBrainzReleaseId") + .HasColumnType("TEXT") + .HasColumnOrder(20); + + b.Property("MusicBrainzTrackId") + .HasColumnType("TEXT") + .HasColumnOrder(22); + + b.Property("MusicBrainzWorkId") + .HasColumnType("TEXT") + .HasColumnOrder(23); + + b.Property("Path") + .IsRequired() + .HasMaxLength(2048) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("ReleaseName") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("ReleaseType") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("ReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(6); + + b.Property("ReplayGainAlbumGain") + .HasColumnType("decimal(8,2)") + .HasColumnOrder(28); + + b.Property("ReplayGainAlbumPeak") + .HasColumnType("decimal(8,6)") + .HasColumnOrder(29); + + b.Property("ReplayGainTrackGain") + .HasColumnType("decimal(8,2)") + .HasColumnOrder(26); + + b.Property("ReplayGainTrackPeak") + .HasColumnType("decimal(8,6)") + .HasColumnOrder(27); + + b.Property("SampleRate") + .HasColumnType("INTEGER") + .HasColumnOrder(12); + + b.Property("TrackNumber") + .HasColumnType("INTEGER") + .HasColumnOrder(9); + + b.Property("TrackTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("WorkTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(24); + + b.HasKey("Id"); + + b.HasIndex("LibraryScanId", "Path") + .IsUnique(); + + b.ToTable("MusicLibraryScanItemMetadata", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.MusicPlayRecordEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("AlbumId") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("ArtistId") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("EndedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("LastPositionMilliseconds") + .HasColumnType("INTEGER") + .HasColumnOrder(7); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("ListenedDurationMilliseconds") + .HasColumnType("INTEGER") + .HasColumnOrder(8); + + b.Property("Status") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("TrackId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("UserId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("Version") + .IsConcurrencyToken() + .HasColumnType("INTEGER") + .HasColumnOrder(10); + + b.HasKey("Id"); + + b.HasIndex("TrackId"); + + b.HasIndex("UserId", "CreatedOnUtc"); + + b.ToTable("MusicPlayRecords", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackContributorEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("MediaContributorId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("Role") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("TrackId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.HasKey("Id"); + + b.HasIndex("MediaContributorId"); + + b.HasIndex("TrackId", "MediaContributorId", "Role") + .IsUnique(); + + b.ToTable("TrackContributors", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("AcoustId") + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnOrder(44); + + b.Property("AlbumId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("AudioCodec") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(24); + + b.Property("BitDepth") + .HasColumnType("INTEGER") + .HasColumnOrder(23); + + b.Property("Bitrate") + .HasColumnType("INTEGER") + .HasColumnOrder(25); + + b.Property("Bpm") + .HasColumnType("INTEGER") + .HasColumnOrder(30); + + b.Property("Channels") + .HasColumnType("INTEGER") + .HasColumnOrder(22); + + b.Property("Container") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(49); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(38); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(37); + + b.Property("Description") + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("Disambiguation") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("DiscNumber") + .HasColumnType("INTEGER") + .HasColumnOrder(27); + + b.Property("DurationInSeconds") + .HasColumnType("INTEGER") + .HasColumnOrder(20); + + b.Property("IsVideo") + .HasColumnType("INTEGER") + .HasColumnOrder(31); + + b.Property("Key") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(29); + + b.Property("LanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("LanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(15); + + b.Property("LanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(16); + + b.Property("LastMetadataUpdateUtc") + .HasColumnType("TEXT") + .HasColumnOrder(42); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("MetadataProvider") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(43); + + b.Property("MetadataStatus") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasDefaultValue("Pending") + .HasColumnOrder(41); + + b.Property("MusicBrainzRecordingId") + .HasColumnType("TEXT") + .HasColumnOrder(34); + + b.Property("MusicBrainzTrackId") + .HasColumnType("TEXT") + .HasColumnOrder(35); + + b.Property("MusicBrainzWorkId") + .HasColumnType("TEXT") + .HasColumnOrder(36); + + b.Property("OriginalLanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(17); + + b.Property("OriginalLanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(18); + + b.Property("OriginalLanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(19); + + b.Property("OriginalReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("OriginalReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(9); + + b.Property("OriginalTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("Path") + .IsRequired() + .HasMaxLength(2048) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("ReReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("ReReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(11); + + b.Property("ReleaseCountry") + .HasMaxLength(2) + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("ReleaseVersion") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("ReplayGainAlbumGain") + .HasColumnType("decimal(8,2)") + .HasColumnOrder(47); + + b.Property("ReplayGainAlbumPeak") + .HasColumnType("decimal(8,6)") + .HasColumnOrder(48); + + b.Property("ReplayGainTrackGain") + .HasColumnType("decimal(8,2)") + .HasColumnOrder(45); + + b.Property("ReplayGainTrackPeak") + .HasColumnType("decimal(8,6)") + .HasColumnOrder(46); + + b.Property("SampleRate") + .HasColumnType("INTEGER") + .HasColumnOrder(21); + + b.Property("Script") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(28); + + b.Property("Title") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("TrackNumber") + .HasColumnType("INTEGER") + .HasColumnOrder(26); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(40); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(39); + + b.Property("WorkTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(32); + + b.Property("WorkType") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(33); + + b.HasKey("Id"); + + b.HasIndex("AlbumId", "TrackNumber"); + + b.HasIndex("LibraryId", "Path") + .IsUnique(); + + b.ToTable("Tracks", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.DirectoryScanFingerprintEntity", b => + { + b.Property("LibraryId") + .HasColumnType("TEXT"); + + b.Property("Path") + .HasMaxLength(1024) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("LastWriteTimeUtc") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.HasKey("LibraryId", "Path"); + + b.HasIndex("LibraryId"); + + b.ToTable("DirectoryScanFingerprints", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("ArtworkProvidersConfigurationFingerprint") + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("CanDownloadMetadataFromWeb") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(true) + .HasColumnOrder(6); + + b.Property("CompletionThresholdPercentage") + .HasColumnType("INTEGER") + .HasColumnOrder(17); + + b.Property("CoverImage") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("IsEnabled") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(true) + .HasColumnOrder(4); + + b.Property("IsLocked") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("LibraryType") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("MetadataProvidersConfigurationFingerprint") + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("PathTemplateFingerprint") + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("ShouldSaveMetadataInMediaDirectories") + .HasColumnType("INTEGER") + .HasColumnOrder(7); + + b.Property("ShouldSkipUnchangedDirectoriesDuringScan") + .HasColumnType("INTEGER") + .HasColumnOrder(8); + + b.Property("ShouldTrackConsumptionProgress") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(false) + .HasColumnOrder(16); + + b.Property("Title") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(15); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("UserId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("Libraries", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("LibraryId") + .HasColumnType("TEXT"); + + b.Property("Status") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UserId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.HasIndex("LibraryId", "Status", "CreatedOnUtc") + .IsDescending(true, false, true); + + b.ToTable("LibraryScans", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanResultEntity", b => + { + b.Property("LibraryScanId") + .HasColumnType("TEXT"); + + b.Property("Path") + .HasMaxLength(1024) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("ContentHash") + .HasMaxLength(24) + .HasColumnType("INTEGER") + .HasColumnOrder(2); + + b.Property("FileSize") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Status") + .IsRequired() + .HasMaxLength(10) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("Ticks") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.HasKey("LibraryScanId", "Path"); + + b.HasIndex("Path"); + + b.HasIndex("ContentHash", "FileSize", "Path"); + + b.ToTable("LibraryScanResults", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanSnapshotEntity", b => + { + b.Property("LibraryId") + .HasColumnType("TEXT"); + + b.Property("Path") + .HasMaxLength(1024) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("ContentHash") + .HasColumnType("INTEGER") + .HasColumnOrder(2); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("FileSize") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Ticks") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.HasKey("LibraryId", "Path"); + + b.HasIndex("LibraryId"); + + b.ToTable("LibraryScanSnapshots", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanStagingResultsEntity", b => + { + b.Property("LibraryScanId") + .HasColumnType("TEXT"); + + b.Property("Path") + .HasMaxLength(1024) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("ContentHash") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("IsNew") + .HasColumnType("INTEGER") + .HasColumnOrder(7); + + b.Property("NeedsRehash") + .HasColumnType("INTEGER") + .HasColumnOrder(6); + + b.Property("PreviousContentHash") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("Size") + .HasColumnType("INTEGER") + .HasColumnOrder(2); + + b.Property("Ticks") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.HasKey("LibraryScanId", "Path"); + + b.HasIndex("LibraryScanId", "NeedsRehash"); + + b.ToTable("LibraryScanStagingResults", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookArtworkEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("ArtworkType") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("BookId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("ContentHash") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("FileName") + .HasMaxLength(2048) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("LastUpdateUtc") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("Ordinal") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("Provider") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("Status") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.HasKey("Id"); + + b.HasIndex("Status"); + + b.HasIndex("BookId", "ArtworkType", "Ordinal") + .IsUnique(); + + b.ToTable("BookArtwork", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookContributorEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("BookId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("MediaContributorId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("Role") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.HasKey("Id"); + + b.HasIndex("MediaContributorId"); + + b.HasIndex("BookId", "MediaContributorId", "Role") + .IsUnique(); + + b.ToTable("BookContributors", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("ASIN") + .HasMaxLength(10) + .HasColumnType("TEXT") + .HasColumnOrder(21); + + b.Property("AppleBooksId") + .HasColumnType("TEXT") + .HasColumnOrder(29); + + b.Property("BarnesAndNobleId") + .HasMaxLength(10) + .HasColumnType("TEXT") + .HasColumnOrder(28); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(33); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(32); + + b.Property("Description") + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("Edition") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(19); + + b.Property("Format") + .HasColumnType("TEXT") + .HasColumnOrder(18); + + b.Property("GoodreadsId") + .HasColumnType("TEXT") + .HasColumnOrder(22); + + b.Property("GoogleBooksId") + .HasMaxLength(12) + .HasColumnType("TEXT") + .HasColumnOrder(27); + + b.Property("LCCN") + .HasColumnType("TEXT") + .HasColumnOrder(23); + + b.Property("LanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("LanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("LanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("LastMetadataUpdateUtc") + .HasColumnType("TEXT") + .HasColumnOrder(39); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(36); + + b.Property("LibraryThingId") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(26); + + b.Property("MetadataProvider") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(40); + + b.Property("MetadataStatus") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(38); + + b.Property("OCLCNumber") + .HasColumnType("TEXT") + .HasColumnOrder(24); + + b.Property("OpenLibraryId") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(25); + + b.Property("OriginalLanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("OriginalLanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("OriginalLanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(15); + + b.Property("OriginalReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("OriginalReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("OriginalTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("PageCount") + .HasColumnType("INTEGER") + .HasColumnOrder(17); + + b.Property("Path") + .IsRequired() + .HasMaxLength(2048) + .HasColumnType("TEXT") + .HasColumnOrder(37); + + b.Property("Publisher") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(16); + + b.Property("ReReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("ReReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(7); + + b.Property("ReleaseCountry") + .HasMaxLength(2) + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("ReleaseVersion") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("Title") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(35); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(34); + + b.Property("VolumeNumber") + .HasColumnType("REAL") + .HasColumnOrder(20); + + b.HasKey("Id"); + + b.HasIndex("LibraryId", "MetadataStatus"); + + b.HasIndex("LibraryId", "Path") + .IsUnique(); + + b.ToTable("Books", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Playlists.PlaylistEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("Description") + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("EntryCount") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(0) + .HasColumnOrder(10); + + b.Property("Name") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("Type") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UserId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("Version") + .IsConcurrencyToken() + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(0L) + .HasColumnOrder(9); + + b.HasKey("Id"); + + b.HasIndex("UserId", "UpdatedOnUtc"); + + b.ToTable("Playlists", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Playlists.PlaylistEntryEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("MediaItemId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("MediaItemType") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("PlaylistId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("Position") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.HasKey("Id"); + + b.HasIndex("MediaItemId"); + + b.HasIndex("PlaylistId", "Position") + .IsUnique(); + + b.ToTable("PlaylistEntries", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Plugins.LibraryArtworkProviderConfigurationEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("IsEnabled") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("PluginId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("Rank") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.HasKey("Id"); + + b.HasIndex("LibraryId", "PluginId"); + + b.ToTable("LibraryArtworkProviderConfigurations", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Plugins.LibraryBookReaderConfigurationEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("IsEnabled") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("PluginId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.HasKey("Id"); + + b.HasIndex("LibraryId", "PluginId") + .IsUnique(); + + b.ToTable("LibraryBookReaderConfigurations", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Plugins.LibraryMetadataProviderConfigurationEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("IsEnabled") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("PluginId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("Rank") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.HasKey("Id"); + + b.HasIndex("LibraryId", "PluginId"); + + b.ToTable("LibraryMetadataProviderConfigurations", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Plugins.PluginEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Author") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("Description") + .IsRequired() + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("LoadError") + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("LoadStatus") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("Name") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("SettingsJson") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("Version") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.HasKey("Id"); + + b.ToTable("Plugins", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Scheduling.ScheduledJobEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("Hour") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("IntervalMinutes") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("LastCompletedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("LastStartedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("Minute") + .HasColumnType("INTEGER") + .HasColumnOrder(6); + + b.Property("Name") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("OwnerUserId") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("ScheduleType") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("Status") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("TaskType") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.HasKey("Id"); + + b.HasIndex("Status"); + + b.ToTable("ScheduledJobs", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Scheduling.ScheduledJobExecutionEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CompletedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("IsCycleRun") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("ScheduledJobId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("StartedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("TaskType") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("WasCycleActive") + .HasColumnType("INTEGER") + .HasColumnOrder(6); + + b.HasKey("Id"); + + b.HasIndex("ScheduledJobId"); + + b.HasIndex("StartedOnUtc", "ScheduledJobId"); + + b.ToTable("ScheduledJobExecutions", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Scheduling.SchedulerDisplayPreferencesEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("DisplayTimeSpan") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("DisplayTimeUnit") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("JobTypeFilter") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UserId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.HasKey("Id"); + + b.HasIndex("UserId") + .IsUnique(); + + b.ToTable("SchedulerDisplayPreferences", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Themes.ThemeEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Author") + .IsRequired() + .HasMaxLength(80) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("Description") + .IsRequired() + .HasMaxLength(300) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("InstallSource") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("InstalledAtUtc") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("IsCurrent") + .HasColumnType("INTEGER") + .HasColumnOrder(8); + + b.Property("IsDeleted") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(false) + .HasColumnOrder(9); + + b.Property("Name") + .IsRequired() + .HasMaxLength(80) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("PreviewPath") + .HasMaxLength(240) + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("ThemeId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("Version") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.HasKey("Id"); + + b.HasIndex("IsCurrent") + .IsUnique() + .HasFilter("IsCurrent = 1"); + + b.HasIndex("ThemeId") + .IsUnique(); + + b.ToTable("Themes", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("Password") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("TempPassword") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("TempPasswordCreated") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("TotpSecret") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("Username") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.HasKey("Id"); + + b.HasIndex("Username") + .IsUnique(); + + b.ToTable("Users", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserSettingsEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("IsGaplessPlaybackEnabled") + .HasColumnType("INTEGER") + .HasColumnOrder(16); + + b.Property("IsMuted") + .HasColumnType("INTEGER") + .HasColumnOrder(29); + + b.Property("IsPaginationEnabled") + .HasColumnType("INTEGER") + .HasColumnOrder(2); + + b.Property("IsThemeCachingEnabled") + .HasColumnType("INTEGER") + .HasColumnOrder(9); + + b.Property("ItemsPerPage") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("ReplayGainMode") + .HasColumnType("INTEGER") + .HasColumnOrder(17); + + b.Property("ShouldAggregateArtworkWhenMissing") + .HasColumnType("INTEGER") + .HasColumnOrder(13); + + b.Property("ShouldAggregateMetadataWhenMissing") + .HasColumnType("INTEGER") + .HasColumnOrder(10); + + b.Property("ShouldAutoplay") + .HasColumnType("INTEGER") + .HasColumnOrder(15); + + b.Property("ShouldIgnoreThePrefixForAlphaPicker") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("ShouldKeepDownloadingWhilePaused") + .HasColumnType("INTEGER") + .HasColumnOrder(14); + + b.Property("ShouldPreserveBookStyles") + .HasColumnType("INTEGER") + .HasColumnOrder(12); + + b.Property("ShouldRenderPdfAsImages") + .HasColumnType("INTEGER") + .HasColumnOrder(11); + + b.Property("StreamingQuality") + .HasColumnType("INTEGER") + .HasColumnOrder(18); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UserId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("Volume") + .HasColumnType("REAL") + .HasColumnOrder(28); + + b.Property("VuMeterHighThreshold") + .HasColumnType("REAL") + .HasColumnOrder(23); + + b.Property("VuMeterMediumThreshold") + .HasColumnType("REAL") + .HasColumnOrder(22); + + b.Property("VuMeterOrientation") + .HasColumnType("INTEGER") + .HasColumnOrder(19); + + b.Property("VuMeterPeakHoldDurationInMilliseconds") + .HasColumnType("INTEGER") + .HasColumnOrder(25); + + b.Property("VuMeterPeakReleasePerSecond") + .HasColumnType("REAL") + .HasColumnOrder(27); + + b.Property("VuMeterReleasePerSecond") + .HasColumnType("REAL") + .HasColumnOrder(26); + + b.Property("VuMeterSegmentCount") + .HasColumnType("INTEGER") + .HasColumnOrder(20); + + b.Property("VuMeterSegmentGap") + .HasColumnType("INTEGER") + .HasColumnOrder(21); + + b.Property("VuMeterShowPeak") + .HasColumnType("INTEGER") + .HasColumnOrder(24); + + b.HasKey("Id"); + + b.HasIndex("UserId") + .IsUnique(); + + b.ToTable("UserSettings", (string)null); + }); + + modelBuilder.Entity("TrackGenres", b => + { + b.Property("TrackId") + .HasColumnType("TEXT"); + + b.Property("GenreId") + .HasColumnType("TEXT"); + + b.HasKey("TrackId", "GenreId"); + + b.HasIndex("GenreId"); + + b.ToTable("TrackGenres", (string)null); + }); + + modelBuilder.Entity("TrackTags", b => + { + b.Property("TrackId") + .HasColumnType("TEXT"); + + b.Property("TagId") + .HasColumnType("TEXT"); + + b.HasKey("TrackId", "TagId"); + + b.HasIndex("TagId"); + + b.ToTable("TrackTags", (string)null); + }); + + modelBuilder.Entity("AlbumGenres", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumEntity", null) + .WithMany() + .HasForeignKey("AlbumId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.GenreEntity", null) + .WithMany() + .HasForeignKey("GenreId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("AlbumTags", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumEntity", null) + .WithMany() + .HasForeignKey("AlbumId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.TagEntity", null) + .WithMany() + .HasForeignKey("TagId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("ArtistGenres", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistEntity", null) + .WithMany() + .HasForeignKey("ArtistId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.GenreEntity", null) + .WithMany() + .HasForeignKey("GenreId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("ArtistTags", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistEntity", null) + .WithMany() + .HasForeignKey("ArtistId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.TagEntity", null) + .WithMany() + .HasForeignKey("TagId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BookGenres", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", null) + .WithMany() + .HasForeignKey("BookId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.GenreEntity", null) + .WithMany() + .HasForeignKey("GenreId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BookTags", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", null) + .WithMany() + .HasForeignKey("BookId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.TagEntity", null) + .WithMany() + .HasForeignKey("TagId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.RolePermissionEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Authorization.PermissionEntity", "Permission") + .WithMany("RolePermissions") + .HasForeignKey("PermissionId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Authorization.RoleEntity", "Role") + .WithMany("RolePermissions") + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Permission"); + + b.Navigation("Role"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.UserPermissionEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Authorization.PermissionEntity", "Permission") + .WithMany("UserPermissions") + .HasForeignKey("PermissionId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", "User") + .WithMany("UserPermissions") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Permission"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.UserRoleEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Authorization.RoleEntity", "Role") + .WithMany("UserRoles") + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", "User") + .WithOne("UserRole") + .HasForeignKey("Lumina.Application.Common.DataAccess.Entities.Authorization.UserRoleEntity", "UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Role"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.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.MediaConsumption.MediaConsumptionRecordEntity", 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.MediaConsumption.MediaResumePointEntity", 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) + .WithMany("Contributors") + .HasForeignKey("AlbumId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistEntity", "Artist") + .WithMany("Albums") + .HasForeignKey("ArtistId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumCatalogNumberEntity", "CatalogNumbers", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("AlbumId") + .HasColumnType("TEXT"); + + b1.Property("CatalogNumber") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("AlbumId"); + + b1.ToTable("AlbumCatalogNumbers", (string)null); + + b1.WithOwner() + .HasForeignKey("AlbumId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AudioRatingEntity", "Ratings", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("AlbumId") + .HasColumnType("TEXT"); + + b1.Property("MaxValue") + .HasColumnType("decimal(3,2)"); + + b1.Property("Source") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.Property("Value") + .HasColumnType("decimal(3,2)"); + + b1.Property("VoteCount") + .HasColumnType("INTEGER"); + + b1.HasKey("Id"); + + b1.HasIndex("AlbumId"); + + b1.ToTable("AlbumRatings", (string)null); + + b1.WithOwner() + .HasForeignKey("AlbumId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumReleaseTypeEntity", "ReleaseTypes", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("AlbumId") + .HasColumnType("TEXT"); + + b1.Property("ReleaseType") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("AlbumId"); + + b1.ToTable("AlbumReleaseTypes", (string)null); + + b1.WithOwner() + .HasForeignKey("AlbumId"); + }); + + b.Navigation("Artist"); + + b.Navigation("CatalogNumbers"); + + b.Navigation("Ratings"); + + b.Navigation("ReleaseTypes"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistContributorEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistEntity", null) + .WithMany("Contributors") + .HasForeignKey("ArtistId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistEntity", b => + { + b.OwnsOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.MusicAreaEntity", "Area", b1 => + { + b1.Property("ArtistEntityId"); + + b1.Property("Disambiguation"); + + b1.Property("Iso3166Code"); + + b1.Property("MusicBrainzAreaId"); + + b1.Property("Name") + .IsRequired(); + + b1.Property("SortName"); + + b1.Property("Type"); + + b1.HasKey("ArtistEntityId"); + + b1.ToTable("Artists"); + + b1 + .ToJson("Area") + .HasColumnType("TEXT"); + + b1.WithOwner() + .HasForeignKey("ArtistEntityId"); + }); + + b.OwnsOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.MusicAreaEntity", "BeginArea", b1 => + { + b1.Property("ArtistEntityId"); + + b1.Property("Disambiguation"); + + b1.Property("Iso3166Code"); + + b1.Property("MusicBrainzAreaId"); + + b1.Property("Name") + .IsRequired(); + + b1.Property("SortName"); + + b1.Property("Type"); + + b1.HasKey("ArtistEntityId"); + + b1.ToTable("Artists"); + + b1 + .ToJson("BeginArea") + .HasColumnType("TEXT"); + + b1.WithOwner() + .HasForeignKey("ArtistEntityId"); + }); + + b.OwnsOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.MusicAreaEntity", "EndArea", b1 => + { + b1.Property("ArtistEntityId"); + + b1.Property("Disambiguation"); + + b1.Property("Iso3166Code"); + + b1.Property("MusicBrainzAreaId"); + + b1.Property("Name") + .IsRequired(); + + b1.Property("SortName"); + + b1.Property("Type"); + + b1.HasKey("ArtistEntityId"); + + b1.ToTable("Artists"); + + b1 + .ToJson("EndArea") + .HasColumnType("TEXT"); + + b1.WithOwner() + .HasForeignKey("ArtistEntityId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistAliasEntity", "Aliases", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("ArtistId") + .HasColumnType("TEXT"); + + b1.Property("BeginDate") + .HasColumnType("TEXT"); + + b1.Property("EndDate") + .HasColumnType("TEXT"); + + b1.Property("IsEnded") + .HasColumnType("INTEGER"); + + b1.Property("IsPrimary") + .HasColumnType("INTEGER"); + + b1.Property("Locale") + .HasMaxLength(20) + .HasColumnType("TEXT"); + + b1.Property("Name") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT"); + + b1.Property("SortName") + .HasMaxLength(255) + .HasColumnType("TEXT"); + + b1.Property("Type") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("ArtistId"); + + b1.ToTable("ArtistAliases", (string)null); + + b1.WithOwner() + .HasForeignKey("ArtistId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AudioRatingEntity", "Ratings", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("ArtistId") + .HasColumnType("TEXT"); + + b1.Property("MaxValue") + .HasColumnType("decimal(3,2)"); + + b1.Property("Source") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.Property("Value") + .HasColumnType("decimal(3,2)"); + + b1.Property("VoteCount") + .HasColumnType("INTEGER"); + + b1.HasKey("Id"); + + b1.HasIndex("ArtistId"); + + b1.ToTable("ArtistRatings", (string)null); + + b1.WithOwner() + .HasForeignKey("ArtistId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistIpiEntity", "Ipis", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("ArtistId") + .HasColumnType("TEXT"); + + b1.Property("Value") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("ArtistId"); + + b1.ToTable("ArtistIpis", (string)null); + + b1.WithOwner() + .HasForeignKey("ArtistId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistIsniEntity", "Isnis", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("ArtistId") + .HasColumnType("TEXT"); + + b1.Property("Value") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("ArtistId"); + + b1.ToTable("ArtistIsnis", (string)null); + + b1.WithOwner() + .HasForeignKey("ArtistId"); + }); + + b.Navigation("Aliases"); + + b.Navigation("Area"); + + b.Navigation("BeginArea"); + + b.Navigation("EndArea"); + + b.Navigation("Ipis"); + + b.Navigation("Isnis"); + + b.Navigation("Ratings"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackContributorEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackEntity", null) + .WithMany("Contributors") + .HasForeignKey("TrackId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumEntity", "Album") + .WithMany("Tracks") + .HasForeignKey("AlbumId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AudioRatingEntity", "Ratings", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("MaxValue") + .HasColumnType("decimal(3,2)"); + + b1.Property("Source") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.Property("TrackId") + .HasColumnType("TEXT"); + + b1.Property("Value") + .HasColumnType("decimal(3,2)"); + + b1.Property("VoteCount") + .HasColumnType("INTEGER"); + + b1.HasKey("Id"); + + b1.HasIndex("TrackId"); + + b1.ToTable("TrackRatings", (string)null); + + b1.WithOwner() + .HasForeignKey("TrackId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackIsrcEntity", "Isrcs", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("TrackId") + .HasColumnType("TEXT"); + + b1.Property("Value") + .IsRequired() + .HasMaxLength(12) + .HasColumnType("TEXT") + .HasColumnName("ISRC"); + + b1.HasKey("Id"); + + b1.HasIndex("TrackId"); + + b1.ToTable("TrackIsrcs", (string)null); + + b1.WithOwner() + .HasForeignKey("TrackId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackMoodEntity", "Moods", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("Name") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.Property("TrackId") + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("TrackId"); + + b1.ToTable("TrackMoods", (string)null); + + b1.WithOwner() + .HasForeignKey("TrackId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackWorkIswcEntity", "WorkIswcs", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("TrackId") + .HasColumnType("TEXT"); + + b1.Property("Value") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("TrackId"); + + b1.ToTable("TrackWorkIswcs", (string)null); + + b1.WithOwner() + .HasForeignKey("TrackId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackWorkLanguageEntity", "WorkLanguages", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("LanguageCode") + .IsRequired() + .HasMaxLength(5) + .HasColumnType("TEXT"); + + b1.Property("LanguageName") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("TEXT"); + + b1.Property("NativeName") + .HasMaxLength(100) + .HasColumnType("TEXT"); + + b1.Property("TrackId") + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("TrackId"); + + b1.ToTable("TrackWorkLanguages", (string)null); + + b1.WithOwner() + .HasForeignKey("TrackId"); + }); + + b.Navigation("Album"); + + b.Navigation("Isrcs"); + + b.Navigation("Moods"); + + b.Navigation("Ratings"); + + b.Navigation("WorkIswcs"); + + b.Navigation("WorkLanguages"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.DirectoryScanFingerprintEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", null) + .WithMany() + .HasForeignKey("LibraryId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", "User") + .WithMany("Libraries") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryContentLocationEntity", "ContentLocations", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("LibraryId") + .HasColumnType("TEXT"); + + b1.Property("Path") + .IsRequired() + .HasMaxLength(260) + .HasColumnType("TEXT") + .HasColumnName("Path"); + + b1.HasKey("Id"); + + b1.HasIndex("LibraryId"); + + b1.ToTable("LibraryContentLocations", (string)null); + + b1.WithOwner() + .HasForeignKey("LibraryId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryPathTemplatePartEntity", "PathTemplateParts", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("IsOptional") + .HasColumnType("INTEGER"); + + b1.Property("Kind") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b1.Property("LibraryId") + .HasColumnType("TEXT"); + + b1.Property("Position") + .HasColumnType("INTEGER") + .HasColumnName("Position"); + + b1.Property("Representation") + .IsRequired() + .HasMaxLength(512) + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("LibraryId", "Position") + .IsUnique(); + + b1.ToTable("LibraryPathTemplateParts", (string)null); + + b1.WithOwner() + .HasForeignKey("LibraryId"); + }); + + b.Navigation("ContentLocations"); + + b.Navigation("PathTemplateParts"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", "Library") + .WithMany("LibraryScans") + .HasForeignKey("LibraryId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", "User") + .WithMany("LibraryScans") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Library"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanResultEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", "LibraryScan") + .WithMany("LibraryScanResults") + .HasForeignKey("LibraryScanId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("LibraryScan"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanSnapshotEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", "Library") + .WithMany() + .HasForeignKey("LibraryId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Library"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanStagingResultsEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", null) + .WithMany() + .HasForeignKey("LibraryScanId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookArtworkEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", null) + .WithMany("Artwork") + .HasForeignKey("BookId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookContributorEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", null) + .WithMany("Contributors") + .HasForeignKey("BookId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", b => + { + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookRatingEntity", "Ratings", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("BookId") + .HasColumnType("TEXT"); + + b1.Property("MaxValue") + .HasColumnType("decimal(3,2)"); + + b1.Property("Source") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.Property("Value") + .HasColumnType("decimal(3,2)"); + + b1.Property("VoteCount") + .HasColumnType("INTEGER"); + + b1.HasKey("Id"); + + b1.HasIndex("BookId"); + + b1.ToTable("BookRatings", (string)null); + + b1.WithOwner() + .HasForeignKey("BookId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.IsbnEntity", "ISBNs", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("BookId") + .HasColumnType("TEXT"); + + b1.Property("Format") + .IsRequired() + .HasMaxLength(6) + .HasColumnType("TEXT"); + + b1.Property("Value") + .IsRequired() + .HasMaxLength(13) + .HasColumnType("TEXT") + .HasColumnName("ISBN"); + + b1.HasKey("Id"); + + b1.HasIndex("BookId"); + + b1.ToTable("BookISBNs", (string)null); + + b1.WithOwner() + .HasForeignKey("BookId"); + }); + + b.Navigation("ISBNs"); + + b.Navigation("Ratings"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Playlists.PlaylistEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Playlists.PlaylistEntryEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Playlists.PlaylistEntity", null) + .WithMany("Entries") + .HasForeignKey("PlaylistId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserSettingsEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", null) + .WithOne() + .HasForeignKey("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserSettingsEntity", "UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("TrackGenres", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.GenreEntity", null) + .WithMany() + .HasForeignKey("GenreId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackEntity", null) + .WithMany() + .HasForeignKey("TrackId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("TrackTags", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.TagEntity", null) + .WithMany() + .HasForeignKey("TagId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackEntity", null) + .WithMany() + .HasForeignKey("TrackId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.PermissionEntity", b => + { + b.Navigation("RolePermissions"); + + b.Navigation("UserPermissions"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.RoleEntity", b => + { + b.Navigation("RolePermissions"); + + b.Navigation("UserRoles"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumEntity", b => + { + b.Navigation("Contributors"); + + b.Navigation("Tracks"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistEntity", b => + { + b.Navigation("Albums"); + + b.Navigation("Contributors"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackEntity", b => + { + b.Navigation("Contributors"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", b => + { + b.Navigation("LibraryScans"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", b => + { + b.Navigation("LibraryScanResults"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", b => + { + b.Navigation("Artwork"); + + b.Navigation("Contributors"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Playlists.PlaylistEntity", b => + { + b.Navigation("Entries"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", b => + { + b.Navigation("Libraries"); + + b.Navigation("LibraryScans"); + + b.Navigation("UserPermissions"); + + b.Navigation("UserRole"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/Lumina.DataAccess/Common/Migrations/20261024161715_AddsMediaConsumptionHistory.cs b/src/Lumina.DataAccess/Common/Migrations/20261024161715_AddsMediaConsumptionHistory.cs new file mode 100644 index 00000000..255f9118 --- /dev/null +++ b/src/Lumina.DataAccess/Common/Migrations/20261024161715_AddsMediaConsumptionHistory.cs @@ -0,0 +1,108 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Lumina.DataAccess.Common.Migrations +{ + /// + public partial class AddsMediaConsumptionHistory : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "MediaConsumptionRecords", + columns: table => new + { + Id = table.Column(type: "TEXT", nullable: false), + UserId = table.Column(type: "TEXT", nullable: false), + LibraryId = table.Column(type: "TEXT", nullable: false), + MediaItemId = table.Column(type: "TEXT", nullable: false), + MediaKind = table.Column(type: "TEXT", maxLength: 20, nullable: false), + Status = table.Column(type: "TEXT", maxLength: 20, nullable: false), + StartedOnUtc = table.Column(type: "TEXT", nullable: false), + LastActivityOnUtc = table.Column(type: "TEXT", nullable: false), + EndedOnUtc = table.Column(type: "TEXT", nullable: true), + ConsumedDurationMilliseconds = table.Column(type: "INTEGER", nullable: false), + LastPositionKind = table.Column(type: "TEXT", maxLength: 20, nullable: true), + LastPositionTimeOffsetMilliseconds = table.Column(type: "INTEGER", nullable: true), + LastPositionLocation = table.Column(type: "TEXT", maxLength: 4096, nullable: true), + LastProgressFraction = table.Column(type: "REAL", nullable: false), + ConsecutivePagesRead = table.Column(type: "INTEGER", nullable: false, defaultValue: 0), + Version = table.Column(type: "INTEGER", nullable: false), + CreatedOnUtc = table.Column(type: "TEXT", nullable: false), + CreatedBy = table.Column(type: "TEXT", nullable: false), + UpdatedOnUtc = table.Column(type: "TEXT", nullable: true), + UpdatedBy = table.Column(type: "TEXT", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_MediaConsumptionRecords", x => x.Id); + table.ForeignKey( + name: "FK_MediaConsumptionRecords_Users_UserId", + column: x => x.UserId, + principalTable: "Users", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateTable( + name: "MediaResumePoints", + columns: table => new + { + Id = table.Column(type: "TEXT", nullable: false), + UserId = table.Column(type: "TEXT", nullable: false), + LibraryId = table.Column(type: "TEXT", nullable: false), + MediaKind = table.Column(type: "TEXT", maxLength: 20, nullable: false), + MediaItemId = table.Column(type: "TEXT", nullable: false), + LastPositionKind = table.Column(type: "TEXT", maxLength: 20, nullable: false), + LastPositionTimeOffsetMilliseconds = table.Column(type: "INTEGER", nullable: true), + LastPositionLocation = table.Column(type: "TEXT", maxLength: 4096, nullable: true), + LastProgressFraction = table.Column(type: "REAL", nullable: false), + LastConsumedOnUtc = table.Column(type: "TEXT", nullable: false), + Version = table.Column(type: "INTEGER", nullable: false), + CreatedOnUtc = table.Column(type: "TEXT", nullable: false), + CreatedBy = table.Column(type: "TEXT", nullable: false), + UpdatedOnUtc = table.Column(type: "TEXT", nullable: true), + UpdatedBy = table.Column(type: "TEXT", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_MediaResumePoints", x => x.Id); + table.ForeignKey( + name: "FK_MediaResumePoints_Users_UserId", + column: x => x.UserId, + principalTable: "Users", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateIndex( + name: "IX_MediaConsumptionRecords_UserId_MediaKind_MediaItemId_LastActivityOnUtc", + table: "MediaConsumptionRecords", + columns: new[] { "UserId", "MediaKind", "MediaItemId", "LastActivityOnUtc" }); + + migrationBuilder.CreateIndex( + name: "IX_MediaConsumptionRecords_UserId_MediaKind_StartedOnUtc", + table: "MediaConsumptionRecords", + columns: new[] { "UserId", "MediaKind", "StartedOnUtc" }); + + migrationBuilder.CreateIndex( + name: "IX_MediaResumePoints_UserId_MediaKind_MediaItemId", + table: "MediaResumePoints", + columns: new[] { "UserId", "MediaKind", "MediaItemId" }, + unique: true); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "MediaConsumptionRecords"); + + migrationBuilder.DropTable( + name: "MediaResumePoints"); + } + } +} diff --git a/src/Lumina.DataAccess/Common/Migrations/20261026153835_DropsMusicPlayRecords.Designer.cs b/src/Lumina.DataAccess/Common/Migrations/20261026153835_DropsMusicPlayRecords.Designer.cs new file mode 100644 index 00000000..ef818694 --- /dev/null +++ b/src/Lumina.DataAccess/Common/Migrations/20261026153835_DropsMusicPlayRecords.Designer.cs @@ -0,0 +1,3896 @@ +// +using System; +using Lumina.DataAccess.Core.UoW; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace Lumina.DataAccess.Common.Migrations +{ + [DbContext(typeof(LuminaDbContext))] + [Migration("20261026153835_DropsMusicPlayRecords")] + partial class DropsMusicPlayRecords + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder.HasAnnotation("ProductVersion", "10.0.11"); + + modelBuilder.Entity("AlbumGenres", b => + { + b.Property("AlbumId") + .HasColumnType("TEXT"); + + b.Property("GenreId") + .HasColumnType("TEXT"); + + b.HasKey("AlbumId", "GenreId"); + + b.HasIndex("GenreId"); + + b.ToTable("AlbumGenres", (string)null); + }); + + modelBuilder.Entity("AlbumTags", b => + { + b.Property("AlbumId") + .HasColumnType("TEXT"); + + b.Property("TagId") + .HasColumnType("TEXT"); + + b.HasKey("AlbumId", "TagId"); + + b.HasIndex("TagId"); + + b.ToTable("AlbumTags", (string)null); + }); + + modelBuilder.Entity("ArtistGenres", b => + { + b.Property("ArtistId") + .HasColumnType("TEXT"); + + b.Property("GenreId") + .HasColumnType("TEXT"); + + b.HasKey("ArtistId", "GenreId"); + + b.HasIndex("GenreId"); + + b.ToTable("ArtistGenres", (string)null); + }); + + modelBuilder.Entity("ArtistTags", b => + { + b.Property("ArtistId") + .HasColumnType("TEXT"); + + b.Property("TagId") + .HasColumnType("TEXT"); + + b.HasKey("ArtistId", "TagId"); + + b.HasIndex("TagId"); + + b.ToTable("ArtistTags", (string)null); + }); + + modelBuilder.Entity("BookGenres", b => + { + b.Property("BookId") + .HasColumnType("TEXT"); + + b.Property("GenreId") + .HasColumnType("TEXT"); + + b.HasKey("BookId", "GenreId"); + + b.HasIndex("GenreId"); + + b.ToTable("BookGenres", (string)null); + }); + + modelBuilder.Entity("BookTags", b => + { + b.Property("BookId") + .HasColumnType("TEXT"); + + b.Property("TagId") + .HasColumnType("TEXT"); + + b.HasKey("BookId", "TagId"); + + b.HasIndex("TagId"); + + b.ToTable("BookTags", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.PermissionEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("PermissionName") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.HasKey("Id"); + + b.ToTable("Permissions", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.RoleEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("RoleName") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.HasKey("Id"); + + b.ToTable("Roles", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.RolePermissionEntity", b => + { + b.Property("RoleId") + .HasColumnType("TEXT"); + + b.Property("PermissionId") + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.HasKey("RoleId", "PermissionId"); + + b.HasIndex("PermissionId"); + + b.HasIndex("RoleId", "PermissionId") + .IsUnique(); + + b.ToTable("RolePermissions", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.UserPermissionEntity", b => + { + b.Property("UserId") + .HasColumnType("TEXT"); + + b.Property("PermissionId") + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.HasKey("UserId", "PermissionId"); + + b.HasIndex("PermissionId"); + + b.HasIndex("UserId", "PermissionId") + .IsUnique(); + + b.ToTable("UserPermissions", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.UserRoleEntity", b => + { + b.Property("UserId") + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("RoleId") + .HasColumnType("TEXT"); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.HasKey("UserId"); + + b.HasIndex("RoleId"); + + b.HasIndex("UserId", "RoleId") + .IsUnique(); + + b.ToTable("UserRoles", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Common.GenreEntity", b => + { + b.Property("Name") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b.HasKey("Name"); + + b.ToTable("Genres", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Common.TagEntity", b => + { + b.Property("Name") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b.HasKey("Name"); + + b.ToTable("Tags", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Favorites.FavoriteEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("MediaItemId") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("MediaKind") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("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.MediaConsumption.MediaConsumptionRecordEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("ConsecutivePagesRead") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(0) + .HasColumnOrder(14); + + b.Property("ConsumedDurationMilliseconds") + .HasColumnType("INTEGER") + .HasColumnOrder(9); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(17); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(16); + + b.Property("EndedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("LastActivityOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("LastPositionKind") + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("LastPositionLocation") + .HasMaxLength(4096) + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("LastPositionTimeOffsetMilliseconds") + .HasColumnType("INTEGER") + .HasColumnOrder(11); + + b.Property("LastProgressFraction") + .HasColumnType("REAL") + .HasColumnOrder(13); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("MediaItemId") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("MediaKind") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("StartedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("Status") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(19); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(18); + + b.Property("UserId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("Version") + .IsConcurrencyToken() + .HasColumnType("INTEGER") + .HasColumnOrder(15); + + b.HasKey("Id"); + + b.HasIndex("UserId", "MediaKind", "StartedOnUtc"); + + b.HasIndex("UserId", "MediaKind", "MediaItemId", "LastActivityOnUtc"); + + b.ToTable("MediaConsumptionRecords", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaConsumption.MediaResumePointEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("LastConsumedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("LastPositionKind") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("LastPositionLocation") + .HasMaxLength(4096) + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("LastPositionTimeOffsetMilliseconds") + .HasColumnType("INTEGER") + .HasColumnOrder(6); + + b.Property("LastProgressFraction") + .HasColumnType("REAL") + .HasColumnOrder(8); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("MediaItemId") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("MediaKind") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("UserId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("Version") + .IsConcurrencyToken() + .HasColumnType("INTEGER") + .HasColumnOrder(10); + + b.HasKey("Id"); + + b.HasIndex("UserId", "MediaKind", "MediaItemId") + .IsUnique(); + + b.ToTable("MediaResumePoints", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaContributors.MediaContributorEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Biography") + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("DateOfBirth") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("DateOfDeath") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("DisplayName") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1) + .UseCollation("NOCASE"); + + b.Property("LegalName") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.HasKey("Id"); + + b.HasIndex("DisplayName") + .IsUnique(); + + b.ToTable("MediaContributors", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumContributorEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("AlbumId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("MediaContributorId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("Role") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.HasKey("Id"); + + b.HasIndex("MediaContributorId"); + + b.HasIndex("AlbumId", "MediaContributorId", "Role") + .IsUnique(); + + b.ToTable("AlbumContributors", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("ASIN") + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(28); + + b.Property("ArtistId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("Barcode") + .HasMaxLength(13) + .HasColumnType("TEXT") + .HasColumnOrder(25); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(33); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(32); + + b.Property("Description") + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("Disambiguation") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("Label") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(27); + + b.Property("LanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("LanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("LanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(15); + + b.Property("LastMetadataUpdateUtc") + .HasColumnType("TEXT") + .HasColumnOrder(37); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("MediaFormat") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(23); + + b.Property("MetadataProvider") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(38); + + b.Property("MetadataStatus") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasDefaultValue("Pending") + .HasColumnOrder(36); + + b.Property("MusicBrainzReleaseArtistId") + .HasColumnType("TEXT") + .HasColumnOrder(31); + + b.Property("MusicBrainzReleaseGroupId") + .HasColumnType("TEXT") + .HasColumnOrder(30); + + b.Property("MusicBrainzReleaseId") + .HasColumnType("TEXT") + .HasColumnOrder(29); + + b.Property("OriginalLanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(16); + + b.Property("OriginalLanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(17); + + b.Property("OriginalLanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(18); + + b.Property("OriginalReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("OriginalReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(8); + + b.Property("OriginalTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("Packaging") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(24); + + b.Property("ReReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("ReReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(10); + + b.Property("ReleaseCountry") + .HasMaxLength(2) + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("ReleaseStatus") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(20); + + b.Property("ReleaseTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(26); + + b.Property("ReleaseVersion") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("Script") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(19); + + b.Property("Title") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("TotalDiscs") + .HasColumnType("INTEGER") + .HasColumnOrder(21); + + b.Property("TotalTracks") + .HasColumnType("INTEGER") + .HasColumnOrder(22); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(35); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(34); + + b.HasKey("Id"); + + b.HasIndex("ArtistId", "Title"); + + b.HasIndex("LibraryId", "Title"); + + b.ToTable("Albums", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistContributorEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("ArtistId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("MediaContributorId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("Role") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.HasKey("Id"); + + b.HasIndex("MediaContributorId"); + + b.HasIndex("ArtistId", "MediaContributorId", "Role") + .IsUnique(); + + b.ToTable("ArtistContributors", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Country") + .HasMaxLength(2) + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("Disambiguation") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("Gender") + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("IsEnded") + .HasColumnType("INTEGER") + .HasColumnOrder(10); + + b.Property("LastMetadataUpdateUtc") + .HasColumnType("TEXT") + .HasColumnOrder(18); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("LifeSpanBegin") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("LifeSpanEnd") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("MetadataProvider") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(19); + + b.Property("MetadataStatus") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasDefaultValue("Pending") + .HasColumnOrder(17); + + b.Property("MusicBrainzArtistId") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("Name") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("SortName") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("Type") + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(16); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(15); + + b.Property("Website") + .HasMaxLength(2048) + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.HasKey("Id"); + + b.HasIndex("LibraryId", "Name") + .IsUnique(); + + b.ToTable("Artists", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.MusicArtworkEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("ArtworkType") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("ContentHash") + .HasColumnType("INTEGER") + .HasColumnOrder(6); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("FileName") + .HasMaxLength(2048) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("LastUpdateUtc") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("Ordinal") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("OwnerId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("OwnerType") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("Provider") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("Status") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.HasKey("Id"); + + b.HasIndex("Status"); + + b.HasIndex("OwnerType", "OwnerId", "ArtworkType", "Ordinal") + .IsUnique(); + + b.ToTable("MusicArtwork", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.MusicLibraryScanItemMetadataEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("AcoustId") + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnOrder(25); + + b.Property("ArtistName") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("AudioCodec") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(15); + + b.Property("BitDepth") + .HasColumnType("INTEGER") + .HasColumnOrder(14); + + b.Property("Bitrate") + .HasColumnType("INTEGER") + .HasColumnOrder(16); + + b.Property("Channels") + .HasColumnType("INTEGER") + .HasColumnOrder(13); + + b.Property("Container") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(31); + + b.Property("DiscNumber") + .HasColumnType("INTEGER") + .HasColumnOrder(10); + + b.Property("DurationInSeconds") + .HasColumnType("INTEGER") + .HasColumnOrder(11); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("LibraryScanId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.PrimitiveCollection("Moods") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(30); + + b.Property("MusicBrainzArtistId") + .HasColumnType("TEXT") + .HasColumnOrder(17); + + b.Property("MusicBrainzRecordingId") + .HasColumnType("TEXT") + .HasColumnOrder(21); + + b.Property("MusicBrainzReleaseArtistId") + .HasColumnType("TEXT") + .HasColumnOrder(18); + + b.Property("MusicBrainzReleaseGroupId") + .HasColumnType("TEXT") + .HasColumnOrder(19); + + b.Property("MusicBrainzReleaseId") + .HasColumnType("TEXT") + .HasColumnOrder(20); + + b.Property("MusicBrainzTrackId") + .HasColumnType("TEXT") + .HasColumnOrder(22); + + b.Property("MusicBrainzWorkId") + .HasColumnType("TEXT") + .HasColumnOrder(23); + + b.Property("Path") + .IsRequired() + .HasMaxLength(2048) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("ReleaseName") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("ReleaseType") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("ReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(6); + + b.Property("ReplayGainAlbumGain") + .HasColumnType("decimal(8,2)") + .HasColumnOrder(28); + + b.Property("ReplayGainAlbumPeak") + .HasColumnType("decimal(8,6)") + .HasColumnOrder(29); + + b.Property("ReplayGainTrackGain") + .HasColumnType("decimal(8,2)") + .HasColumnOrder(26); + + b.Property("ReplayGainTrackPeak") + .HasColumnType("decimal(8,6)") + .HasColumnOrder(27); + + b.Property("SampleRate") + .HasColumnType("INTEGER") + .HasColumnOrder(12); + + b.Property("TrackNumber") + .HasColumnType("INTEGER") + .HasColumnOrder(9); + + b.Property("TrackTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("WorkTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(24); + + b.HasKey("Id"); + + b.HasIndex("LibraryScanId", "Path") + .IsUnique(); + + b.ToTable("MusicLibraryScanItemMetadata", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackContributorEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("MediaContributorId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("Role") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("TrackId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.HasKey("Id"); + + b.HasIndex("MediaContributorId"); + + b.HasIndex("TrackId", "MediaContributorId", "Role") + .IsUnique(); + + b.ToTable("TrackContributors", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("AcoustId") + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnOrder(44); + + b.Property("AlbumId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("AudioCodec") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(24); + + b.Property("BitDepth") + .HasColumnType("INTEGER") + .HasColumnOrder(23); + + b.Property("Bitrate") + .HasColumnType("INTEGER") + .HasColumnOrder(25); + + b.Property("Bpm") + .HasColumnType("INTEGER") + .HasColumnOrder(30); + + b.Property("Channels") + .HasColumnType("INTEGER") + .HasColumnOrder(22); + + b.Property("Container") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(49); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(38); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(37); + + b.Property("Description") + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("Disambiguation") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("DiscNumber") + .HasColumnType("INTEGER") + .HasColumnOrder(27); + + b.Property("DurationInSeconds") + .HasColumnType("INTEGER") + .HasColumnOrder(20); + + b.Property("IsVideo") + .HasColumnType("INTEGER") + .HasColumnOrder(31); + + b.Property("Key") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(29); + + b.Property("LanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("LanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(15); + + b.Property("LanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(16); + + b.Property("LastMetadataUpdateUtc") + .HasColumnType("TEXT") + .HasColumnOrder(42); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("MetadataProvider") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(43); + + b.Property("MetadataStatus") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasDefaultValue("Pending") + .HasColumnOrder(41); + + b.Property("MusicBrainzRecordingId") + .HasColumnType("TEXT") + .HasColumnOrder(34); + + b.Property("MusicBrainzTrackId") + .HasColumnType("TEXT") + .HasColumnOrder(35); + + b.Property("MusicBrainzWorkId") + .HasColumnType("TEXT") + .HasColumnOrder(36); + + b.Property("OriginalLanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(17); + + b.Property("OriginalLanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(18); + + b.Property("OriginalLanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(19); + + b.Property("OriginalReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("OriginalReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(9); + + b.Property("OriginalTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("Path") + .IsRequired() + .HasMaxLength(2048) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("ReReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("ReReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(11); + + b.Property("ReleaseCountry") + .HasMaxLength(2) + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("ReleaseVersion") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("ReplayGainAlbumGain") + .HasColumnType("decimal(8,2)") + .HasColumnOrder(47); + + b.Property("ReplayGainAlbumPeak") + .HasColumnType("decimal(8,6)") + .HasColumnOrder(48); + + b.Property("ReplayGainTrackGain") + .HasColumnType("decimal(8,2)") + .HasColumnOrder(45); + + b.Property("ReplayGainTrackPeak") + .HasColumnType("decimal(8,6)") + .HasColumnOrder(46); + + b.Property("SampleRate") + .HasColumnType("INTEGER") + .HasColumnOrder(21); + + b.Property("Script") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(28); + + b.Property("Title") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("TrackNumber") + .HasColumnType("INTEGER") + .HasColumnOrder(26); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(40); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(39); + + b.Property("WorkTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(32); + + b.Property("WorkType") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(33); + + b.HasKey("Id"); + + b.HasIndex("AlbumId", "TrackNumber"); + + b.HasIndex("LibraryId", "Path") + .IsUnique(); + + b.ToTable("Tracks", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.DirectoryScanFingerprintEntity", b => + { + b.Property("LibraryId") + .HasColumnType("TEXT"); + + b.Property("Path") + .HasMaxLength(1024) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("LastWriteTimeUtc") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.HasKey("LibraryId", "Path"); + + b.HasIndex("LibraryId"); + + b.ToTable("DirectoryScanFingerprints", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("ArtworkProvidersConfigurationFingerprint") + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("CanDownloadMetadataFromWeb") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(true) + .HasColumnOrder(6); + + b.Property("CompletionThresholdPercentage") + .HasColumnType("INTEGER") + .HasColumnOrder(17); + + b.Property("CoverImage") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("IsEnabled") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(true) + .HasColumnOrder(4); + + b.Property("IsLocked") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("LibraryType") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("MetadataProvidersConfigurationFingerprint") + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("PathTemplateFingerprint") + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("ShouldSaveMetadataInMediaDirectories") + .HasColumnType("INTEGER") + .HasColumnOrder(7); + + b.Property("ShouldSkipUnchangedDirectoriesDuringScan") + .HasColumnType("INTEGER") + .HasColumnOrder(8); + + b.Property("ShouldTrackConsumptionProgress") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(false) + .HasColumnOrder(16); + + b.Property("Title") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(15); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("UserId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("Libraries", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("LibraryId") + .HasColumnType("TEXT"); + + b.Property("Status") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UserId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.HasIndex("LibraryId", "Status", "CreatedOnUtc") + .IsDescending(true, false, true); + + b.ToTable("LibraryScans", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanResultEntity", b => + { + b.Property("LibraryScanId") + .HasColumnType("TEXT"); + + b.Property("Path") + .HasMaxLength(1024) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("ContentHash") + .HasMaxLength(24) + .HasColumnType("INTEGER") + .HasColumnOrder(2); + + b.Property("FileSize") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Status") + .IsRequired() + .HasMaxLength(10) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("Ticks") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.HasKey("LibraryScanId", "Path"); + + b.HasIndex("Path"); + + b.HasIndex("ContentHash", "FileSize", "Path"); + + b.ToTable("LibraryScanResults", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanSnapshotEntity", b => + { + b.Property("LibraryId") + .HasColumnType("TEXT"); + + b.Property("Path") + .HasMaxLength(1024) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("ContentHash") + .HasColumnType("INTEGER") + .HasColumnOrder(2); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("FileSize") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Ticks") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.HasKey("LibraryId", "Path"); + + b.HasIndex("LibraryId"); + + b.ToTable("LibraryScanSnapshots", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanStagingResultsEntity", b => + { + b.Property("LibraryScanId") + .HasColumnType("TEXT"); + + b.Property("Path") + .HasMaxLength(1024) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("ContentHash") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("IsNew") + .HasColumnType("INTEGER") + .HasColumnOrder(7); + + b.Property("NeedsRehash") + .HasColumnType("INTEGER") + .HasColumnOrder(6); + + b.Property("PreviousContentHash") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("Size") + .HasColumnType("INTEGER") + .HasColumnOrder(2); + + b.Property("Ticks") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.HasKey("LibraryScanId", "Path"); + + b.HasIndex("LibraryScanId", "NeedsRehash"); + + b.ToTable("LibraryScanStagingResults", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookArtworkEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("ArtworkType") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("BookId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("ContentHash") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("FileName") + .HasMaxLength(2048) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("LastUpdateUtc") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("Ordinal") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("Provider") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("Status") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.HasKey("Id"); + + b.HasIndex("Status"); + + b.HasIndex("BookId", "ArtworkType", "Ordinal") + .IsUnique(); + + b.ToTable("BookArtwork", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookContributorEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("BookId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("MediaContributorId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("Role") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.HasKey("Id"); + + b.HasIndex("MediaContributorId"); + + b.HasIndex("BookId", "MediaContributorId", "Role") + .IsUnique(); + + b.ToTable("BookContributors", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("ASIN") + .HasMaxLength(10) + .HasColumnType("TEXT") + .HasColumnOrder(21); + + b.Property("AppleBooksId") + .HasColumnType("TEXT") + .HasColumnOrder(29); + + b.Property("BarnesAndNobleId") + .HasMaxLength(10) + .HasColumnType("TEXT") + .HasColumnOrder(28); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(33); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(32); + + b.Property("Description") + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("Edition") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(19); + + b.Property("Format") + .HasColumnType("TEXT") + .HasColumnOrder(18); + + b.Property("GoodreadsId") + .HasColumnType("TEXT") + .HasColumnOrder(22); + + b.Property("GoogleBooksId") + .HasMaxLength(12) + .HasColumnType("TEXT") + .HasColumnOrder(27); + + b.Property("LCCN") + .HasColumnType("TEXT") + .HasColumnOrder(23); + + b.Property("LanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("LanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("LanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("LastMetadataUpdateUtc") + .HasColumnType("TEXT") + .HasColumnOrder(39); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(36); + + b.Property("LibraryThingId") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(26); + + b.Property("MetadataProvider") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(40); + + b.Property("MetadataStatus") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(38); + + b.Property("OCLCNumber") + .HasColumnType("TEXT") + .HasColumnOrder(24); + + b.Property("OpenLibraryId") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(25); + + b.Property("OriginalLanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("OriginalLanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("OriginalLanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(15); + + b.Property("OriginalReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("OriginalReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("OriginalTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("PageCount") + .HasColumnType("INTEGER") + .HasColumnOrder(17); + + b.Property("Path") + .IsRequired() + .HasMaxLength(2048) + .HasColumnType("TEXT") + .HasColumnOrder(37); + + b.Property("Publisher") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(16); + + b.Property("ReReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("ReReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(7); + + b.Property("ReleaseCountry") + .HasMaxLength(2) + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("ReleaseVersion") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("Title") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(35); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(34); + + b.Property("VolumeNumber") + .HasColumnType("REAL") + .HasColumnOrder(20); + + b.HasKey("Id"); + + b.HasIndex("LibraryId", "MetadataStatus"); + + b.HasIndex("LibraryId", "Path") + .IsUnique(); + + b.ToTable("Books", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Playlists.PlaylistEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("Description") + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("EntryCount") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(0) + .HasColumnOrder(10); + + b.Property("Name") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("Type") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UserId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("Version") + .IsConcurrencyToken() + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(0L) + .HasColumnOrder(9); + + b.HasKey("Id"); + + b.HasIndex("UserId", "UpdatedOnUtc"); + + b.ToTable("Playlists", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Playlists.PlaylistEntryEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("MediaItemId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("MediaItemType") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("PlaylistId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("Position") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.HasKey("Id"); + + b.HasIndex("MediaItemId"); + + b.HasIndex("PlaylistId", "Position") + .IsUnique(); + + b.ToTable("PlaylistEntries", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Plugins.LibraryArtworkProviderConfigurationEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("IsEnabled") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("PluginId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("Rank") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.HasKey("Id"); + + b.HasIndex("LibraryId", "PluginId"); + + b.ToTable("LibraryArtworkProviderConfigurations", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Plugins.LibraryBookReaderConfigurationEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("IsEnabled") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("PluginId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.HasKey("Id"); + + b.HasIndex("LibraryId", "PluginId") + .IsUnique(); + + b.ToTable("LibraryBookReaderConfigurations", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Plugins.LibraryMetadataProviderConfigurationEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("IsEnabled") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("PluginId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("Rank") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.HasKey("Id"); + + b.HasIndex("LibraryId", "PluginId"); + + b.ToTable("LibraryMetadataProviderConfigurations", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Plugins.PluginEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Author") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("Description") + .IsRequired() + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("LoadError") + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("LoadStatus") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("Name") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("SettingsJson") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("Version") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.HasKey("Id"); + + b.ToTable("Plugins", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Scheduling.ScheduledJobEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("Hour") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("IntervalMinutes") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("LastCompletedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("LastStartedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("Minute") + .HasColumnType("INTEGER") + .HasColumnOrder(6); + + b.Property("Name") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("OwnerUserId") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("ScheduleType") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("Status") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("TaskType") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.HasKey("Id"); + + b.HasIndex("Status"); + + b.ToTable("ScheduledJobs", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Scheduling.ScheduledJobExecutionEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CompletedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("IsCycleRun") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("ScheduledJobId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("StartedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("TaskType") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("WasCycleActive") + .HasColumnType("INTEGER") + .HasColumnOrder(6); + + b.HasKey("Id"); + + b.HasIndex("ScheduledJobId"); + + b.HasIndex("StartedOnUtc", "ScheduledJobId"); + + b.ToTable("ScheduledJobExecutions", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Scheduling.SchedulerDisplayPreferencesEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("DisplayTimeSpan") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("DisplayTimeUnit") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("JobTypeFilter") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UserId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.HasKey("Id"); + + b.HasIndex("UserId") + .IsUnique(); + + b.ToTable("SchedulerDisplayPreferences", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Themes.ThemeEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Author") + .IsRequired() + .HasMaxLength(80) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("Description") + .IsRequired() + .HasMaxLength(300) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("InstallSource") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("InstalledAtUtc") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("IsCurrent") + .HasColumnType("INTEGER") + .HasColumnOrder(8); + + b.Property("IsDeleted") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(false) + .HasColumnOrder(9); + + b.Property("Name") + .IsRequired() + .HasMaxLength(80) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("PreviewPath") + .HasMaxLength(240) + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("ThemeId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("Version") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.HasKey("Id"); + + b.HasIndex("IsCurrent") + .IsUnique() + .HasFilter("IsCurrent = 1"); + + b.HasIndex("ThemeId") + .IsUnique(); + + b.ToTable("Themes", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("Password") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("TempPassword") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("TempPasswordCreated") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("TotpSecret") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("Username") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.HasKey("Id"); + + b.HasIndex("Username") + .IsUnique(); + + b.ToTable("Users", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserSettingsEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("IsGaplessPlaybackEnabled") + .HasColumnType("INTEGER") + .HasColumnOrder(16); + + b.Property("IsMuted") + .HasColumnType("INTEGER") + .HasColumnOrder(29); + + b.Property("IsPaginationEnabled") + .HasColumnType("INTEGER") + .HasColumnOrder(2); + + b.Property("IsThemeCachingEnabled") + .HasColumnType("INTEGER") + .HasColumnOrder(9); + + b.Property("ItemsPerPage") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("ReplayGainMode") + .HasColumnType("INTEGER") + .HasColumnOrder(17); + + b.Property("ShouldAggregateArtworkWhenMissing") + .HasColumnType("INTEGER") + .HasColumnOrder(13); + + b.Property("ShouldAggregateMetadataWhenMissing") + .HasColumnType("INTEGER") + .HasColumnOrder(10); + + b.Property("ShouldAutoplay") + .HasColumnType("INTEGER") + .HasColumnOrder(15); + + b.Property("ShouldIgnoreThePrefixForAlphaPicker") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("ShouldKeepDownloadingWhilePaused") + .HasColumnType("INTEGER") + .HasColumnOrder(14); + + b.Property("ShouldPreserveBookStyles") + .HasColumnType("INTEGER") + .HasColumnOrder(12); + + b.Property("ShouldRenderPdfAsImages") + .HasColumnType("INTEGER") + .HasColumnOrder(11); + + b.Property("StreamingQuality") + .HasColumnType("INTEGER") + .HasColumnOrder(18); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UserId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("Volume") + .HasColumnType("REAL") + .HasColumnOrder(28); + + b.Property("VuMeterHighThreshold") + .HasColumnType("REAL") + .HasColumnOrder(23); + + b.Property("VuMeterMediumThreshold") + .HasColumnType("REAL") + .HasColumnOrder(22); + + b.Property("VuMeterOrientation") + .HasColumnType("INTEGER") + .HasColumnOrder(19); + + b.Property("VuMeterPeakHoldDurationInMilliseconds") + .HasColumnType("INTEGER") + .HasColumnOrder(25); + + b.Property("VuMeterPeakReleasePerSecond") + .HasColumnType("REAL") + .HasColumnOrder(27); + + b.Property("VuMeterReleasePerSecond") + .HasColumnType("REAL") + .HasColumnOrder(26); + + b.Property("VuMeterSegmentCount") + .HasColumnType("INTEGER") + .HasColumnOrder(20); + + b.Property("VuMeterSegmentGap") + .HasColumnType("INTEGER") + .HasColumnOrder(21); + + b.Property("VuMeterShowPeak") + .HasColumnType("INTEGER") + .HasColumnOrder(24); + + b.HasKey("Id"); + + b.HasIndex("UserId") + .IsUnique(); + + b.ToTable("UserSettings", (string)null); + }); + + modelBuilder.Entity("TrackGenres", b => + { + b.Property("TrackId") + .HasColumnType("TEXT"); + + b.Property("GenreId") + .HasColumnType("TEXT"); + + b.HasKey("TrackId", "GenreId"); + + b.HasIndex("GenreId"); + + b.ToTable("TrackGenres", (string)null); + }); + + modelBuilder.Entity("TrackTags", b => + { + b.Property("TrackId") + .HasColumnType("TEXT"); + + b.Property("TagId") + .HasColumnType("TEXT"); + + b.HasKey("TrackId", "TagId"); + + b.HasIndex("TagId"); + + b.ToTable("TrackTags", (string)null); + }); + + modelBuilder.Entity("AlbumGenres", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumEntity", null) + .WithMany() + .HasForeignKey("AlbumId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.GenreEntity", null) + .WithMany() + .HasForeignKey("GenreId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("AlbumTags", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumEntity", null) + .WithMany() + .HasForeignKey("AlbumId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.TagEntity", null) + .WithMany() + .HasForeignKey("TagId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("ArtistGenres", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistEntity", null) + .WithMany() + .HasForeignKey("ArtistId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.GenreEntity", null) + .WithMany() + .HasForeignKey("GenreId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("ArtistTags", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistEntity", null) + .WithMany() + .HasForeignKey("ArtistId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.TagEntity", null) + .WithMany() + .HasForeignKey("TagId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BookGenres", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", null) + .WithMany() + .HasForeignKey("BookId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.GenreEntity", null) + .WithMany() + .HasForeignKey("GenreId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BookTags", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", null) + .WithMany() + .HasForeignKey("BookId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.TagEntity", null) + .WithMany() + .HasForeignKey("TagId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.RolePermissionEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Authorization.PermissionEntity", "Permission") + .WithMany("RolePermissions") + .HasForeignKey("PermissionId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Authorization.RoleEntity", "Role") + .WithMany("RolePermissions") + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Permission"); + + b.Navigation("Role"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.UserPermissionEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Authorization.PermissionEntity", "Permission") + .WithMany("UserPermissions") + .HasForeignKey("PermissionId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", "User") + .WithMany("UserPermissions") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Permission"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.UserRoleEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Authorization.RoleEntity", "Role") + .WithMany("UserRoles") + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", "User") + .WithOne("UserRole") + .HasForeignKey("Lumina.Application.Common.DataAccess.Entities.Authorization.UserRoleEntity", "UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Role"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.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.MediaConsumption.MediaConsumptionRecordEntity", 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.MediaConsumption.MediaResumePointEntity", 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) + .WithMany("Contributors") + .HasForeignKey("AlbumId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistEntity", "Artist") + .WithMany("Albums") + .HasForeignKey("ArtistId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumCatalogNumberEntity", "CatalogNumbers", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("AlbumId") + .HasColumnType("TEXT"); + + b1.Property("CatalogNumber") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("AlbumId"); + + b1.ToTable("AlbumCatalogNumbers", (string)null); + + b1.WithOwner() + .HasForeignKey("AlbumId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AudioRatingEntity", "Ratings", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("AlbumId") + .HasColumnType("TEXT"); + + b1.Property("MaxValue") + .HasColumnType("decimal(3,2)"); + + b1.Property("Source") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.Property("Value") + .HasColumnType("decimal(3,2)"); + + b1.Property("VoteCount") + .HasColumnType("INTEGER"); + + b1.HasKey("Id"); + + b1.HasIndex("AlbumId"); + + b1.ToTable("AlbumRatings", (string)null); + + b1.WithOwner() + .HasForeignKey("AlbumId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumReleaseTypeEntity", "ReleaseTypes", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("AlbumId") + .HasColumnType("TEXT"); + + b1.Property("ReleaseType") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("AlbumId"); + + b1.ToTable("AlbumReleaseTypes", (string)null); + + b1.WithOwner() + .HasForeignKey("AlbumId"); + }); + + b.Navigation("Artist"); + + b.Navigation("CatalogNumbers"); + + b.Navigation("Ratings"); + + b.Navigation("ReleaseTypes"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistContributorEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistEntity", null) + .WithMany("Contributors") + .HasForeignKey("ArtistId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistEntity", b => + { + b.OwnsOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.MusicAreaEntity", "Area", b1 => + { + b1.Property("ArtistEntityId"); + + b1.Property("Disambiguation"); + + b1.Property("Iso3166Code"); + + b1.Property("MusicBrainzAreaId"); + + b1.Property("Name") + .IsRequired(); + + b1.Property("SortName"); + + b1.Property("Type"); + + b1.HasKey("ArtistEntityId"); + + b1.ToTable("Artists"); + + b1 + .ToJson("Area") + .HasColumnType("TEXT"); + + b1.WithOwner() + .HasForeignKey("ArtistEntityId"); + }); + + b.OwnsOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.MusicAreaEntity", "BeginArea", b1 => + { + b1.Property("ArtistEntityId"); + + b1.Property("Disambiguation"); + + b1.Property("Iso3166Code"); + + b1.Property("MusicBrainzAreaId"); + + b1.Property("Name") + .IsRequired(); + + b1.Property("SortName"); + + b1.Property("Type"); + + b1.HasKey("ArtistEntityId"); + + b1.ToTable("Artists"); + + b1 + .ToJson("BeginArea") + .HasColumnType("TEXT"); + + b1.WithOwner() + .HasForeignKey("ArtistEntityId"); + }); + + b.OwnsOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.MusicAreaEntity", "EndArea", b1 => + { + b1.Property("ArtistEntityId"); + + b1.Property("Disambiguation"); + + b1.Property("Iso3166Code"); + + b1.Property("MusicBrainzAreaId"); + + b1.Property("Name") + .IsRequired(); + + b1.Property("SortName"); + + b1.Property("Type"); + + b1.HasKey("ArtistEntityId"); + + b1.ToTable("Artists"); + + b1 + .ToJson("EndArea") + .HasColumnType("TEXT"); + + b1.WithOwner() + .HasForeignKey("ArtistEntityId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistAliasEntity", "Aliases", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("ArtistId") + .HasColumnType("TEXT"); + + b1.Property("BeginDate") + .HasColumnType("TEXT"); + + b1.Property("EndDate") + .HasColumnType("TEXT"); + + b1.Property("IsEnded") + .HasColumnType("INTEGER"); + + b1.Property("IsPrimary") + .HasColumnType("INTEGER"); + + b1.Property("Locale") + .HasMaxLength(20) + .HasColumnType("TEXT"); + + b1.Property("Name") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT"); + + b1.Property("SortName") + .HasMaxLength(255) + .HasColumnType("TEXT"); + + b1.Property("Type") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("ArtistId"); + + b1.ToTable("ArtistAliases", (string)null); + + b1.WithOwner() + .HasForeignKey("ArtistId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AudioRatingEntity", "Ratings", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("ArtistId") + .HasColumnType("TEXT"); + + b1.Property("MaxValue") + .HasColumnType("decimal(3,2)"); + + b1.Property("Source") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.Property("Value") + .HasColumnType("decimal(3,2)"); + + b1.Property("VoteCount") + .HasColumnType("INTEGER"); + + b1.HasKey("Id"); + + b1.HasIndex("ArtistId"); + + b1.ToTable("ArtistRatings", (string)null); + + b1.WithOwner() + .HasForeignKey("ArtistId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistIpiEntity", "Ipis", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("ArtistId") + .HasColumnType("TEXT"); + + b1.Property("Value") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("ArtistId"); + + b1.ToTable("ArtistIpis", (string)null); + + b1.WithOwner() + .HasForeignKey("ArtistId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistIsniEntity", "Isnis", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("ArtistId") + .HasColumnType("TEXT"); + + b1.Property("Value") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("ArtistId"); + + b1.ToTable("ArtistIsnis", (string)null); + + b1.WithOwner() + .HasForeignKey("ArtistId"); + }); + + b.Navigation("Aliases"); + + b.Navigation("Area"); + + b.Navigation("BeginArea"); + + b.Navigation("EndArea"); + + b.Navigation("Ipis"); + + b.Navigation("Isnis"); + + b.Navigation("Ratings"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackContributorEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackEntity", null) + .WithMany("Contributors") + .HasForeignKey("TrackId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumEntity", "Album") + .WithMany("Tracks") + .HasForeignKey("AlbumId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AudioRatingEntity", "Ratings", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("MaxValue") + .HasColumnType("decimal(3,2)"); + + b1.Property("Source") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.Property("TrackId") + .HasColumnType("TEXT"); + + b1.Property("Value") + .HasColumnType("decimal(3,2)"); + + b1.Property("VoteCount") + .HasColumnType("INTEGER"); + + b1.HasKey("Id"); + + b1.HasIndex("TrackId"); + + b1.ToTable("TrackRatings", (string)null); + + b1.WithOwner() + .HasForeignKey("TrackId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackIsrcEntity", "Isrcs", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("TrackId") + .HasColumnType("TEXT"); + + b1.Property("Value") + .IsRequired() + .HasMaxLength(12) + .HasColumnType("TEXT") + .HasColumnName("ISRC"); + + b1.HasKey("Id"); + + b1.HasIndex("TrackId"); + + b1.ToTable("TrackIsrcs", (string)null); + + b1.WithOwner() + .HasForeignKey("TrackId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackMoodEntity", "Moods", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("Name") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.Property("TrackId") + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("TrackId"); + + b1.ToTable("TrackMoods", (string)null); + + b1.WithOwner() + .HasForeignKey("TrackId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackWorkIswcEntity", "WorkIswcs", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("TrackId") + .HasColumnType("TEXT"); + + b1.Property("Value") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("TrackId"); + + b1.ToTable("TrackWorkIswcs", (string)null); + + b1.WithOwner() + .HasForeignKey("TrackId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackWorkLanguageEntity", "WorkLanguages", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("LanguageCode") + .IsRequired() + .HasMaxLength(5) + .HasColumnType("TEXT"); + + b1.Property("LanguageName") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("TEXT"); + + b1.Property("NativeName") + .HasMaxLength(100) + .HasColumnType("TEXT"); + + b1.Property("TrackId") + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("TrackId"); + + b1.ToTable("TrackWorkLanguages", (string)null); + + b1.WithOwner() + .HasForeignKey("TrackId"); + }); + + b.Navigation("Album"); + + b.Navigation("Isrcs"); + + b.Navigation("Moods"); + + b.Navigation("Ratings"); + + b.Navigation("WorkIswcs"); + + b.Navigation("WorkLanguages"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.DirectoryScanFingerprintEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", null) + .WithMany() + .HasForeignKey("LibraryId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", "User") + .WithMany("Libraries") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryContentLocationEntity", "ContentLocations", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("LibraryId") + .HasColumnType("TEXT"); + + b1.Property("Path") + .IsRequired() + .HasMaxLength(260) + .HasColumnType("TEXT") + .HasColumnName("Path"); + + b1.HasKey("Id"); + + b1.HasIndex("LibraryId"); + + b1.ToTable("LibraryContentLocations", (string)null); + + b1.WithOwner() + .HasForeignKey("LibraryId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryPathTemplatePartEntity", "PathTemplateParts", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("IsOptional") + .HasColumnType("INTEGER"); + + b1.Property("Kind") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b1.Property("LibraryId") + .HasColumnType("TEXT"); + + b1.Property("Position") + .HasColumnType("INTEGER") + .HasColumnName("Position"); + + b1.Property("Representation") + .IsRequired() + .HasMaxLength(512) + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("LibraryId", "Position") + .IsUnique(); + + b1.ToTable("LibraryPathTemplateParts", (string)null); + + b1.WithOwner() + .HasForeignKey("LibraryId"); + }); + + b.Navigation("ContentLocations"); + + b.Navigation("PathTemplateParts"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", "Library") + .WithMany("LibraryScans") + .HasForeignKey("LibraryId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", "User") + .WithMany("LibraryScans") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Library"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanResultEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", "LibraryScan") + .WithMany("LibraryScanResults") + .HasForeignKey("LibraryScanId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("LibraryScan"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanSnapshotEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", "Library") + .WithMany() + .HasForeignKey("LibraryId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Library"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanStagingResultsEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", null) + .WithMany() + .HasForeignKey("LibraryScanId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookArtworkEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", null) + .WithMany("Artwork") + .HasForeignKey("BookId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookContributorEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", null) + .WithMany("Contributors") + .HasForeignKey("BookId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", b => + { + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookRatingEntity", "Ratings", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("BookId") + .HasColumnType("TEXT"); + + b1.Property("MaxValue") + .HasColumnType("decimal(3,2)"); + + b1.Property("Source") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.Property("Value") + .HasColumnType("decimal(3,2)"); + + b1.Property("VoteCount") + .HasColumnType("INTEGER"); + + b1.HasKey("Id"); + + b1.HasIndex("BookId"); + + b1.ToTable("BookRatings", (string)null); + + b1.WithOwner() + .HasForeignKey("BookId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.IsbnEntity", "ISBNs", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("BookId") + .HasColumnType("TEXT"); + + b1.Property("Format") + .IsRequired() + .HasMaxLength(6) + .HasColumnType("TEXT"); + + b1.Property("Value") + .IsRequired() + .HasMaxLength(13) + .HasColumnType("TEXT") + .HasColumnName("ISBN"); + + b1.HasKey("Id"); + + b1.HasIndex("BookId"); + + b1.ToTable("BookISBNs", (string)null); + + b1.WithOwner() + .HasForeignKey("BookId"); + }); + + b.Navigation("ISBNs"); + + b.Navigation("Ratings"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Playlists.PlaylistEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Playlists.PlaylistEntryEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Playlists.PlaylistEntity", null) + .WithMany("Entries") + .HasForeignKey("PlaylistId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserSettingsEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", null) + .WithOne() + .HasForeignKey("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserSettingsEntity", "UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("TrackGenres", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.GenreEntity", null) + .WithMany() + .HasForeignKey("GenreId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackEntity", null) + .WithMany() + .HasForeignKey("TrackId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("TrackTags", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.TagEntity", null) + .WithMany() + .HasForeignKey("TagId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackEntity", null) + .WithMany() + .HasForeignKey("TrackId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.PermissionEntity", b => + { + b.Navigation("RolePermissions"); + + b.Navigation("UserPermissions"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.RoleEntity", b => + { + b.Navigation("RolePermissions"); + + b.Navigation("UserRoles"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumEntity", b => + { + b.Navigation("Contributors"); + + b.Navigation("Tracks"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistEntity", b => + { + b.Navigation("Albums"); + + b.Navigation("Contributors"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackEntity", b => + { + b.Navigation("Contributors"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", b => + { + b.Navigation("LibraryScans"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", b => + { + b.Navigation("LibraryScanResults"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", b => + { + b.Navigation("Artwork"); + + b.Navigation("Contributors"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Playlists.PlaylistEntity", b => + { + b.Navigation("Entries"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", b => + { + b.Navigation("Libraries"); + + b.Navigation("LibraryScans"); + + b.Navigation("UserPermissions"); + + b.Navigation("UserRole"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/Lumina.DataAccess/Common/Migrations/20261026153835_DropsMusicPlayRecords.cs b/src/Lumina.DataAccess/Common/Migrations/20261026153835_DropsMusicPlayRecords.cs new file mode 100644 index 00000000..b888304e --- /dev/null +++ b/src/Lumina.DataAccess/Common/Migrations/20261026153835_DropsMusicPlayRecords.cs @@ -0,0 +1,57 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Lumina.DataAccess.Common.Migrations +{ + /// + public partial class DropsMusicPlayRecords : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "MusicPlayRecords"); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "MusicPlayRecords", + columns: table => new + { + Id = table.Column(type: "TEXT", nullable: false), + UserId = table.Column(type: "TEXT", nullable: false), + TrackId = table.Column(type: "TEXT", nullable: false), + LibraryId = table.Column(type: "TEXT", nullable: false), + AlbumId = table.Column(type: "TEXT", nullable: false), + ArtistId = table.Column(type: "TEXT", nullable: false), + Status = table.Column(type: "TEXT", maxLength: 20, nullable: false), + LastPositionMilliseconds = table.Column(type: "INTEGER", nullable: false), + ListenedDurationMilliseconds = table.Column(type: "INTEGER", nullable: false), + EndedOnUtc = table.Column(type: "TEXT", nullable: true), + Version = table.Column(type: "INTEGER", nullable: false), + CreatedOnUtc = table.Column(type: "TEXT", nullable: false), + CreatedBy = table.Column(type: "TEXT", nullable: false), + UpdatedOnUtc = table.Column(type: "TEXT", nullable: true), + UpdatedBy = table.Column(type: "TEXT", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_MusicPlayRecords", x => x.Id); + }); + + migrationBuilder.CreateIndex( + name: "IX_MusicPlayRecords_TrackId", + table: "MusicPlayRecords", + column: "TrackId"); + + migrationBuilder.CreateIndex( + name: "IX_MusicPlayRecords_UserId_CreatedOnUtc", + table: "MusicPlayRecords", + columns: new[] { "UserId", "CreatedOnUtc" }); + } + } +} diff --git a/src/Lumina.DataAccess/Common/Migrations/LuminaDbContextModelSnapshot.cs b/src/Lumina.DataAccess/Common/Migrations/LuminaDbContextModelSnapshot.cs index d2db1993..f6d75310 100644 --- a/src/Lumina.DataAccess/Common/Migrations/LuminaDbContextModelSnapshot.cs +++ b/src/Lumina.DataAccess/Common/Migrations/LuminaDbContextModelSnapshot.cs @@ -1,4 +1,4 @@ -// +// using System; using Lumina.DataAccess.Core.UoW; using Microsoft.EntityFrameworkCore; @@ -299,6 +299,230 @@ namespace Lumina.DataAccess.Common.Migrations b.ToTable("Tags", (string)null); }); + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Favorites.FavoriteEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("MediaItemId") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("MediaKind") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("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.MediaConsumption.MediaConsumptionRecordEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("ConsecutivePagesRead") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(0) + .HasColumnOrder(14); + + b.Property("ConsumedDurationMilliseconds") + .HasColumnType("INTEGER") + .HasColumnOrder(9); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(17); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(16); + + b.Property("EndedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("LastActivityOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("LastPositionKind") + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("LastPositionLocation") + .HasMaxLength(4096) + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("LastPositionTimeOffsetMilliseconds") + .HasColumnType("INTEGER") + .HasColumnOrder(11); + + b.Property("LastProgressFraction") + .HasColumnType("REAL") + .HasColumnOrder(13); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("MediaItemId") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("MediaKind") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("StartedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("Status") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(19); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(18); + + b.Property("UserId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("Version") + .IsConcurrencyToken() + .HasColumnType("INTEGER") + .HasColumnOrder(15); + + b.HasKey("Id"); + + b.HasIndex("UserId", "MediaKind", "StartedOnUtc"); + + b.HasIndex("UserId", "MediaKind", "MediaItemId", "LastActivityOnUtc"); + + b.ToTable("MediaConsumptionRecords", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaConsumption.MediaResumePointEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("LastConsumedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("LastPositionKind") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("LastPositionLocation") + .HasMaxLength(4096) + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("LastPositionTimeOffsetMilliseconds") + .HasColumnType("INTEGER") + .HasColumnOrder(6); + + b.Property("LastProgressFraction") + .HasColumnType("REAL") + .HasColumnOrder(8); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("MediaItemId") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("MediaKind") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("UserId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("Version") + .IsConcurrencyToken() + .HasColumnType("INTEGER") + .HasColumnOrder(10); + + b.HasKey("Id"); + + b.HasIndex("UserId", "MediaKind", "MediaItemId") + .IsUnique(); + + b.ToTable("MediaResumePoints", (string)null); + }); + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaContributors.MediaContributorEntity", b => { b.Property("Id") @@ -844,6 +1068,11 @@ namespace Lumina.DataAccess.Common.Migrations .HasColumnType("INTEGER") .HasColumnOrder(13); + b.Property("Container") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(31); + b.Property("DiscNumber") .HasColumnType("INTEGER") .HasColumnOrder(10); @@ -1037,6 +1266,11 @@ namespace Lumina.DataAccess.Common.Migrations .HasColumnType("INTEGER") .HasColumnOrder(22); + b.Property("Container") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(49); + b.Property("CreatedBy") .HasColumnType("TEXT") .HasColumnOrder(38); @@ -1270,6 +1504,10 @@ namespace Lumina.DataAccess.Common.Migrations .HasDefaultValue(true) .HasColumnOrder(6); + b.Property("CompletionThresholdPercentage") + .HasColumnType("INTEGER") + .HasColumnOrder(17); + b.Property("CoverImage") .HasMaxLength(255) .HasColumnType("TEXT") @@ -1316,6 +1554,12 @@ namespace Lumina.DataAccess.Common.Migrations .HasColumnType("INTEGER") .HasColumnOrder(8); + b.Property("ShouldTrackConsumptionProgress") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(false) + .HasColumnOrder(16); + b.Property("Title") .IsRequired() .HasMaxLength(255) @@ -1820,6 +2064,119 @@ namespace Lumina.DataAccess.Common.Migrations b.ToTable("Books", (string)null); }); + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Playlists.PlaylistEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("Description") + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("EntryCount") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(0) + .HasColumnOrder(10); + + b.Property("Name") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("Type") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UserId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("Version") + .IsConcurrencyToken() + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(0L) + .HasColumnOrder(9); + + b.HasKey("Id"); + + b.HasIndex("UserId", "UpdatedOnUtc"); + + b.ToTable("Playlists", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Playlists.PlaylistEntryEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("MediaItemId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("MediaItemType") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("PlaylistId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("Position") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.HasKey("Id"); + + b.HasIndex("MediaItemId"); + + b.HasIndex("PlaylistId", "Position") + .IsUnique(); + + b.ToTable("PlaylistEntries", (string)null); + }); + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Plugins.LibraryArtworkProviderConfigurationEntity", b => { b.Property("Id") @@ -2349,6 +2706,14 @@ namespace Lumina.DataAccess.Common.Migrations .HasColumnType("TEXT") .HasColumnOrder(5); + b.Property("IsGaplessPlaybackEnabled") + .HasColumnType("INTEGER") + .HasColumnOrder(16); + + b.Property("IsMuted") + .HasColumnType("INTEGER") + .HasColumnOrder(29); + b.Property("IsPaginationEnabled") .HasColumnType("INTEGER") .HasColumnOrder(2); @@ -2361,6 +2726,10 @@ namespace Lumina.DataAccess.Common.Migrations .HasColumnType("INTEGER") .HasColumnOrder(3); + b.Property("ReplayGainMode") + .HasColumnType("INTEGER") + .HasColumnOrder(17); + b.Property("ShouldAggregateArtworkWhenMissing") .HasColumnType("INTEGER") .HasColumnOrder(13); @@ -2369,10 +2738,18 @@ namespace Lumina.DataAccess.Common.Migrations .HasColumnType("INTEGER") .HasColumnOrder(10); + b.Property("ShouldAutoplay") + .HasColumnType("INTEGER") + .HasColumnOrder(15); + b.Property("ShouldIgnoreThePrefixForAlphaPicker") .HasColumnType("INTEGER") .HasColumnOrder(4); + b.Property("ShouldKeepDownloadingWhilePaused") + .HasColumnType("INTEGER") + .HasColumnOrder(14); + b.Property("ShouldPreserveBookStyles") .HasColumnType("INTEGER") .HasColumnOrder(12); @@ -2381,6 +2758,10 @@ namespace Lumina.DataAccess.Common.Migrations .HasColumnType("INTEGER") .HasColumnOrder(11); + b.Property("StreamingQuality") + .HasColumnType("INTEGER") + .HasColumnOrder(18); + b.Property("UpdatedBy") .HasColumnType("TEXT") .HasColumnOrder(8); @@ -2393,6 +2774,46 @@ namespace Lumina.DataAccess.Common.Migrations .HasColumnType("TEXT") .HasColumnOrder(1); + b.Property("Volume") + .HasColumnType("REAL") + .HasColumnOrder(28); + + b.Property("VuMeterHighThreshold") + .HasColumnType("REAL") + .HasColumnOrder(23); + + b.Property("VuMeterMediumThreshold") + .HasColumnType("REAL") + .HasColumnOrder(22); + + b.Property("VuMeterOrientation") + .HasColumnType("INTEGER") + .HasColumnOrder(19); + + b.Property("VuMeterPeakHoldDurationInMilliseconds") + .HasColumnType("INTEGER") + .HasColumnOrder(25); + + b.Property("VuMeterPeakReleasePerSecond") + .HasColumnType("REAL") + .HasColumnOrder(27); + + b.Property("VuMeterReleasePerSecond") + .HasColumnType("REAL") + .HasColumnOrder(26); + + b.Property("VuMeterSegmentCount") + .HasColumnType("INTEGER") + .HasColumnOrder(20); + + b.Property("VuMeterSegmentGap") + .HasColumnType("INTEGER") + .HasColumnOrder(21); + + b.Property("VuMeterShowPeak") + .HasColumnType("INTEGER") + .HasColumnOrder(24); + b.HasKey("Id"); b.HasIndex("UserId") @@ -2578,6 +2999,33 @@ 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.MediaConsumption.MediaConsumptionRecordEntity", 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.MediaConsumption.MediaResumePointEntity", 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) @@ -3317,6 +3765,24 @@ namespace Lumina.DataAccess.Common.Migrations b.Navigation("Ratings"); }); + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Playlists.PlaylistEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Playlists.PlaylistEntryEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Playlists.PlaylistEntity", null) + .WithMany("Entries") + .HasForeignKey("PlaylistId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserSettingsEntity", b => { b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", null) @@ -3406,6 +3872,11 @@ namespace Lumina.DataAccess.Common.Migrations b.Navigation("Contributors"); }); + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Playlists.PlaylistEntity", b => + { + b.Navigation("Entries"); + }); + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", b => { b.Navigation("Libraries"); diff --git a/src/Lumina.DataAccess/Common/Persistence/CollectionReconciler.cs b/src/Lumina.DataAccess/Common/Persistence/CollectionReconciler.cs index 3fa99b6b..4bf9642b 100644 --- a/src/Lumina.DataAccess/Common/Persistence/CollectionReconciler.cs +++ b/src/Lumina.DataAccess/Common/Persistence/CollectionReconciler.cs @@ -16,8 +16,9 @@ internal static class CollectionReconciler /// /// /// Existing items that are absent from the desired set are removed, desired items that are absent are added, and matched items are left untouched, unless - /// reports that their non-key values changed, in which case only that item is replaced. Because the tracked instances are - /// never rebuilt as a whole, the rows that did not change keep their identity and their audit columns. + /// reports that their non-key values changed, in which case only that item is replaced, or is + /// provided, in which case the matched tracked item is updated in place. Because the tracked instances are never rebuilt as a whole, the rows that did not change + /// keep their identity and their audit columns. /// /// The type of the tracked items. /// The type of the desired items. @@ -28,13 +29,15 @@ internal static class CollectionReconciler /// Selects the matching key of a desired item. /// Determines whether a matched tracked item must be replaced, because a non-key value changed. /// Creates the entity used for a desired item that is not matched by any tracked item. + /// Applies the incoming non-key values onto a matched tracked item, when the caller updates matched items in place instead of replacing them. public static void Reconcile( ICollection existingItems, IEnumerable incomingItems, Func existingKeySelector, Func incomingKeySelector, Func shouldReplace, - Func createNew) + Func createNew, + Action? applyMatched = null) where TExisting : class where TKey : notnull { @@ -65,6 +68,10 @@ internal static class CollectionReconciler existingItems.Add(replacementItem); existingByKey[incomingKey] = replacementItem; } + else if (applyMatched is not null) + // The caller updates the matched instance in place. This keeps the tracked instance and its key, which is the only + // safe option when the key is user-assigned and the tracked instance is still in the change tracker. + applyMatched(matchedItem, incomingItem); } else { diff --git a/src/Lumina.DataAccess/Common/Persistence/EditableValuesCopier.cs b/src/Lumina.DataAccess/Common/Persistence/EditableValuesCopier.cs index 915e921b..15e56d0a 100644 --- a/src/Lumina.DataAccess/Common/Persistence/EditableValuesCopier.cs +++ b/src/Lumina.DataAccess/Common/Persistence/EditableValuesCopier.cs @@ -47,7 +47,13 @@ internal static class EditableValuesCopier { if (excludedProperties.Contains(property.Name)) continue; - trackedEntry.Property(property.Name).CurrentValue = incomingEntry.Property(property.Name).CurrentValue; + PropertyEntry trackedProperty = trackedEntry.Property(property.Name); + object? incomingValue = incomingEntry.Property(property.Name).CurrentValue; + // Only an actual change is assigned and marked modified. Assigning every value unconditionally, or relying on change detection that has not run yet, would make the caller unable to tell a no-op save from a real edit. + if (Equals(trackedProperty.CurrentValue, incomingValue)) + continue; + trackedProperty.CurrentValue = incomingValue; + trackedProperty.IsModified = true; } } } diff --git a/src/Lumina.DataAccess/Common/Persistence/SharedReferenceResolver.cs b/src/Lumina.DataAccess/Common/Persistence/SharedReferenceResolver.cs index 55d60ffa..ef2000ba 100644 --- a/src/Lumina.DataAccess/Common/Persistence/SharedReferenceResolver.cs +++ b/src/Lumina.DataAccess/Common/Persistence/SharedReferenceResolver.cs @@ -17,25 +17,26 @@ namespace Lumina.DataAccess.Common.Persistence; /// /// /// This is the toolkit's only concern expressed over a family of entity shapes, through the marker interface: -/// a shared reference is resolved by its name, the stored row wins over the incoming instance, and within-request duplicates are collapsed to one instance. +/// a shared reference is resolved by its normalized name, trimmed and lowercased with the invariant culture, the stored row wins over the incoming instance, +/// and within-request duplicates are collapsed to one instance. Differently cased spellings of the same name therefore resolve to the same row. /// No per-entity method is ever needed, so a new shared reference type adds no new persistence type. A shared reference whose name is null or whitespace /// cannot be keyed and would be lost silently, so it fails the resolution with the caller-provided error instead of being dropped. /// internal static class SharedReferenceResolver { /// - /// Resolves the single instance that represents each distinct name carried by . + /// Resolves the single instance that represents each distinct normalized name carried by . /// /// /// The stored row wins over the incoming instance, so that a shared reference that is already persisted is reused instead of inserted again. The - /// instances are also collapsed by name, so that a name shared by several parents of the same request is only ever tracked once. + /// instances are also collapsed by normalized name, so that a name shared by several parents of the same request is only ever tracked once. /// /// The type of the shared reference entity. /// The Entity Framework context the stored rows are read through. /// The shared references carried by the entity that is about to be persisted. /// The error returned when a shared reference carries a name that is null or whitespace. /// Cancellation token that can be used to stop the execution. - /// A result containing either a dictionary that maps each distinct name to the single instance that represents it, or an error. + /// A result containing either a dictionary that maps each distinct normalized name to the single instance that represents it, or an error. internal static async Task>> ResolveAsync(LuminaDbContext context, IEnumerable incomingEntities, Error invalidNameError, CancellationToken cancellationToken) where TEntity : class, ISharedReferenceEntity { @@ -47,7 +48,7 @@ internal static class SharedReferenceResolver string? name = incomingEntity.Name; if (string.IsNullOrWhiteSpace(name)) return invalidNameError; - resolvedByName.TryAdd(name, incomingEntity); + resolvedByName.TryAdd(NormalizeName(name), incomingEntity); } if (resolvedByName.Count == 0) @@ -58,10 +59,13 @@ internal static class SharedReferenceResolver foreach (TEntity trackedEntity in context.Set().Local) { string? trackedName = trackedEntity.Name; - if (!string.IsNullOrWhiteSpace(trackedName) && resolvedByName.ContainsKey(trackedName)) + if (string.IsNullOrWhiteSpace(trackedName)) + continue; + string normalizedTrackedName = NormalizeName(trackedName); + if (resolvedByName.ContainsKey(normalizedTrackedName)) { - resolvedByName[trackedName] = trackedEntity; - namesResolvedFromTrackedEntities.Add(trackedName); + resolvedByName[normalizedTrackedName] = trackedEntity; + namesResolvedFromTrackedEntities.Add(normalizedTrackedName); } } @@ -69,12 +73,13 @@ internal static class SharedReferenceResolver List unresolvedNames = [.. resolvedByName.Keys.Where(name => !namesResolvedFromTrackedEntities.Contains(name))]; if (unresolvedNames.Count > 0) { + // Stored names are normalized when they are written, so the normalized incoming names are matched directly against the primary key. List storedEntities = await context.Set() .Where(entity => unresolvedNames.Contains(EF.Property(entity, nameof(ISharedReferenceEntity.Name)))) .ToListAsync(cancellationToken).ConfigureAwait(false); foreach (TEntity storedEntity in storedEntities) - resolvedByName[storedEntity.Name!] = storedEntity; + resolvedByName[NormalizeName(storedEntity.Name!)] = storedEntity; } return resolvedByName; @@ -96,12 +101,22 @@ internal static class SharedReferenceResolver string? name = incomingEntity.Name; if (string.IsNullOrWhiteSpace(name)) continue; - if (resolvedEntities.TryGetValue(name, out TEntity? resolvedEntity) && resolvedEntity is not null) + if (resolvedEntities.TryGetValue(NormalizeName(name), out TEntity? resolvedEntity) && resolvedEntity is not null) normalizedEntities.Add(resolvedEntity); } return normalizedEntities; } + /// + /// Normalizes a shared reference name to the form that identifies it: trimmed and lowercased with the invariant culture. + /// + /// The name to normalize, which must not be null or whitespace. + /// The normalized name. + private static string NormalizeName(string name) + { + return name.Trim().ToLowerInvariant(); + } + /// /// Reconciles the shared reference collection against , reusing the stored rows whose names already exist. /// diff --git a/src/Lumina.DataAccess/Core/Repositories/BookLibrary/BookRepository.cs b/src/Lumina.DataAccess/Core/Repositories/BookLibrary/BookRepository.cs index 9269db51..e735e3b7 100644 --- a/src/Lumina.DataAccess/Core/Repositories/BookLibrary/BookRepository.cs +++ b/src/Lumina.DataAccess/Core/Repositories/BookLibrary/BookRepository.cs @@ -226,16 +226,14 @@ internal sealed class BookRepository : IBookRepository // Apply sorting based on the specified sortBy and sortOrder parameters. booksQuery = ApplySorting(booksQuery, sortBy, sortOrder ?? SortOrder.Ascending, libraryFilter.ShouldIgnoreThePrefixForAlphaPicker); - IQueryable liteRowsQuery = booksQuery.Select(book => new BookLiteRow - { - Id = book.Id, - Title = book.Title, - ReleaseYear = book.ReReleaseYear ?? book.OriginalReleaseYear, - CoverPath = book.Artwork + IQueryable liteRowsQuery = booksQuery.Select(book => new BookLiteRow( + book.Id, + book.Title, + book.ReReleaseYear ?? book.OriginalReleaseYear, + book.Artwork .Where(artwork => artwork.ArtworkType == ArtworkType.Cover) .Select(artwork => artwork.FileName) - .FirstOrDefault() - }); + .FirstOrDefault())); // If no pagination was requested, return all the books of the library. if (paginationData is null) @@ -486,20 +484,57 @@ internal sealed class BookRepository : IBookRepository /// An containing either the display names of the authors of the books, keyed by book Id, or an error. public async Task>> GetAuthorsDisplayNamesByBookIdsAsync(IReadOnlyCollection bookIds, CancellationToken cancellationToken) { - List authorRows = await _luminaDbContext.BookContributors - .Where(bookContributor => bookIds.Contains(bookContributor.BookId) && bookContributor.Role == MediaContributorRole.Author) - .Join(_luminaDbContext.MediaContributors, - bookContributor => bookContributor.MediaContributorId, - contributor => contributor.Id, - (bookContributor, contributor) => new AuthorRow(bookContributor.BookId, contributor.DisplayName)) - .ToListAsync(cancellationToken) - .ConfigureAwait(false); + List authorRows = []; + // The lookup is split into bounded chunks, so an unpaginated history never exceeds the storage parameter limit. + const int LOOKUP_CHUNK_SIZE = 500; + foreach (Guid[] chunk in bookIds.Chunk(LOOKUP_CHUNK_SIZE)) + { + authorRows.AddRange(await _luminaDbContext.BookContributors + .Where(bookContributor => chunk.Contains(bookContributor.BookId) && bookContributor.Role == MediaContributorRole.Author) + .Join(_luminaDbContext.MediaContributors, + bookContributor => bookContributor.MediaContributorId, + contributor => contributor.Id, + (bookContributor, contributor) => new AuthorRow(bookContributor.BookId, contributor.DisplayName)) + .ToListAsync(cancellationToken) + .ConfigureAwait(false)); + } return authorRows .GroupBy(row => row.BookId) .ToDictionary(group => group.Key, group => group.Min(row => row.DisplayName)); } + /// + /// Gets the books identified by , optionally together with their navigation properties. + /// + /// The Ids of the books to get. + /// Whether the navigation properties of the books should be loaded together with the books themselves. + /// Cancellation token that can be used to stop the execution. + /// An containing either the existing books, or an error. + public async Task>> GetByIdsAsync(IReadOnlyCollection bookIds, bool shouldIncludeNavigationProperties, CancellationToken cancellationToken) + { + List books = []; + // The lookup is split into bounded chunks, so even an unpaginated history never exceeds the storage parameter limit. + const int LOOKUP_CHUNK_SIZE = 500; + foreach (Guid[] chunk in bookIds.Chunk(LOOKUP_CHUNK_SIZE)) + { + IQueryable query = _luminaDbContext.Books.AsNoTracking(); + if (shouldIncludeNavigationProperties) + { + query = query + .Include(book => book.Tags) + .Include(book => book.Genres) + .Include(book => book.ISBNs) + .Include(book => book.Ratings) + .Include(book => book.Contributors) + .Include(book => book.Artwork) + .AsSplitQuery(); + } + books.AddRange(await query.Where(book => chunk.Contains(book.Id)).ToListAsync(cancellationToken).ConfigureAwait(false)); + } + return Result.From>(books); + } + /// /// The author row of a book, joining the participation of an author contributor in a book with the display name of the contributor. /// diff --git a/src/Lumina.DataAccess/Core/Repositories/Favorites/FavoriteRepository.cs b/src/Lumina.DataAccess/Core/Repositories/Favorites/FavoriteRepository.cs new file mode 100644 index 00000000..9afaf0c8 --- /dev/null +++ b/src/Lumina.DataAccess/Core/Repositories/Favorites/FavoriteRepository.cs @@ -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; + +/// +/// Repository for favorites. +/// +/// +/// 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. +/// +internal sealed class FavoriteRepository : IFavoriteRepository +{ + private readonly LuminaDbContext _luminaDbContext; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Entity Framework DbContext. + public FavoriteRepository(LuminaDbContext luminaDbContext) + { + _luminaDbContext = luminaDbContext; + } + + /// + /// Adds a new favorite. + /// + /// The favorite to add. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + public Task> 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); + } + + /// + /// Deletes the favorite identified by . + /// + /// The Id of the favorite to delete. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + public async Task> DeleteByIdAsync(Guid id, CancellationToken cancellationToken) + { + // 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; + } + + /// + /// Gets the favorite of the user identified by on the media item identified by and , if it exists. + /// + /// The Id of the user the favorite must belong to. + /// The kind of the favorited media item. + /// The Id of the favorited media item. + /// Whether the retrieved entity should be tracked by the persistence medium, so that changes to it can be saved. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either the favorite, when the user has not favorited the media item, or an error. + /// + public async Task> 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 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); + } + + /// + /// Gets the Id of the media library that contains the media item identified by and , if the media item exists. + /// + /// The kind of the media item. + /// The Id of the media item. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either the Id of the library that contains the media item, when the + /// media item does not exist or its kind has no catalogued library yet, or an error. + /// + public async Task> 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.Success(libraryId); + } + + /// + /// Gets the paginated favorites of the user identified by , 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 . + /// + /// The Id of the user whose favorites are retrieved. + /// The kind of media item to restrict the favorites to, or for every kind. + /// The pagination data that includes the current page and the number of items per page to retrieve. If , all matching favorites are returned. + /// Whether the retrieved entities should be tracked by the persistence medium, so that changes to them can be saved. Pass for read-only scenarios, to avoid the tracking overhead. + /// Cancellation token that can be used to stop the execution. + /// An containing either a , or an error. + public async Task>> 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 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 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 allFavorites = await ToFavoriteItemsAsync(orderedFavoritesQuery, cancellationToken).ConfigureAwait(false); + return new PaginatedResultDto + { + 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 pageQuery = orderedFavoritesQuery + .Skip((currentPage - 1) * paginationData.PerPage) + .Take(paginationData.PerPage); + IReadOnlyList paginatedResult = await ToFavoriteItemsAsync(pageQuery, cancellationToken).ConfigureAwait(false); + + return new PaginatedResultDto + { + Data = paginatedResult, + CurrentPage = currentPage, + PerPage = paginationData.PerPage, + Count = count, + NumberOfPages = numberOfPages + }; + } + + /// + /// Reads the display data of the media items referenced by the favorites of , one query per media kind present. + /// + /// The query of the favorites to read the display data for. + /// Cancellation token that can be used to stop the execution. + /// The favorites together with the display data of the media items they reference. + private async Task> ToFavoriteItemsAsync(IQueryable favoritesQuery, CancellationToken cancellationToken) + { + List favorites = await favoritesQuery.ToListAsync(cancellationToken).ConfigureAwait(false); + + Dictionary> displayDataByKind = []; + foreach (IGrouping kindGroup in favorites.GroupBy(favorite => favorite.MediaKind)) + { + List 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 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; + } + + /// + /// Gets the Ids, among , of the media items of kind that the user identified by has favorited. + /// + /// The Id of the user whose favorites are checked. + /// The kind of the media items. + /// The Ids of the media items to check. + /// Cancellation token that can be used to stop the execution. + /// An containing either the subset of the Ids that are favorites of the user, or an error. + public async Task>> GetFavoritedMediaItemIdsForUserAsync(Guid userId, FavoriteMediaKind mediaKind, IReadOnlyCollection 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 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); + } + + /// + /// Reads the display data of the media items of kind identified by in one query per bounded chunk. + /// + /// The kind of the media items. + /// The Ids of the media items whose display data is read. + /// Cancellation token that can be used to stop the execution. + /// The display data keyed by media item Id. A media item that no longer exists, or whose kind has no catalogue yet, is absent. + private async Task> GetDisplayDataAsync(FavoriteMediaKind mediaKind, IReadOnlyCollection 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 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)); + } + + /// + /// Reads the display data of one bounded chunk of media items of kind in a single query. + /// + /// The kind of the media items. + /// The bounded chunk of media item Ids whose display data is read. + /// Cancellation token that can be used to stop the execution. + /// The display rows of the media items that exist. + private async Task> GetDisplayRowsAsync(FavoriteMediaKind mediaKind, Guid[] requestedIds, CancellationToken cancellationToken) + { + List 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; + } + + /// + /// The display data of one favorited media item as read from storage, before the absent values are normalized to the generic "no value" form. + /// + /// The Id of the media item. + /// The Id of the media library that contains the media item. + /// The title of the media item. + /// The Id of the collection that contains the media item, if any. + /// The title of the collection that contains the media item, if any. + /// The Id of the creator of the media item, if any. + /// The name of the creator of the media item, if any. + /// The path of the cover art of the media item, if available. + private sealed record DisplayRow( + Guid MediaItemId, + Guid LibraryId, + string Title, + Guid? CollectionId, + string? CollectionTitle, + Guid? CreatorId, + string? CreatorName, + string? CoverPath + ); +} diff --git a/src/Lumina.DataAccess/Core/Repositories/Libraries/LibraryScanSnapshotRepository.cs b/src/Lumina.DataAccess/Core/Repositories/Libraries/LibraryScanSnapshotRepository.cs index 4652c2d3..e7d63840 100644 --- a/src/Lumina.DataAccess/Core/Repositories/Libraries/LibraryScanSnapshotRepository.cs +++ b/src/Lumina.DataAccess/Core/Repositories/Libraries/LibraryScanSnapshotRepository.cs @@ -102,7 +102,7 @@ internal sealed class LibraryScanSnapshotRepository : ILibraryScanSnapshotReposi DateTime nowUtc = DateTime.UtcNow; object parameters = new { libraryId, scanId, userId, nowUtc }; - // the Id of the inserted rows is generated in SQL as a random 16 byte value formatted as lowercase hex (hex(randomblob(16))), which the storage layer parses as a Guid; + // the Id of the inserted rows is generated in SQL as a random 16 byte value formatted as upper case hex (hex(randomblob(16))), which the storage layer parses as a Guid; // generating the Ids in code would defeat the purpose of these single statement bulk inserts // add an audit entry for every media library scan snapshot item that is no longer present in the current scan, meaning it was deleted from the storage medium diff --git a/src/Lumina.DataAccess/Core/Repositories/MediaConsumption/ConsumptionStatisticsRepository.cs b/src/Lumina.DataAccess/Core/Repositories/MediaConsumption/ConsumptionStatisticsRepository.cs new file mode 100644 index 00000000..973af957 --- /dev/null +++ b/src/Lumina.DataAccess/Core/Repositories/MediaConsumption/ConsumptionStatisticsRepository.cs @@ -0,0 +1,102 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaConsumption; +using Lumina.Application.Common.DataAccess.Repositories.MediaConsumption; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.Common.Primitives; +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; +#endregion + +namespace Lumina.DataAccess.Core.Repositories.MediaConsumption; + +/// +/// Repository for the consumption records used to build consumption statistics. +/// +/// +/// The repository only binds the filters and returns the records. Counting, grouping, ordering, display data resolution, and mapping stay in the +/// application handlers, so the same records can serve the summary, the history lists, the all-users summary, and the tag breakdown. +/// +internal sealed class ConsumptionStatisticsRepository : IConsumptionStatisticsRepository +{ + private readonly LuminaDbContext _luminaDbContext; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Entity Framework DbContext. + public ConsumptionStatisticsRepository(LuminaDbContext luminaDbContext) + { + _luminaDbContext = luminaDbContext; + } + + /// + /// Gets the consumption records of the user identified by , optionally limited to a media library, a media kind, and a date range. + /// + /// The Id of the user whose consumption records are retrieved. + /// The Id of the media library to restrict the records to, or for every library. + /// The kind of media to restrict the records to, or for every kind. + /// The start of the date range, or when the range has no start. + /// The end of the date range, or when the range has no end. + /// Cancellation token that can be used to stop the execution. + /// An containing either the consumption records of the user, or an error. + public async Task>> GetForUserAsync( + Guid userId, Guid? libraryId, MediaKind? mediaKind, DateTime? fromUtc, DateTime? toUtc, CancellationToken cancellationToken) + { + // The user is part of the query rather than a check performed after the read, so the storage medium never returns a record of another user. + IQueryable query = _luminaDbContext.MediaConsumptionRecords + .AsNoTracking() + .Where(record => record.UserId == userId); + query = ApplyFilters(query, libraryId, mediaKind, fromUtc, toUtc); + List records = await query.ToListAsync(cancellationToken).ConfigureAwait(false); + return Result.From>(records); + } + + /// + /// Gets the consumption records of every user, optionally limited to a media library, a media kind, and a date range. + /// + /// The Id of the media library to restrict the records to, or for every library. + /// The kind of media to restrict the records to, or for every kind. + /// The start of the date range, or when the range has no start. + /// The end of the date range, or when the range has no end. + /// Cancellation token that can be used to stop the execution. + /// An containing either the consumption records of every user, or an error. + public async Task>> GetForAllUsersAsync( + Guid? libraryId, MediaKind? mediaKind, DateTime? fromUtc, DateTime? toUtc, CancellationToken cancellationToken) + { + // This is the only query that is not scoped to one user, and it exists only for the explicit admin all-users summary. + IQueryable query = _luminaDbContext.MediaConsumptionRecords.AsNoTracking(); + query = ApplyFilters(query, libraryId, mediaKind, fromUtc, toUtc); + List records = await query.ToListAsync(cancellationToken).ConfigureAwait(false); + return Result.From>(records); + } + + /// + /// Applies the optional library, media kind, and date range filters to . + /// + /// The query to filter. + /// The Id of the media library to restrict the records to, or for every library. + /// The kind of media to restrict the records to, or for every kind. + /// The start of the date range, or when the range has no start. + /// The end of the date range, or when the range has no end. + /// The filtered query. + private static IQueryable ApplyFilters( + IQueryable query, Guid? libraryId, MediaKind? mediaKind, DateTime? fromUtc, DateTime? toUtc) + { + // Every filter is bound in the query, so the database never materializes rows that the caller did not ask for. + if (libraryId.HasValue) + query = query.Where(record => record.LibraryId == libraryId.Value); + if (mediaKind.HasValue) + query = query.Where(record => record.MediaKind == mediaKind.Value); + // The date range is applied to the start of the session, which is the indexed timestamp the statistics of a user are read by. + if (fromUtc.HasValue) + query = query.Where(record => record.StartedOnUtc >= fromUtc.Value); + if (toUtc.HasValue) + query = query.Where(record => record.StartedOnUtc <= toUtc.Value); + return query; + } +} diff --git a/src/Lumina.DataAccess/Core/Repositories/MediaConsumption/MediaConsumptionRecordRepository.cs b/src/Lumina.DataAccess/Core/Repositories/MediaConsumption/MediaConsumptionRecordRepository.cs new file mode 100644 index 00000000..218dc426 --- /dev/null +++ b/src/Lumina.DataAccess/Core/Repositories/MediaConsumption/MediaConsumptionRecordRepository.cs @@ -0,0 +1,189 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaConsumption; +using Lumina.Application.Common.DataAccess.Repositories.MediaConsumption; +using Lumina.DataAccess.Common.Persistence; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.Common.Primitives; +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.MediaConsumption; + +/// +/// Repository for media consumption records. +/// +/// +/// Records are always read, updated, and deleted scoped to their owner. The media item they reference is kept by kind and Id only, so a deleted media item leaves the record and its statistics intact. +/// +internal sealed class MediaConsumptionRecordRepository : IMediaConsumptionRecordRepository +{ + private readonly LuminaDbContext _luminaDbContext; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Entity Framework DbContext. + public MediaConsumptionRecordRepository(LuminaDbContext luminaDbContext) + { + _luminaDbContext = luminaDbContext; + } + + /// + /// Adds a new consumption record. + /// + /// The consumption record to add. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + public Task> InsertAsync(MediaConsumptionRecordEntity data, CancellationToken cancellationToken) + { + // The handler creates a new session with a newly generated Id, so this always adds a row. + _luminaDbContext.MediaConsumptionRecords.Add(data); + return Task.FromResult>(Result.Created); + } + + /// + /// Gets the consumption record identified by when it belongs to the user identified by , if it exists. + /// + /// The Id of the consumption record to get. + /// The Id of the user the consumption record must belong to. + /// Whether the retrieved record should be tracked by the persistence medium, so that changes to it can be saved. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either the consumption record identified by and owned by + /// , when no such record exists, or an error. + /// + public async Task> GetByIdForUserAsync(Guid id, Guid userId, 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 record that belongs to another user in the first place. + IQueryable query = _luminaDbContext.MediaConsumptionRecords + .Where(record => record.Id == id && record.UserId == userId); + if (!shouldTrackEntities) + query = query.AsNoTracking(); + return await query.FirstOrDefaultAsync(cancellationToken).ConfigureAwait(false); + } + + /// + /// Updates the consumption record of the user identified by , when the record belongs to that user and still holds the version it was read with. + /// + /// The consumption record whose editable values are applied to the stored record. Its owner must match . + /// The Id of the user the consumption record must belong to. It is authoritative for locating the stored record; the owner carried by is not used to select it. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful update, or an error. + public async Task> UpdateForUserAsync(MediaConsumptionRecordEntity data, Guid userId, CancellationToken cancellationToken) + { + // The user is part of both the tracked and the stored lookup, so a caller can never update a record that belongs to another user merely by knowing its Id. + MediaConsumptionRecordEntity? foundRecord = _luminaDbContext.MediaConsumptionRecords.Local + .FirstOrDefault(record => record.Id == data.Id && record.UserId == userId) + ?? await _luminaDbContext.MediaConsumptionRecords + .FirstOrDefaultAsync(record => record.Id == data.Id && record.UserId == userId, cancellationToken).ConfigureAwait(false); + if (foundRecord is null) + return DomainErrors.MediaConsumption.ConsumptionRecordNotFound; + + // A report that carries the values that are already stored is a no-op: writing it would bump the version for nothing, and a + // concurrent stop or complete that read the same version could then fail for a report that changed no data. + if (!HasEditableChanges(foundRecord, data)) + return Result.Updated; + + // The stored identity is never overwritten by an edit, and the audit columns are only ever written by the auditing interceptor. + // The version is captured before the copy and incremented after it, so the update is only applied when the row still holds the version the report read. + Guid storedUserId = foundRecord.UserId; + Guid libraryId = foundRecord.LibraryId; + Guid mediaItemId = foundRecord.MediaItemId; + MediaKind mediaKind = foundRecord.MediaKind; + DateTime startedOnUtc = foundRecord.StartedOnUtc; + long version = foundRecord.Version; + EditableValuesCopier.CopyEditableValues(_luminaDbContext, foundRecord, data); + foundRecord.UserId = storedUserId; + foundRecord.LibraryId = libraryId; + foundRecord.MediaItemId = mediaItemId; + foundRecord.MediaKind = mediaKind; + foundRecord.StartedOnUtc = startedOnUtc; + foundRecord.Version = version + 1; + return Result.Updated; + } + + /// + /// Deletes the consumption record identified by when it belongs to the user identified by . A record that does not exist is not an error. + /// + /// The Id of the consumption record to delete. + /// The Id of the user the consumption record must belong to. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful deletion, or an error. + public async Task> DeleteForUserAsync(Guid id, Guid userId, CancellationToken cancellationToken) + { + // A handler may already have loaded the same record in this unit of work, so the tracked instance is preferred over materializing a second copy. + MediaConsumptionRecordEntity? record = _luminaDbContext.MediaConsumptionRecords.Local + .FirstOrDefault(trackedRecord => trackedRecord.Id == id && trackedRecord.UserId == userId) + ?? await _luminaDbContext.MediaConsumptionRecords + .FirstOrDefaultAsync(foundRecord => foundRecord.Id == id && foundRecord.UserId == userId, cancellationToken).ConfigureAwait(false); + if (record is null) + return Result.Deleted; + + _luminaDbContext.MediaConsumptionRecords.Remove(record); + return Result.Deleted; + } + + /// + /// Deletes every consumption record of a media item of the user identified by . + /// + /// The Id of the user whose consumption records are deleted. + /// The kind of the consumed media item. + /// The Id of the consumed media item. + /// The Id of the media library that contains the media item. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful deletion, or an error. + public async Task> DeleteAllByMediaItemIdForUserAsync(Guid userId, MediaKind mediaKind, Guid mediaItemId, Guid libraryId, CancellationToken cancellationToken) + { + List records = await _luminaDbContext.MediaConsumptionRecords + .Where(record => record.UserId == userId && + record.MediaKind == mediaKind && + record.MediaItemId == mediaItemId && + record.LibraryId == libraryId) + .ToListAsync(cancellationToken).ConfigureAwait(false); + if (records.Count > 0) + _luminaDbContext.MediaConsumptionRecords.RemoveRange(records); + return Result.Deleted; + } + + /// + /// Deletes every consumption record of the user identified by . + /// + /// The Id of the user whose consumption records are deleted. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful deletion, or an error. + public async Task> DeleteAllForUserAsync(Guid userId, CancellationToken cancellationToken) + { + List records = await _luminaDbContext.MediaConsumptionRecords + .Where(record => record.UserId == userId) + .ToListAsync(cancellationToken).ConfigureAwait(false); + if (records.Count > 0) + _luminaDbContext.MediaConsumptionRecords.RemoveRange(records); + return Result.Deleted; + } + + /// + /// Determines whether carries values that differ from the stored record. + /// + /// The record currently stored in the persistence medium. + /// The record carrying the values to apply. + /// if an editable value changed, otherwise. + private static bool HasEditableChanges(MediaConsumptionRecordEntity stored, MediaConsumptionRecordEntity incoming) + { + return stored.Status != incoming.Status || + stored.LastActivityOnUtc != incoming.LastActivityOnUtc || + stored.EndedOnUtc != incoming.EndedOnUtc || + stored.ConsumedDurationMilliseconds != incoming.ConsumedDurationMilliseconds || + stored.LastPositionKind != incoming.LastPositionKind || + stored.LastPositionTimeOffsetMilliseconds != incoming.LastPositionTimeOffsetMilliseconds || + stored.LastPositionLocation != incoming.LastPositionLocation || + stored.LastProgressFraction != incoming.LastProgressFraction || + stored.ConsecutivePagesRead != incoming.ConsecutivePagesRead; + } +} diff --git a/src/Lumina.DataAccess/Core/Repositories/MediaConsumption/MediaResumePointRepository.cs b/src/Lumina.DataAccess/Core/Repositories/MediaConsumption/MediaResumePointRepository.cs new file mode 100644 index 00000000..3af4edfa --- /dev/null +++ b/src/Lumina.DataAccess/Core/Repositories/MediaConsumption/MediaResumePointRepository.cs @@ -0,0 +1,179 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaConsumption; +using Lumina.Application.Common.DataAccess.Repositories.MediaConsumption; +using Lumina.DataAccess.Common.Persistence; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.Common.Primitives; +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; +#endregion + +namespace Lumina.DataAccess.Core.Repositories.MediaConsumption; + +/// +/// Repository for media resume points. +/// +/// +/// The business key of a resume point is the user, the media kind, and the media item. The unique index on those columns makes the storage +/// medium the owner of the "one resume point per user and item" invariant, and an upsert updates the existing row instead of inserting a second one. +/// +internal sealed class MediaResumePointRepository : IMediaResumePointRepository +{ + private readonly LuminaDbContext _luminaDbContext; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Entity Framework DbContext. + public MediaResumePointRepository(LuminaDbContext luminaDbContext) + { + _luminaDbContext = luminaDbContext; + } + + /// + /// Gets the resume point of the user identified by for the media item identified by and , if it exists. + /// + /// The Id of the user the resume point must belong to. + /// The kind of the media item to resume. + /// The Id of the media item to resume. + /// Whether the retrieved resume point should be tracked by the persistence medium, so that changes to it can be saved. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either the resume point of the user for the media item, when no such resume point exists, or an error. + /// + public async Task> GetForUserAndMediaItemAsync(Guid userId, MediaKind 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 resume point that belongs to another user in the first place. + IQueryable query = _luminaDbContext.MediaResumePoints + .Where(resumePoint => resumePoint.UserId == userId && + resumePoint.MediaKind == mediaKind && + resumePoint.MediaItemId == mediaItemId); + if (!shouldTrackEntities) + query = query.AsNoTracking(); + return await query.FirstOrDefaultAsync(cancellationToken).ConfigureAwait(false); + } + + /// + /// Saves the resume point of the user identified by , inserting it when it does not exist and updating it otherwise. The + /// business key of the resume point, made of the user, the media kind, and the media item, is preserved. + /// + /// The resume point whose values are saved. Its owner must match . + /// The Id of the user the resume point must belong to. It is authoritative for locating the stored resume point and for the owner of a new one; the owner carried by is not used to select it. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful save, or an error. + public async Task> UpsertForUserAsync(MediaResumePointEntity data, Guid userId, CancellationToken cancellationToken) + { + // The business key is located in the tracked entities first, so an upsert of a resume point that this unit of work already loaded updates that instance instead of materializing a second copy. + MediaResumePointEntity? foundResumePoint = _luminaDbContext.MediaResumePoints.Local + .FirstOrDefault(resumePoint => resumePoint.UserId == userId && + resumePoint.MediaKind == data.MediaKind && + resumePoint.MediaItemId == data.MediaItemId) + ?? await _luminaDbContext.MediaResumePoints + .FirstOrDefaultAsync(resumePoint => resumePoint.UserId == userId && + resumePoint.MediaKind == data.MediaKind && + resumePoint.MediaItemId == data.MediaItemId, cancellationToken).ConfigureAwait(false); + if (foundResumePoint is null) + { + // The user argument is authoritative for the owner of the new row, not the owner carried by the caller. + data.UserId = userId; + _luminaDbContext.MediaResumePoints.Add(data); + return Result.Updated; + } + + // A report that carries the values that are already stored is a no-op: writing it would bump the version for nothing. + if (!HasEditableChanges(foundResumePoint, data)) + return Result.Updated; + + // The business key is never reassigned by an upsert. The version is captured before the copy and incremented after it, so the update is only applied when the row still holds the version the report read. + Guid storedUserId = foundResumePoint.UserId; + MediaKind mediaKind = foundResumePoint.MediaKind; + Guid mediaItemId = foundResumePoint.MediaItemId; + long version = foundResumePoint.Version; + EditableValuesCopier.CopyEditableValues(_luminaDbContext, foundResumePoint, data); + foundResumePoint.UserId = storedUserId; + foundResumePoint.MediaKind = mediaKind; + foundResumePoint.MediaItemId = mediaItemId; + foundResumePoint.Version = version + 1; + return Result.Updated; + } + + /// + /// Deletes the resume point of the user identified by for the media item identified by and + /// . A resume point that does not exist is not an error. + /// + /// The Id of the user the resume point must belong to. + /// The kind of the media item to resume. + /// The Id of the media item to resume. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful deletion, or an error. + public async Task> DeleteForUserAndMediaItemAsync(Guid userId, MediaKind mediaKind, Guid mediaItemId, CancellationToken cancellationToken) + { + MediaResumePointEntity? resumePoint = _luminaDbContext.MediaResumePoints.Local + .FirstOrDefault(trackedResumePoint => trackedResumePoint.UserId == userId && + trackedResumePoint.MediaKind == mediaKind && + trackedResumePoint.MediaItemId == mediaItemId) + ?? await _luminaDbContext.MediaResumePoints + .FirstOrDefaultAsync(foundResumePoint => foundResumePoint.UserId == userId && + foundResumePoint.MediaKind == mediaKind && + foundResumePoint.MediaItemId == mediaItemId, cancellationToken).ConfigureAwait(false); + if (resumePoint is null) + return Result.Deleted; + + _luminaDbContext.MediaResumePoints.Remove(resumePoint); + return Result.Deleted; + } + + /// + /// Deletes every resume point of the user identified by . + /// + /// The Id of the user whose resume points are deleted. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful deletion, or an error. + public async Task> DeleteAllForUserAsync(Guid userId, CancellationToken cancellationToken) + { + List resumePoints = await _luminaDbContext.MediaResumePoints + .Where(resumePoint => resumePoint.UserId == userId) + .ToListAsync(cancellationToken).ConfigureAwait(false); + if (resumePoints.Count > 0) + _luminaDbContext.MediaResumePoints.RemoveRange(resumePoints); + return Result.Deleted; + } + + /// + /// Deletes every resume point of the user identified by in the media library identified by . + /// + /// The Id of the user whose resume points are deleted. + /// The Id of the media library whose resume points are deleted. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful deletion, or an error. + public async Task> DeleteAllForUserInLibraryAsync(Guid userId, Guid libraryId, CancellationToken cancellationToken) + { + List resumePoints = await _luminaDbContext.MediaResumePoints + .Where(resumePoint => resumePoint.UserId == userId && resumePoint.LibraryId == libraryId) + .ToListAsync(cancellationToken).ConfigureAwait(false); + if (resumePoints.Count > 0) + _luminaDbContext.MediaResumePoints.RemoveRange(resumePoints); + return Result.Deleted; + } + + /// + /// Determines whether carries values that differ from the stored resume point. + /// + /// The resume point currently stored in the persistence medium. + /// The resume point carrying the values to apply. + /// if an editable value changed, otherwise. + private static bool HasEditableChanges(MediaResumePointEntity stored, MediaResumePointEntity incoming) + { + return stored.LibraryId != incoming.LibraryId || + stored.LastPositionKind != incoming.LastPositionKind || + stored.LastPositionTimeOffsetMilliseconds != incoming.LastPositionTimeOffsetMilliseconds || + stored.LastPositionLocation != incoming.LastPositionLocation || + stored.LastProgressFraction != incoming.LastProgressFraction || + stored.LastConsumedOnUtc != incoming.LastConsumedOnUtc; + } +} diff --git a/src/Lumina.DataAccess/Core/Repositories/MediaContributors/MediaContributorRepository.cs b/src/Lumina.DataAccess/Core/Repositories/MediaContributors/MediaContributorRepository.cs index cddee8c2..ffac00b5 100644 --- a/src/Lumina.DataAccess/Core/Repositories/MediaContributors/MediaContributorRepository.cs +++ b/src/Lumina.DataAccess/Core/Repositories/MediaContributors/MediaContributorRepository.cs @@ -106,9 +106,16 @@ internal sealed class MediaContributorRepository : IMediaContributorRepository /// An containing either the retrieved s, or an error. public async Task>> GetByIdsAsync(IReadOnlyCollection ids, CancellationToken cancellationToken) { - return await _luminaDbContext.MediaContributors - .Where(contributor => ids.Contains(contributor.Id)) - .ToListAsync(cancellationToken) - .ConfigureAwait(false); + List contributors = []; + // The lookup is split into bounded chunks, so an unpaginated history never exceeds the storage parameter limit. + const int LOOKUP_CHUNK_SIZE = 500; + foreach (Guid[] chunk in ids.Chunk(LOOKUP_CHUNK_SIZE)) + { + contributors.AddRange(await _luminaDbContext.MediaContributors + .Where(contributor => chunk.Contains(contributor.Id)) + .ToListAsync(cancellationToken) + .ConfigureAwait(false)); + } + return Result.From>(contributors); } } diff --git a/src/Lumina.DataAccess/Core/Repositories/MusicLibrary/AlbumRepository.cs b/src/Lumina.DataAccess/Core/Repositories/MusicLibrary/AlbumRepository.cs index 232342f7..7add1179 100644 --- a/src/Lumina.DataAccess/Core/Repositories/MusicLibrary/AlbumRepository.cs +++ b/src/Lumina.DataAccess/Core/Repositories/MusicLibrary/AlbumRepository.cs @@ -275,25 +275,23 @@ internal sealed class AlbumRepository : IAlbumRepository public async Task>> GetAlbumsLiteByArtistIdAsync(Guid artistId, PaginationDataDto? paginationData, CancellationToken cancellationToken) { // The lightweight read models are always retrieved without tracking, because they are never modified by the caller. + // The release year and the release types are exposed so that the clients can group and order the releases of an artist. + // The cover of the album is the cover artwork stored for it, if any, and it is exposed so that the clients can display it without loading the whole album. IQueryable liteRowsQuery = _luminaDbContext.Albums .AsNoTracking() .Where(album => album.ArtistId == artistId) .OrderBy(album => album.Title) .ThenBy(album => album.Id) - .Select(album => new AlbumLiteRow - { - Id = album.Id, - Title = album.Title, - TotalTracks = album.TotalTracks, - // The release year and the release types are exposed so that the clients can group and order the releases of an artist. - ReleaseYear = album.ReReleaseYear ?? album.OriginalReleaseYear, - ReleaseTypes = album.ReleaseTypes.Select(releaseType => releaseType.ReleaseType).ToList(), - // The cover of the album is the cover artwork stored for it, if any, and it is exposed so that the clients can display it without loading the whole album. - CoverPath = _luminaDbContext.MusicArtwork + .Select(album => new AlbumLiteRow( + album.Id, + album.Title, + album.TotalTracks, + _luminaDbContext.MusicArtwork .Where(artwork => artwork.OwnerType == MusicArtworkOwnerType.Album && artwork.OwnerId == album.Id && artwork.ArtworkType == ArtworkType.Cover) .Select(artwork => artwork.FileName) - .FirstOrDefault() - }); + .FirstOrDefault(), + album.ReReleaseYear ?? album.OriginalReleaseYear, + album.ReleaseTypes.Select(releaseType => releaseType.ReleaseType).ToList())); if (paginationData is null) { diff --git a/src/Lumina.DataAccess/Core/Repositories/MusicLibrary/ArtistRepository.cs b/src/Lumina.DataAccess/Core/Repositories/MusicLibrary/ArtistRepository.cs index ff9a8e08..faf9039b 100644 --- a/src/Lumina.DataAccess/Core/Repositories/MusicLibrary/ArtistRepository.cs +++ b/src/Lumina.DataAccess/Core/Repositories/MusicLibrary/ArtistRepository.cs @@ -565,17 +565,15 @@ internal sealed class ArtistRepository : IArtistRepository if (filterSpecification is not null) artistsQuery = artistsQuery.Where(filterSpecification.ToExpression()); + // The cover of the artist is the cover artwork stored for it, if any, and it is exposed so that the clients can display it without loading the whole artist. IQueryable liteRowsQuery = ApplySorting(artistsQuery, sortBy, sortOrder ?? SortOrder.Ascending, libraryFilter.ShouldIgnoreThePrefixForAlphaPicker) - .Select(artist => new ArtistLiteRow - { - Id = artist.Id, - Name = artist.Name, - // The cover of the artist is the cover artwork stored for it, if any, and it is exposed so that the clients can display it without loading the whole artist. - CoverPath = _luminaDbContext.MusicArtwork + .Select(artist => new ArtistLiteRow( + artist.Id, + artist.Name, + _luminaDbContext.MusicArtwork .Where(artwork => artwork.OwnerType == MusicArtworkOwnerType.Artist && artwork.OwnerId == artist.Id && artwork.ArtworkType == ArtworkType.Cover) .Select(artwork => artwork.FileName) - .FirstOrDefault() - }); + .FirstOrDefault())); // If no pagination was requested, return all the artists of the library. if (paginationData is null) diff --git a/src/Lumina.DataAccess/Core/Repositories/MusicLibrary/MusicArtworkRepository.cs b/src/Lumina.DataAccess/Core/Repositories/MusicLibrary/MusicArtworkRepository.cs index f9f56768..0fbf50fd 100644 --- a/src/Lumina.DataAccess/Core/Repositories/MusicLibrary/MusicArtworkRepository.cs +++ b/src/Lumina.DataAccess/Core/Repositories/MusicLibrary/MusicArtworkRepository.cs @@ -62,6 +62,30 @@ internal sealed class MusicArtworkRepository : IMusicArtworkRepository return Result.From(artwork); } + /// + /// Gets the pieces of artwork owned by the music library items of the provided identified by any of . + /// + /// The type of the music library items that own the artwork. + /// The Ids of the music library items that own the artwork. + /// Cancellation token that can be used to stop the execution. + /// An containing either the artwork of the existing owners, or an error. + public async Task>> GetByOwnersAsync(MusicArtworkOwnerType ownerType, IReadOnlyCollection ownerIds, CancellationToken cancellationToken) + { + List artwork = []; + // The lookup is split into bounded chunks, so a history page never exceeds the storage parameter limit. + const int LOOKUP_CHUNK_SIZE = 500; + foreach (Guid[] chunk in ownerIds.Chunk(LOOKUP_CHUNK_SIZE)) + { + artwork.AddRange(await _luminaDbContext.MusicArtwork + .AsNoTracking() + .Where(musicArtwork => musicArtwork.OwnerType == ownerType && chunk.Contains(musicArtwork.OwnerId)) + .OrderBy(musicArtwork => musicArtwork.ArtworkType) + .ThenBy(musicArtwork => musicArtwork.Ordinal) + .ToListAsync(cancellationToken).ConfigureAwait(false)); + } + return Result.From>(artwork); + } + /// /// Deletes all the pieces of artwork owned by the music library item of the provided identified by . /// diff --git a/src/Lumina.DataAccess/Core/Repositories/MusicLibrary/TrackRepository.cs b/src/Lumina.DataAccess/Core/Repositories/MusicLibrary/TrackRepository.cs index a4bbe4ad..64146407 100644 --- a/src/Lumina.DataAccess/Core/Repositories/MusicLibrary/TrackRepository.cs +++ b/src/Lumina.DataAccess/Core/Repositories/MusicLibrary/TrackRepository.cs @@ -8,6 +8,7 @@ using Lumina.DataAccess.Common.Persistence; using Lumina.DataAccess.Core.UoW; using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Primitives; +using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using Microsoft.EntityFrameworkCore; using System; @@ -265,14 +266,12 @@ internal sealed class TrackRepository : ITrackRepository .OrderBy(track => track.DiscNumber ?? 1) // some releases don't have a disc number, assume 1 .ThenBy(track => track.TrackNumber) .ThenBy(track => track.Id) - .Select(track => new TrackLiteRow - { - Id = track.Id, - Title = track.Title, - TrackNumber = track.TrackNumber, - DiscNumber = track.DiscNumber, - DurationInSeconds = track.DurationInSeconds - }); + .Select(track => new TrackLiteRow( + track.Id, + track.Title, + track.TrackNumber, + track.DiscNumber, + track.DurationInSeconds)); if (paginationData is null) { @@ -306,6 +305,50 @@ internal sealed class TrackRepository : ITrackRepository }; } + /// + /// Gets a uniformly random selection of tracks of the library identified by , optionally scoped to + /// an artist or an album, excluding the tracks in . + /// + /// The Id of the library whose tracks are sampled. + /// The Id of the artist whose tracks are sampled, or for every artist of the library. + /// The Id of the album whose tracks are sampled, or for every album of the scope. + /// The tracks that must not be returned. + /// The maximum number of tracks to return. + /// Cancellation token that can be used to stop the execution. + /// An containing either a collection of , or an error. + public async Task>> GetShuffleTracksLiteAsync(Guid libraryId, Guid? artistId, Guid? albumId, IReadOnlyCollection excludedTrackIds, int count, CancellationToken cancellationToken) + { + IQueryable query = _luminaDbContext.Tracks + .AsNoTracking() + .Where(track => track.LibraryId == libraryId); + + if (artistId is not null) + query = query.Where(track => track.Album!.ArtistId == artistId.Value); + if (albumId is not null) + query = query.Where(track => track.AlbumId == albumId.Value); + // The exclusions are materialized as an array, so EF translates them the same way as the other Id collections it already parameterizes. + Guid[] excludedIds = excludedTrackIds is Guid[] ids ? ids : [.. excludedTrackIds]; + if (excludedIds.Length > 0) + query = query.Where(track => !excludedIds.Contains(track.Id)); + + // SQLite randomizes the rows before the limit, so the result is a uniform sample of every matching track. The cover is the cover artwork stored for the album, exactly like the album cards expose it. + return await query + .OrderBy(_ => EF.Functions.Random()) + .Take(count) + .Select(track => new ShuffleTrackRowDto( + track.Id, + track.Title, + track.DurationInSeconds, + track.AlbumId, + track.Album!.Title, + track.Album!.ArtistId, + _luminaDbContext.MusicArtwork + .Where(artwork => artwork.OwnerType == MusicArtworkOwnerType.Album && artwork.OwnerId == track.AlbumId && artwork.ArtworkType == ArtworkType.Cover) + .Select(artwork => artwork.FileName) + .FirstOrDefault())) + .ToListAsync(cancellationToken).ConfigureAwait(false); + } + /// /// Gets the track of the library identified by that is stored at the provided . /// @@ -320,6 +363,79 @@ internal sealed class TrackRepository : ITrackRepository return track; } + /// + /// Gets the data needed to stream the audio file of the track identified by , when it belongs to the album identified by + /// and to the media library identified by , and that album belongs to the artist identified by + /// . + /// + /// The Id of the media library the track must belong to. + /// The Id of the album the track must belong to. + /// The Id of the artist that must own the album the track belongs to. + /// The Id of the track whose streaming data is retrieved. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either the of the track, when no track matches the + /// provided identifiers, or an error. + /// + public async Task> GetTrackStreamInfoAsync(Guid libraryId, Guid albumId, Guid artistId, Guid trackId, CancellationToken cancellationToken) + { + // The projection is flat and untracked, and the album is joined both to scope the track by its artist and to project the artist Id, so a track + // that is not in the named library, album and artist simply yields no row. + return await _luminaDbContext.Tracks + .AsNoTracking() + .Where(track => track.Id == trackId && track.LibraryId == libraryId && track.AlbumId == albumId && track.Album!.ArtistId == artistId) + .Select(track => new TrackStreamDto( + track.Path, + track.LibraryId, + track.AlbumId, + track.Album!.ArtistId, + track.Container, + track.AudioCodec, + track.DurationInSeconds, + track.SampleRate, + track.Channels, + track.BitDepth, + track.Bitrate)) + .FirstOrDefaultAsync(cancellationToken).ConfigureAwait(false); + } + + /// + /// Gets the stored probe result needed to build the playback manifest of the track identified by , when it belongs to + /// the album identified by and to the media library identified by , and that album belongs + /// to the artist identified by . + /// + /// The Id of the media library the track must belong to. + /// The Id of the album the track must belong to. + /// The Id of the artist that must own the album the track belongs to. + /// The Id of the track whose playback manifest data is retrieved. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either the of the track, when no track + /// matches the provided identifiers, or an error. + /// + public async Task> GetPlaybackManifestInfoAsync(Guid libraryId, Guid albumId, Guid artistId, Guid trackId, CancellationToken cancellationToken) + { + // The projection is flat and untracked, and the album is joined both to scope the track by its artist and to project the artist Id, so a track + // that is not in the named library, album and artist simply yields no row. + return await _luminaDbContext.Tracks + .AsNoTracking() + .Where(track => track.Id == trackId && track.LibraryId == libraryId && track.AlbumId == albumId && track.Album!.ArtistId == artistId) + .Select(track => new TrackPlaybackManifestDto( + track.Path, + track.Container, + track.AudioCodec, + track.DurationInSeconds, + track.SampleRate, + track.Channels, + track.BitDepth, + track.Bitrate, + track.ReplayGainTrackGain, + track.ReplayGainTrackPeak, + track.ReplayGainAlbumGain, + track.ReplayGainAlbumPeak)) + .FirstOrDefaultAsync(cancellationToken).ConfigureAwait(false); + } + /// /// Deletes the track identified by , together with its owned collections and contributions, by the database cascade. /// @@ -408,4 +524,95 @@ internal sealed class TrackRepository : ITrackRepository .ExecuteUpdateAsync(setters => setters.SetProperty(track => track.MetadataStatus, MetadataStatus.Pending), cancellationToken).ConfigureAwait(false); return Result.Updated; } + + /// + /// Gets the number of tracks in that exist, together with the distinct Ids of the libraries that contain them. + /// + /// The Ids of the tracks whose access information is retrieved. + /// Cancellation token that can be used to stop the execution. + /// An containing either the access summary of the existing tracks, or an error. + public async Task> GetAccessInfoByIdsAsync(IReadOnlyCollection trackIds, CancellationToken cancellationToken) + { + if (trackIds.Count == 0) + return Result.From(new TrackAccessSummaryDto(0, [])); + + // The chunk is deliberately large: it stays below the SQLite parameter limit while keeping a 100k queue to a handful of sequential round trips. + // The projection groups by library, so the storage medium returns one row per library instead of one row per requested track. + const int LOOKUP_CHUNK_SIZE = 20_000; + int trackCount = 0; + HashSet libraryIds = []; + foreach (Guid[] chunk in trackIds.Chunk(LOOKUP_CHUNK_SIZE)) + { + List chunkCounts = await _luminaDbContext.Tracks + .AsNoTracking() + .Where(track => chunk.Contains(track.Id)) + .GroupBy(track => track.LibraryId) + .Select(group => new TrackLibraryCount + { + LibraryId = group.Key, + TrackCount = group.Count() + }) + .ToListAsync(cancellationToken).ConfigureAwait(false); + trackCount += chunkCounts.Sum(count => count.TrackCount); + libraryIds.UnionWith(chunkCounts.Select(count => count.LibraryId)); + } + return Result.From(new TrackAccessSummaryDto(trackCount, [.. libraryIds])); + } + + /// + /// Gets the tracks identified by , optionally together with their navigation properties. + /// + /// The Ids of the tracks to get. + /// Whether the navigation properties of the tracks should be loaded together with the tracks themselves. + /// Cancellation token that can be used to stop the execution. + /// An containing either the existing tracks, or an error. + public async Task>> GetByIdsAsync(IReadOnlyCollection trackIds, bool shouldIncludeNavigationProperties, CancellationToken cancellationToken) + { + List tracks = []; + // The lookup is split into bounded chunks, so even an unpaginated history never exceeds the storage parameter limit. + const int LOOKUP_CHUNK_SIZE = 500; + foreach (Guid[] chunk in trackIds.Chunk(LOOKUP_CHUNK_SIZE)) + { + IQueryable query = _luminaDbContext.Tracks.AsNoTracking(); + if (shouldIncludeNavigationProperties) + { + query = query + .Include(track => track.Album) + .ThenInclude(album => album!.Tags) + .Include(track => track.Album) + .ThenInclude(album => album!.Genres) + .Include(track => track.Album) + .ThenInclude(album => album!.Artist) + .ThenInclude(artist => artist!.Tags) + .Include(track => track.Album) + .ThenInclude(album => album!.Artist) + .ThenInclude(artist => artist!.Genres) + .Include(track => track.Ratings) + .Include(track => track.Tags) + .Include(track => track.Genres) + .Include(track => track.Moods) + .Include(track => track.Isrcs) + .Include(track => track.Contributors) + .AsSplitQuery(); + } + tracks.AddRange(await query.Where(track => chunk.Contains(track.Id)).ToListAsync(cancellationToken).ConfigureAwait(false)); + } + return Result.From>(tracks); + } + + /// + /// The number of requested tracks that exist in one library. + /// + private sealed class TrackLibraryCount + { + /// + /// Gets or sets the Id of the library. + /// + public Guid LibraryId { get; set; } + + /// + /// Gets or sets the number of requested tracks in the library. + /// + public int TrackCount { get; set; } + } } diff --git a/src/Lumina.DataAccess/Core/Repositories/Playlists/PlaylistRepository.cs b/src/Lumina.DataAccess/Core/Repositories/Playlists/PlaylistRepository.cs new file mode 100644 index 00000000..ee38ba94 --- /dev/null +++ b/src/Lumina.DataAccess/Core/Repositories/Playlists/PlaylistRepository.cs @@ -0,0 +1,1059 @@ +#region ========================================================================= USING ===================================================================================== +using Dapper; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Common.DataAccess.Entities.Playlists; +using Lumina.Application.Common.DataAccess.Repositories.Playlists; +using Lumina.Application.Common.DTO.Pagination; +using Lumina.Application.Common.DTO.Playlists; +using Lumina.DataAccess.Common.Persistence; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.Playlists; +using Microsoft.Data.Sqlite; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.ChangeTracking; +using Microsoft.EntityFrameworkCore.Storage; +using System; +using System.Collections.Generic; +using System.Data; +using System.Data.Common; +using System.Linq; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +using DomainErrors = Lumina.Domain.Common.Errors.Errors; +#endregion + +namespace Lumina.DataAccess.Core.Repositories.Playlists; + +/// +/// Repository for playlists. +/// +/// +/// Entry mutations are set-based because a playlist can hold a whole library. Appends bypass the change tracker, so they maintain the audit +/// columns and the denormalized entry count themselves. Positions are sparse order keys enforced by the unique (PlaylistId, Position) index. +/// +internal sealed class PlaylistRepository : IPlaylistRepository +{ + // Keeps the number of bound parameters of one multi-row INSERT well under the SQLite parameter limit. + private const int INSERT_BATCH_SIZE = 500; + // Leaves a wide numeric gap between adjacent entries, so a move or a removal normally writes one row instead of the whole range. + private const long POSITION_STEP = 1_000_000_000L; + + private readonly LuminaDbContext _luminaDbContext; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Entity Framework DbContext. + public PlaylistRepository(LuminaDbContext luminaDbContext) + { + _luminaDbContext = luminaDbContext; + } + + /// + /// Adds a new playlist. + /// + /// The playlist to add. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + public async Task> InsertAsync(PlaylistEntity data, CancellationToken cancellationToken) + { + // The Id comes from the aggregate, so a row with this Id means the same playlist was already persisted, for example by a retried request. + bool doesPlaylistExist = await _luminaDbContext.Playlists + .AnyAsync(playlist => playlist.Id == data.Id, cancellationToken).ConfigureAwait(false); + if (doesPlaylistExist) + return DomainErrors.Playlists.PlaylistAlreadyExists; + + _luminaDbContext.Playlists.Add(data); + return Result.Created; + } + + /// + /// Updates the playlist identified by , applying only the editable data that actually changed, while preserving its + /// identity, its entries, and its audit columns. + /// + /// The playlist whose editable data is applied to the stored playlist. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful update, or an error. + public async Task> UpdateAsync(PlaylistEntity data, CancellationToken cancellationToken) + { + // The playlist details are a scalar edit. Entry mutations are set-based repository operations, so this update never loads or reconciles the entry collection. + // A handler may already have loaded the same playlist in this unit of work, so the tracked instance is preferred over materializing a second copy. + PlaylistEntity? foundPlaylist = _luminaDbContext.Playlists.Local + .FirstOrDefault(playlist => playlist.Id == data.Id && playlist.UserId == data.UserId); + foundPlaylist ??= await _luminaDbContext.Playlists.FirstOrDefaultAsync(playlist => playlist.Id == data.Id && playlist.UserId == data.UserId, cancellationToken).ConfigureAwait(false); + if (foundPlaylist is null) + return DomainErrors.Playlists.PlaylistNotFound; + + // The stored identity is never overwritten by an edit. The audit columns stay under the ownership of the auditing interceptor, + // and the version is incremented here so a concurrent details edit or entry operation is detected. + Guid storedUserId = foundPlaylist.UserId; + long storedVersion = foundPlaylist.Version; + int storedEntryCount = foundPlaylist.EntryCount; + EditableValuesCopier.CopyEditableValues(_luminaDbContext, foundPlaylist, data); + foundPlaylist.UserId = storedUserId; + + // The version and the entry count are not editable values of the aggregate. The count is maintained by the set-based entry + // operations, so a details edit can never overwrite it with the count of the mapped entity. + EntityEntry trackedEntry = _luminaDbContext.Entry(foundPlaylist); + trackedEntry.Property(playlist => playlist.UserId).IsModified = false; + trackedEntry.Property(playlist => playlist.Version).CurrentValue = storedVersion; + trackedEntry.Property(playlist => playlist.EntryCount).CurrentValue = storedEntryCount; + trackedEntry.Property(playlist => playlist.EntryCount).IsModified = false; + + // The version is only incremented when another editable value actually changed, so a save that leaves the details untouched does + // not stamp an activity or a concurrency change that the user never made. The comparison against the tracked original values is + // explicit, because no change detection has run between the copy and this check. + bool hasEditableChanges = trackedEntry.Properties + .Any(property => property.Metadata.Name != nameof(PlaylistEntity.Version) + && property.Metadata.Name != nameof(PlaylistEntity.EntryCount) + && !Equals(property.OriginalValue, property.CurrentValue)); + if (!hasEditableChanges) + { + trackedEntry.Property(playlist => playlist.Version).IsModified = false; + return Result.Updated; + } + foundPlaylist.Version = storedVersion + 1; + return Result.Updated; + } + + /// + /// Gets the playlist identified by when it belongs to the user identified by , if it exists. + /// + /// The Id of the playlist to get. + /// The Id of the user the playlist must belong to. + /// Whether the entries of the playlist should be loaded together with the playlist itself. + /// Whether the retrieved entities should be tracked by the persistence medium, so that changes to them can be saved. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either the playlist identified by and owned by , when no such playlist exists, or an error. + /// + public async Task> GetByIdForUserAsync(Guid id, Guid userId, bool shouldIncludeNavigationProperties = true, bool shouldTrackEntities = true, CancellationToken cancellationToken = default) + { + // The user is part of the filter rather than a check performed after the read, so the storage medium never returns a playlist that belongs to another user in the first place. + IQueryable query = _luminaDbContext.Playlists; + if (!shouldTrackEntities) + query = query.AsNoTracking(); + if (shouldIncludeNavigationProperties) + query = query.Include(playlist => playlist.Entries); + return await query.FirstOrDefaultAsync(playlist => playlist.Id == id && playlist.UserId == userId, cancellationToken).ConfigureAwait(false); + } + + /// + /// Gets the playlists of the user identified by , ordered by their most recent activity. + /// + /// The Id of the user whose playlists are retrieved. + /// Cancellation token that can be used to stop the execution. + /// An containing either the playlists of the user, or an error. + public async Task>> GetAllForUserAsync(Guid userId, CancellationToken cancellationToken) + { + IReadOnlyList playlists = await _luminaDbContext.Playlists + .AsNoTracking() + .Where(playlist => playlist.UserId == userId) + .OrderByDescending(playlist => playlist.UpdatedOnUtc ?? playlist.CreatedOnUtc) + .ThenBy(playlist => playlist.Name) + // The count is stored on the playlist row, so listing the playlists never counts every entry of every playlist. + .Select(playlist => new PlaylistSummaryDto( + playlist.Id, + playlist.Name, + playlist.Description, + playlist.Type, + playlist.EntryCount, + playlist.CreatedOnUtc, + playlist.UpdatedOnUtc)) + .ToListAsync(cancellationToken).ConfigureAwait(false); + return Result.From(playlists); + } + + /// + /// Gets the playlist identified by together with a page of the display details of the media items its entries reference, + /// when the playlist belongs to the user identified by , or all the entries when the pagination data is . + /// + /// The Id of the playlist to get. + /// The Id of the user the playlist must belong to. + /// The pagination data that includes the current page and the number of items per page to retrieve. If , all matching entries are returned. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either the playlist details and the paginated entries, when no such playlist exists, or an error. + /// + public async Task> 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 + .AsNoTracking() + .FirstOrDefaultAsync(foundPlaylist => foundPlaylist.Id == id && foundPlaylist.UserId == userId, cancellationToken).ConfigureAwait(false); + if (playlist is null) + return Result.Success(null); + + IQueryable entriesQuery = _luminaDbContext.PlaylistEntries + .AsNoTracking() + .Where(entry => entry.PlaylistId == id) + .OrderBy(entry => entry.Position); + + // If no pagination was requested, return all the entries of the playlist. + if (paginationData is null) + { + IReadOnlyList allEntries = await ToPlaylistEntriesAsync(entriesQuery, offset: 0, cancellationToken).ConfigureAwait(false); + return new PlaylistDetailsDto(playlist, new PaginatedResultDto + { + 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 pageQuery = entriesQuery + .Skip(offset) + .Take(paginationData.PerPage); + IReadOnlyList paginatedResult = await ToPlaylistEntriesAsync(pageQuery, offset, cancellationToken).ConfigureAwait(false); + + return new PlaylistDetailsDto(playlist, new PaginatedResultDto + { + Data = paginatedResult, + CurrentPage = currentPage, + PerPage = paginationData.PerPage, + Count = count, + NumberOfPages = numberOfPages + }); + } + + /// + /// Reads the display data of the tracks referenced by the entries of . + /// + /// The ordered query of the entries to read the display data for. + /// The zero based position of the first entry of the page, used to compute the dense display position. + /// Cancellation token that can be used to stop the execution. + /// The entries together with the display data of the tracks they reference. + private async Task> ToPlaylistEntriesAsync(IQueryable entriesQuery, int offset, CancellationToken cancellationToken) + { + List entries = await entriesQuery.ToListAsync(cancellationToken).ConfigureAwait(false); + + List trackIds = [.. entries + .Where(entry => entry.MediaItemType == PlaylistMediaItemType.MusicTrack) + .Select(entry => entry.MediaItemId) + .Distinct()]; + Dictionary displayDataByTrackId = await GetTrackDisplayDataAsync(trackIds, cancellationToken).ConfigureAwait(false); + + // An entry whose track was deleted is kept with no display data, so its owner can still see and remove it instead of it silently + // disappearing from the playlist. The sparse order key is converted to a dense display position for the response. + List items = []; + for (int index = 0; index < entries.Count; index++) + { + PlaylistEntryEntity entry = entries[index]; + displayDataByTrackId.TryGetValue(entry.MediaItemId, out PlaylistEntryDisplayDto? displayData); + items.Add(new PlaylistEntryDto(entry, displayData, offset + index)); + } + return items; + } + + /// + /// Gets the entry that was just appended to a playlist of the user identified by , together with the display details of the media item it references. + /// + /// The Id of the playlist the entry must belong to. + /// The Id of the user the playlist must belong to. + /// The Id of the appended entry to get. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either the entry details, when the entry does not exist in that playlist of the user, or an error. + /// + public async Task> GetAppendedEntryDetailsForUserAsync(Guid playlistId, Guid userId, Guid entryId, CancellationToken cancellationToken) + { + // The user is part of the join, so the read never returns an entry of a playlist that belongs to another user. + AppendedEntryState? state = await (from candidate in _luminaDbContext.PlaylistEntries.AsNoTracking() + join playlist in _luminaDbContext.Playlists on candidate.PlaylistId equals playlist.Id + where candidate.Id == entryId && candidate.PlaylistId == playlistId && playlist.UserId == userId + select new AppendedEntryState + { + Entry = candidate, + EntryCount = playlist.EntryCount + }) + .FirstOrDefaultAsync(cancellationToken).ConfigureAwait(false); + if (state is null) + return Result.Success(null); + + List trackIds = state.Entry.MediaItemType == PlaylistMediaItemType.MusicTrack ? [state.Entry.MediaItemId] : []; + Dictionary displayDataByTrackId = await GetTrackDisplayDataAsync(trackIds, cancellationToken).ConfigureAwait(false); + displayDataByTrackId.TryGetValue(state.Entry.MediaItemId, out PlaylistEntryDisplayDto? displayData); + // The appended entry is the last entry, so its dense display position is the stored entry count minus one. Counting every entry + // before it would scan an index of the whole playlist for a value that the playlist row already holds. + int displayPosition = Math.Max(0, state.EntryCount - 1); + return new PlaylistEntryDto(state.Entry, displayData, displayPosition); + } + + /// + /// Appends a batch of media items of one kind to the end of the ordered entries of a playlist of the user identified by , + /// using batched bulk inserts, and updates the activity time, the entry count and the concurrency token of the playlist in the same transaction. + /// + /// The Id of the playlist to append to. + /// The Id of the user the playlist must belong to. + /// The Ids of the media items to append, in order. Duplicates are kept. + /// The kind of media item referenced by every appended entry. + /// The Ids to assign to the appended entries, in the same order as , or to generate them. + /// The activity time to store on the playlist. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either the sparse order key of the first appended entry and the added count, or an error. + /// + public async Task> AddEntriesAsync(Guid playlistId, Guid userId, IReadOnlyList mediaItemIds, PlaylistMediaItemType mediaItemType, IReadOnlyList? entryIds, DateTime updatedOnUtc, CancellationToken cancellationToken) + { + if (entryIds is not null && entryIds.Count != mediaItemIds.Count) + return DomainErrors.Playlists.PlaylistEntryIdCannotBeEmpty; + + // The shared helper owns the playlist checks, the transaction, the activity update and the entry count. The callback only writes the rows. + return await AppendEntriesAsync( + playlistId, + userId, + updatedOnUtc, + (connection, transaction, firstPosition, appendCancellationToken) => InsertEntryBatchesAsync( + connection, + transaction, + ToStorageId(playlistId), + ToStorageId(userId), + firstPosition, + mediaItemIds, + entryIds, + mediaItemType, + updatedOnUtc, + appendCancellationToken), + cancellationToken).ConfigureAwait(false); + } + + /// + /// Appends every media item of a library, an artist or an album to the end of the ordered entries of a playlist of the user identified by , in catalogue order, without materializing the scope. + /// + /// The Id of the playlist to append to. + /// The Id of the user the playlist must belong to. + /// The Id of the library whose media items are appended. + /// The Id of the artist the scope is limited to, or for every artist of the library. + /// The Id of the album the scope is limited to, or for every album of the scope. + /// The kind of media item referenced by every appended entry. + /// The activity time to store on the playlist. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either the sparse order key of the first appended entry and the added count, or an error. + /// + public async Task> AddScopeEntriesAsync(Guid playlistId, Guid userId, Guid libraryId, Guid? artistId, Guid? albumId, PlaylistMediaItemType mediaItemType, DateTime updatedOnUtc, CancellationToken cancellationToken) + { + // The callback inserts the scope with SQL instead of receiving a list, which is what keeps a whole-library append from materializing every track Id before the insert starts. + return await AppendEntriesAsync( + playlistId, + userId, + updatedOnUtc, + (connection, transaction, firstPosition, appendCancellationToken) => InsertScopeEntriesAsync( + connection, + transaction, + ToStorageId(playlistId), + ToStorageId(userId), + firstPosition, + libraryId, + artistId, + albumId, + mediaItemType, + updatedOnUtc, + appendCancellationToken), + cancellationToken).ConfigureAwait(false); + } + + /// + /// Appends entries to a playlist with a set-based operation, and updates the activity time, the entry count and the concurrency token of the playlist in the same transaction. + /// + /// The Id of the playlist to append to. + /// The Id of the user the playlist must belong to. + /// The activity time to store on the playlist. + /// + /// The operation that inserts the entries and returns the number of rows it inserted, using the connection, the transaction and the + /// sparse order key of the first appended entry supplied by this method. + /// + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either the sparse order key of the first appended entry and the added count, or an error. + /// + private async Task> AppendEntriesAsync( + Guid playlistId, + Guid userId, + DateTime updatedOnUtc, + Func> appendEntries, + CancellationToken cancellationToken) + { + // The Ids are written in the same upper case TEXT representation the Entity Framework provider uses, so the raw inserts join the + // existing rows, their indexes and their foreign keys consistently. The registered Dapper Guid type handler uses the same form. + string playlistIdText = ToStorageId(playlistId); + string userIdText = ToStorageId(userId); + + // The raw inserts run on the connection and transaction of the request's unit of work, so they participate in the same + // atomic operation as the rest of the command instead of opening a second connection that would fight for the SQLite write lock. + DbConnection connection = _luminaDbContext.Database.GetDbConnection(); + if (connection.State != ConnectionState.Open) + await connection.OpenAsync(cancellationToken).ConfigureAwait(false); + DbTransaction? existingTransaction = _luminaDbContext.Database.CurrentTransaction?.GetDbTransaction(); + DbTransaction transaction = existingTransaction ?? await connection.BeginTransactionAsync(cancellationToken).ConfigureAwait(false); + // The request middleware owns the transaction it opened and decides its fate. The repository only commits or rolls back a + // transaction it opened itself, which happens when it runs without an ambient request transaction. + bool ownsTransaction = existingTransaction is null; + + try + { + // The validation failures below happen before any row is written. There is therefore nothing for an ambient request transaction to roll back, so only a transaction opened here is closed. + // The append only needs to know that the playlist still exists for this user. + const string PLAYLIST_EXISTS_SQL = "SELECT 1 FROM Playlists WHERE Id = @playlistId AND UserId = @userId LIMIT 1;"; + CommandDefinition playlistExistsCommand = new(PLAYLIST_EXISTS_SQL, new { playlistId = playlistIdText, userId = userIdText }, transaction, cancellationToken: cancellationToken); + long? playlistExists = await connection.ExecuteScalarAsync(playlistExistsCommand).ConfigureAwait(false); + if (playlistExists is null) + { + await RollbackOwnedTransactionAsync(transaction, ownsTransaction).ConfigureAwait(false); + return DomainErrors.Playlists.PlaylistNotFound; + } + + // The append starts one sparse step after the highest stored key. MAX seeks the (PlaylistId, Position) index; COUNT(*) would scan the playlist for every single add. + const string FIRST_POSITION_SQL = "SELECT COALESCE(MAX(Position) + @step, 0) FROM PlaylistEntries WHERE PlaylistId = @playlistId;"; + CommandDefinition firstPositionCommand = new(FIRST_POSITION_SQL, new { playlistId = playlistIdText, step = POSITION_STEP }, transaction, cancellationToken: cancellationToken); + long firstPosition = await connection.ExecuteScalarAsync(firstPositionCommand).ConfigureAwait(false); + + int addedCount = await appendEntries(connection, transaction, firstPosition, cancellationToken).ConfigureAwait(false); + if (addedCount == 0) + { + // An empty scope is a successful no-op. The playlist activity, version and count must not change just because nothing was added. + if (ownsTransaction) + await transaction.CommitAsync(cancellationToken).ConfigureAwait(false); + return new PlaylistBulkAddResultDto(firstPosition, 0); + } + + // The count is updated in the same statement, so a window read never counts the entries of a whole playlist. + const string UPDATE_ACTIVITY_SQL = """ + UPDATE Playlists + SET UpdatedOnUtc = @updatedOnUtc, UpdatedBy = @userId, Version = Version + 1, EntryCount = EntryCount + @addedCount + WHERE Id = @playlistId AND UserId = @userId; + """; + CommandDefinition updateActivityCommand = new(UPDATE_ACTIVITY_SQL, new { updatedOnUtc, playlistId = playlistIdText, userId = userIdText, addedCount }, transaction, cancellationToken: cancellationToken); + int updatedPlaylistCount = await connection.ExecuteAsync(updateActivityCommand).ConfigureAwait(false); + if (updatedPlaylistCount == 0) + { + // The entries were already written. A transaction opened here is rolled back before the error is returned; the request + // transaction is left to the middleware, which rolls it back because this command answers with a failure. + await RollbackOwnedTransactionAsync(transaction, ownsTransaction).ConfigureAwait(false); + return DomainErrors.Playlists.PlaylistNotFound; + } + + // The request middleware owns the transaction and commits it after the response, so only a transaction opened here is committed here. + if (ownsTransaction) + await transaction.CommitAsync(cancellationToken).ConfigureAwait(false); + return new PlaylistBulkAddResultDto(firstPosition, addedCount); + } + catch (SqliteException exception) when (IsUniqueConstraintViolation(exception)) + { + await RollbackOwnedTransactionAsync(transaction, ownsTransaction).ConfigureAwait(false); + return ApplicationErrors.Persistence.UniqueConstraintViolation; + } + catch (SqliteException exception) when (IsConcurrencyConflict(exception)) + { + await RollbackOwnedTransactionAsync(transaction, ownsTransaction).ConfigureAwait(false); + return ApplicationErrors.Persistence.ConcurrencyConflict; + } + catch (OperationCanceledException) + { + // A client abort is reported as a non-success status by the exception handling middleware, so the request transaction is rolled + // back there. A transaction opened here still has to be closed before the exception propagates. + await RollbackOwnedTransactionAsync(transaction, ownsTransaction).ConfigureAwait(false); + throw; + } + catch + { + // Any other failure also leaves a transaction opened here unusable, so it is closed before the failure propagates. The request + // transaction is left to the middleware, which rolls it back because the error answers with a non-success status. + await RollbackOwnedTransactionAsync(transaction, ownsTransaction).ConfigureAwait(false); + throw; + } + } + + /// + /// Inserts explicit media item Ids in bounded batches, so a long queue does not build one enormous SQL statement. + /// + /// The open connection that carries the append transaction. + /// The transaction the inserts run in. + /// The storage representation of the playlist Id. + /// The storage representation of the user Id. + /// The sparse order key of the first appended entry. + /// The Ids of the media items to append, in order. Duplicates are kept. + /// The Ids to assign to the appended entries, or to generate them. + /// The kind of media item referenced by every appended entry. + /// The activity time to stamp on the appended entries. + /// Cancellation token that can be used to stop the execution. + /// The number of inserted entries. + private static async Task InsertEntryBatchesAsync( + DbConnection connection, + DbTransaction transaction, + string playlistIdText, + string userIdText, + long firstPosition, + IReadOnlyList mediaItemIds, + IReadOnlyList? entryIds, + PlaylistMediaItemType mediaItemType, + DateTime updatedOnUtc, + CancellationToken cancellationToken) + { + for (int offset = 0; offset < mediaItemIds.Count; offset += INSERT_BATCH_SIZE) + { + cancellationToken.ThrowIfCancellationRequested(); + int count = Math.Min(INSERT_BATCH_SIZE, mediaItemIds.Count - offset); + StringBuilder insertSql = new("INSERT INTO PlaylistEntries (Id, PlaylistId, MediaItemId, MediaItemType, Position, CreatedOnUtc, CreatedBy) VALUES "); + DynamicParameters parameters = new(); + parameters.Add("mediaItemType", mediaItemType.ToString()); + parameters.Add("createdOnUtc", updatedOnUtc); + parameters.Add("createdBy", userIdText); + for (int index = 0; index < count; index++) + { + if (index > 0) + insertSql.Append(", "); + insertSql.Append($"(@Id{index}, @PlaylistId{index}, @MediaItemId{index}, @mediaItemType, @Position{index}, @createdOnUtc, @createdBy)"); + Guid entryId = entryIds is null ? Guid.NewGuid() : entryIds[offset + index]; + parameters.Add($"Id{index}", ToStorageId(entryId)); + parameters.Add($"PlaylistId{index}", playlistIdText); + parameters.Add($"MediaItemId{index}", ToStorageId(mediaItemIds[offset + index])); + // Every appended entry is one sparse step after the previous one, so later moves can change a single key without rewriting the entries that follow it. + parameters.Add($"Position{index}", firstPosition + ((offset + index) * POSITION_STEP)); + } + CommandDefinition insertCommand = new(insertSql.ToString(), parameters, transaction, cancellationToken: cancellationToken); + await connection.ExecuteAsync(insertCommand).ConfigureAwait(false); + } + // The caller uses this count to update the stored entry count, so it returns the requested rows rather than the number of batches. + return mediaItemIds.Count; + } + + /// + /// Inserts every track of a library, an artist or an album with one INSERT ... SELECT statement, in catalogue order, so the scope is + /// never materialized and sorted in memory. + /// + /// The open connection that carries the append transaction. + /// The transaction the insert runs in. + /// The storage representation of the playlist Id. + /// The storage representation of the user Id. + /// The sparse order key of the first appended entry. + /// The Id of the library whose tracks are appended. + /// The Id of the artist the scope is limited to, or for every artist of the library. + /// The Id of the album the scope is limited to, or for every album of the scope. + /// The kind of media item referenced by every appended entry. + /// The activity time to stamp on the appended entries. + /// Cancellation token that can be used to stop the execution. + /// The number of inserted entries. + private static async Task InsertScopeEntriesAsync( + DbConnection connection, + DbTransaction transaction, + string playlistIdText, + string userIdText, + long firstPosition, + Guid libraryId, + Guid? artistId, + Guid? albumId, + PlaylistMediaItemType mediaItemType, + DateTime updatedOnUtc, + CancellationToken cancellationToken) + { + // The entry Ids are generated by SQLite in the same upper case, hyphenated TEXT form the Entity Framework provider stores. Generating + // them inside the statement is what lets the scope stay a single insert instead of being materialized in C# just to assign Ids. + // The positions are computed by the same ordering the artist and album pages use, so the playlist receives catalogue order directly. + // ROW_NUMBER() produces the dense rank, and multiplying it by POSITION_STEP keeps the stored keys sparse. + StringBuilder insertSql = new(""" + INSERT INTO PlaylistEntries (Id, PlaylistId, MediaItemId, MediaItemType, Position, CreatedOnUtc, CreatedBy) + SELECT + HEX(RANDOMBLOB(4)) || '-' || HEX(RANDOMBLOB(2)) || '-' || HEX(RANDOMBLOB(2)) || '-' || HEX(RANDOMBLOB(2)) || '-' || HEX(RANDOMBLOB(6)), + @playlistId, + track.Id, + @mediaItemType, + @firstPosition + (ROW_NUMBER() OVER (ORDER BY artist.Name, album.Title, album.OriginalReleaseYear, COALESCE(track.DiscNumber, 1), track.TrackNumber, track.Id) - 1) * @step, + @createdOnUtc, + @createdBy + FROM Tracks AS track + INNER JOIN Albums AS album ON album.Id = track.AlbumId + INNER JOIN Artists AS artist ON artist.Id = album.ArtistId + WHERE track.LibraryId = @libraryId + """); + if (artistId is not null) + insertSql.Append(" AND album.ArtistId = @artistId"); + if (albumId is not null) + insertSql.Append(" AND track.AlbumId = @albumId"); + insertSql.Append(';'); + + DynamicParameters parameters = new(); + parameters.Add("playlistId", playlistIdText); + parameters.Add("libraryId", ToStorageId(libraryId)); + parameters.Add("mediaItemType", mediaItemType.ToString()); + parameters.Add("firstPosition", firstPosition); + parameters.Add("step", POSITION_STEP); + parameters.Add("createdOnUtc", updatedOnUtc); + parameters.Add("createdBy", userIdText); + if (artistId is not null) + parameters.Add("artistId", ToStorageId(artistId.Value)); + if (albumId is not null) + parameters.Add("albumId", ToStorageId(albumId.Value)); + + CommandDefinition insertCommand = new(insertSql.ToString(), parameters, transaction, cancellationToken: cancellationToken); + return await connection.ExecuteAsync(insertCommand).ConfigureAwait(false); + } + + /// + /// Moves one entry of a playlist of the user identified by to a new dense position by changing only its + /// sparse order key, and updates the activity time and the concurrency token of the playlist in the same transaction. + /// + /// The Id of the playlist whose entry is moved. + /// The Id of the user the playlist must belong to. + /// The Id of the entry to move. + /// The new zero based position of the entry. + /// The activity time to store on the playlist. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful move, or an error. + public async Task> MoveEntryAsync(Guid playlistId, Guid userId, Guid entryId, int targetPosition, DateTime updatedOnUtc, CancellationToken cancellationToken) + { + try + { + // The version, the entry count and the existence of the entry are read in one statement. The count comes from the playlist + // row, so a drag on a very large playlist never scans the entry index to find out how many entries it holds. Keeping the + // existence check in the same query also preserves the not-found result for a one-entry playlist, where no entry update runs. + PlaylistMoveState? playlistState = await _luminaDbContext.Playlists + .AsNoTracking() + .Where(playlist => playlist.Id == playlistId && playlist.UserId == userId) + .Select(playlist => new PlaylistMoveState + { + Version = playlist.Version, + EntryCount = playlist.EntryCount, + DoesEntryExist = _luminaDbContext.PlaylistEntries.Any(entry => entry.Id == entryId && entry.PlaylistId == playlistId) + }) + .FirstOrDefaultAsync(cancellationToken).ConfigureAwait(false); + if (playlistState is null) + return DomainErrors.Playlists.PlaylistNotFound; + if (!playlistState.DoesEntryExist) + return DomainErrors.Playlists.PlaylistEntryNotFound; + + long playlistVersion = playlistState.Version; + int entryCount = playlistState.EntryCount; + if (targetPosition < 0 || targetPosition >= entryCount) + return DomainErrors.Playlists.PlaylistMoveTargetPositionIsInvalid; + + // A one-entry playlist has no order to change, so only the activity time is updated below. + if (entryCount > 1) + { + long newPosition; + if (targetPosition == 0) + { + // Moving to the front needs a sparse key before the current first entry. + long? nextPosition = await _luminaDbContext.PlaylistEntries + .AsNoTracking() + .Where(entry => entry.PlaylistId == playlistId && entry.Id != entryId) + .OrderBy(entry => entry.Position) + .Select(entry => (long?)entry.Position) + .FirstOrDefaultAsync(cancellationToken).ConfigureAwait(false); + if (nextPosition is null) + return ApplicationErrors.Persistence.ConcurrencyConflict; + newPosition = nextPosition.Value - POSITION_STEP; + } + else if (targetPosition == entryCount - 1) + { + // Moving to the end needs a sparse key after the current last entry. + long? previousPosition = await _luminaDbContext.PlaylistEntries + .AsNoTracking() + .Where(entry => entry.PlaylistId == playlistId && entry.Id != entryId) + .OrderByDescending(entry => entry.Position) + .Select(entry => (long?)entry.Position) + .FirstOrDefaultAsync(cancellationToken).ConfigureAwait(false); + if (previousPosition is null) + return ApplicationErrors.Persistence.ConcurrencyConflict; + newPosition = previousPosition.Value + POSITION_STEP; + } + else + { + // A middle move only needs the two rows that will surround the moved entry. Its new key is the midpoint between them. + List neighbors = await GetMoveNeighborsAsync(playlistId, entryId, targetPosition, cancellationToken).ConfigureAwait(false); + if (neighbors.Count < 2) + return ApplicationErrors.Persistence.ConcurrencyConflict; + if (neighbors[1] - neighbors[0] <= 1) + { + // The numeric gap between the two neighbors was exhausted by earlier midpoint moves. This is the rare repair path; + // it rewrites the order keys once, then the move continues with a fresh gap. + await RebalancePositionsAsync(playlistId, cancellationToken).ConfigureAwait(false); + neighbors = await GetMoveNeighborsAsync(playlistId, entryId, targetPosition, cancellationToken).ConfigureAwait(false); + if (neighbors.Count < 2) + return ApplicationErrors.Persistence.ConcurrencyConflict; + } + long gap = neighbors[1] - neighbors[0]; + if (gap <= 1) + return ApplicationErrors.Persistence.ConcurrencyConflict; + newPosition = neighbors[0] + (gap / 2); + } + + int updatedEntryCount = await _luminaDbContext.PlaylistEntries + .Where(entry => entry.Id == entryId && entry.PlaylistId == playlistId) + .ExecuteUpdateAsync(setters => setters + .SetProperty(entry => entry.Position, newPosition) + .SetProperty(entry => entry.UpdatedOnUtc, updatedOnUtc) + .SetProperty(entry => entry.UpdatedBy, (Guid?)userId), cancellationToken).ConfigureAwait(false); + if (updatedEntryCount == 0) + return DomainErrors.Playlists.PlaylistEntryNotFound; + } + + int updatedPlaylistCount = await UpdatePlaylistActivityAsync(playlistId, userId, playlistVersion, updatedOnUtc, entryCountDelta: 0, cancellationToken).ConfigureAwait(false); + if (updatedPlaylistCount == 0) + return ApplicationErrors.Persistence.ConcurrencyConflict; + return Result.Updated; + } + catch (DbUpdateException exception) when (exception.InnerException is SqliteException sqliteException && IsUniqueConstraintViolation(sqliteException)) + { + return ApplicationErrors.Persistence.UniqueConstraintViolation; + } + catch (DbUpdateException exception) when (exception.InnerException is SqliteException sqliteException && IsConcurrencyConflict(sqliteException)) + { + return ApplicationErrors.Persistence.ConcurrencyConflict; + } + catch (SqliteException exception) when (IsUniqueConstraintViolation(exception)) + { + return ApplicationErrors.Persistence.UniqueConstraintViolation; + } + catch (SqliteException exception) when (IsConcurrencyConflict(exception)) + { + return ApplicationErrors.Persistence.ConcurrencyConflict; + } + } + + /// + /// Removes one entry of a playlist of the user identified by by deleting only that row, and updates the + /// activity time, the entry count and the concurrency token of the playlist in the same transaction. + /// + /// The Id of the playlist whose entry is removed. + /// The Id of the user the playlist must belong to. + /// The Id of the entry to remove. + /// The activity time to store on the playlist. + /// Cancellation token that can be used to stop the execution. + /// An containing either zero repositioned entries, or an error. + public async Task> RemoveEntryAsync(Guid playlistId, Guid userId, Guid entryId, DateTime updatedOnUtc, CancellationToken cancellationToken) + { + try + { + // The version is captured before the delete, so the following count update only applies if no other writer changed the playlist meanwhile. + long? playlistVersion = await _luminaDbContext.Playlists + .AsNoTracking() + .Where(playlist => playlist.Id == playlistId && playlist.UserId == userId) + .Select(playlist => (long?)playlist.Version) + .FirstOrDefaultAsync(cancellationToken).ConfigureAwait(false); + if (playlistVersion is null) + return DomainErrors.Playlists.PlaylistNotFound; + + // The delete reports how many rows it removed, so a missing or already removed entry needs no separate existence query. + int deletedEntryCount = await _luminaDbContext.PlaylistEntries + .Where(entry => entry.Id == entryId && entry.PlaylistId == playlistId) + .ExecuteDeleteAsync(cancellationToken).ConfigureAwait(false); + if (deletedEntryCount == 0) + return DomainErrors.Playlists.PlaylistEntryNotFound; + + // The deleted row decrements the stored count by one. The version predicate ties that decrement to the version read above, so a + // concurrent writer is reported instead of leaving the count out of step with the entries. + int updatedPlaylistCount = await UpdatePlaylistActivityAsync(playlistId, userId, playlistVersion.Value, updatedOnUtc, entryCountDelta: -1, cancellationToken).ConfigureAwait(false); + if (updatedPlaylistCount == 0) + return ApplicationErrors.Persistence.ConcurrencyConflict; + return 0; + } + catch (DbUpdateException exception) when (exception.InnerException is SqliteException sqliteException && IsUniqueConstraintViolation(sqliteException)) + { + return ApplicationErrors.Persistence.UniqueConstraintViolation; + } + catch (DbUpdateException exception) when (exception.InnerException is SqliteException sqliteException && IsConcurrencyConflict(sqliteException)) + { + return ApplicationErrors.Persistence.ConcurrencyConflict; + } + catch (SqliteException exception) when (IsUniqueConstraintViolation(exception)) + { + return ApplicationErrors.Persistence.UniqueConstraintViolation; + } + catch (SqliteException exception) when (IsConcurrencyConflict(exception)) + { + return ApplicationErrors.Persistence.ConcurrencyConflict; + } + } + + /// + /// Gets the two entries that surround the dense target position, excluding the entry being moved. + /// + /// The Id of the playlist. + /// The Id of the entry being moved. + /// The dense target position of the moved entry. + /// Cancellation token that can be used to stop the execution. + /// The sparse order keys of the previous and next entries at the target position. + private async Task> GetMoveNeighborsAsync(Guid playlistId, Guid entryId, int targetPosition, CancellationToken cancellationToken) + { + // The moved entry is excluded from the ordering, so the dense target position maps to the two rows before and after it. + return await _luminaDbContext.PlaylistEntries + .AsNoTracking() + .Where(entry => entry.PlaylistId == playlistId && entry.Id != entryId) + .OrderBy(entry => entry.Position) + .Skip(targetPosition - 1) + .Take(2) + .Select(entry => entry.Position) + .ToListAsync(cancellationToken).ConfigureAwait(false); + } + + /// + /// Rewrites the sparse order keys of a playlist to evenly spaced values. + /// + /// + /// This is a rare repair path, used only when repeated midpoint moves exhaust the numeric gap between two adjacent entries. It runs on + /// the request connection and transaction, parks every row at a unique negative key, and then applies the new keys from a temporary table + /// so the unique index is never violated during the rewrite. + /// + /// The Id of the playlist whose order keys are rewritten. + /// Cancellation token that can be used to stop the execution. + /// A task representing the asynchronous operation. + private async Task RebalancePositionsAsync(Guid playlistId, CancellationToken cancellationToken) + { + string playlistIdText = ToStorageId(playlistId); + DbConnection connection = _luminaDbContext.Database.GetDbConnection(); + if (connection.State != ConnectionState.Open) + await connection.OpenAsync(cancellationToken).ConfigureAwait(false); + DbTransaction? existingTransaction = _luminaDbContext.Database.CurrentTransaction?.GetDbTransaction(); + DbTransaction transaction = existingTransaction ?? await connection.BeginTransactionAsync(cancellationToken).ConfigureAwait(false); + bool ownsTransaction = existingTransaction is null; + try + { + const string MIN_POSITION_SQL = "SELECT MIN(Position) FROM PlaylistEntries WHERE PlaylistId = @playlistId;"; + CommandDefinition minPositionCommand = new(MIN_POSITION_SQL, new { playlistId = playlistIdText }, transaction, cancellationToken: cancellationToken); + long? minPosition = await connection.ExecuteScalarAsync(minPositionCommand).ConfigureAwait(false); + if (minPosition is null) + { + if (ownsTransaction) + await transaction.CommitAsync(cancellationToken).ConfigureAwait(false); + return; + } + + const string DROP_TEMP_TABLE_SQL = "DROP TABLE IF EXISTS PlaylistPositionRebalance;"; + const string CREATE_TEMP_TABLE_SQL = "CREATE TEMP TABLE PlaylistPositionRebalance (Id TEXT NOT NULL PRIMARY KEY, Position INTEGER NOT NULL, ParkPosition INTEGER NOT NULL);"; + // The final keys and a temporary unique negative key are computed once, in playlist order. + const string FILL_TEMP_TABLE_SQL = """ + INSERT INTO PlaylistPositionRebalance (Id, Position, ParkPosition) + SELECT Id, + (ROW_NUMBER() OVER (ORDER BY Position) - 1) * @step, + @minPosition - ROW_NUMBER() OVER (ORDER BY Position) + FROM PlaylistEntries + WHERE PlaylistId = @playlistId; + """; + // Every row is first moved to its unique negative key, so applying the final keys cannot collide with the unique index. + const string PARK_SQL = """ + UPDATE PlaylistEntries + SET Position = ( + SELECT ParkPosition + FROM PlaylistPositionRebalance + WHERE PlaylistPositionRebalance.Id = PlaylistEntries.Id + ) + WHERE PlaylistId = @playlistId; + """; + // The negative keys are then replaced by the final evenly spaced keys. + const string APPLY_SQL = """ + UPDATE PlaylistEntries + SET Position = ( + SELECT Position + FROM PlaylistPositionRebalance + WHERE PlaylistPositionRebalance.Id = PlaylistEntries.Id + ) + WHERE PlaylistId = @playlistId; + """; + object parameters = new { playlistId = playlistIdText, step = POSITION_STEP, minPosition = minPosition.Value }; + List commands = + [ + new(DROP_TEMP_TABLE_SQL, transaction: transaction, cancellationToken: cancellationToken), + new(CREATE_TEMP_TABLE_SQL, transaction: transaction, cancellationToken: cancellationToken), + new(FILL_TEMP_TABLE_SQL, parameters, transaction, cancellationToken: cancellationToken), + new(PARK_SQL, parameters, transaction, cancellationToken: cancellationToken), + new(APPLY_SQL, parameters, transaction, cancellationToken: cancellationToken), + new(DROP_TEMP_TABLE_SQL, transaction: transaction, cancellationToken: cancellationToken) + ]; + foreach (CommandDefinition command in commands) + await connection.ExecuteAsync(command).ConfigureAwait(false); + if (ownsTransaction) + await transaction.CommitAsync(cancellationToken).ConfigureAwait(false); + } + catch + { + if (ownsTransaction) + await transaction.RollbackAsync(cancellationToken).ConfigureAwait(false); + throw; + } + } + + /// + /// Deletes the playlist identified by . + /// + /// The Id of the playlist to delete. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + public async Task> DeleteByIdAsync(Guid id, CancellationToken cancellationToken) + { + PlaylistEntity? playlist = await _luminaDbContext.Playlists + .FirstOrDefaultAsync(foundPlaylist => foundPlaylist.Id == id, cancellationToken).ConfigureAwait(false); + if (playlist is null) + return DomainErrors.Playlists.PlaylistNotFound; + + _luminaDbContext.Playlists.Remove(playlist); + return Result.Deleted; + } + + /// + /// Updates the activity time, the entry count and the concurrency token of the playlist identified by , when its version still matches . + /// + /// The Id of the playlist to update. + /// The Id of the user the playlist must belong to. + /// The concurrency token the playlist must still carry. + /// The activity time to store on the playlist. + /// The number of entries the operation added to or removed from the playlist. + /// Cancellation token that can be used to stop the execution. + /// The number of playlist rows that were updated. + private async Task UpdatePlaylistActivityAsync(Guid playlistId, Guid userId, long expectedVersion, DateTime updatedOnUtc, int entryCountDelta, CancellationToken cancellationToken) + { + // ExecuteUpdate sends one UPDATE and never loads the entries or the playlist. The version predicate is the optimistic concurrency + // check, and the returned row count tells the caller whether another writer won the race. + return await _luminaDbContext.Playlists + .Where(playlist => playlist.Id == playlistId && playlist.UserId == userId && playlist.Version == expectedVersion) + .ExecuteUpdateAsync(setters => setters + .SetProperty(playlist => playlist.UpdatedOnUtc, updatedOnUtc) + .SetProperty(playlist => playlist.UpdatedBy, (Guid?)userId) + .SetProperty(playlist => playlist.EntryCount, playlist => playlist.EntryCount + entryCountDelta) + .SetProperty(playlist => playlist.Version, playlist => playlist.Version + 1), cancellationToken).ConfigureAwait(false); + } + + /// + /// Rolls back a transaction that this repository opened, leaving the request's ambient transaction untouched when it did not open one. + /// + /// + /// The request middleware owns the transaction it opened, and it commits or rolls it back once the response status is known. The repository + /// only closes a transaction it opened itself, so it never takes a decision about work that belongs to the request. + /// + /// The transaction to roll back. + /// Whether this repository opened the transaction. + /// A task representing the asynchronous operation. + private static async Task RollbackOwnedTransactionAsync(DbTransaction transaction, bool ownsTransaction) + { + if (!ownsTransaction) + return; + // Cleanup still has to run when the request token has already been cancelled, which is exactly the failure path that reaches here. + await transaction.RollbackAsync(CancellationToken.None).ConfigureAwait(false); + } + + /// + /// Reads the display details of the tracks identified by with their album, artist and cover, in a single + /// query per bounded chunk. + /// + /// The Ids of the tracks whose display details are read. + /// Cancellation token that can be used to stop the execution. + /// The display details keyed by track Id. + private async Task> GetTrackDisplayDataAsync(IReadOnlyCollection trackIds, CancellationToken cancellationToken) + { + if (trackIds.Count == 0) + return []; + + // The album and the artist are joined by Id, so a playlist never issues a query per entry. The cover is the one stored for the album + // of the track. The lookup is split into bounded chunks, so even a large requested window never exceeds the storage parameter limit. + const int LOOKUP_CHUNK_SIZE = 500; + List trackDetails = []; + foreach (Guid[] chunk in trackIds.Chunk(LOOKUP_CHUNK_SIZE)) + { + List chunkDetails = await (from track in _luminaDbContext.Tracks.AsNoTracking() + join album in _luminaDbContext.Albums on track.AlbumId equals album.Id + join artist in _luminaDbContext.Artists on album.ArtistId equals artist.Id + where chunk.Contains(track.Id) + select new PlaylistEntryDisplayDto( + track.Id, + track.Title, + track.DurationInSeconds, + track.LibraryId, + track.AlbumId, + album.Title, + artist.Id, + artist.Name, + _luminaDbContext.MusicArtwork + .Where(artwork => artwork.OwnerType == MusicArtworkOwnerType.Album + && artwork.OwnerId == album.Id + && artwork.ArtworkType == ArtworkType.Cover) + .Select(artwork => artwork.FileName) + .FirstOrDefault())) + .ToListAsync(cancellationToken).ConfigureAwait(false); + trackDetails.AddRange(chunkDetails); + } + return trackDetails.ToDictionary(track => track.TrackId); + } + + /// + /// Determines whether reports a unique constraint violation. + /// + /// The storage exception to inspect. + /// for a unique constraint violation, otherwise. + private static bool IsUniqueConstraintViolation(SqliteException exception) + { + return exception.SqliteExtendedErrorCode == 2067; // SQLITE_CONSTRAINT_UNIQUE + } + + /// + /// Determines whether reports a busy or locked SQLite database. + /// + /// The storage exception to inspect. + /// for a busy or locked database, otherwise. + private static bool IsConcurrencyConflict(SqliteException exception) + { + return exception.SqliteErrorCode is 5 or 6; // SQLITE_BUSY, SQLITE_LOCKED + } + + /// + /// Converts an Id to the TEXT representation used by the Entity Framework SQLite provider for columns. + /// + /// + /// Entity Framework and the Dapper parameter binding both write values as upper case TEXT. + /// + /// The Id to convert. + /// The upper case TEXT representation of the Id. + private static string ToStorageId(Guid value) + { + return value.ToString().ToUpperInvariant(); + } + + /// + /// The concurrency token and entry count of a playlist, together with whether a specific entry exists in it. + /// + private sealed class PlaylistMoveState + { + /// + /// Gets or sets the concurrency token of the playlist. + /// + public long Version { get; init; } + + /// + /// Gets or sets the number of entries the playlist holds. + /// + public int EntryCount { get; init; } + + /// + /// Gets or sets whether the moved entry exists in the playlist. + /// + public bool DoesEntryExist { get; init; } + } + + /// + /// The appended entry and the stored entry count of its playlist. + /// + private sealed class AppendedEntryState + { + /// + /// Gets or sets the appended entry. + /// + public PlaylistEntryEntity Entry { get; init; } = null!; + + /// + /// Gets or sets the number of entries the playlist holds after the append. + /// + public int EntryCount { get; init; } + } +} diff --git a/src/Lumina.DataAccess/Core/Seed/DataSeedService.cs b/src/Lumina.DataAccess/Core/Seed/DataSeedService.cs index 5e0f4b86..974698bf 100644 --- a/src/Lumina.DataAccess/Core/Seed/DataSeedService.cs +++ b/src/Lumina.DataAccess/Core/Seed/DataSeedService.cs @@ -7,12 +7,12 @@ using Lumina.Application.Common.DataAccess.UoW; using Lumina.Application.Common.DTO.Filtering; using Lumina.Application.Common.DTO.Pagination; using Lumina.Application.Common.Errors; +using Lumina.Application.Common.Infrastructure.Authorization; using Lumina.Application.Common.Infrastructure.Time; using Lumina.Domain.Common.Primitives; using Lumina.Domain.SharedKernel.Common.Enums.Authorization; using Lumina.Domain.SharedKernel.Common.Enums.Scheduling; using System; -using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; #endregion @@ -77,7 +77,7 @@ public class DataSeedService : IDataSeedService // Create the default authorization roles and add them to the repository. RoleEntity[] defaultRoles = [ - new() { RoleName = "Admin", CreatedBy = userId, CreatedOnUtc = _dateTimeProvider.UtcNow } + new() { RoleName = AuthorizationRoles.ADMIN, CreatedBy = userId, CreatedOnUtc = _dateTimeProvider.UtcNow } ]; foreach (RoleEntity role in defaultRoles) { @@ -100,7 +100,7 @@ public class DataSeedService : IDataSeedService public async Task> SetAdminRolePermissionsAsync(Guid userId, CancellationToken cancellationToken) { // Get the admin role. - Result getAdminRoleResult = await _unitOfWork.RoleRepository.GetByNameAsync("Admin", cancellationToken).ConfigureAwait(false); + Result getAdminRoleResult = await _unitOfWork.RoleRepository.GetByNameAsync(AuthorizationRoles.ADMIN, cancellationToken).ConfigureAwait(false); if (getAdminRoleResult.IsFailure) return getAdminRoleResult.Errors; @@ -143,7 +143,7 @@ public class DataSeedService : IDataSeedService public async Task> SetAdminRoleToAdministratorAccount(Guid userId, CancellationToken cancellationToken) { // Get the admin role. - Result getAdminRoleResult = await _unitOfWork.RoleRepository.GetByNameAsync("Admin", cancellationToken).ConfigureAwait(false); + Result getAdminRoleResult = await _unitOfWork.RoleRepository.GetByNameAsync(AuthorizationRoles.ADMIN, cancellationToken).ConfigureAwait(false); if (getAdminRoleResult.IsFailure) return getAdminRoleResult.Errors; diff --git a/src/Lumina.DataAccess/Core/UoW/LuminaDbContext.cs b/src/Lumina.DataAccess/Core/UoW/LuminaDbContext.cs index fcbe9802..110d10d0 100644 --- a/src/Lumina.DataAccess/Core/UoW/LuminaDbContext.cs +++ b/src/Lumina.DataAccess/Core/UoW/LuminaDbContext.cs @@ -1,9 +1,12 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.DataAccess.Entities.Authorization; +using Lumina.Application.Common.DataAccess.Entities.Favorites; +using Lumina.Application.Common.DataAccess.Entities.MediaConsumption; using Lumina.Application.Common.DataAccess.Entities.MediaContributors; using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Application.Common.DataAccess.Entities.Playlists; using Lumina.Application.Common.DataAccess.Entities.Plugins; using Lumina.Application.Common.DataAccess.Entities.Scheduling; using Lumina.Application.Common.DataAccess.Entities.Themes; @@ -49,6 +52,11 @@ public class LuminaDbContext : DbContext public virtual DbSet ScheduledJobs { get; set; } = null!; public virtual DbSet ScheduledJobExecutions { get; set; } = null!; public virtual DbSet SchedulerDisplayPreferences { get; set; } = null!; + public virtual DbSet Playlists { get; set; } = null!; + public virtual DbSet PlaylistEntries { get; set; } = null!; + public virtual DbSet Favorites { get; set; } = null!; + public virtual DbSet MediaConsumptionRecords { get; set; } = null!; + public virtual DbSet MediaResumePoints { get; set; } = null!; /// /// Initializes a new instance of the class. diff --git a/src/Lumina.DataAccess/Core/UoW/UnitOfWork.cs b/src/Lumina.DataAccess/Core/UoW/UnitOfWork.cs index fd78d4bf..f6a29ab7 100644 --- a/src/Lumina.DataAccess/Core/UoW/UnitOfWork.cs +++ b/src/Lumina.DataAccess/Core/UoW/UnitOfWork.cs @@ -1,9 +1,12 @@ #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.MediaConsumption; using Lumina.Application.Common.DataAccess.Repositories.MediaContributors; using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary; using Lumina.Application.Common.DataAccess.Repositories.MusicLibrary; +using Lumina.Application.Common.DataAccess.Repositories.Playlists; using Lumina.Application.Common.DataAccess.Repositories.Plugins; using Lumina.Application.Common.DataAccess.Repositories.Scheduling; using Lumina.Application.Common.DataAccess.Repositories.Themes; @@ -12,9 +15,12 @@ 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.MediaConsumption; using Lumina.DataAccess.Core.Repositories.MediaContributors; using Lumina.DataAccess.Core.Repositories.MusicLibrary; +using Lumina.DataAccess.Core.Repositories.Playlists; using Lumina.DataAccess.Core.Repositories.Plugins; using Lumina.DataAccess.Core.Repositories.Scheduling; using Lumina.DataAccess.Core.Repositories.Themes; @@ -64,6 +70,11 @@ public class UnitOfWork : IUnitOfWork, IDisposable private IThemeRepository? _themeRepository; private IUserRepository? _userRepository; private IUserSettingsRepository? _userSettingsRepository; + private IPlaylistRepository? _playlistRepository; + private IFavoriteRepository? _favoriteRepository; + private IMediaConsumptionRecordRepository? _mediaConsumptionRecordRepository; + private IMediaResumePointRepository? _mediaResumePointRepository; + private IConsumptionStatisticsRepository? _consumptionStatisticsRepository; /// /// Gets the permission repository. @@ -374,6 +385,66 @@ public class UnitOfWork : IUnitOfWork, IDisposable } } + /// + /// Gets the playlist repository. + /// + public IPlaylistRepository PlaylistRepository + { + get + { + _playlistRepository ??= new PlaylistRepository(_luminaDbContext); + return _playlistRepository; + } + } + + /// + /// Gets the favorite repository. + /// + public IFavoriteRepository FavoriteRepository + { + get + { + _favoriteRepository ??= new FavoriteRepository(_luminaDbContext); + return _favoriteRepository; + } + } + + /// + /// Gets the media consumption record repository. + /// + public IMediaConsumptionRecordRepository MediaConsumptionRecordRepository + { + get + { + _mediaConsumptionRecordRepository ??= new MediaConsumptionRecordRepository(_luminaDbContext); + return _mediaConsumptionRecordRepository; + } + } + + /// + /// Gets the media resume point repository. + /// + public IMediaResumePointRepository MediaResumePointRepository + { + get + { + _mediaResumePointRepository ??= new MediaResumePointRepository(_luminaDbContext); + return _mediaResumePointRepository; + } + } + + /// + /// Gets the repository for the consumption records used to build consumption statistics. + /// + public IConsumptionStatisticsRepository ConsumptionStatisticsRepository + { + get + { + _consumptionStatisticsRepository ??= new ConsumptionStatisticsRepository(_luminaDbContext); + return _consumptionStatisticsRepository; + } + } + /// /// Initializes a new instance of the class. /// @@ -395,13 +466,28 @@ public class UnitOfWork : IUnitOfWork, IDisposable await _luminaDbContext.SaveChangesAsync(cancellationToken).ConfigureAwait(false); return Result.Success; } + // A concurrency conflict means that another request changed the same row after this request read it. It is an expected persistence + // conflict, so it is reported as a failure result instead of bubbling up as an unhandled exception. + catch (DbUpdateConcurrencyException) + { + return Errors.Persistence.ConcurrencyConflict; + } // A unique constraint violation is an expected persistence conflict, so it is reported as a failure result instead of bubbling up - // as an unhandled exception and being turned into a generic internal server error. Any other exception is unexpected and is left - // to propagate to the centralized exception handling middleware. + // as an unhandled exception and being turned into a generic internal server error. catch (DbUpdateException exception) when (IsUniqueConstraintViolation(exception)) { return Errors.Persistence.UniqueConstraintViolation; } + // SQLite reports a busy or locked database when another writer holds the lock. It is a concurrent write conflict, not an unexpected + // server failure, so it is reported the same way as an optimistic concurrency conflict. + catch (DbUpdateException exception) when (IsSqliteConcurrencyConflict(exception)) + { + return Errors.Persistence.ConcurrencyConflict; + } + catch (SqliteException exception) when (IsSqliteBusyOrLocked(exception)) + { + return Errors.Persistence.ConcurrencyConflict; + } } /// @@ -416,6 +502,26 @@ public class UnitOfWork : IUnitOfWork, IDisposable && sqliteException.SqliteExtendedErrorCode == 2067; // SQLITE_CONSTRAINT_UNIQUE } + /// + /// Determines whether the provided was caused by a SQLite write conflict. + /// + /// The exception to inspect. + /// if the exception was caused by a busy or locked database, otherwise. + private static bool IsSqliteConcurrencyConflict(DbUpdateException exception) + { + return exception.InnerException is SqliteException sqliteException && IsSqliteBusyOrLocked(sqliteException); + } + + /// + /// Determines whether the provided reports a busy or locked SQLite database. + /// + /// The exception to inspect. + /// if the database is busy or locked, otherwise. + private static bool IsSqliteBusyOrLocked(SqliteException exception) + { + return exception.SqliteErrorCode is 5 or 6; // SQLITE_BUSY, SQLITE_LOCKED + } + /// /// Detaches all the entities tracked by the unit of work, freeing the memory they occupy. /// diff --git a/src/Lumina.Domain.SharedKernel/Common/Enums/AudioLibrary/AudioFileFormat.cs b/src/Lumina.Domain.SharedKernel/Common/Enums/AudioLibrary/AudioFileFormat.cs new file mode 100644 index 00000000..4e9a121c --- /dev/null +++ b/src/Lumina.Domain.SharedKernel/Common/Enums/AudioLibrary/AudioFileFormat.cs @@ -0,0 +1,82 @@ +namespace Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; + +/// +/// Enumeration for the file formats of audio files. +/// +public enum AudioFileFormat +{ + /// + /// No audio file format specified. + /// + None, + + /// + /// MPEG-1 Audio Layer III. + /// + MP3, + + /// + /// Free Lossless Audio Codec. + /// + FLAC, + + /// + /// MPEG-4 Part 14 audio. + /// + M4A, + + /// + /// Advanced Audio Coding. + /// + AAC, + + /// + /// The Ogg container format. + /// + OGG, + + /// + /// Opus. + /// + OPUS, + + /// + /// Waveform Audio File Format. + /// + WAV, + + /// + /// Windows Media Audio. + /// + WMA, + + /// + /// Audio Interchange File Format. + /// + AIFF, + + /// + /// Monkey's Audio. + /// + APE, + + /// + /// WavPack. + /// + WAVPACK, + + /// + /// Direct Stream Digital. + /// + DSF, + + /// + /// Direct Stream Digital Interchange File Format. + /// + DFF, + + /// + /// Matroska audio. + /// + MATROSKA, +} diff --git a/src/Lumina.Domain.SharedKernel/Common/Enums/Favorites/FavoriteMediaKind.cs b/src/Lumina.Domain.SharedKernel/Common/Enums/Favorites/FavoriteMediaKind.cs new file mode 100644 index 00000000..28e4c1f2 --- /dev/null +++ b/src/Lumina.Domain.SharedKernel/Common/Enums/Favorites/FavoriteMediaKind.cs @@ -0,0 +1,47 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Domain.SharedKernel.Common.Enums.Favorites; + +/// +/// Enumeration for the kinds of media item that can be marked as a favorite. +/// +[DebuggerDisplay("{ToString()}")] +public enum FavoriteMediaKind +{ + /// + /// No media kind. Used as the default value; it is not a kind that can be marked as a favorite. + /// + None = 0, + + /// + /// A favorite that references an artist of a music library. + /// + MusicArtist, + + /// + /// A favorite that references an album of a music library. + /// + MusicAlbum, + + /// + /// A favorite that references a track of a music library. + /// + MusicTrack, + + /// + /// A favorite that references a book of a book library. + /// + Book, + + /// + /// A favorite that references a video file. Planned: video libraries are not catalogued yet, so this kind cannot be favorited. + /// + Video, + + /// + /// A favorite that references a photo. Planned: photo libraries are not catalogued yet, so this kind cannot be favorited. + /// + Photo, +} diff --git a/src/Lumina.Domain.SharedKernel/Common/Enums/MediaConsumption/ConsumptionStatus.cs b/src/Lumina.Domain.SharedKernel/Common/Enums/MediaConsumption/ConsumptionStatus.cs new file mode 100644 index 00000000..fbb932ed --- /dev/null +++ b/src/Lumina.Domain.SharedKernel/Common/Enums/MediaConsumption/ConsumptionStatus.cs @@ -0,0 +1,22 @@ +namespace Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption; + +/// +/// Enumeration for the states of a media consumption session. +/// +public enum ConsumptionStatus +{ + /// + /// The consumption session started and has not ended yet. + /// + InProgress, + + /// + /// The consumption session reached its explicit completion or the completion threshold of its library. + /// + Completed, + + /// + /// The consumption session ended before it completed. + /// + Stopped +} diff --git a/src/Lumina.Domain.SharedKernel/Common/Enums/MediaConsumption/MediaPositionKind.cs b/src/Lumina.Domain.SharedKernel/Common/Enums/MediaConsumption/MediaPositionKind.cs new file mode 100644 index 00000000..0c4dc575 --- /dev/null +++ b/src/Lumina.Domain.SharedKernel/Common/Enums/MediaConsumption/MediaPositionKind.cs @@ -0,0 +1,17 @@ +namespace Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption; + +/// +/// Enumeration for the kinds of position that a media consumption session can report. +/// +public enum MediaPositionKind +{ + /// + /// The position is a time offset within the media item. + /// + TimeOffset, + + /// + /// The position is an opaque locator within the media item, such as a reading location of a book. + /// + Location +} diff --git a/src/Lumina.Domain.SharedKernel/Common/Enums/MediaLibrary/MediaKind.cs b/src/Lumina.Domain.SharedKernel/Common/Enums/MediaLibrary/MediaKind.cs new file mode 100644 index 00000000..cfee4790 --- /dev/null +++ b/src/Lumina.Domain.SharedKernel/Common/Enums/MediaLibrary/MediaKind.cs @@ -0,0 +1,52 @@ +namespace Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; + +/// +/// Enumeration for the kinds of media items. +/// +public enum MediaKind +{ + /// + /// No media kind. Used as the default value; it is not a valid kind for a media item. + /// + None = 0, + + /// + /// A track of a music library. + /// + MusicTrack, + + /// + /// An episode of a podcast. + /// + PodcastEpisode, + + /// + /// An audiobook. + /// + Audiobook, + + /// + /// A movie. + /// + Movie, + + /// + /// An episode of a TV show. + /// + TvEpisode, + + /// + /// A book of a written content library. + /// + Book, + + /// + /// A photo. + /// + Photo, + + /// + /// A video file. + /// + Video +} diff --git a/src/Lumina.Domain.SharedKernel/Common/Enums/Playback/PlaybackDeliveryMode.cs b/src/Lumina.Domain.SharedKernel/Common/Enums/Playback/PlaybackDeliveryMode.cs new file mode 100644 index 00000000..134e976e --- /dev/null +++ b/src/Lumina.Domain.SharedKernel/Common/Enums/Playback/PlaybackDeliveryMode.cs @@ -0,0 +1,22 @@ +namespace Lumina.Domain.SharedKernel.Common.Enums.Playback; + +/// +/// Enumeration for the ways in which a track's audio is delivered to a player. +/// +public enum PlaybackDeliveryMode +{ + /// + /// The original audio file is delivered unchanged, because the player can demux its container and decode its codec as stored. + /// + DirectPlay, + + /// + /// The audio is repackaged into a container the player can demux, without re-encoding its codec. + /// + Remux, + + /// + /// The audio is re-encoded into a codec the player can decode, because the stored codec is not one the player supports. + /// + Transcode, +} diff --git a/src/Lumina.Domain.SharedKernel/Common/Enums/Playback/PlaybackDeliveryShape.cs b/src/Lumina.Domain.SharedKernel/Common/Enums/Playback/PlaybackDeliveryShape.cs new file mode 100644 index 00000000..dfbad916 --- /dev/null +++ b/src/Lumina.Domain.SharedKernel/Common/Enums/Playback/PlaybackDeliveryShape.cs @@ -0,0 +1,18 @@ +namespace Lumina.Domain.SharedKernel.Common.Enums.Playback; + +/// +/// Enumeration for the shapes in which delivered audio is addressed and seeked. +/// +public enum PlaybackDeliveryShape +{ + /// + /// The delivered media is the original file itself, addressed and seeked by byte range. + /// + ByteRangeSeekable, + + /// + /// The delivered media is a sequence of fixed duration segments, addressed and seeked by time, so that finding a time never + /// requires mapping a byte range to it. + /// + TimeAddressedSegments, +} diff --git a/src/Lumina.Domain.SharedKernel/Common/Enums/Playback/PlaybackDeliveryShapeExtensions.cs b/src/Lumina.Domain.SharedKernel/Common/Enums/Playback/PlaybackDeliveryShapeExtensions.cs new file mode 100644 index 00000000..27e6672e --- /dev/null +++ b/src/Lumina.Domain.SharedKernel/Common/Enums/Playback/PlaybackDeliveryShapeExtensions.cs @@ -0,0 +1,21 @@ +namespace Lumina.Domain.SharedKernel.Common.Enums.Playback; + +/// +/// Extension methods for . +/// +public static class PlaybackDeliveryShapeExtensions +{ + /// + /// Gets whether the audio delivered in the provided can be seeked by a player. + /// + /// The shape the delivered audio is addressed and seeked by. + /// + /// when the shape can be seeked, otherwise . Audio delivered as the original file is + /// seeked by byte range, and audio delivered as time addressed segments is seeked by segment, so both of the shapes the server + /// produces are seekable; a future shape that cannot be seeked reports . + /// + public static bool IsSeekable(this PlaybackDeliveryShape shape) + { + return shape is PlaybackDeliveryShape.ByteRangeSeekable or PlaybackDeliveryShape.TimeAddressedSegments; + } +} diff --git a/src/Lumina.Domain.SharedKernel/Common/Enums/Playback/PlaybackStreamingQuality.cs b/src/Lumina.Domain.SharedKernel/Common/Enums/Playback/PlaybackStreamingQuality.cs new file mode 100644 index 00000000..0e3ecd72 --- /dev/null +++ b/src/Lumina.Domain.SharedKernel/Common/Enums/Playback/PlaybackStreamingQuality.cs @@ -0,0 +1,31 @@ +namespace Lumina.Domain.SharedKernel.Common.Enums.Playback; + +/// +/// Enumeration for the quality cap applied to the audio the server normalizes (remuxes or transcodes) for a user. +/// +/// +/// The caps apply only to audio the server re-encodes into a lossy codec. A track that is played directly is delivered as it was stored, a remux only +/// repackages the stored codec without re-encoding it, and a lossless transcode is not reduced, so none of those deliveries is capped. +/// +public enum PlaybackStreamingQuality +{ + /// + /// The server chooses the quality, with a default cap of 192 kbps for a lossy re-encode. + /// + Auto, + + /// + /// A lossy normalized audio stream is capped at 96 kbps. + /// + Low, + + /// + /// A lossy normalized audio stream is capped at 160 kbps. + /// + Medium, + + /// + /// A lossy normalized audio stream is capped at 320 kbps. + /// + High, +} diff --git a/src/Lumina.Domain.SharedKernel/Common/Enums/Playback/ReplayGainMode.cs b/src/Lumina.Domain.SharedKernel/Common/Enums/Playback/ReplayGainMode.cs new file mode 100644 index 00000000..fea96752 --- /dev/null +++ b/src/Lumina.Domain.SharedKernel/Common/Enums/Playback/ReplayGainMode.cs @@ -0,0 +1,23 @@ +namespace Lumina.Domain.SharedKernel.Common.Enums.Playback; + +/// +/// Enumeration for the ways ReplayGain normalization is applied to the tracks a user plays. +/// +public enum ReplayGainMode +{ + /// + /// ReplayGain is not applied. Tracks play at the loudness at which they were stored. + /// + Off, + + /// + /// Each track is normalized using its own ReplayGain track gain, so tracks from different albums play at a similar loudness. + /// + Track, + + /// + /// Each track is normalized using the ReplayGain album gain of the album it belongs to, so an album keeps its relative loudness + /// while albums play at a similar loudness to each other. + /// + Album, +} diff --git a/src/Lumina.Domain.SharedKernel/Common/Enums/Playback/VuMeterOrientation.cs b/src/Lumina.Domain.SharedKernel/Common/Enums/Playback/VuMeterOrientation.cs new file mode 100644 index 00000000..b696d75c --- /dev/null +++ b/src/Lumina.Domain.SharedKernel/Common/Enums/Playback/VuMeterOrientation.cs @@ -0,0 +1,18 @@ +namespace Lumina.Domain.SharedKernel.Common.Enums.Playback; + +/// +/// Enumeration for the direction in which each channel of the VU meter of the audio player grows. +/// +public enum VuMeterOrientation +{ + /// + /// The channels of the meter are columns and their levels grow from bottom to top. + /// + Vertical, + + /// + /// The channels of the meter are rows and their levels grow from left to right. + /// + Horizontal, +} + diff --git a/src/Lumina.Domain.SharedKernel/Common/Enums/Playlists/PlaylistMediaItemType.cs b/src/Lumina.Domain.SharedKernel/Common/Enums/Playlists/PlaylistMediaItemType.cs new file mode 100644 index 00000000..37e81b01 --- /dev/null +++ b/src/Lumina.Domain.SharedKernel/Common/Enums/Playlists/PlaylistMediaItemType.cs @@ -0,0 +1,22 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Domain.SharedKernel.Common.Enums.Playlists; + +/// +/// Enumeration for the kinds of media item an ordered playlist entry can reference. +/// +[DebuggerDisplay("{ToString()}")] +public enum PlaylistMediaItemType +{ + /// + /// An entry that references a music track. + /// + MusicTrack, + + /// + /// An entry that references a video file. + /// + VideoFile, +} diff --git a/src/Lumina.Domain.SharedKernel/Common/Enums/Playlists/PlaylistType.cs b/src/Lumina.Domain.SharedKernel/Common/Enums/Playlists/PlaylistType.cs new file mode 100644 index 00000000..369e7554 --- /dev/null +++ b/src/Lumina.Domain.SharedKernel/Common/Enums/Playlists/PlaylistType.cs @@ -0,0 +1,17 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Domain.SharedKernel.Common.Enums.Playlists; + +/// +/// Enumeration for the kinds of media a playlist can hold. +/// +[DebuggerDisplay("{ToString()}")] +public enum PlaylistType +{ + /// + /// A playlist whose ordered entries reference music tracks. + /// + Music, +} diff --git a/src/Lumina.Domain/Common/Errors/Errors.Favorite.cs b/src/Lumina.Domain/Common/Errors/Errors.Favorite.cs new file mode 100644 index 00000000..9d40ee8e --- /dev/null +++ b/src/Lumina.Domain/Common/Errors/Errors.Favorite.cs @@ -0,0 +1,22 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Primitives; +#endregion + +namespace Lumina.Domain.Common.Errors; + +/// +/// Favorite error types. +/// +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)); + } +} diff --git a/src/Lumina.Domain/Common/Errors/Errors.Library.cs b/src/Lumina.Domain/Common/Errors/Errors.Library.cs index ffff621a..cb5fad2d 100644 --- a/src/Lumina.Domain/Common/Errors/Errors.Library.cs +++ b/src/Lumina.Domain/Common/Errors/Errors.Library.cs @@ -29,5 +29,7 @@ public static partial class Errors public static Error PathTemplateValuePartMustContainSinglePlaceholder => Error.Validation(description: nameof(PathTemplateValuePartMustContainSinglePlaceholder)); public static Error PathTemplatePartKindNotSupportedForLibraryType => Error.Validation(description: nameof(PathTemplatePartKindNotSupportedForLibraryType)); public static Error PathTemplateIsNotSupportedForLibraryType => Error.Validation(description: nameof(PathTemplateIsNotSupportedForLibraryType)); + public static Error CompletionThresholdPercentageMustBeNullWhenProgressTrackingIsOff => Error.Validation(description: nameof(CompletionThresholdPercentageMustBeNullWhenProgressTrackingIsOff)); + public static Error CompletionThresholdPercentageMustBeBetweenZeroAndOneHundred => Error.Validation(description: nameof(CompletionThresholdPercentageMustBeBetweenZeroAndOneHundred)); } } diff --git a/src/Lumina.Domain/Common/Errors/Errors.MediaConsumption.cs b/src/Lumina.Domain/Common/Errors/Errors.MediaConsumption.cs new file mode 100644 index 00000000..09a5a71a --- /dev/null +++ b/src/Lumina.Domain/Common/Errors/Errors.MediaConsumption.cs @@ -0,0 +1,37 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Primitives; +#endregion + +namespace Lumina.Domain.Common.Errors; + +/// +/// Media consumption error types. +/// +public static partial class Errors +{ + public static class MediaConsumption + { + public static Error UnsupportedMediaKind => Error.Validation(description: nameof(UnsupportedMediaKind)); + public static Error MediaKindCannotStartCompleted => Error.Forbidden(description: nameof(MediaKindCannotStartCompleted)); + public static Error MediaKindCannotResume => Error.Forbidden(description: nameof(MediaKindCannotResume)); + public static Error ConsumptionRecordNotFound => Error.NotFound(description: nameof(ConsumptionRecordNotFound)); + public static Error MediaResumePointNotFound => Error.NotFound(description: nameof(MediaResumePointNotFound)); + public static Error ConsumptionRecordIdCannotBeEmpty => Error.Validation(description: nameof(ConsumptionRecordIdCannotBeEmpty)); + public static Error MediaItemIdCannotBeEmpty => Error.Validation(description: nameof(MediaItemIdCannotBeEmpty)); + public static Error TargetUserIdIsInvalid => Error.Validation(description: nameof(TargetUserIdIsInvalid)); + public static Error ConsumptionDateRangeIsInvalid => Error.Validation(description: nameof(ConsumptionDateRangeIsInvalid)); + public static Error InvalidMediaPosition => Error.Validation(description: nameof(InvalidMediaPosition)); + public static Error InvalidProgressFraction => Error.Validation(description: nameof(InvalidProgressFraction)); + public static Error ConsumedDurationMustBeNonNegative => Error.Validation(description: nameof(ConsumedDurationMustBeNonNegative)); + public static Error ConsumedDurationIsOutOfRange => Error.Validation(description: nameof(ConsumedDurationIsOutOfRange)); + public static Error ConsumedDurationCannotDecrease => Error.Forbidden(description: nameof(ConsumedDurationCannotDecrease)); + public static Error ConsecutivePagesReadMustBeNonNegative => Error.Validation(description: nameof(ConsecutivePagesReadMustBeNonNegative)); + public static Error ConsecutivePagesReadIsOnlySupportedForPageBasedMedia => Error.Forbidden(description: nameof(ConsecutivePagesReadIsOnlySupportedForPageBasedMedia)); + public static Error ConsumptionIsNotInProgress => Error.Conflict(description: nameof(ConsumptionIsNotInProgress)); + public static Error ConsumptionIsAlreadyTerminal => Error.Conflict(description: nameof(ConsumptionIsAlreadyTerminal)); + public static Error InProgressConsumptionCannotHaveEndTime => Error.Validation(description: nameof(InProgressConsumptionCannotHaveEndTime)); + public static Error EndedConsumptionMustHaveEndTime => Error.Validation(description: nameof(EndedConsumptionMustHaveEndTime)); + public static Error LastActivityCannotPrecedeStart => Error.Forbidden(description: nameof(LastActivityCannotPrecedeStart)); + public static Error EndedConsumptionCannotPrecedeLastActivity => Error.Forbidden(description: nameof(EndedConsumptionCannotPrecedeLastActivity)); + } +} diff --git a/src/Lumina.Domain/Common/Errors/Errors.Music.cs b/src/Lumina.Domain/Common/Errors/Errors.Music.cs index b636930d..f3031651 100644 --- a/src/Lumina.Domain/Common/Errors/Errors.Music.cs +++ b/src/Lumina.Domain/Common/Errors/Errors.Music.cs @@ -38,6 +38,7 @@ public static partial class Errors public static Error UnknownMusicKey => Error.Validation(description: nameof(UnknownMusicKey)); public static Error CatalogNumberMustBeMaximum50CharactersLong => Error.Validation(description: nameof(CatalogNumberMustBeMaximum50CharactersLong)); public static Error TrackNotFound => Error.NotFound(description: nameof(TrackNotFound)); + public static Error TrackFileNotFound => Error.NotFound(description: nameof(TrackFileNotFound)); public static Error TrackAlreadyExists => Error.Conflict(description: nameof(TrackAlreadyExists)); public static Error TrackIdCannotBeEmpty => Error.Validation(description: nameof(TrackIdCannotBeEmpty)); public static Error TracksListCannotBeNull => Error.Validation(description: nameof(TracksListCannotBeNull)); @@ -66,5 +67,7 @@ public static partial class Errors public static Error IsniValueMustBeMaximum20CharactersLong => Error.Validation(description: nameof(IsniValueMustBeMaximum20CharactersLong)); public static Error WorkTitleCannotBeEmpty => Error.Validation(description: nameof(WorkTitleCannotBeEmpty)); public static Error CoverCannotBeNull => Error.Validation(description: nameof(CoverCannotBeNull)); + public static Error ShuffleTrackCountMustBeGreaterThanZero => Error.Validation(description: nameof(ShuffleTrackCountMustBeGreaterThanZero)); + public static Error ShuffleTrackCountMustBeAtMost500 => Error.Validation(description: nameof(ShuffleTrackCountMustBeAtMost500)); } } diff --git a/src/Lumina.Domain/Common/Errors/Errors.Playback.cs b/src/Lumina.Domain/Common/Errors/Errors.Playback.cs new file mode 100644 index 00000000..c18c8c5a --- /dev/null +++ b/src/Lumina.Domain/Common/Errors/Errors.Playback.cs @@ -0,0 +1,32 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Primitives; +#endregion + +namespace Lumina.Domain.Common.Errors; + +/// +/// Domain playback related error types. +/// +public static partial class Errors +{ + public static class Playback + { + public static Error NoSupportedPlaybackFormat => Error.Forbidden(description: nameof(NoSupportedPlaybackFormat)); + public static Error PlaybackDeliveryChanged => Error.Conflict(description: nameof(PlaybackDeliveryChanged)); + public static Error PlaybackDeliveryNotFound => Error.NotFound(description: nameof(PlaybackDeliveryNotFound)); + public static Error DeliveryIdCannotBeEmpty => Error.Validation(description: nameof(DeliveryIdCannotBeEmpty)); + public static Error DeliveryIdIsInvalid => Error.Validation(description: nameof(DeliveryIdIsInvalid)); + public static Error PlaybackFormatNotImplemented => Error.Internal(description: nameof(PlaybackFormatNotImplemented)); + public static Error NormalizedTrackCacheEntryNotFound => Error.NotFound(description: nameof(NormalizedTrackCacheEntryNotFound)); + public static Error NormalizedTrackSegmentNotFound => Error.NotFound(description: nameof(NormalizedTrackSegmentNotFound)); + public static Error NormalizationFailed => Error.Failure(description: nameof(NormalizationFailed)); + public static Error NormalizationCacheLimitExceeded => Error.Failure(description: nameof(NormalizationCacheLimitExceeded)); + public static Error NormalizationTimedOut => Error.Timeout(description: nameof(NormalizationTimedOut)); + public static Error NormalizationUnavailable => Error.ResourceUnavailable(description: nameof(NormalizationUnavailable)); + public static Error NormalizationIsNotRequiredForDirectPlay => Error.Conflict(description: nameof(NormalizationIsNotRequiredForDirectPlay)); + public static Error SegmentDurationMustBePositive => Error.Validation(description: nameof(SegmentDurationMustBePositive)); + public static Error SegmentIndexCannotBeEmpty => Error.Validation(description: nameof(SegmentIndexCannotBeEmpty)); + public static Error SegmentIndexMustBeValid => Error.Validation(description: nameof(SegmentIndexMustBeValid)); + public static Error TrackDurationMustBePositive => Error.Validation(description: nameof(TrackDurationMustBePositive)); + } +} diff --git a/src/Lumina.Domain/Common/Errors/Errors.Playlist.cs b/src/Lumina.Domain/Common/Errors/Errors.Playlist.cs new file mode 100644 index 00000000..01245db5 --- /dev/null +++ b/src/Lumina.Domain/Common/Errors/Errors.Playlist.cs @@ -0,0 +1,27 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Primitives; +#endregion + +namespace Lumina.Domain.Common.Errors; + +/// +/// Playlist error types. +/// +public static partial class Errors +{ + public static class Playlists + { + public static Error PlaylistNotFound => Error.NotFound(description: nameof(PlaylistNotFound)); + public static Error PlaylistAlreadyExists => Error.Conflict(description: nameof(PlaylistAlreadyExists)); + public static Error PlaylistIdCannotBeEmpty => Error.Validation(description: nameof(PlaylistIdCannotBeEmpty)); + public static Error PlaylistEntryIdCannotBeEmpty => Error.Validation(description: nameof(PlaylistEntryIdCannotBeEmpty)); + public static Error PlaylistNameCannotBeEmpty => Error.Validation(description: nameof(PlaylistNameCannotBeEmpty)); + public static Error PlaylistNameMustBeMaximum255CharactersLong => Error.Validation(description: nameof(PlaylistNameMustBeMaximum255CharactersLong)); + public static Error PlaylistDescriptionMustBeMaximum2000CharactersLong => Error.Validation(description: nameof(PlaylistDescriptionMustBeMaximum2000CharactersLong)); + public static Error PlaylistTypeIsInvalid => Error.Validation(description: nameof(PlaylistTypeIsInvalid)); + public static Error PlaylistDoesNotAcceptMediaItems => Error.Forbidden(description: nameof(PlaylistDoesNotAcceptMediaItems)); + public static Error PlaylistEntryNotFound => Error.NotFound(description: nameof(PlaylistEntryNotFound)); + public static Error PlaylistEntryPositionsAreInvalid => Error.Validation(description: nameof(PlaylistEntryPositionsAreInvalid)); + public static Error PlaylistMoveTargetPositionIsInvalid => Error.Validation(description: nameof(PlaylistMoveTargetPositionIsInvalid)); + } +} diff --git a/src/Lumina.Domain/Common/Errors/Errors.UserSettings.cs b/src/Lumina.Domain/Common/Errors/Errors.UserSettings.cs index 4778b3f2..ae7a784f 100644 --- a/src/Lumina.Domain/Common/Errors/Errors.UserSettings.cs +++ b/src/Lumina.Domain/Common/Errors/Errors.UserSettings.cs @@ -14,5 +14,33 @@ public static partial class Errors public static Error UserSettingsAlreadyExists => Error.Conflict(description: nameof(UserSettingsAlreadyExists)); public static Error UserSettingsNotFound => Error.NotFound(description: nameof(UserSettingsNotFound)); public static Error ItemsPerPageMustBeGreaterThanZero => Error.Validation(description: nameof(ItemsPerPageMustBeGreaterThanZero)); + public static Error VolumeCannotBeNull => Error.Validation(description: nameof(VolumeCannotBeNull)); + public static Error VolumeMustBeBetweenZeroAndOne => Error.Validation(description: nameof(VolumeMustBeBetweenZeroAndOne)); + public static Error IsMutedCannotBeNull => Error.Validation(description: nameof(IsMutedCannotBeNull)); + public static Error ShouldKeepDownloadingWhilePausedCannotBeNull => Error.Validation(description: nameof(ShouldKeepDownloadingWhilePausedCannotBeNull)); + public static Error ShouldAutoplayCannotBeNull => Error.Validation(description: nameof(ShouldAutoplayCannotBeNull)); + public static Error IsGaplessPlaybackEnabledCannotBeNull => Error.Validation(description: nameof(IsGaplessPlaybackEnabledCannotBeNull)); + public static Error ReplayGainModeCannotBeNull => Error.Validation(description: nameof(ReplayGainModeCannotBeNull)); + public static Error StreamingQualityCannotBeNull => Error.Validation(description: nameof(StreamingQualityCannotBeNull)); + public static Error InvalidReplayGainMode => Error.Validation(description: nameof(InvalidReplayGainMode)); + public static Error InvalidStreamingQuality => Error.Validation(description: nameof(InvalidStreamingQuality)); + public static Error VuMeterOrientationCannotBeNull => Error.Validation(description: nameof(VuMeterOrientationCannotBeNull)); + public static Error InvalidVuMeterOrientation => Error.Validation(description: nameof(InvalidVuMeterOrientation)); + public static Error VuMeterSegmentCountCannotBeNull => Error.Validation(description: nameof(VuMeterSegmentCountCannotBeNull)); + public static Error VuMeterSegmentCountMustBeBetweenOneAndOneHundredTwentyEight => Error.Validation(description: nameof(VuMeterSegmentCountMustBeBetweenOneAndOneHundredTwentyEight)); + public static Error VuMeterSegmentGapCannotBeNull => Error.Validation(description: nameof(VuMeterSegmentGapCannotBeNull)); + public static Error VuMeterSegmentGapMustBeBetweenZeroAndThirtyTwo => Error.Validation(description: nameof(VuMeterSegmentGapMustBeBetweenZeroAndThirtyTwo)); + public static Error VuMeterMediumThresholdCannotBeNull => Error.Validation(description: nameof(VuMeterMediumThresholdCannotBeNull)); + public static Error VuMeterMediumThresholdMustBeBetweenZeroAndOne => Error.Validation(description: nameof(VuMeterMediumThresholdMustBeBetweenZeroAndOne)); + public static Error VuMeterHighThresholdCannotBeNull => Error.Validation(description: nameof(VuMeterHighThresholdCannotBeNull)); + public static Error VuMeterHighThresholdMustBeBetweenZeroAndOne => Error.Validation(description: nameof(VuMeterHighThresholdMustBeBetweenZeroAndOne)); + public static Error VuMeterHighThresholdMustBeGreaterThanOrEqualToMediumThreshold => Error.Validation(description: nameof(VuMeterHighThresholdMustBeGreaterThanOrEqualToMediumThreshold)); + public static Error VuMeterShowPeakCannotBeNull => Error.Validation(description: nameof(VuMeterShowPeakCannotBeNull)); + public static Error VuMeterPeakHoldDurationCannotBeNull => Error.Validation(description: nameof(VuMeterPeakHoldDurationCannotBeNull)); + public static Error VuMeterPeakHoldDurationMustBeBetweenZeroAndTenThousandMilliseconds => Error.Validation(description: nameof(VuMeterPeakHoldDurationMustBeBetweenZeroAndTenThousandMilliseconds)); + public static Error VuMeterReleasePerSecondCannotBeNull => Error.Validation(description: nameof(VuMeterReleasePerSecondCannotBeNull)); + public static Error VuMeterReleasePerSecondMustBeBetweenZeroAndOneHundred => Error.Validation(description: nameof(VuMeterReleasePerSecondMustBeBetweenZeroAndOneHundred)); + public static Error VuMeterPeakReleasePerSecondCannotBeNull => Error.Validation(description: nameof(VuMeterPeakReleasePerSecondCannotBeNull)); + public static Error VuMeterPeakReleasePerSecondMustBeBetweenZeroAndOneHundred => Error.Validation(description: nameof(VuMeterPeakReleasePerSecondMustBeBetweenZeroAndOneHundred)); } } diff --git a/src/Lumina.Domain/Common/Events/IDomainEventHandler.cs b/src/Lumina.Domain/Common/Events/IDomainEventHandler.cs index 9209e99d..14354c5d 100644 --- a/src/Lumina.Domain/Common/Events/IDomainEventHandler.cs +++ b/src/Lumina.Domain/Common/Events/IDomainEventHandler.cs @@ -15,7 +15,7 @@ public interface IDomainEventHandler where TDomainEvent : IDomainE /// Handles the specified . /// /// The domain event to handle. - /// Token to monitor for cancellation requests. + /// Cancellation token that can be used to stop the execution. /// A task that represents the asynchronous operation. ValueTask HandleAsync(TDomainEvent domainEvent, CancellationToken cancellationToken); } diff --git a/src/Lumina.Domain/Common/Events/IDomainEventPublisher.cs b/src/Lumina.Domain/Common/Events/IDomainEventPublisher.cs index df8b69fa..1529fd61 100644 --- a/src/Lumina.Domain/Common/Events/IDomainEventPublisher.cs +++ b/src/Lumina.Domain/Common/Events/IDomainEventPublisher.cs @@ -14,7 +14,7 @@ public interface IDomainEventPublisher /// Publishes the specified to all its registered handlers, in registration order. /// /// The domain event to publish. - /// Token to monitor for cancellation requests. + /// Cancellation token that can be used to stop the execution. /// A task that represents the asynchronous operation. ValueTask PublishAsync(IDomainEvent domainEvent, CancellationToken cancellationToken = default); } diff --git a/src/Lumina.Domain/Common/ValueObjects/Metadata/Genre.cs b/src/Lumina.Domain/Common/ValueObjects/Metadata/Genre.cs index b95ca9e8..c20c7957 100644 --- a/src/Lumina.Domain/Common/ValueObjects/Metadata/Genre.cs +++ b/src/Lumina.Domain/Common/ValueObjects/Metadata/Genre.cs @@ -14,17 +14,17 @@ namespace Lumina.Domain.Common.ValueObjects.Metadata; public class Genre : ValueObject { /// - /// Gets the name of the genre element of the media item. + /// Gets the name of the genre element of the media item, in lowercase and culture-invariant form. /// public string Name { get; } /// /// Initializes a new instance of the class. /// - /// The value representing this object. + /// The value representing this object, which is trimmed and lowercased with the invariant culture. private Genre(string name) { - Name = name.Trim(); + Name = name.Trim().ToLowerInvariant(); } /// diff --git a/src/Lumina.Domain/Common/ValueObjects/Metadata/Tag.cs b/src/Lumina.Domain/Common/ValueObjects/Metadata/Tag.cs index c55a60b0..8f9b7b8b 100644 --- a/src/Lumina.Domain/Common/ValueObjects/Metadata/Tag.cs +++ b/src/Lumina.Domain/Common/ValueObjects/Metadata/Tag.cs @@ -15,17 +15,17 @@ namespace Lumina.Domain.Common.ValueObjects.Metadata; public class Tag : ValueObject { /// - /// Gets the name of the tag element of the media item. + /// Gets the name of the tag element of the media item, in lowercase and culture-invariant form. /// public string Name { get; } /// /// Initializes a new instance of the class. /// - /// The value representing this object. + /// The value representing this object, which is trimmed and lowercased with the invariant culture. private Tag(string name) { - Name = name.Trim(); + Name = name.Trim().ToLowerInvariant(); } /// diff --git a/src/Lumina.Domain/Core/BoundedContexts/AudioLibraryBoundedContext/Common/ValueObjects/AudioMetadata.cs b/src/Lumina.Domain/Core/BoundedContexts/AudioLibraryBoundedContext/Common/ValueObjects/AudioMetadata.cs index 27db4eda..9b16e989 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/AudioLibraryBoundedContext/Common/ValueObjects/AudioMetadata.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/AudioLibraryBoundedContext/Common/ValueObjects/AudioMetadata.cs @@ -38,6 +38,11 @@ public class AudioMetadata : BaseMetadata /// public Optional AudioCodec { get; } + /// + /// Gets the container of the audio, as read from the file itself, for example MP3, FLAC, OGG, AAC, MP4 or WAV. + /// + public Optional Container { get; } + /// /// Gets the bitrate of the audio in kbps. /// @@ -82,6 +87,7 @@ public class AudioMetadata : BaseMetadata /// The optional original language of the audio. /// The bit depth of the audio. /// The audio codec used. + /// The container of the audio. /// The genres of the audio. /// The tags associated with the audio. /// The bitrate of the audio in kbps. @@ -104,6 +110,7 @@ public class AudioMetadata : BaseMetadata Optional originalLanguage, Optional bitDepth, Optional audioCodec, + Optional container, Optional bitrate, Optional acoustId, Optional replayGainTrackGain, @@ -117,6 +124,7 @@ public class AudioMetadata : BaseMetadata Channels = channels; BitDepth = bitDepth; AudioCodec = audioCodec; + Container = container; Bitrate = bitrate; AcoustId = acoustId; ReplayGainTrackGain = replayGainTrackGain; @@ -139,6 +147,7 @@ public class AudioMetadata : BaseMetadata /// The optional original language of the audio. /// The bit depth of the audio. /// The audio codec used. + /// The container of the audio. /// The genres of the audio. /// The tags associated with the audio. /// The bitrate of the audio in kbps. @@ -164,6 +173,7 @@ public class AudioMetadata : BaseMetadata Optional originalLanguage, Optional bitDepth, Optional audioCodec, + Optional container, Optional bitrate, Optional acoustId, Optional replayGainTrackGain, @@ -185,6 +195,7 @@ public class AudioMetadata : BaseMetadata originalLanguage, bitDepth, audioCodec, + container, bitrate, acoustId, replayGainTrackGain, @@ -193,6 +204,38 @@ public class AudioMetadata : BaseMetadata replayGainAlbumPeak); } + /// + /// Creates a copy of this audio metadata with the provided , keeping every other property unchanged. + /// + /// The container of the audio. + /// + /// An containing either a copy of this audio metadata with the provided container, or an error message. + /// + internal Result WithContainer(Optional container) + { + return Create( + Title, + OriginalTitle, + DurationInSeconds, + SampleRate, + Channels, + ReleaseInfo, + Description, + [.. Genres], + [.. Tags], + Language, + OriginalLanguage, + BitDepth, + AudioCodec, + container, + Bitrate, + AcoustId, + ReplayGainTrackGain, + ReplayGainTrackPeak, + ReplayGainAlbumGain, + ReplayGainAlbumPeak); + } + /// /// Gets the list of items that define equality of the object. /// @@ -206,6 +249,7 @@ public class AudioMetadata : BaseMetadata yield return Channels; yield return BitDepth; yield return AudioCodec; + yield return Container; yield return Bitrate; yield return AcoustId; yield return ReplayGainTrackGain; diff --git a/src/Lumina.Domain/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/Artist.cs b/src/Lumina.Domain/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/Artist.cs index 5a5043f2..9fda2db6 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/Artist.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/Artist.cs @@ -638,11 +638,11 @@ public sealed class Artist : AggregateRoot /// /// A track is a child entity of the artist aggregate, not an aggregate root, so it is mutated through its owning artist, /// which is the consistency boundary. Book is itself an aggregate root, so its update flow reconstitutes it directly - /// with its own Create method instead. This difference is intentional. + /// with its own Create method instead. This difference is intentional. The file system path of the track is never updated + /// here: a track path is set only when the track is created by the scanner. /// /// The album the track belongs to. /// The track to update. - /// The file system path of the track. /// The audio metadata of the track. /// The optional disambiguation comment of the track. /// The number of the track on its disc. @@ -662,7 +662,6 @@ public sealed class Artist : AggregateRoot public Result UpdateTrackInAlbum( Album album, Track track, - string path, AudioMetadata metadata, Optional disambiguation, int trackNumber, @@ -686,7 +685,6 @@ public sealed class Artist : AggregateRoot return Errors.Music.TrackNotFound; track.UpdateDetails( - path, metadata, disambiguation, trackNumber, diff --git a/src/Lumina.Domain/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/Entities/Track.cs b/src/Lumina.Domain/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/Entities/Track.cs index 0f3842a4..196f5276 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/Entities/Track.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/Entities/Track.cs @@ -343,9 +343,13 @@ public sealed class Track : Entity } /// - /// Updates the details of the track, without touching the moods, the ISRCs, the media contributors, and the ratings. + /// Updates the details of the track, without touching the file system path, the moods, the ISRCs, the media contributors, and the ratings. /// - /// The file system path of the track. + /// + /// The file system path is intentionally not editable here: it is set only when the track is created by the scanner, so that a client + /// can never point an existing track at an arbitrary file of the host. The container is captured from the file itself and is not part of + /// an edit either, so an update that does not carry one keeps the container already stored for the track. + /// /// The audio metadata of the track. /// The optional disambiguation comment of the track. /// The number of the track on its disc. @@ -359,7 +363,6 @@ public sealed class Track : Entity /// The optional MusicBrainz identifier of the track. /// An representing either a successful operation, or an error. internal Result UpdateDetails( - string path, AudioMetadata metadata, Optional disambiguation, int trackNumber, @@ -372,8 +375,16 @@ public sealed class Track : Entity Optional musicBrainzRecordingId, Optional musicBrainzTrackId) { - Path = path; - Metadata = metadata; + // The container is captured from the file itself and is never part of an edit, so an update that does not carry one keeps the stored container. + if (metadata.Container.HasValue) + Metadata = metadata; + else + { + Result metadataWithStoredContainerResult = metadata.WithContainer(Metadata.Container); + if (metadataWithStoredContainerResult.IsFailure) + return metadataWithStoredContainerResult.Errors; + Metadata = metadataWithStoredContainerResult.Value; + } Disambiguation = disambiguation; TrackNumber = trackNumber; DiscNumber = discNumber; diff --git a/src/Lumina.Domain/Core/BoundedContexts/FavoriteBoundedContext/ExternalIdentifiers/MediaLibraryBoundedContext/MediaItemAggregate/MediaItemId.cs b/src/Lumina.Domain/Core/BoundedContexts/FavoriteBoundedContext/ExternalIdentifiers/MediaLibraryBoundedContext/MediaItemAggregate/MediaItemId.cs new file mode 100644 index 00000000..ae51d775 --- /dev/null +++ b/src/Lumina.Domain/Core/BoundedContexts/FavoriteBoundedContext/ExternalIdentifiers/MediaLibraryBoundedContext/MediaItemAggregate/MediaItemId.cs @@ -0,0 +1,51 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Models.Core; +using System; +using System.Collections.Generic; +using System.Diagnostics; +#endregion + +namespace Lumina.Domain.Core.BoundedContexts.FavoriteBoundedContext.ExternalIdentifiers.MediaLibraryBoundedContext.MediaItemAggregate; + +/// +/// Value Object for the Id of a media item, declared by the favorite bounded context to keep the reference to the catalogue decoupled. +/// +[DebuggerDisplay("{Value}")] +public sealed class MediaItemId : EntityId +{ + /// + /// Initializes a new instance of the class. + /// + /// The value representing this object. + private MediaItemId(Guid value) : base(value) + { + } + + /// + /// Creates a new instance of the class. + /// + /// The created instance. + public static MediaItemId CreateUnique() + { + return new MediaItemId(Guid.NewGuid()); + } + + /// + /// Creates a new instance of the class, from a pre-existing . + /// + /// The value used to create the instance. + /// The created instance. + public static MediaItemId Create(Guid value) + { + return new MediaItemId(value); + } + + /// + /// Gets the list of items that define equality of the object. + /// + /// A list of items defining the equality. + public override IEnumerable GetEqualityComponents() + { + yield return Value; + } +} diff --git a/src/Lumina.Domain/Core/BoundedContexts/FavoriteBoundedContext/ExternalIdentifiers/UserManagementBoundedContext/UserAggregate/UserId.cs b/src/Lumina.Domain/Core/BoundedContexts/FavoriteBoundedContext/ExternalIdentifiers/UserManagementBoundedContext/UserAggregate/UserId.cs new file mode 100644 index 00000000..c39f4000 --- /dev/null +++ b/src/Lumina.Domain/Core/BoundedContexts/FavoriteBoundedContext/ExternalIdentifiers/UserManagementBoundedContext/UserAggregate/UserId.cs @@ -0,0 +1,51 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Models.Core; +using System; +using System.Collections.Generic; +using System.Diagnostics; +#endregion + +namespace Lumina.Domain.Core.BoundedContexts.FavoriteBoundedContext.ExternalIdentifiers.UserManagementBoundedContext.UserAggregate; + +/// +/// Value Object for the Id of a user, duplicated from the UserManagement bounded context to keep the cross bounded context references decoupled. +/// +[DebuggerDisplay("{Value}")] +public sealed class UserId : EntityId +{ + /// + /// Initializes a new instance of the class. + /// + /// The value representing this object. + private UserId(Guid value) : base(value) + { + } + + /// + /// Creates a new instance of the class. + /// + /// The created instance. + public static UserId CreateUnique() + { + return new UserId(Guid.NewGuid()); + } + + /// + /// Creates a new instance of the class, from a pre-existing . + /// + /// The value used to create the instance. + /// The created instance. + public static UserId Create(Guid value) + { + return new UserId(value); + } + + /// + /// Gets the list of items that define equality of the object. + /// + /// A list of items defining the equality. + public override IEnumerable GetEqualityComponents() + { + yield return Value; + } +} diff --git a/src/Lumina.Domain/Core/BoundedContexts/FavoriteBoundedContext/FavoriteAggregate/Events/FavoriteAddedDomainEvent.cs b/src/Lumina.Domain/Core/BoundedContexts/FavoriteBoundedContext/FavoriteAggregate/Events/FavoriteAddedDomainEvent.cs new file mode 100644 index 00000000..198eee38 --- /dev/null +++ b/src/Lumina.Domain/Core/BoundedContexts/FavoriteBoundedContext/FavoriteAggregate/Events/FavoriteAddedDomainEvent.cs @@ -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; + +/// +/// Domain event raised when a media item is marked as a favorite. +/// +/// The unique identifier of the domain event. +/// The unique identifier of the favorite. +/// The unique identifier of the user that favorited the media item. +/// The unique identifier of the favorited media item. +/// The kind of the favorited media item. +/// The date and time when the domain event occurred. +[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; diff --git a/src/Lumina.Domain/Core/BoundedContexts/FavoriteBoundedContext/FavoriteAggregate/Events/FavoriteRemovedDomainEvent.cs b/src/Lumina.Domain/Core/BoundedContexts/FavoriteBoundedContext/FavoriteAggregate/Events/FavoriteRemovedDomainEvent.cs new file mode 100644 index 00000000..da91c20a --- /dev/null +++ b/src/Lumina.Domain/Core/BoundedContexts/FavoriteBoundedContext/FavoriteAggregate/Events/FavoriteRemovedDomainEvent.cs @@ -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; + +/// +/// Domain event raised when a media item is removed from the favorites. +/// +/// The unique identifier of the domain event. +/// The unique identifier of the favorite. +/// The unique identifier of the user that owned the favorite. +/// The unique identifier of the media item that was unfavorited. +/// The kind of the media item that was unfavorited. +/// The date and time when the domain event occurred. +[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; diff --git a/src/Lumina.Domain/Core/BoundedContexts/FavoriteBoundedContext/FavoriteAggregate/Favorite.cs b/src/Lumina.Domain/Core/BoundedContexts/FavoriteBoundedContext/FavoriteAggregate/Favorite.cs new file mode 100644 index 00000000..a8b15f6e --- /dev/null +++ b/src/Lumina.Domain/Core/BoundedContexts/FavoriteBoundedContext/FavoriteAggregate/Favorite.cs @@ -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; + +/// +/// Aggregate root for a favorite, the marker a user places on a media item. +/// +[DebuggerDisplay("Id: {Id.Value}; MediaKind: {MediaKind}; MediaItemId: {MediaItemId.Value}")] +public sealed class Favorite : AggregateRoot +{ + /// + /// Gets the object representing the unique identifier of the user that owns the favorite. + /// + public UserId UserId { get; private set; } + + /// + /// Gets the Id of the favorited media item. + /// + public MediaItemId MediaItemId { get; private set; } + + /// + /// Gets the kind of the favorited media item. + /// + public FavoriteMediaKind MediaKind { get; private set; } + + /// + /// Gets a value indicating whether the favorite was marked for removal in this unit of work. + /// + public bool IsRemoved { get; private set; } + + /// + /// Initializes a new instance of the class. + /// + /// The object representing the unique identifier of the favorite. + /// The object representing the unique identifier of the user that owns the favorite. + /// The Id of the favorited media item. + /// The kind of the favorited media item. + /// The date and time when the favorite was created. + /// The date and time when the favorite was last updated. + private Favorite( + FavoriteId id, + UserId userId, + MediaItemId mediaItemId, + FavoriteMediaKind mediaKind, + DateTime createdOnUtc, + Optional updatedOnUtc) : base(id) + { + Id = id; + UserId = userId; + MediaItemId = mediaItemId; + MediaKind = mediaKind; + CreatedOnUtc = createdOnUtc; + UpdatedOnUtc = updatedOnUtc; + } + + /// + /// Creates a new favorite of the media item identified by for the user identified by . + /// + /// The object representing the unique identifier of the user that owns the favorite. + /// The Id of the media item to favorite. + /// The kind of the media item to favorite. + /// + /// An containing either a successfully created , or an error message. + /// + public static Result 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.None()); + + favorite._domainEvents.Add(new FavoriteAddedDomainEvent( + Guid.NewGuid(), + favorite.Id, + userId, + mediaItemId, + mediaKind, + occurredOnUtc)); + return favorite; + } + + /// + /// Creates a new instance of the class, with pre-existing data. + /// + /// The object representing the unique identifier of the favorite. + /// The object representing the unique identifier of the user that owns the favorite. + /// The Id of the favorited media item. + /// The kind of the favorited media item. + /// The date and time when the favorite was created. + /// The date and time when the favorite was last updated. + /// + /// An containing either a successfully created , or an error message. + /// + public static Result Create( + FavoriteId id, + UserId userId, + MediaItemId mediaItemId, + FavoriteMediaKind mediaKind, + DateTime createdOnUtc, + Optional 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); + } + + /// + /// Marks the favorite as removed, raising the domain event that announces its removal. + /// + /// An representing either a successful operation, or an error. + public Result 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; + } + + /// + /// Determines whether media items of can be favorited today. + /// + /// The kind of media item. + /// if items of the media kind can be favorited, otherwise. + public static bool IsSupported(FavoriteMediaKind mediaKind) + { + return mediaKind switch + { + FavoriteMediaKind.MusicArtist => true, + FavoriteMediaKind.MusicAlbum => true, + FavoriteMediaKind.MusicTrack => true, + FavoriteMediaKind.Book => true, + _ => false + }; + } +} diff --git a/src/Lumina.Domain/Core/BoundedContexts/FavoriteBoundedContext/FavoriteAggregate/ValueObjects/FavoriteId.cs b/src/Lumina.Domain/Core/BoundedContexts/FavoriteBoundedContext/FavoriteAggregate/ValueObjects/FavoriteId.cs new file mode 100644 index 00000000..d2e89791 --- /dev/null +++ b/src/Lumina.Domain/Core/BoundedContexts/FavoriteBoundedContext/FavoriteAggregate/ValueObjects/FavoriteId.cs @@ -0,0 +1,51 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Models.Core; +using System; +using System.Collections.Generic; +using System.Diagnostics; +#endregion + +namespace Lumina.Domain.Core.BoundedContexts.FavoriteBoundedContext.FavoriteAggregate.ValueObjects; + +/// +/// Value Object for the Id of a favorite. +/// +[DebuggerDisplay("{Value}")] +public sealed class FavoriteId : EntityId +{ + /// + /// Initializes a new instance of the class. + /// + /// The value representing this object. + private FavoriteId(Guid value) : base(value) + { + } + + /// + /// Creates a new instance of the class. + /// + /// The created instance. + public static FavoriteId CreateUnique() + { + return new FavoriteId(Guid.NewGuid()); + } + + /// + /// Creates a new instance of the class, from a pre-existing . + /// + /// The value used to create the instance. + /// The created instance. + public static FavoriteId Create(Guid value) + { + return new FavoriteId(value); + } + + /// + /// Gets the list of items that define equality of the object. + /// + /// A list of items defining the equality. + public override IEnumerable GetEqualityComponents() + { + yield return Value; + } +} diff --git a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/Library.cs b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/Library.cs index 546bfde3..5bc0f89e 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/Library.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/Library.cs @@ -76,6 +76,11 @@ public class Library : AggregateRoot /// public bool ShouldSkipUnchangedDirectoriesDuringScan { get; private set; } + /// + /// Gets the consumption settings of the media library. + /// + public LibraryConsumptionSettings ConsumptionSettings { get; private set; } + /// /// Gets the template describing the structure of the media library on disk, always populated with the effective template: the one specified by the /// user, or the ideal structure of the library type when none was provided. @@ -106,6 +111,7 @@ public class Library : AggregateRoot /// Whether this media library should update the metadata of its elements from the web, or not. /// Whether this media library should copy the downloaded metadata into the media library content locations, or not. /// Whether this media library should skip the directories whose contents have not changed since the last scan, during the scan, or not. + /// The consumption settings of the media library. /// The template describing the structure of the media library on disk. /// The list of objects representing the unique identifier of scans of the media library. private Library( @@ -120,6 +126,7 @@ public class Library : AggregateRoot bool canDownloadMetadataFromWeb, bool shouldSaveMetadataInMediaDirectories, bool shouldSkipUnchangedDirectoriesDuringScan, + LibraryConsumptionSettings consumptionSettings, LibraryPathTemplate pathTemplate, List scanIds) : base(id) { @@ -133,6 +140,7 @@ public class Library : AggregateRoot CanDownloadMetadataFromWeb = canDownloadMetadataFromWeb; ShouldSaveMetadataInMediaDirectories = shouldSaveMetadataInMediaDirectories; ShouldSkipUnchangedDirectoriesDuringScan = shouldSkipUnchangedDirectoriesDuringScan; + ConsumptionSettings = consumptionSettings; PathTemplate = pathTemplate; _scanIds = scanIds; } @@ -150,6 +158,7 @@ public class Library : AggregateRoot /// Whether this media library should update the metadata of its elements from the web, or not. /// Whether this media library should copy the downloaded metadata into the media library content locations, or not. /// Whether this media library should skip the directories whose contents have not changed since the last scan, during the scan, or not. + /// The consumption settings of the media library. /// The template describing the structure of the media library on disk. /// The list of objects representing the unique identifier of scans of the media library. /// @@ -166,6 +175,7 @@ public class Library : AggregateRoot bool canDownloadMetadataFromWeb, bool shouldSaveMetadataInMediaDirectories, bool shouldSkipUnchangedDirectoriesDuringScan, + LibraryConsumptionSettings consumptionSettings, LibraryPathTemplate pathTemplate, List scanIds) { @@ -190,6 +200,7 @@ public class Library : AggregateRoot canDownloadMetadataFromWeb, shouldSaveMetadataInMediaDirectories, shouldSkipUnchangedDirectoriesDuringScan, + consumptionSettings, pathTemplate, scanIds ); @@ -209,6 +220,7 @@ public class Library : AggregateRoot /// Whether this media library should update the metadata of its elements from the web, or not. /// Whether this media library should copy the downloaded metadata into the media library content locations, or not. /// Whether this media library should skip the directories whose contents have not changed since the last scan, during the scan, or not. + /// The consumption settings of the media library. /// The template describing the structure of the media library on disk. /// The list of objects representing the unique identifier of scans of the media library. /// @@ -226,6 +238,7 @@ public class Library : AggregateRoot bool canDownloadMetadataFromWeb, bool shouldSaveMetadataInMediaDirectories, bool shouldSkipUnchangedDirectoriesDuringScan, + LibraryConsumptionSettings consumptionSettings, LibraryPathTemplate pathTemplate, List scanIds) { @@ -250,6 +263,7 @@ public class Library : AggregateRoot canDownloadMetadataFromWeb, shouldSaveMetadataInMediaDirectories, shouldSkipUnchangedDirectoriesDuringScan, + consumptionSettings, pathTemplate, scanIds ); diff --git a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/ValueObjects/LibraryConsumptionSettings.cs b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/ValueObjects/LibraryConsumptionSettings.cs new file mode 100644 index 00000000..a9b47065 --- /dev/null +++ b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/ValueObjects/LibraryConsumptionSettings.cs @@ -0,0 +1,116 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Models.Core; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using System.Collections.Generic; +#endregion + +namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; + +/// +/// Value Object for the consumption settings of a media library. +/// +public sealed class LibraryConsumptionSettings : ValueObject +{ + /// + /// Gets a value indicating whether the consumption progress of the media library items is tracked. + /// + public bool ShouldTrackConsumptionProgress { get; private set; } + + /// + /// Gets the percentage of a media library item that must be consumed for its session to be considered completed. The value is absent when + /// progress tracking is disabled, and for library types whose completion is only recorded explicitly. + /// + public Optional CompletionThresholdPercentage { get; private set; } + + /// + /// Initializes a new instance of the class. + /// + /// Whether the consumption progress of the media library items is tracked. + /// The percentage of a media library item that must be consumed for its session to be considered completed. + private LibraryConsumptionSettings(bool shouldTrackConsumptionProgress, Optional completionThresholdPercentage) + { + ShouldTrackConsumptionProgress = shouldTrackConsumptionProgress; + // A completion threshold has no meaning when progress is not tracked, so it is never stored in that case. + CompletionThresholdPercentage = shouldTrackConsumptionProgress ? completionThresholdPercentage : Optional.None(); + } + + /// + /// Creates a new instance of the class. + /// + /// Whether the consumption progress of the media library items is tracked. + /// The percentage of a media library item that must be consumed for its session to be considered completed. + /// The created consumption settings. + public static LibraryConsumptionSettings Create(bool shouldTrackConsumptionProgress, Optional completionThresholdPercentage) + { + return new LibraryConsumptionSettings(shouldTrackConsumptionProgress, completionThresholdPercentage); + } + + /// + /// Creates the default consumption settings for . + /// + /// + /// A library type without a default completion threshold is created with progress tracking off. If progress tracking is enabled explicitly for + /// such a type without a threshold, completion is only recorded when it is reported explicitly. + /// + /// The type of the media library for which to create the default consumption settings. + /// The default consumption settings of the media library type. + public static LibraryConsumptionSettings CreateDefault(LibraryType libraryType) + { + return libraryType switch + { + // Written content. + LibraryType.Book or LibraryType.EBook or LibraryType.ComicBook or LibraryType.Magazine or LibraryType.Newspaper or LibraryType.Manga or + LibraryType.GraphicNovel or LibraryType.AcademicPaper or LibraryType.SheetMusic + => Create(shouldTrackConsumptionProgress: true, Optional.Some(100)), + // Video. + LibraryType.TvShow or LibraryType.Movie or LibraryType.Documentary or LibraryType.Anime or LibraryType.ConcertVideo or LibraryType.TutorialVideo or + LibraryType.HomeVideo or LibraryType.YouTubeVideo or LibraryType.MusicVideo or LibraryType.LiveRecordingVideo or LibraryType.InterviewVideo or + LibraryType.CoverSongVideo + => Create(shouldTrackConsumptionProgress: true, Optional.Some(90)), + // Audiobooks and podcasts. + LibraryType.Audiobook or LibraryType.PodcastAudio or LibraryType.PodcastVideo + => Create(shouldTrackConsumptionProgress: true, Optional.Some(95)), + // Music audio and photos. + LibraryType.Music or LibraryType.Remix or LibraryType.SoundEffect or LibraryType.LiveRecordingAudio or LibraryType.InterviewAudio or + LibraryType.CoverSongAudio or LibraryType.Photo + => Create(shouldTrackConsumptionProgress: false, Optional.None()), + // Library types that are not media libraries, and any type added later, stay off until they are classified here. + LibraryType.Playlist or LibraryType.Collection or LibraryType.Subtitles or LibraryType.Lyrics or LibraryType.Other + => Create(shouldTrackConsumptionProgress: false, Optional.None()), + _ => Create(shouldTrackConsumptionProgress: false, Optional.None()) + }; + } + + /// + /// Creates the default consumption settings for . + /// + /// + /// A media kind without a default completion threshold is created with progress tracking off. If progress tracking is enabled explicitly for + /// such a kind without a threshold, completion is only recorded when it is reported explicitly. + /// + /// The kind of media for which to create the default consumption settings. + /// The default consumption settings of the media kind. + public static LibraryConsumptionSettings CreateDefault(MediaKind mediaKind) + { + return mediaKind switch + { + MediaKind.Book => Create(shouldTrackConsumptionProgress: true, Optional.Some(100)), + MediaKind.Movie or MediaKind.TvEpisode or MediaKind.Video => Create(shouldTrackConsumptionProgress: true, Optional.Some(90)), + MediaKind.PodcastEpisode or MediaKind.Audiobook => Create(shouldTrackConsumptionProgress: true, Optional.Some(95)), + // Kinds that do not track progress, and any kind added later, stay off until they are classified here. + MediaKind.None or MediaKind.MusicTrack or MediaKind.Photo => Create(shouldTrackConsumptionProgress: false, Optional.None()), + _ => Create(shouldTrackConsumptionProgress: false, Optional.None()) + }; + } + + /// + /// Gets the list of items that define equality of the object. + /// + /// A list of items defining the equality. + public override IEnumerable GetEqualityComponents() + { + yield return ShouldTrackConsumptionProgress; + yield return CompletionThresholdPercentage; + } +} diff --git a/src/Lumina.Domain/Core/BoundedContexts/MediaConsumptionBoundedContext/Common/ValueObjects/DurationThresholdConsumptionRule.cs b/src/Lumina.Domain/Core/BoundedContexts/MediaConsumptionBoundedContext/Common/ValueObjects/DurationThresholdConsumptionRule.cs new file mode 100644 index 00000000..c1cad270 --- /dev/null +++ b/src/Lumina.Domain/Core/BoundedContexts/MediaConsumptionBoundedContext/Common/ValueObjects/DurationThresholdConsumptionRule.cs @@ -0,0 +1,29 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption; +using System; +#endregion + +namespace Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.Common.ValueObjects; + +/// +/// Value Object for the consumption rules of a kind of media whose sessions count when they are completed or reach a minimum consumed duration. I.e.: movies. +/// +public abstract class DurationThresholdConsumptionRule : MediaConsumptionRule +{ + /// + /// Gets the minimum consumed duration that a session of this kind of media must reach to be counted, when it is not completed. + /// + public abstract TimeSpan MinimumCountedDuration { get; } + + /// + /// Determines whether a consumption session of this kind of media counts towards statistics. + /// + /// The status of the consumption session. + /// The active duration consumed by the consumption session. + /// The number of consecutive pages read in the consumption session. It is ignored, because this kind of media is counted by duration. + /// if the consumption session counts towards statistics, otherwise. + public override bool Counts(ConsumptionStatus status, TimeSpan consumedDuration, int consecutivePagesRead) + { + return status == ConsumptionStatus.Completed || consumedDuration >= MinimumCountedDuration; + } +} diff --git a/src/Lumina.Domain/Core/BoundedContexts/MediaConsumptionBoundedContext/Common/ValueObjects/EverySessionConsumptionRule.cs b/src/Lumina.Domain/Core/BoundedContexts/MediaConsumptionBoundedContext/Common/ValueObjects/EverySessionConsumptionRule.cs new file mode 100644 index 00000000..75aa857a --- /dev/null +++ b/src/Lumina.Domain/Core/BoundedContexts/MediaConsumptionBoundedContext/Common/ValueObjects/EverySessionConsumptionRule.cs @@ -0,0 +1,24 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption; +using System; +#endregion + +namespace Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.Common.ValueObjects; + +/// +/// Value Object for the consumption rules of a kind of media whose sessions count every time, regardless of their duration or progress. I.e.: photos. +/// +public abstract class EverySessionConsumptionRule : MediaConsumptionRule +{ + /// + /// Determines whether a consumption session of this kind of media counts towards statistics. + /// + /// The status of the consumption session. It is ignored, because every session of this kind of media counts. + /// The active duration consumed by the consumption session. It is ignored, because every session of this kind of media counts. + /// The number of consecutive pages read in the consumption session. It is ignored, because every session of this kind of media counts. + /// , because every session of this kind of media counts towards statistics. + public override bool Counts(ConsumptionStatus status, TimeSpan consumedDuration, int consecutivePagesRead) + { + return true; + } +} diff --git a/src/Lumina.Domain/Core/BoundedContexts/MediaConsumptionBoundedContext/Common/ValueObjects/MediaConsumptionRule.cs b/src/Lumina.Domain/Core/BoundedContexts/MediaConsumptionBoundedContext/Common/ValueObjects/MediaConsumptionRule.cs new file mode 100644 index 00000000..a9cfe826 --- /dev/null +++ b/src/Lumina.Domain/Core/BoundedContexts/MediaConsumptionBoundedContext/Common/ValueObjects/MediaConsumptionRule.cs @@ -0,0 +1,88 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Models.Core; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.MediaConsumptionRecordAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using System; +using System.Collections.Generic; +#endregion + +namespace Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.Common.ValueObjects; + +/// +/// Value Object for the consumption rules of a kind of media. +/// +/// +/// The rules are shared by the consumption record aggregate, the resume point aggregate and the statistics read model, so they live in the common +/// folder of the bounded context. Each concrete rule describes the counting behavior and the resumability of one media kind, and the factory returns +/// the rule for a kind so that callers never switch on the media kind themselves. +/// +public abstract class MediaConsumptionRule : ValueObject +{ + /// + /// Gets the kind of media that this rule applies to. + /// + public abstract MediaKind MediaKind { get; } + + /// + /// Gets a value indicating whether the current catalogues support this kind of media. + /// + public abstract bool IsSupportedByCurrentCatalogues { get; } + + /// + /// Gets the kind of position used to resume this kind of media, if the kind can be resumed. + /// + public abstract Optional PositionKind { get; } + + /// + /// Gets a value indicating whether a consumption session of this kind of media can be resumed. + /// + public bool CanResume => PositionKind.HasValue; + + /// + /// Gets a value indicating whether a consumption session of this kind of media is a one-shot session, which completes at the moment it starts. + /// + public abstract bool IsOneShot { get; } + + /// + /// Determines whether a consumption session of this kind of media counts towards statistics. + /// + /// The status of the consumption session. + /// The active duration consumed by the consumption session. + /// The number of consecutive pages read in the consumption session. + /// if the consumption session counts towards statistics, otherwise. + public abstract bool Counts(ConsumptionStatus status, TimeSpan consumedDuration, int consecutivePagesRead); + + /// + /// Gets the consumption rule for . + /// + /// The kind of media for which to get the consumption rule. + /// + /// An containing the consumption rule for , or no value when the kind has no rule. + /// + public static Optional For(MediaKind mediaKind) + { + return mediaKind switch + { + MediaKind.MusicTrack => Optional.Some(new MusicTrackConsumptionRule()), + MediaKind.PodcastEpisode => Optional.Some(new PodcastEpisodeConsumptionRule()), + MediaKind.Audiobook => Optional.Some(new AudiobookConsumptionRule()), + MediaKind.Movie => Optional.Some(new MovieConsumptionRule()), + MediaKind.TvEpisode => Optional.Some(new TvEpisodeConsumptionRule()), + MediaKind.Book => Optional.Some(new BookConsumptionRule()), + MediaKind.Photo => Optional.Some(new PhotoConsumptionRule()), + MediaKind.Video => Optional.Some(new VideoConsumptionRule()), + _ => Optional.None() + }; + } + + /// + /// Gets the list of items that define equality of the object. + /// + /// A list of items defining the equality. + public override IEnumerable GetEqualityComponents() + { + yield return MediaKind; + } +} diff --git a/src/Lumina.Domain/Core/BoundedContexts/MediaConsumptionBoundedContext/Common/ValueObjects/MediaPosition.cs b/src/Lumina.Domain/Core/BoundedContexts/MediaConsumptionBoundedContext/Common/ValueObjects/MediaPosition.cs new file mode 100644 index 00000000..23f0f3b0 --- /dev/null +++ b/src/Lumina.Domain/Core/BoundedContexts/MediaConsumptionBoundedContext/Common/ValueObjects/MediaPosition.cs @@ -0,0 +1,74 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Models.Core; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption; +using System; +using System.Collections.Generic; +#endregion + +namespace Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.Common.ValueObjects; + +/// +/// Value Object for the position reached in a media item during a consumption session. +/// +public sealed class MediaPosition : ValueObject +{ + /// + /// Gets the kind of representation that the position uses. + /// + public MediaPositionKind Kind { get; private set; } + + /// + /// Gets the position within the media item, for positions that are expressed as a time offset. + /// + public Optional TimeOffset { get; private set; } + + /// + /// Gets the opaque locator within the media item, for positions that are not expressed as a time offset, such as a reading location of a book. + /// + public Optional Location { get; private set; } + + /// + /// Initializes a new instance of the class. + /// + /// The kind of representation that the position uses. + /// The position within the media item, for positions that are expressed as a time offset. + /// The opaque locator within the media item, for positions that are not expressed as a time offset. + private MediaPosition(MediaPositionKind kind, Optional timeOffset, Optional location) + { + Kind = kind; + TimeOffset = timeOffset; + Location = location; + } + + /// + /// Creates a position expressed as a time offset within the media item. + /// + /// The position within the media item. + /// The created instance. + public static MediaPosition CreateTimeOffset(TimeSpan timeOffset) + { + return new MediaPosition(MediaPositionKind.TimeOffset, Optional.Some(timeOffset), Optional.None()); + } + + /// + /// Creates a position expressed as an opaque locator within the media item. + /// + /// The opaque locator within the media item. + /// The created instance. + public static MediaPosition CreateLocation(string location) + { + return new MediaPosition(MediaPositionKind.Location, Optional.None(), Optional.Some(location)); + } + + /// + /// Gets the list of items that define equality of the object. + /// + /// A list of items defining the equality. + public override IEnumerable GetEqualityComponents() + { + yield return Kind; + yield return TimeOffset; + yield return Location; + } +} diff --git a/src/Lumina.Domain/Core/BoundedContexts/MediaConsumptionBoundedContext/Common/ValueObjects/PageThresholdConsumptionRule.cs b/src/Lumina.Domain/Core/BoundedContexts/MediaConsumptionBoundedContext/Common/ValueObjects/PageThresholdConsumptionRule.cs new file mode 100644 index 00000000..2c79edf6 --- /dev/null +++ b/src/Lumina.Domain/Core/BoundedContexts/MediaConsumptionBoundedContext/Common/ValueObjects/PageThresholdConsumptionRule.cs @@ -0,0 +1,29 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption; +using System; +#endregion + +namespace Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.Common.ValueObjects; + +/// +/// Value Object for the consumption rules of a kind of media whose sessions count when they are completed or reach a minimum number of consecutive pages read. I.e.: books. +/// +public abstract class PageThresholdConsumptionRule : MediaConsumptionRule +{ + /// + /// Gets the minimum number of consecutive pages that a session of this kind of media must read to be counted, when it is not completed. + /// + public abstract int MinimumConsecutivePages { get; } + + /// + /// Determines whether a consumption session of this kind of media counts towards statistics. + /// + /// The status of the consumption session. + /// The active duration consumed by the consumption session. It is ignored, because this kind of media is counted by pages. + /// The number of consecutive pages read in the consumption session. + /// if the consumption session counts towards statistics, otherwise. + public override bool Counts(ConsumptionStatus status, TimeSpan consumedDuration, int consecutivePagesRead) + { + return status == ConsumptionStatus.Completed || consecutivePagesRead > MinimumConsecutivePages; + } +} diff --git a/src/Lumina.Domain/Core/BoundedContexts/MediaConsumptionBoundedContext/ExternalIdentifiers/LibraryManagementBoundedContext/LibraryAggregate/LibraryId.cs b/src/Lumina.Domain/Core/BoundedContexts/MediaConsumptionBoundedContext/ExternalIdentifiers/LibraryManagementBoundedContext/LibraryAggregate/LibraryId.cs new file mode 100644 index 00000000..0cc2d6b7 --- /dev/null +++ b/src/Lumina.Domain/Core/BoundedContexts/MediaConsumptionBoundedContext/ExternalIdentifiers/LibraryManagementBoundedContext/LibraryAggregate/LibraryId.cs @@ -0,0 +1,51 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Models.Core; +using System; +using System.Collections.Generic; +using System.Diagnostics; +#endregion + +namespace Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.ExternalIdentifiers.LibraryManagementBoundedContext.LibraryAggregate; + +/// +/// Value Object for the Id of a media library, duplicated from the LibraryManagement bounded context to keep the cross bounded context references decoupled. +/// +[DebuggerDisplay("{Value}")] +public sealed class LibraryId : EntityId +{ + /// + /// Initializes a new instance of the class. + /// + /// The value representing this object. + private LibraryId(Guid value) : base(value) + { + } + + /// + /// Creates a new instance of the class. + /// + /// The created instance. + public static LibraryId CreateUnique() + { + return new LibraryId(Guid.NewGuid()); + } + + /// + /// Creates a new instance of the class, from a pre-existing . + /// + /// The value used to create the instance. + /// The created instance. + public static LibraryId Create(Guid value) + { + return new LibraryId(value); + } + + /// + /// Gets the list of items that define equality of the object. + /// + /// A list of items defining the equality. + public override IEnumerable GetEqualityComponents() + { + yield return Value; + } +} diff --git a/src/Lumina.Domain/Core/BoundedContexts/MediaConsumptionBoundedContext/ExternalIdentifiers/MediaLibraryBoundedContext/MediaItemAggregate/MediaItemId.cs b/src/Lumina.Domain/Core/BoundedContexts/MediaConsumptionBoundedContext/ExternalIdentifiers/MediaLibraryBoundedContext/MediaItemAggregate/MediaItemId.cs new file mode 100644 index 00000000..6232478f --- /dev/null +++ b/src/Lumina.Domain/Core/BoundedContexts/MediaConsumptionBoundedContext/ExternalIdentifiers/MediaLibraryBoundedContext/MediaItemAggregate/MediaItemId.cs @@ -0,0 +1,51 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Models.Core; +using System; +using System.Collections.Generic; +using System.Diagnostics; +#endregion + +namespace Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.ExternalIdentifiers.MediaLibraryBoundedContext.MediaItemAggregate; + +/// +/// Value Object for the Id of a media item, duplicated from the media library bounded contexts to keep the cross bounded context references decoupled. +/// +[DebuggerDisplay("{Value}")] +public sealed class MediaItemId : EntityId +{ + /// + /// Initializes a new instance of the class. + /// + /// The value representing this object. + private MediaItemId(Guid value) : base(value) + { + } + + /// + /// Creates a new instance of the class. + /// + /// The created instance. + public static MediaItemId CreateUnique() + { + return new MediaItemId(Guid.NewGuid()); + } + + /// + /// Creates a new instance of the class, from a pre-existing . + /// + /// The value used to create the instance. + /// The created instance. + public static MediaItemId Create(Guid value) + { + return new MediaItemId(value); + } + + /// + /// Gets the list of items that define equality of the object. + /// + /// A list of items defining the equality. + public override IEnumerable GetEqualityComponents() + { + yield return Value; + } +} diff --git a/src/Lumina.Domain/Core/BoundedContexts/MediaConsumptionBoundedContext/ExternalIdentifiers/UserManagementBoundedContext/UserAggregate/UserId.cs b/src/Lumina.Domain/Core/BoundedContexts/MediaConsumptionBoundedContext/ExternalIdentifiers/UserManagementBoundedContext/UserAggregate/UserId.cs new file mode 100644 index 00000000..1237c088 --- /dev/null +++ b/src/Lumina.Domain/Core/BoundedContexts/MediaConsumptionBoundedContext/ExternalIdentifiers/UserManagementBoundedContext/UserAggregate/UserId.cs @@ -0,0 +1,51 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Models.Core; +using System; +using System.Collections.Generic; +using System.Diagnostics; +#endregion + +namespace Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.ExternalIdentifiers.UserManagementBoundedContext.UserAggregate; + +/// +/// Value Object for the Id of a user, duplicated from the UserManagement bounded context to keep the cross bounded context references decoupled. +/// +[DebuggerDisplay("{Value}")] +public sealed class UserId : EntityId +{ + /// + /// Initializes a new instance of the class. + /// + /// The value representing this object. + private UserId(Guid value) : base(value) + { + } + + /// + /// Creates a new instance of the class. + /// + /// The created instance. + public static UserId CreateUnique() + { + return new UserId(Guid.NewGuid()); + } + + /// + /// Creates a new instance of the class, from a pre-existing . + /// + /// The value used to create the instance. + /// The created instance. + public static UserId Create(Guid value) + { + return new UserId(value); + } + + /// + /// Gets the list of items that define equality of the object. + /// + /// A list of items defining the equality. + public override IEnumerable GetEqualityComponents() + { + yield return Value; + } +} diff --git a/src/Lumina.Domain/Core/BoundedContexts/MediaConsumptionBoundedContext/MediaConsumptionRecordAggregate/Events/MediaConsumptionCompletedDomainEvent.cs b/src/Lumina.Domain/Core/BoundedContexts/MediaConsumptionBoundedContext/MediaConsumptionRecordAggregate/Events/MediaConsumptionCompletedDomainEvent.cs new file mode 100644 index 00000000..9ae86c67 --- /dev/null +++ b/src/Lumina.Domain/Core/BoundedContexts/MediaConsumptionBoundedContext/MediaConsumptionRecordAggregate/Events/MediaConsumptionCompletedDomainEvent.cs @@ -0,0 +1,43 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Events; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.Common.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.ExternalIdentifiers.LibraryManagementBoundedContext.LibraryAggregate; +using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.ExternalIdentifiers.MediaLibraryBoundedContext.MediaItemAggregate; +using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.ExternalIdentifiers.UserManagementBoundedContext.UserAggregate; +using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.MediaConsumptionRecordAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.MediaConsumptionRecordAggregate.Events; + +/// +/// Domain event raised when a media consumption session completes. +/// +/// The unique identifier of the domain event. +/// The unique identifier of the consumption record. +/// The unique identifier of the user that owns the consumption record. +/// The unique identifier of the media library that contains the consumed item. +/// The unique identifier of the consumed media item. +/// The kind of media that was consumed. +/// The last known position for the media item, if any. +/// The final progress fraction reported for the media item. +/// The active duration consumed by the session. +/// The number of consecutive pages read in the session. +/// The date and time when the domain event occurred. +[DebuggerDisplay("MediaConsumptionRecordId: {MediaConsumptionRecordId.Value}; MediaKind: {MediaKind}")] +public record MediaConsumptionCompletedDomainEvent( + Guid Id, + MediaConsumptionRecordId MediaConsumptionRecordId, + UserId UserId, + LibraryId LibraryId, + MediaItemId MediaItemId, + MediaKind MediaKind, + Optional LastPosition, + double LastProgressFraction, + TimeSpan ConsumedDuration, + int ConsecutivePagesRead, + DateTime OccurredOnUtc +) : IDomainEvent; diff --git a/src/Lumina.Domain/Core/BoundedContexts/MediaConsumptionBoundedContext/MediaConsumptionRecordAggregate/Events/MediaConsumptionProgressedDomainEvent.cs b/src/Lumina.Domain/Core/BoundedContexts/MediaConsumptionBoundedContext/MediaConsumptionRecordAggregate/Events/MediaConsumptionProgressedDomainEvent.cs new file mode 100644 index 00000000..d9fc0801 --- /dev/null +++ b/src/Lumina.Domain/Core/BoundedContexts/MediaConsumptionBoundedContext/MediaConsumptionRecordAggregate/Events/MediaConsumptionProgressedDomainEvent.cs @@ -0,0 +1,43 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Events; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.Common.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.ExternalIdentifiers.LibraryManagementBoundedContext.LibraryAggregate; +using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.ExternalIdentifiers.MediaLibraryBoundedContext.MediaItemAggregate; +using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.ExternalIdentifiers.UserManagementBoundedContext.UserAggregate; +using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.MediaConsumptionRecordAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.MediaConsumptionRecordAggregate.Events; + +/// +/// Domain event raised when a client reports the progress of a media consumption session. +/// +/// The unique identifier of the domain event. +/// The unique identifier of the consumption record. +/// The unique identifier of the user that owns the consumption record. +/// The unique identifier of the media library that contains the consumed item. +/// The unique identifier of the consumed media item. +/// The kind of media that is being consumed. +/// The last known position for the media item, if any. +/// The last progress fraction reported by the client. +/// The active duration consumed so far. +/// The number of consecutive pages read so far. +/// The date and time when the domain event occurred. +[DebuggerDisplay("MediaConsumptionRecordId: {MediaConsumptionRecordId.Value}; LastProgressFraction: {LastProgressFraction}")] +public record MediaConsumptionProgressedDomainEvent( + Guid Id, + MediaConsumptionRecordId MediaConsumptionRecordId, + UserId UserId, + LibraryId LibraryId, + MediaItemId MediaItemId, + MediaKind MediaKind, + Optional LastPosition, + double LastProgressFraction, + TimeSpan ConsumedDuration, + int ConsecutivePagesRead, + DateTime OccurredOnUtc +) : IDomainEvent; diff --git a/src/Lumina.Domain/Core/BoundedContexts/MediaConsumptionBoundedContext/MediaConsumptionRecordAggregate/Events/MediaConsumptionStartedDomainEvent.cs b/src/Lumina.Domain/Core/BoundedContexts/MediaConsumptionBoundedContext/MediaConsumptionRecordAggregate/Events/MediaConsumptionStartedDomainEvent.cs new file mode 100644 index 00000000..270620bf --- /dev/null +++ b/src/Lumina.Domain/Core/BoundedContexts/MediaConsumptionBoundedContext/MediaConsumptionRecordAggregate/Events/MediaConsumptionStartedDomainEvent.cs @@ -0,0 +1,33 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Events; +using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.ExternalIdentifiers.LibraryManagementBoundedContext.LibraryAggregate; +using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.ExternalIdentifiers.MediaLibraryBoundedContext.MediaItemAggregate; +using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.ExternalIdentifiers.UserManagementBoundedContext.UserAggregate; +using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.MediaConsumptionRecordAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.MediaConsumptionRecordAggregate.Events; + +/// +/// Domain event raised when a media consumption session starts. +/// +/// The unique identifier of the domain event. +/// The unique identifier of the consumption record. +/// The unique identifier of the user that started the session. +/// The unique identifier of the media library that contains the consumed item. +/// The unique identifier of the consumed media item. +/// The kind of media that is being consumed. +/// The date and time when the domain event occurred. +[DebuggerDisplay("MediaConsumptionRecordId: {MediaConsumptionRecordId.Value}; MediaKind: {MediaKind}")] +public record MediaConsumptionStartedDomainEvent( + Guid Id, + MediaConsumptionRecordId MediaConsumptionRecordId, + UserId UserId, + LibraryId LibraryId, + MediaItemId MediaItemId, + MediaKind MediaKind, + DateTime OccurredOnUtc +) : IDomainEvent; diff --git a/src/Lumina.Domain/Core/BoundedContexts/MediaConsumptionBoundedContext/MediaConsumptionRecordAggregate/Events/MediaConsumptionStoppedDomainEvent.cs b/src/Lumina.Domain/Core/BoundedContexts/MediaConsumptionBoundedContext/MediaConsumptionRecordAggregate/Events/MediaConsumptionStoppedDomainEvent.cs new file mode 100644 index 00000000..482122be --- /dev/null +++ b/src/Lumina.Domain/Core/BoundedContexts/MediaConsumptionBoundedContext/MediaConsumptionRecordAggregate/Events/MediaConsumptionStoppedDomainEvent.cs @@ -0,0 +1,43 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Events; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.Common.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.ExternalIdentifiers.LibraryManagementBoundedContext.LibraryAggregate; +using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.ExternalIdentifiers.MediaLibraryBoundedContext.MediaItemAggregate; +using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.ExternalIdentifiers.UserManagementBoundedContext.UserAggregate; +using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.MediaConsumptionRecordAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.MediaConsumptionRecordAggregate.Events; + +/// +/// Domain event raised when a media consumption session stops before it completes. +/// +/// The unique identifier of the domain event. +/// The unique identifier of the consumption record. +/// The unique identifier of the user that owns the consumption record. +/// The unique identifier of the media library that contains the consumed item. +/// The unique identifier of the consumed media item. +/// The kind of media that was consumed. +/// The last known position for the media item, if any. +/// The final progress fraction reported for the media item. +/// The active duration consumed by the session. +/// The number of consecutive pages read in the session. +/// The date and time when the domain event occurred. +[DebuggerDisplay("MediaConsumptionRecordId: {MediaConsumptionRecordId.Value}; MediaKind: {MediaKind}")] +public record MediaConsumptionStoppedDomainEvent( + Guid Id, + MediaConsumptionRecordId MediaConsumptionRecordId, + UserId UserId, + LibraryId LibraryId, + MediaItemId MediaItemId, + MediaKind MediaKind, + Optional LastPosition, + double LastProgressFraction, + TimeSpan ConsumedDuration, + int ConsecutivePagesRead, + DateTime OccurredOnUtc +) : IDomainEvent; diff --git a/src/Lumina.Domain/Core/BoundedContexts/MediaConsumptionBoundedContext/MediaConsumptionRecordAggregate/MediaConsumptionRecord.cs b/src/Lumina.Domain/Core/BoundedContexts/MediaConsumptionBoundedContext/MediaConsumptionRecordAggregate/MediaConsumptionRecord.cs new file mode 100644 index 00000000..2dd64891 --- /dev/null +++ b/src/Lumina.Domain/Core/BoundedContexts/MediaConsumptionBoundedContext/MediaConsumptionRecordAggregate/MediaConsumptionRecord.cs @@ -0,0 +1,509 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Models.Core; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.Common.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.ExternalIdentifiers.LibraryManagementBoundedContext.LibraryAggregate; +using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.ExternalIdentifiers.MediaLibraryBoundedContext.MediaItemAggregate; +using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.ExternalIdentifiers.UserManagementBoundedContext.UserAggregate; +using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.MediaConsumptionRecordAggregate.Events; +using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.MediaConsumptionRecordAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.MediaConsumptionRecordAggregate; + +/// +/// Aggregate root for a media consumption session. +/// +[DebuggerDisplay("Id: {Id.Value}; MediaKind: {MediaKind}; Status: {Status}")] +public sealed class MediaConsumptionRecord : AggregateRoot +{ + /// + /// Gets the object representing the unique identifier of the user that started the consumption session. + /// + public UserId UserId { get; private set; } + + /// + /// Gets the Id of the media library that contains the consumed media item. + /// + public LibraryId LibraryId { get; private set; } + + /// + /// Gets the Id of the consumed media item. + /// + public MediaItemId MediaItemId { get; private set; } + + /// + /// Gets the kind of media that is consumed. + /// + public MediaKind MediaKind { get; private set; } + + /// + /// Gets the state of the consumption session. + /// + public ConsumptionStatus Status { get; private set; } + + /// + /// Gets the date and time when the consumption session started. + /// + public DateTime StartedOnUtc { get; private set; } + + /// + /// Gets the date and time when the consumption session last received activity. + /// + public DateTime LastActivityOnUtc { get; private set; } + + /// + /// Gets the date and time when the consumption session completed or stopped, if it has ended. + /// + public Optional EndedOnUtc { get; private set; } + + /// + /// Gets the active duration that the user has consumed in the session. It never decreases within one record. + /// + public TimeSpan ConsumedDuration { get; private set; } + + /// + /// Gets the last position reported for the media item, if the session has a known position. The position is the latest reported one, so it may + /// be earlier in the media item than a previously reported position. + /// + public Optional LastPosition { get; private set; } + + /// + /// Gets the latest reported progress fraction of the media item. It is the latest reported value, so it may be lower than a previously reported + /// fraction. + /// + public double LastProgressFraction { get; private set; } + + /// + /// Gets the number of consecutive pages reported read in the current session. It is zero for every kind of media except books. + /// + public int ConsecutivePagesRead { get; private set; } + + /// + /// Initializes a new instance of the class. + /// + /// The object representing the unique identifier of the consumption record. + /// The object representing the unique identifier of the user that started the consumption session. + /// The Id of the media library that contains the consumed media item. + /// The Id of the consumed media item. + /// The kind of media that is consumed. + /// The state of the consumption session. + /// The date and time when the consumption session started. + /// The date and time when the consumption session last received activity. + /// The date and time when the consumption session completed or stopped, if it has ended. + /// The active duration that the user has consumed in the session. + /// The last position reported for the media item, if the session has a known position. + /// The latest reported progress fraction of the media item. + /// The number of consecutive pages reported read in the current session. + private MediaConsumptionRecord( + MediaConsumptionRecordId id, + UserId userId, + LibraryId libraryId, + MediaItemId mediaItemId, + MediaKind mediaKind, + ConsumptionStatus status, + DateTime startedOnUtc, + DateTime lastActivityOnUtc, + Optional endedOnUtc, + TimeSpan consumedDuration, + Optional lastPosition, + double lastProgressFraction, + int consecutivePagesRead) : base(id) + { + Id = id; + UserId = userId; + LibraryId = libraryId; + MediaItemId = mediaItemId; + MediaKind = mediaKind; + Status = status; + StartedOnUtc = startedOnUtc; + LastActivityOnUtc = lastActivityOnUtc; + EndedOnUtc = endedOnUtc; + ConsumedDuration = consumedDuration; + LastPosition = lastPosition; + LastProgressFraction = lastProgressFraction; + ConsecutivePagesRead = consecutivePagesRead; + CreatedOnUtc = startedOnUtc; + UpdatedOnUtc = lastActivityOnUtc > startedOnUtc ? Optional.Some(lastActivityOnUtc) : Optional.None(); + } + + /// + /// Starts a new consumption session for a media item. + /// + /// The object representing the unique identifier of the user that starts the consumption session. + /// The Id of the media library that contains the consumed media item. + /// The Id of the consumed media item. + /// The kind of media that is consumed. + /// The position to initialize the session with, such as the position of an existing resume point, if any. + /// The progress fraction to initialize the session with, such as the fraction of an existing resume point. + /// + /// An containing either a successfully started , or an error message. + /// + public static Result Start(UserId userId, LibraryId libraryId, MediaItemId mediaItemId, MediaKind mediaKind, Optional lastPosition, double lastProgressFraction) + { + Optional ruleResult = MediaConsumptionRule.For(mediaKind); + if (!ruleResult.HasValue) + return Errors.MediaConsumption.UnsupportedMediaKind; + if (!IsProgressFractionValid(lastProgressFraction)) + return Errors.MediaConsumption.InvalidProgressFraction; + if (!DoesPositionMatchRule(ruleResult.Value, lastPosition)) + return Errors.MediaConsumption.InvalidMediaPosition; + + DateTime occurredOnUtc = DateTime.UtcNow; + MediaConsumptionRecord record = new( + MediaConsumptionRecordId.CreateUnique(), + userId, + libraryId, + mediaItemId, + mediaKind, + ConsumptionStatus.InProgress, + occurredOnUtc, + occurredOnUtc, + Optional.None(), + TimeSpan.Zero, + lastPosition, + lastProgressFraction, + 0); + + record._domainEvents.Add(new MediaConsumptionStartedDomainEvent( + Guid.NewGuid(), + record.Id, + userId, + libraryId, + mediaItemId, + mediaKind, + occurredOnUtc)); + return record; + } + + /// + /// Starts and completes a consumption session in the same call, for one-shot discrete kinds of media such as a photo view. + /// + /// The object representing the unique identifier of the user that consumed the media item. + /// The Id of the media library that contains the consumed media item. + /// The Id of the consumed media item. + /// The kind of media that is consumed. + /// + /// An containing either a successfully created completed , or an error message. + /// + public static Result StartCompleted(UserId userId, LibraryId libraryId, MediaItemId mediaItemId, MediaKind mediaKind) + { + Optional ruleResult = MediaConsumptionRule.For(mediaKind); + if (!ruleResult.HasValue) + return Errors.MediaConsumption.UnsupportedMediaKind; + if (!ruleResult.Value.IsOneShot) + return Errors.MediaConsumption.MediaKindCannotStartCompleted; + + DateTime occurredOnUtc = DateTime.UtcNow; + MediaConsumptionRecord record = new( + MediaConsumptionRecordId.CreateUnique(), + userId, + libraryId, + mediaItemId, + mediaKind, + ConsumptionStatus.Completed, + occurredOnUtc, + occurredOnUtc, + Optional.Some(occurredOnUtc), + TimeSpan.Zero, + Optional.None(), + 1, + 0); + + record._domainEvents.Add(new MediaConsumptionStartedDomainEvent( + Guid.NewGuid(), + record.Id, + userId, + libraryId, + mediaItemId, + mediaKind, + occurredOnUtc)); + record._domainEvents.Add(new MediaConsumptionCompletedDomainEvent( + Guid.NewGuid(), + record.Id, + userId, + libraryId, + mediaItemId, + mediaKind, + record.LastPosition, + record.LastProgressFraction, + record.ConsumedDuration, + record.ConsecutivePagesRead, + occurredOnUtc)); + return record; + } + + /// + /// Creates a new instance of the class, with pre-existing data. + /// + /// The object representing the unique identifier of the consumption record. + /// The object representing the unique identifier of the user that started the consumption session. + /// The Id of the media library that contains the consumed media item. + /// The Id of the consumed media item. + /// The kind of media that is consumed. + /// The state of the consumption session. + /// The date and time when the consumption session started. + /// The date and time when the consumption session last received activity. + /// The date and time when the consumption session completed or stopped, if it has ended. + /// The active duration that the user has consumed in the session. + /// The last position reported for the media item, if the session has a known position. + /// The latest reported progress fraction of the media item. + /// The number of consecutive pages reported read in the current session. + /// + /// An containing either a successfully reconstituted , or an error message. + /// + public static Result Reconstitute( + MediaConsumptionRecordId id, + UserId userId, + LibraryId libraryId, + MediaItemId mediaItemId, + MediaKind mediaKind, + ConsumptionStatus status, + DateTime startedOnUtc, + DateTime lastActivityOnUtc, + Optional endedOnUtc, + TimeSpan consumedDuration, + Optional lastPosition, + double lastProgressFraction, + int consecutivePagesRead) + { + Optional ruleResult = MediaConsumptionRule.For(mediaKind); + if (!ruleResult.HasValue) + return Errors.MediaConsumption.UnsupportedMediaKind; + if (!IsProgressFractionValid(lastProgressFraction)) + return Errors.MediaConsumption.InvalidProgressFraction; + if (consecutivePagesRead > 0 && !IsPageBased(ruleResult.Value)) + return Errors.MediaConsumption.ConsecutivePagesReadIsOnlySupportedForPageBasedMedia; + if (!DoesPositionMatchRule(ruleResult.Value, lastPosition)) + return Errors.MediaConsumption.InvalidMediaPosition; + if (status == ConsumptionStatus.InProgress && endedOnUtc.HasValue) + return Errors.MediaConsumption.InProgressConsumptionCannotHaveEndTime; + if (status != ConsumptionStatus.InProgress && !endedOnUtc.HasValue) + return Errors.MediaConsumption.EndedConsumptionMustHaveEndTime; + if (lastActivityOnUtc < startedOnUtc) + return Errors.MediaConsumption.LastActivityCannotPrecedeStart; + if (status != ConsumptionStatus.InProgress && endedOnUtc.Value < lastActivityOnUtc) + return Errors.MediaConsumption.EndedConsumptionCannotPrecedeLastActivity; + + return new MediaConsumptionRecord( + id, + userId, + libraryId, + mediaItemId, + mediaKind, + status, + startedOnUtc, + lastActivityOnUtc, + endedOnUtc, + consumedDuration, + lastPosition, + lastProgressFraction, + consecutivePagesRead); + } + + /// + /// Updates the measured progress of an in-progress consumption session. + /// + /// The last position reported by the client, if the report carries one. When it is absent, the last known position is kept. + /// The last progress fraction reported by the client. + /// The active duration consumed so far. + /// The number of consecutive pages read in the current session. + /// An representing either a successful update, or an error. + public Result ReportProgress(Optional lastPosition, double lastProgressFraction, TimeSpan consumedDuration, int consecutivePagesRead) + { + if (Status != ConsumptionStatus.InProgress) + return Errors.MediaConsumption.ConsumptionIsNotInProgress; + + Optional ruleResult = MediaConsumptionRule.For(MediaKind); + if (!ruleResult.HasValue) + return Errors.MediaConsumption.UnsupportedMediaKind; + if (!IsProgressFractionValid(lastProgressFraction)) + return Errors.MediaConsumption.InvalidProgressFraction; + if (consumedDuration < ConsumedDuration) + return Errors.MediaConsumption.ConsumedDurationCannotDecrease; + if (consecutivePagesRead > 0 && !IsPageBased(ruleResult.Value)) + return Errors.MediaConsumption.ConsecutivePagesReadIsOnlySupportedForPageBasedMedia; + if (!DoesPositionMatchRule(ruleResult.Value, lastPosition)) + return Errors.MediaConsumption.InvalidMediaPosition; + + if (lastPosition.HasValue) + LastPosition = lastPosition; + LastProgressFraction = lastProgressFraction; + ConsumedDuration = consumedDuration; + ConsecutivePagesRead = consecutivePagesRead; + + DateTime occurredOnUtc = GetNextActivityOnUtc(); + LastActivityOnUtc = occurredOnUtc; + UpdatedOnUtc = Optional.Some(occurredOnUtc); + _domainEvents.Add(new MediaConsumptionProgressedDomainEvent( + Guid.NewGuid(), + Id, + UserId, + LibraryId, + MediaItemId, + MediaKind, + LastPosition, + LastProgressFraction, + ConsumedDuration, + ConsecutivePagesRead, + occurredOnUtc)); + return Result.Updated; + } + + /// + /// Marks an in-progress consumption session as completed. + /// + /// The final position reported by the client, if the call carries one. When it is absent, the last known position is kept. + /// The final progress fraction reported by the client. + /// The active duration consumed by the session. + /// The number of consecutive pages read in the session, when the client reported it. When it is absent, the count of the last progress report is kept. + /// An representing either a successful completion, or an error. + public Result Complete(Optional lastPosition, double lastProgressFraction, TimeSpan consumedDuration, Optional consecutivePagesRead) + { + if (Status != ConsumptionStatus.InProgress) + return Errors.MediaConsumption.ConsumptionIsAlreadyTerminal; + + Optional ruleResult = MediaConsumptionRule.For(MediaKind); + if (!ruleResult.HasValue) + return Errors.MediaConsumption.UnsupportedMediaKind; + if (!IsProgressFractionValid(lastProgressFraction)) + return Errors.MediaConsumption.InvalidProgressFraction; + if (consumedDuration < ConsumedDuration) + return Errors.MediaConsumption.ConsumedDurationCannotDecrease; + if (consecutivePagesRead.HasValue && consecutivePagesRead.Value > 0 && !IsPageBased(ruleResult.Value)) + return Errors.MediaConsumption.ConsecutivePagesReadIsOnlySupportedForPageBasedMedia; + if (!DoesPositionMatchRule(ruleResult.Value, lastPosition)) + return Errors.MediaConsumption.InvalidMediaPosition; + + if (lastPosition.HasValue) + LastPosition = lastPosition; + LastProgressFraction = lastProgressFraction; + ConsumedDuration = consumedDuration; + if (consecutivePagesRead.HasValue) + ConsecutivePagesRead = consecutivePagesRead.Value; + Status = ConsumptionStatus.Completed; + + DateTime occurredOnUtc = GetNextActivityOnUtc(); + EndedOnUtc = Optional.Some(occurredOnUtc); + LastActivityOnUtc = occurredOnUtc; + UpdatedOnUtc = Optional.Some(occurredOnUtc); + _domainEvents.Add(new MediaConsumptionCompletedDomainEvent( + Guid.NewGuid(), + Id, + UserId, + LibraryId, + MediaItemId, + MediaKind, + LastPosition, + LastProgressFraction, + ConsumedDuration, + ConsecutivePagesRead, + occurredOnUtc)); + return Result.Updated; + } + + /// + /// Marks an in-progress consumption session as stopped before it completed. + /// + /// The final position reported by the client, if the call carries one. When it is absent, the last known position is kept. + /// The final progress fraction reported by the client. + /// The active duration consumed by the session. + /// The number of consecutive pages read in the session, when the client reported it. When it is absent, the count of the last progress report is kept. + /// An representing either a successful stop, or an error. + public Result Stop(Optional lastPosition, double lastProgressFraction, TimeSpan consumedDuration, Optional consecutivePagesRead) + { + if (Status != ConsumptionStatus.InProgress) + return Errors.MediaConsumption.ConsumptionIsAlreadyTerminal; + + Optional ruleResult = MediaConsumptionRule.For(MediaKind); + if (!ruleResult.HasValue) + return Errors.MediaConsumption.UnsupportedMediaKind; + if (!IsProgressFractionValid(lastProgressFraction)) + return Errors.MediaConsumption.InvalidProgressFraction; + if (consumedDuration < ConsumedDuration) + return Errors.MediaConsumption.ConsumedDurationCannotDecrease; + if (consecutivePagesRead.HasValue && consecutivePagesRead.Value > 0 && !IsPageBased(ruleResult.Value)) + return Errors.MediaConsumption.ConsecutivePagesReadIsOnlySupportedForPageBasedMedia; + if (!DoesPositionMatchRule(ruleResult.Value, lastPosition)) + return Errors.MediaConsumption.InvalidMediaPosition; + + if (lastPosition.HasValue) + LastPosition = lastPosition; + LastProgressFraction = lastProgressFraction; + ConsumedDuration = consumedDuration; + if (consecutivePagesRead.HasValue) + ConsecutivePagesRead = consecutivePagesRead.Value; + Status = ConsumptionStatus.Stopped; + + DateTime occurredOnUtc = GetNextActivityOnUtc(); + EndedOnUtc = Optional.Some(occurredOnUtc); + LastActivityOnUtc = occurredOnUtc; + UpdatedOnUtc = Optional.Some(occurredOnUtc); + _domainEvents.Add(new MediaConsumptionStoppedDomainEvent( + Guid.NewGuid(), + Id, + UserId, + LibraryId, + MediaItemId, + MediaKind, + LastPosition, + LastProgressFraction, + ConsumedDuration, + ConsecutivePagesRead, + occurredOnUtc)); + return Result.Updated; + } + + /// + /// Determines whether the progress fraction is a finite value between zero and one. + /// + /// The progress fraction to check. + /// if the progress fraction is valid, otherwise. + private static bool IsProgressFractionValid(double progressFraction) + { + return double.IsFinite(progressFraction) && progressFraction >= 0 && progressFraction <= 1; + } + + /// + /// Determines whether the rule of the media kind counts its sessions by the number of consecutive pages read. + /// + /// The consumption rule of the media kind. + /// if the rule is page based, otherwise. + private static bool IsPageBased(MediaConsumptionRule rule) + { + return rule is PageThresholdConsumptionRule; + } + + /// + /// Determines whether a reported position uses the position representation of the consumption rule of the media kind. + /// + /// The consumption rule of the media kind. + /// The reported position, if the report carries one. + /// if the position is valid for the media kind, otherwise. + private static bool DoesPositionMatchRule(MediaConsumptionRule rule, Optional lastPosition) + { + if (!lastPosition.HasValue) + return true; + return rule.PositionKind.HasValue && lastPosition.Value.Kind == rule.PositionKind.Value; + } + + /// + /// Gets the current UTC date and time, advanced past the last recorded activity so that activity timestamps never go backwards. When the last + /// recorded activity is already the maximum representable timestamp, that timestamp is returned instead of advancing it. + /// + /// The date and time of the new activity. + private DateTime GetNextActivityOnUtc() + { + DateTime utcNow = DateTime.UtcNow; + if (utcNow > LastActivityOnUtc) + return utcNow; + if (LastActivityOnUtc == DateTime.MaxValue) + return DateTime.MaxValue; + return LastActivityOnUtc.AddTicks(1); + } +} diff --git a/src/Lumina.Domain/Core/BoundedContexts/MediaConsumptionBoundedContext/MediaConsumptionRecordAggregate/ValueObjects/AudiobookConsumptionRule.cs b/src/Lumina.Domain/Core/BoundedContexts/MediaConsumptionBoundedContext/MediaConsumptionRecordAggregate/ValueObjects/AudiobookConsumptionRule.cs new file mode 100644 index 00000000..6eb589be --- /dev/null +++ b/src/Lumina.Domain/Core/BoundedContexts/MediaConsumptionBoundedContext/MediaConsumptionRecordAggregate/ValueObjects/AudiobookConsumptionRule.cs @@ -0,0 +1,40 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.Common.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using System; +#endregion + +namespace Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.MediaConsumptionRecordAggregate.ValueObjects; + +/// +/// Value Object for the consumption rules of an audiobook. +/// +public sealed class AudiobookConsumptionRule : DurationThresholdConsumptionRule +{ + /// + /// Gets the kind of media that this rule applies to. + /// + public override MediaKind MediaKind { get; } = MediaKind.Audiobook; + + /// + /// Gets a value indicating whether the current catalogues support this kind of media. + /// + public override bool IsSupportedByCurrentCatalogues { get; } = false; + + /// + /// Gets the kind of position used to resume this kind of media, if the kind can be resumed. + /// + public override Optional PositionKind { get; } = MediaPositionKind.TimeOffset; + + /// + /// Gets a value indicating whether a consumption session of this kind of media is a one-shot session, which completes at the moment it starts. + /// + public override bool IsOneShot { get; } = false; + + /// + /// Gets the minimum consumed duration that a session of this kind of media must reach to be counted, when it is not completed. + /// + public override TimeSpan MinimumCountedDuration { get; } = TimeSpan.FromSeconds(60); +} diff --git a/src/Lumina.Domain/Core/BoundedContexts/MediaConsumptionBoundedContext/MediaConsumptionRecordAggregate/ValueObjects/BookConsumptionRule.cs b/src/Lumina.Domain/Core/BoundedContexts/MediaConsumptionBoundedContext/MediaConsumptionRecordAggregate/ValueObjects/BookConsumptionRule.cs new file mode 100644 index 00000000..6a903d1e --- /dev/null +++ b/src/Lumina.Domain/Core/BoundedContexts/MediaConsumptionBoundedContext/MediaConsumptionRecordAggregate/ValueObjects/BookConsumptionRule.cs @@ -0,0 +1,39 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.Common.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +#endregion + +namespace Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.MediaConsumptionRecordAggregate.ValueObjects; + +/// +/// Value Object for the consumption rules of a book. +/// +public sealed class BookConsumptionRule : PageThresholdConsumptionRule +{ + /// + /// Gets the kind of media that this rule applies to. + /// + public override MediaKind MediaKind { get; } = MediaKind.Book; + + /// + /// Gets a value indicating whether the current catalogues support this kind of media. + /// + public override bool IsSupportedByCurrentCatalogues { get; } = true; + + /// + /// Gets the kind of position used to resume this kind of media, if the kind can be resumed. + /// + public override Optional PositionKind { get; } = MediaPositionKind.Location; + + /// + /// Gets a value indicating whether a consumption session of this kind of media is a one-shot session, which completes at the moment it starts. + /// + public override bool IsOneShot { get; } = false; + + /// + /// Gets the minimum number of consecutive pages that a session of this kind of media must read to be counted, when it is not completed. + /// + public override int MinimumConsecutivePages { get; } = 5; +} diff --git a/src/Lumina.Domain/Core/BoundedContexts/MediaConsumptionBoundedContext/MediaConsumptionRecordAggregate/ValueObjects/MediaConsumptionRecordId.cs b/src/Lumina.Domain/Core/BoundedContexts/MediaConsumptionBoundedContext/MediaConsumptionRecordAggregate/ValueObjects/MediaConsumptionRecordId.cs new file mode 100644 index 00000000..8b219eb2 --- /dev/null +++ b/src/Lumina.Domain/Core/BoundedContexts/MediaConsumptionBoundedContext/MediaConsumptionRecordAggregate/ValueObjects/MediaConsumptionRecordId.cs @@ -0,0 +1,51 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Models.Core; +using System; +using System.Collections.Generic; +using System.Diagnostics; +#endregion + +namespace Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.MediaConsumptionRecordAggregate.ValueObjects; + +/// +/// Value Object for the Id of a media consumption record. +/// +[DebuggerDisplay("{Value}")] +public sealed class MediaConsumptionRecordId : EntityId +{ + /// + /// Initializes a new instance of the class. + /// + /// The value representing this object. + private MediaConsumptionRecordId(Guid value) : base(value) + { + } + + /// + /// Creates a new instance of the class. + /// + /// The created instance. + public static MediaConsumptionRecordId CreateUnique() + { + return new MediaConsumptionRecordId(Guid.NewGuid()); + } + + /// + /// Creates a new instance of the class, from a pre-existing . + /// + /// The value used to create the instance. + /// The created instance. + public static MediaConsumptionRecordId Create(Guid value) + { + return new MediaConsumptionRecordId(value); + } + + /// + /// Gets the list of items that define equality of the object. + /// + /// A list of items defining the equality. + public override IEnumerable GetEqualityComponents() + { + yield return Value; + } +} diff --git a/src/Lumina.Domain/Core/BoundedContexts/MediaConsumptionBoundedContext/MediaConsumptionRecordAggregate/ValueObjects/MovieConsumptionRule.cs b/src/Lumina.Domain/Core/BoundedContexts/MediaConsumptionBoundedContext/MediaConsumptionRecordAggregate/ValueObjects/MovieConsumptionRule.cs new file mode 100644 index 00000000..e86cf9d5 --- /dev/null +++ b/src/Lumina.Domain/Core/BoundedContexts/MediaConsumptionBoundedContext/MediaConsumptionRecordAggregate/ValueObjects/MovieConsumptionRule.cs @@ -0,0 +1,40 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.Common.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using System; +#endregion + +namespace Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.MediaConsumptionRecordAggregate.ValueObjects; + +/// +/// Value Object for the consumption rules of a movie. +/// +public sealed class MovieConsumptionRule : DurationThresholdConsumptionRule +{ + /// + /// Gets the kind of media that this rule applies to. + /// + public override MediaKind MediaKind { get; } = MediaKind.Movie; + + /// + /// Gets a value indicating whether the current catalogues support this kind of media. + /// + public override bool IsSupportedByCurrentCatalogues { get; } = false; + + /// + /// Gets the kind of position used to resume this kind of media, if the kind can be resumed. + /// + public override Optional PositionKind { get; } = MediaPositionKind.TimeOffset; + + /// + /// Gets a value indicating whether a consumption session of this kind of media is a one-shot session, which completes at the moment it starts. + /// + public override bool IsOneShot { get; } = false; + + /// + /// Gets the minimum consumed duration that a session of this kind of media must reach to be counted, when it is not completed. + /// + public override TimeSpan MinimumCountedDuration { get; } = TimeSpan.FromMinutes(3); +} diff --git a/src/Lumina.Domain/Core/BoundedContexts/MediaConsumptionBoundedContext/MediaConsumptionRecordAggregate/ValueObjects/MusicTrackConsumptionRule.cs b/src/Lumina.Domain/Core/BoundedContexts/MediaConsumptionBoundedContext/MediaConsumptionRecordAggregate/ValueObjects/MusicTrackConsumptionRule.cs new file mode 100644 index 00000000..1b3033bd --- /dev/null +++ b/src/Lumina.Domain/Core/BoundedContexts/MediaConsumptionBoundedContext/MediaConsumptionRecordAggregate/ValueObjects/MusicTrackConsumptionRule.cs @@ -0,0 +1,40 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.Common.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using System; +#endregion + +namespace Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.MediaConsumptionRecordAggregate.ValueObjects; + +/// +/// Value Object for the consumption rules of a music track. +/// +public sealed class MusicTrackConsumptionRule : DurationThresholdConsumptionRule +{ + /// + /// Gets the kind of media that this rule applies to. + /// + public override MediaKind MediaKind { get; } = MediaKind.MusicTrack; + + /// + /// Gets a value indicating whether the current catalogues support this kind of media. + /// + public override bool IsSupportedByCurrentCatalogues { get; } = true; + + /// + /// Gets the kind of position used to resume this kind of media, if the kind can be resumed. + /// + public override Optional PositionKind { get; } = MediaPositionKind.TimeOffset; + + /// + /// Gets a value indicating whether a consumption session of this kind of media is a one-shot session, which completes at the moment it starts. + /// + public override bool IsOneShot { get; } = false; + + /// + /// Gets the minimum consumed duration that a session of this kind of media must reach to be counted, when it is not completed. + /// + public override TimeSpan MinimumCountedDuration { get; } = TimeSpan.FromSeconds(30); +} diff --git a/src/Lumina.Domain/Core/BoundedContexts/MediaConsumptionBoundedContext/MediaConsumptionRecordAggregate/ValueObjects/PhotoConsumptionRule.cs b/src/Lumina.Domain/Core/BoundedContexts/MediaConsumptionBoundedContext/MediaConsumptionRecordAggregate/ValueObjects/PhotoConsumptionRule.cs new file mode 100644 index 00000000..212e4454 --- /dev/null +++ b/src/Lumina.Domain/Core/BoundedContexts/MediaConsumptionBoundedContext/MediaConsumptionRecordAggregate/ValueObjects/PhotoConsumptionRule.cs @@ -0,0 +1,34 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.Common.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +#endregion + +namespace Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.MediaConsumptionRecordAggregate.ValueObjects; + +/// +/// Value Object for the consumption rules of a photo. +/// +public sealed class PhotoConsumptionRule : EverySessionConsumptionRule +{ + /// + /// Gets the kind of media that this rule applies to. + /// + public override MediaKind MediaKind { get; } = MediaKind.Photo; + + /// + /// Gets a value indicating whether the current catalogues support this kind of media. + /// + public override bool IsSupportedByCurrentCatalogues { get; } = false; + + /// + /// Gets the kind of position used to resume this kind of media. A photo cannot be resumed, so it has no position kind. + /// + public override Optional PositionKind { get; } = Optional.None(); + + /// + /// Gets a value indicating whether a consumption session of this kind of media is a one-shot session, which completes at the moment it starts. + /// + public override bool IsOneShot { get; } = true; +} diff --git a/src/Lumina.Domain/Core/BoundedContexts/MediaConsumptionBoundedContext/MediaConsumptionRecordAggregate/ValueObjects/PodcastEpisodeConsumptionRule.cs b/src/Lumina.Domain/Core/BoundedContexts/MediaConsumptionBoundedContext/MediaConsumptionRecordAggregate/ValueObjects/PodcastEpisodeConsumptionRule.cs new file mode 100644 index 00000000..a3b27752 --- /dev/null +++ b/src/Lumina.Domain/Core/BoundedContexts/MediaConsumptionBoundedContext/MediaConsumptionRecordAggregate/ValueObjects/PodcastEpisodeConsumptionRule.cs @@ -0,0 +1,40 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.Common.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using System; +#endregion + +namespace Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.MediaConsumptionRecordAggregate.ValueObjects; + +/// +/// Value Object for the consumption rules of a podcast episode. +/// +public sealed class PodcastEpisodeConsumptionRule : DurationThresholdConsumptionRule +{ + /// + /// Gets the kind of media that this rule applies to. + /// + public override MediaKind MediaKind { get; } = MediaKind.PodcastEpisode; + + /// + /// Gets a value indicating whether the current catalogues support this kind of media. + /// + public override bool IsSupportedByCurrentCatalogues { get; } = false; + + /// + /// Gets the kind of position used to resume this kind of media, if the kind can be resumed. + /// + public override Optional PositionKind { get; } = MediaPositionKind.TimeOffset; + + /// + /// Gets a value indicating whether a consumption session of this kind of media is a one-shot session, which completes at the moment it starts. + /// + public override bool IsOneShot { get; } = false; + + /// + /// Gets the minimum consumed duration that a session of this kind of media must reach to be counted, when it is not completed. + /// + public override TimeSpan MinimumCountedDuration { get; } = TimeSpan.FromSeconds(30); +} diff --git a/src/Lumina.Domain/Core/BoundedContexts/MediaConsumptionBoundedContext/MediaConsumptionRecordAggregate/ValueObjects/TvEpisodeConsumptionRule.cs b/src/Lumina.Domain/Core/BoundedContexts/MediaConsumptionBoundedContext/MediaConsumptionRecordAggregate/ValueObjects/TvEpisodeConsumptionRule.cs new file mode 100644 index 00000000..61e5478c --- /dev/null +++ b/src/Lumina.Domain/Core/BoundedContexts/MediaConsumptionBoundedContext/MediaConsumptionRecordAggregate/ValueObjects/TvEpisodeConsumptionRule.cs @@ -0,0 +1,40 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.Common.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using System; +#endregion + +namespace Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.MediaConsumptionRecordAggregate.ValueObjects; + +/// +/// Value Object for the consumption rules of a TV show episode. +/// +public sealed class TvEpisodeConsumptionRule : DurationThresholdConsumptionRule +{ + /// + /// Gets the kind of media that this rule applies to. + /// + public override MediaKind MediaKind { get; } = MediaKind.TvEpisode; + + /// + /// Gets a value indicating whether the current catalogues support this kind of media. + /// + public override bool IsSupportedByCurrentCatalogues { get; } = false; + + /// + /// Gets the kind of position used to resume this kind of media, if the kind can be resumed. + /// + public override Optional PositionKind { get; } = MediaPositionKind.TimeOffset; + + /// + /// Gets a value indicating whether a consumption session of this kind of media is a one-shot session, which completes at the moment it starts. + /// + public override bool IsOneShot { get; } = false; + + /// + /// Gets the minimum consumed duration that a session of this kind of media must reach to be counted, when it is not completed. + /// + public override TimeSpan MinimumCountedDuration { get; } = TimeSpan.FromMinutes(3); +} diff --git a/src/Lumina.Domain/Core/BoundedContexts/MediaConsumptionBoundedContext/MediaConsumptionRecordAggregate/ValueObjects/VideoConsumptionRule.cs b/src/Lumina.Domain/Core/BoundedContexts/MediaConsumptionBoundedContext/MediaConsumptionRecordAggregate/ValueObjects/VideoConsumptionRule.cs new file mode 100644 index 00000000..c9801bde --- /dev/null +++ b/src/Lumina.Domain/Core/BoundedContexts/MediaConsumptionBoundedContext/MediaConsumptionRecordAggregate/ValueObjects/VideoConsumptionRule.cs @@ -0,0 +1,40 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.Common.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using System; +#endregion + +namespace Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.MediaConsumptionRecordAggregate.ValueObjects; + +/// +/// Value Object for the consumption rules of a video. +/// +public sealed class VideoConsumptionRule : DurationThresholdConsumptionRule +{ + /// + /// Gets the kind of media that this rule applies to. + /// + public override MediaKind MediaKind { get; } = MediaKind.Video; + + /// + /// Gets a value indicating whether the current catalogues support this kind of media. + /// + public override bool IsSupportedByCurrentCatalogues { get; } = false; + + /// + /// Gets the kind of position used to resume this kind of media, if the kind can be resumed. + /// + public override Optional PositionKind { get; } = MediaPositionKind.TimeOffset; + + /// + /// Gets a value indicating whether a consumption session of this kind of media is a one-shot session, which completes at the moment it starts. + /// + public override bool IsOneShot { get; } = false; + + /// + /// Gets the minimum consumed duration that a session of this kind of media must reach to be counted, when it is not completed. + /// + public override TimeSpan MinimumCountedDuration { get; } = TimeSpan.FromMinutes(3); +} diff --git a/src/Lumina.Domain/Core/BoundedContexts/MediaConsumptionBoundedContext/MediaResumePointAggregate/MediaResumePoint.cs b/src/Lumina.Domain/Core/BoundedContexts/MediaConsumptionBoundedContext/MediaResumePointAggregate/MediaResumePoint.cs new file mode 100644 index 00000000..e20e564c --- /dev/null +++ b/src/Lumina.Domain/Core/BoundedContexts/MediaConsumptionBoundedContext/MediaResumePointAggregate/MediaResumePoint.cs @@ -0,0 +1,236 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Models.Core; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.Common.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.ExternalIdentifiers.LibraryManagementBoundedContext.LibraryAggregate; +using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.ExternalIdentifiers.MediaLibraryBoundedContext.MediaItemAggregate; +using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.ExternalIdentifiers.UserManagementBoundedContext.UserAggregate; +using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.MediaResumePointAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.MediaResumePointAggregate; + +/// +/// Aggregate root for the point at which a user can resume consuming a media item. +/// +[DebuggerDisplay("Id: {Id.Value}; MediaKind: {MediaKind}; MediaItemId: {MediaItemId.Value}")] +public sealed class MediaResumePoint : AggregateRoot +{ + /// + /// Gets the object representing the unique identifier of the user that owns the resume point. + /// + public UserId UserId { get; private set; } + + /// + /// Gets the Id of the media library that contains the media item. + /// + public LibraryId LibraryId { get; private set; } + + /// + /// Gets the Id of the media item to resume. + /// + public MediaItemId MediaItemId { get; private set; } + + /// + /// Gets the kind of media that is resumed. + /// + public MediaKind MediaKind { get; private set; } + + /// + /// Gets the position at which the media item can be resumed. + /// + public MediaPosition LastPosition { get; private set; } + + /// + /// Gets the progress fraction at which the media item can be resumed. + /// + public double LastProgressFraction { get; private set; } + + /// + /// Gets the date and time when the media item was last consumed. + /// + public DateTime LastConsumedOnUtc { get; private set; } + + /// + /// Initializes a new instance of the class. + /// + /// The object representing the unique identifier of the resume point. + /// The object representing the unique identifier of the user that owns the resume point. + /// The Id of the media library that contains the media item. + /// The Id of the media item to resume. + /// The kind of media that is resumed. + /// The position at which the media item can be resumed. + /// The progress fraction at which the media item can be resumed. + /// The date and time when the media item was last consumed. + /// The date and time when the resume point was created. + /// The date and time when the resume point was last updated, if applicable. + private MediaResumePoint( + MediaResumePointId id, + UserId userId, + LibraryId libraryId, + MediaItemId mediaItemId, + MediaKind mediaKind, + MediaPosition lastPosition, + double lastProgressFraction, + DateTime lastConsumedOnUtc, + DateTime createdOnUtc, + Optional updatedOnUtc) : base(id) + { + Id = id; + UserId = userId; + LibraryId = libraryId; + MediaItemId = mediaItemId; + MediaKind = mediaKind; + LastPosition = lastPosition; + LastProgressFraction = lastProgressFraction; + LastConsumedOnUtc = lastConsumedOnUtc; + CreatedOnUtc = createdOnUtc; + UpdatedOnUtc = updatedOnUtc; + } + + /// + /// Creates a new resume point for a media item. + /// + /// The object representing the unique identifier of the user that owns the resume point. + /// The Id of the media library that contains the media item. + /// The Id of the media item to resume. + /// The kind of media that is resumed. + /// The position at which the media item can be resumed. + /// The progress fraction at which the media item can be resumed. + /// The date and time when the media item was last consumed. + /// + /// An containing either a successfully created , or an error message. + /// + public static Result Create( + UserId userId, + LibraryId libraryId, + MediaItemId mediaItemId, + MediaKind mediaKind, + MediaPosition lastPosition, + double lastProgressFraction, + DateTime lastConsumedOnUtc) + { + Optional ruleResult = MediaConsumptionRule.For(mediaKind); + if (!ruleResult.HasValue) + return Errors.MediaConsumption.UnsupportedMediaKind; + if (!ruleResult.Value.CanResume) + return Errors.MediaConsumption.MediaKindCannotResume; + if (!DoesPositionMatchRule(ruleResult.Value, lastPosition)) + return Errors.MediaConsumption.InvalidMediaPosition; + if (!IsProgressFractionValid(lastProgressFraction)) + return Errors.MediaConsumption.InvalidProgressFraction; + + // A resume point is created when the media item is first consumed, so the first consumption time is also its creation time. + return new MediaResumePoint( + MediaResumePointId.CreateUnique(), + userId, + libraryId, + mediaItemId, + mediaKind, + lastPosition, + lastProgressFraction, + lastConsumedOnUtc, + lastConsumedOnUtc, + Optional.None()); + } + + /// + /// Creates a new instance of the class, with pre-existing data. + /// + /// The object representing the unique identifier of the resume point. + /// The object representing the unique identifier of the user that owns the resume point. + /// The Id of the media library that contains the media item. + /// The Id of the media item to resume. + /// The kind of media that is resumed. + /// The position at which the media item can be resumed. + /// The progress fraction at which the media item can be resumed. + /// The date and time when the media item was last consumed. + /// The date and time when the resume point was created. + /// The date and time when the resume point was last updated, if applicable. + /// + /// An containing either a successfully reconstituted , or an error message. + /// + public static Result Reconstitute( + MediaResumePointId id, + UserId userId, + LibraryId libraryId, + MediaItemId mediaItemId, + MediaKind mediaKind, + MediaPosition lastPosition, + double lastProgressFraction, + DateTime lastConsumedOnUtc, + DateTime createdOnUtc, + Optional updatedOnUtc) + { + Optional ruleResult = MediaConsumptionRule.For(mediaKind); + if (!ruleResult.HasValue) + return Errors.MediaConsumption.UnsupportedMediaKind; + if (!ruleResult.Value.CanResume) + return Errors.MediaConsumption.MediaKindCannotResume; + if (!DoesPositionMatchRule(ruleResult.Value, lastPosition)) + return Errors.MediaConsumption.InvalidMediaPosition; + if (!IsProgressFractionValid(lastProgressFraction)) + return Errors.MediaConsumption.InvalidProgressFraction; + + return new MediaResumePoint( + id, + userId, + libraryId, + mediaItemId, + mediaKind, + lastPosition, + lastProgressFraction, + lastConsumedOnUtc, + createdOnUtc, + updatedOnUtc); + } + + /// + /// Moves the resume point to a new position and progress fraction. + /// + /// The position at which the media item can be resumed. + /// The progress fraction at which the media item can be resumed. + /// The date and time when the media item was last consumed. + /// An representing either a successful update, or an error. + public Result Advance(MediaPosition position, double progressFraction, DateTime lastConsumedOnUtc) + { + Optional ruleResult = MediaConsumptionRule.For(MediaKind); + if (!ruleResult.HasValue) + return Errors.MediaConsumption.UnsupportedMediaKind; + if (!DoesPositionMatchRule(ruleResult.Value, position)) + return Errors.MediaConsumption.InvalidMediaPosition; + if (!IsProgressFractionValid(progressFraction)) + return Errors.MediaConsumption.InvalidProgressFraction; + + LastPosition = position; + LastProgressFraction = progressFraction; + LastConsumedOnUtc = lastConsumedOnUtc; + UpdatedOnUtc = Optional.Some(lastConsumedOnUtc); + return Result.Updated; + } + + /// + /// Determines whether the progress fraction is a finite value between zero and one. + /// + /// The progress fraction to check. + /// if the progress fraction is valid, otherwise. + private static bool IsProgressFractionValid(double progressFraction) + { + return double.IsFinite(progressFraction) && progressFraction >= 0 && progressFraction <= 1; + } + + /// + /// Determines whether the position uses the position representation of the consumption rule of the media kind. + /// + /// The consumption rule of the media kind. + /// The position to check. + /// if the position is valid for the media kind, otherwise. + private static bool DoesPositionMatchRule(MediaConsumptionRule rule, MediaPosition position) + { + return rule.PositionKind.HasValue && position.Kind == rule.PositionKind.Value; + } +} diff --git a/src/Lumina.Domain/Core/BoundedContexts/MediaConsumptionBoundedContext/MediaResumePointAggregate/ValueObjects/MediaResumePointId.cs b/src/Lumina.Domain/Core/BoundedContexts/MediaConsumptionBoundedContext/MediaResumePointAggregate/ValueObjects/MediaResumePointId.cs new file mode 100644 index 00000000..4e24a555 --- /dev/null +++ b/src/Lumina.Domain/Core/BoundedContexts/MediaConsumptionBoundedContext/MediaResumePointAggregate/ValueObjects/MediaResumePointId.cs @@ -0,0 +1,51 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Models.Core; +using System; +using System.Collections.Generic; +using System.Diagnostics; +#endregion + +namespace Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.MediaResumePointAggregate.ValueObjects; + +/// +/// Value Object for the Id of a media resume point. +/// +[DebuggerDisplay("{Value}")] +public sealed class MediaResumePointId : EntityId +{ + /// + /// Initializes a new instance of the class. + /// + /// The value representing this object. + private MediaResumePointId(Guid value) : base(value) + { + } + + /// + /// Creates a new instance of the class. + /// + /// The created instance. + public static MediaResumePointId CreateUnique() + { + return new MediaResumePointId(Guid.NewGuid()); + } + + /// + /// Creates a new instance of the class, from a pre-existing . + /// + /// The value used to create the instance. + /// The created instance. + public static MediaResumePointId Create(Guid value) + { + return new MediaResumePointId(value); + } + + /// + /// Gets the list of items that define equality of the object. + /// + /// A list of items defining the equality. + public override IEnumerable GetEqualityComponents() + { + yield return Value; + } +} diff --git a/src/Lumina.Domain/Core/BoundedContexts/PlaylistBoundedContext/ExternalIdentifiers/MediaLibraryBoundedContext/MediaItemAggregate/MediaItemId.cs b/src/Lumina.Domain/Core/BoundedContexts/PlaylistBoundedContext/ExternalIdentifiers/MediaLibraryBoundedContext/MediaItemAggregate/MediaItemId.cs new file mode 100644 index 00000000..37adf434 --- /dev/null +++ b/src/Lumina.Domain/Core/BoundedContexts/PlaylistBoundedContext/ExternalIdentifiers/MediaLibraryBoundedContext/MediaItemAggregate/MediaItemId.cs @@ -0,0 +1,54 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Models.Core; +using System; +using System.Collections.Generic; +using System.Diagnostics; +#endregion + +namespace Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.ExternalIdentifiers.MediaLibraryBoundedContext.MediaItemAggregate; + +/// +/// Value Object for the Id of a media item, duplicated from the media library bounded contexts to keep the cross bounded context references decoupled. +/// +/// +/// The kind of media item is carried by the playlist entry and by the playlist type, so this identifier stays generic across music tracks and video files. +/// +[DebuggerDisplay("{Value}")] +public sealed class MediaItemId : EntityId +{ + /// + /// Initializes a new instance of the class. + /// + /// The value representing this object. + private MediaItemId(Guid value) : base(value) + { + } + + /// + /// Creates a new instance of the class. + /// + /// The created instance. + public static MediaItemId CreateUnique() + { + return new MediaItemId(Guid.NewGuid()); + } + + /// + /// Creates a new instance of the class, from a pre-existing . + /// + /// The value used to create the instance. + /// The created instance. + public static MediaItemId Create(Guid value) + { + return new MediaItemId(value); + } + + /// + /// Gets the list of items that define equality of the object. + /// + /// A list of items defining the equality. + public override IEnumerable GetEqualityComponents() + { + yield return Value; + } +} diff --git a/src/Lumina.Domain/Core/BoundedContexts/PlaylistBoundedContext/ExternalIdentifiers/UserManagementBoundedContext/UserAggregate/UserId.cs b/src/Lumina.Domain/Core/BoundedContexts/PlaylistBoundedContext/ExternalIdentifiers/UserManagementBoundedContext/UserAggregate/UserId.cs new file mode 100644 index 00000000..1104b077 --- /dev/null +++ b/src/Lumina.Domain/Core/BoundedContexts/PlaylistBoundedContext/ExternalIdentifiers/UserManagementBoundedContext/UserAggregate/UserId.cs @@ -0,0 +1,51 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Models.Core; +using System; +using System.Collections.Generic; +using System.Diagnostics; +#endregion + +namespace Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.ExternalIdentifiers.UserManagementBoundedContext.UserAggregate; + +/// +/// Value Object for the Id of a user, duplicated from the UserManagement bounded context to keep the cross bounded context references decoupled. +/// +[DebuggerDisplay("{Value}")] +public sealed class UserId : EntityId +{ + /// + /// Initializes a new instance of the class. + /// + /// The value representing this object. + private UserId(Guid value) : base(value) + { + } + + /// + /// Creates a new instance of the class. + /// + /// The created instance. + public static UserId CreateUnique() + { + return new UserId(Guid.NewGuid()); + } + + /// + /// Creates a new instance of the class, from a pre-existing . + /// + /// The value used to create the instance. + /// The created instance. + public static UserId Create(Guid value) + { + return new UserId(value); + } + + /// + /// Gets the list of items that define equality of the object. + /// + /// A list of items defining the equality. + public override IEnumerable GetEqualityComponents() + { + yield return Value; + } +} diff --git a/src/Lumina.Domain/Core/BoundedContexts/PlaylistBoundedContext/PlaylistAggregate/Entities/PlaylistEntry.cs b/src/Lumina.Domain/Core/BoundedContexts/PlaylistBoundedContext/PlaylistAggregate/Entities/PlaylistEntry.cs new file mode 100644 index 00000000..50b9aa0c --- /dev/null +++ b/src/Lumina.Domain/Core/BoundedContexts/PlaylistBoundedContext/PlaylistAggregate/Entities/PlaylistEntry.cs @@ -0,0 +1,62 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Models.Core; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.ExternalIdentifiers.MediaLibraryBoundedContext.MediaItemAggregate; +using Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.Playlists; +using System.Diagnostics; +#endregion + +namespace Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate.Entities; + +/// +/// Entity for an ordered entry of a playlist. +/// +[DebuggerDisplay("Id: {Id.Value}; MediaItemId: {MediaItemId.Value}; MediaItemType: {MediaItemType}; Position: {Position}")] +public sealed class PlaylistEntry : Entity +{ + /// + /// Gets the Id of the media item referenced by the entry. + /// + public MediaItemId MediaItemId { get; private set; } + + /// + /// Gets the kind of media item referenced by the entry. + /// + public PlaylistMediaItemType MediaItemType { get; private set; } + + /// + /// Gets the sparse order key of the entry in the ordered entries of the playlist. + /// + public long Position { get; private set; } + + /// + /// Initializes a new instance of the class. + /// + /// The object representing the unique identifier of the entry. + /// The Id of the media item referenced by the entry. + /// The kind of media item referenced by the entry. + /// The sparse order key of the entry in the ordered entries of the playlist. + private PlaylistEntry(PlaylistEntryId id, MediaItemId mediaItemId, PlaylistMediaItemType mediaItemType, long position) : base(id) + { + Id = id; + MediaItemId = mediaItemId; + MediaItemType = mediaItemType; + Position = position; + } + + /// + /// Creates a new instance of the class, with a pre-existing . + /// + /// The object representing the unique identifier of the entry. + /// The Id of the media item referenced by the entry. + /// The kind of media item referenced by the entry. + /// The sparse order key of the entry in the ordered entries of the playlist. + /// + /// An containing either a successfully created , or an error message. + /// + public static Result Create(PlaylistEntryId id, MediaItemId mediaItemId, PlaylistMediaItemType mediaItemType, long position) + { + return new PlaylistEntry(id, mediaItemId, mediaItemType, position); + } +} diff --git a/src/Lumina.Domain/Core/BoundedContexts/PlaylistBoundedContext/PlaylistAggregate/Events/PlaylistCreatedDomainEvent.cs b/src/Lumina.Domain/Core/BoundedContexts/PlaylistBoundedContext/PlaylistAggregate/Events/PlaylistCreatedDomainEvent.cs new file mode 100644 index 00000000..992b4be9 --- /dev/null +++ b/src/Lumina.Domain/Core/BoundedContexts/PlaylistBoundedContext/PlaylistAggregate/Events/PlaylistCreatedDomainEvent.cs @@ -0,0 +1,29 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Events; +using Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.ExternalIdentifiers.UserManagementBoundedContext.UserAggregate; +using Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.Playlists; +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate.Events; + +/// +/// Domain event raised when a playlist is created. +/// +/// The unique identifier of the domain event. +/// The unique identifier of the playlist. +/// The unique identifier of the user that owns the playlist. +/// The name of the playlist. +/// The kind of media the playlist holds. +/// The date and time when the domain event occurred. +[DebuggerDisplay("PlaylistId: {PlaylistId.Value}; UserId: {UserId.Value}")] +public record PlaylistCreatedDomainEvent( + Guid Id, + PlaylistId PlaylistId, + UserId UserId, + string Name, + PlaylistType Type, + DateTime OccurredOnUtc +) : IDomainEvent; diff --git a/src/Lumina.Domain/Core/BoundedContexts/PlaylistBoundedContext/PlaylistAggregate/Events/PlaylistDeletedDomainEvent.cs b/src/Lumina.Domain/Core/BoundedContexts/PlaylistBoundedContext/PlaylistAggregate/Events/PlaylistDeletedDomainEvent.cs new file mode 100644 index 00000000..8fbf84b9 --- /dev/null +++ b/src/Lumina.Domain/Core/BoundedContexts/PlaylistBoundedContext/PlaylistAggregate/Events/PlaylistDeletedDomainEvent.cs @@ -0,0 +1,24 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Events; +using Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.ExternalIdentifiers.UserManagementBoundedContext.UserAggregate; +using Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate.ValueObjects; +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate.Events; + +/// +/// Domain event raised when a playlist is deleted. +/// +/// The unique identifier of the domain event. +/// The unique identifier of the playlist. +/// The unique identifier of the user that owned the playlist. +/// The date and time when the domain event occurred. +[DebuggerDisplay("PlaylistId: {PlaylistId.Value}; UserId: {UserId.Value}")] +public record PlaylistDeletedDomainEvent( + Guid Id, + PlaylistId PlaylistId, + UserId UserId, + DateTime OccurredOnUtc +) : IDomainEvent; diff --git a/src/Lumina.Domain/Core/BoundedContexts/PlaylistBoundedContext/PlaylistAggregate/Events/PlaylistDetailsUpdatedDomainEvent.cs b/src/Lumina.Domain/Core/BoundedContexts/PlaylistBoundedContext/PlaylistAggregate/Events/PlaylistDetailsUpdatedDomainEvent.cs new file mode 100644 index 00000000..03cf3861 --- /dev/null +++ b/src/Lumina.Domain/Core/BoundedContexts/PlaylistBoundedContext/PlaylistAggregate/Events/PlaylistDetailsUpdatedDomainEvent.cs @@ -0,0 +1,26 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Events; +using Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.ExternalIdentifiers.UserManagementBoundedContext.UserAggregate; +using Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate.ValueObjects; +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate.Events; + +/// +/// Domain event raised when the details of a playlist are updated. +/// +/// The unique identifier of the domain event. +/// The unique identifier of the playlist. +/// The unique identifier of the user that owns the playlist. +/// The new name of the playlist. +/// The date and time when the domain event occurred. +[DebuggerDisplay("PlaylistId: {PlaylistId.Value}; Name: {Name}")] +public record PlaylistDetailsUpdatedDomainEvent( + Guid Id, + PlaylistId PlaylistId, + UserId UserId, + string Name, + DateTime OccurredOnUtc +) : IDomainEvent; diff --git a/src/Lumina.Domain/Core/BoundedContexts/PlaylistBoundedContext/PlaylistAggregate/Playlist.cs b/src/Lumina.Domain/Core/BoundedContexts/PlaylistBoundedContext/PlaylistAggregate/Playlist.cs new file mode 100644 index 00000000..b18e7986 --- /dev/null +++ b/src/Lumina.Domain/Core/BoundedContexts/PlaylistBoundedContext/PlaylistAggregate/Playlist.cs @@ -0,0 +1,228 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Models.Core; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.ExternalIdentifiers.UserManagementBoundedContext.UserAggregate; +using Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate.Entities; +using Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate.Events; +using Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.Playlists; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; +#endregion + +namespace Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate; + +/// +/// Aggregate root for a playlist. +/// +[DebuggerDisplay("Id: {Id.Value}; Name: {Name}; Type: {Type}")] +public sealed class Playlist : AggregateRoot +{ + private readonly List _entries; + + /// + /// Gets the object representing the unique identifier of the user that owns the playlist. + /// + public UserId UserId { get; private set; } + + /// + /// Gets the name of the playlist. + /// + public string Name { get; private set; } + + /// + /// Gets the description of the playlist, if applicable. + /// + public Optional Description { get; private set; } + + /// + /// Gets the kind of media the playlist holds. + /// + public PlaylistType Type { get; private set; } + + /// + /// Gets a value indicating whether the playlist was marked for deletion in this unit of work. + /// + public bool IsDeleted { get; private set; } + + /// + /// Gets the ordered entries of the playlist. + /// + public IReadOnlyCollection Entries => _entries.AsReadOnly(); + + /// + /// Initializes a new instance of the class. + /// + /// The object representing the unique identifier of the playlist. + /// The object representing the unique identifier of the user that owns the playlist. + /// The name of the playlist. + /// The optional description of the playlist. + /// The kind of media the playlist holds. + /// The ordered entries of the playlist. + /// The date and time when the playlist was created. + /// The date and time when the playlist was last updated. + private Playlist( + PlaylistId id, + UserId userId, + string name, + Optional description, + PlaylistType type, + List entries, + DateTime createdOnUtc, + Optional updatedOnUtc) : base(id) + { + Id = id; + UserId = userId; + Name = name; + Description = description; + Type = type; + _entries = entries; + CreatedOnUtc = createdOnUtc; + UpdatedOnUtc = updatedOnUtc; + } + + /// + /// Creates a new playlist for the user identified by . + /// + /// The object representing the unique identifier of the user that owns the playlist. + /// The name of the playlist. + /// The optional description of the playlist. + /// The kind of media the playlist holds. + /// + /// An containing either a successfully created , or an error message. + /// + public static Result Create(UserId userId, string name, Optional description, PlaylistType type) + { + DateTime occurredOnUtc = DateTime.UtcNow; + Playlist playlist = new( + PlaylistId.CreateUnique(), + userId, + name, + description, + type, + [], + occurredOnUtc, + Optional.None()); + + playlist._domainEvents.Add(new PlaylistCreatedDomainEvent( + Guid.NewGuid(), + playlist.Id, + userId, + name, + type, + occurredOnUtc)); + return playlist; + } + + /// + /// Creates a new instance of the class, with pre-existing data. + /// + /// The object representing the unique identifier of the playlist. + /// The object representing the unique identifier of the user that owns the playlist. + /// The name of the playlist. + /// The optional description of the playlist. + /// The kind of media the playlist holds. + /// The ordered entries of the playlist. + /// The date and time when the playlist was created. + /// The date and time when the playlist was last updated. + /// + /// An containing either a successfully created , or an error message. + /// + public static Result Create( + PlaylistId id, + UserId userId, + string name, + Optional description, + PlaylistType type, + List entries, + DateTime createdOnUtc, + Optional updatedOnUtc) + { + if (entries.Any(entry => !CanContain(type, entry.MediaItemType))) + return Errors.Playlists.PlaylistDoesNotAcceptMediaItems; + // The positions are sparse order keys, so they must be unique. The gaps between them are intentional and are not a reason to reject an otherwise readable playlist. + if (!ArePositionsValid(entries)) + return Errors.Playlists.PlaylistEntryPositionsAreInvalid; + + return new Playlist(id, userId, name, description, type, entries, createdOnUtc, updatedOnUtc); + } + + /// + /// Updates the name and the description of the playlist, without touching its entries. + /// + /// The name of the playlist. + /// The optional description of the playlist. + /// An representing either a successful update, or an error. + public Result UpdateDetails(string name, Optional description) + { + bool hasChanged = Name != name + || Description.HasValue != description.HasValue + || (Description.HasValue && description.HasValue && Description.Value != description.Value); + if (!hasChanged) + return Result.Updated; + + Name = name; + Description = description; + DateTime occurredOnUtc = DateTime.UtcNow; + _domainEvents.Add(new PlaylistDetailsUpdatedDomainEvent( + Guid.NewGuid(), + Id, + UserId, + name, + occurredOnUtc)); + return Result.Updated; + } + + /// + /// Marks the playlist as deleted, raising the domain event that announces its deletion. + /// + /// An representing either a successful operation, or an error. + public Result Delete() + { + if (IsDeleted) + return Result.Deleted; + + // Earlier events become irrelevant once the playlist is deleted. + _domainEvents.Clear(); + IsDeleted = true; + _domainEvents.Add(new PlaylistDeletedDomainEvent( + Guid.NewGuid(), + Id, + UserId, + DateTime.UtcNow)); + return Result.Deleted; + } + + /// + /// Determines whether a playlist of can contain . + /// + /// The kind of media the playlist holds. + /// The kind of media item referenced by an entry. + /// if the media item type belongs to the playlist type, otherwise. + public static bool CanContain(PlaylistType playlistType, PlaylistMediaItemType mediaItemType) + { + return playlistType switch + { + PlaylistType.Music => mediaItemType == PlaylistMediaItemType.MusicTrack, + _ => false + }; + } + + /// + /// Determines whether the positions of are unique. + /// + /// The entries whose positions are checked. + /// if the positions are unique, otherwise. + private static bool ArePositionsValid(IReadOnlyCollection entries) + { + // The storage enforces unique order keys with a unique index, and the sparse keys are allowed to have wide gaps. + HashSet positions = []; + foreach (PlaylistEntry entry in entries) + if (!positions.Add(entry.Position)) + return false; + return true; + } +} diff --git a/src/Lumina.Domain/Core/BoundedContexts/PlaylistBoundedContext/PlaylistAggregate/ValueObjects/PlaylistEntryId.cs b/src/Lumina.Domain/Core/BoundedContexts/PlaylistBoundedContext/PlaylistAggregate/ValueObjects/PlaylistEntryId.cs new file mode 100644 index 00000000..18378ef6 --- /dev/null +++ b/src/Lumina.Domain/Core/BoundedContexts/PlaylistBoundedContext/PlaylistAggregate/ValueObjects/PlaylistEntryId.cs @@ -0,0 +1,51 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Models.Core; +using System; +using System.Collections.Generic; +using System.Diagnostics; +#endregion + +namespace Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate.ValueObjects; + +/// +/// Value Object for the Id of an entry of a playlist. +/// +[DebuggerDisplay("{Value}")] +public sealed class PlaylistEntryId : EntityId +{ + /// + /// Initializes a new instance of the class. + /// + /// The value representing this object. + private PlaylistEntryId(Guid value) : base(value) + { + } + + /// + /// Creates a new instance of the class. + /// + /// The created instance. + public static PlaylistEntryId CreateUnique() + { + return new PlaylistEntryId(Guid.NewGuid()); + } + + /// + /// Creates a new instance of the class, from a pre-existing . + /// + /// The value used to create the instance. + /// The created instance. + public static PlaylistEntryId Create(Guid value) + { + return new PlaylistEntryId(value); + } + + /// + /// Gets the list of items that define equality of the object. + /// + /// A list of items defining the equality. + public override IEnumerable GetEqualityComponents() + { + yield return Value; + } +} diff --git a/src/Lumina.Domain/Core/BoundedContexts/PlaylistBoundedContext/PlaylistAggregate/ValueObjects/PlaylistId.cs b/src/Lumina.Domain/Core/BoundedContexts/PlaylistBoundedContext/PlaylistAggregate/ValueObjects/PlaylistId.cs new file mode 100644 index 00000000..786941bb --- /dev/null +++ b/src/Lumina.Domain/Core/BoundedContexts/PlaylistBoundedContext/PlaylistAggregate/ValueObjects/PlaylistId.cs @@ -0,0 +1,51 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Models.Core; +using System; +using System.Collections.Generic; +using System.Diagnostics; +#endregion + +namespace Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate.ValueObjects; + +/// +/// Value Object for the Id of a playlist. +/// +[DebuggerDisplay("{Value}")] +public sealed class PlaylistId : EntityId +{ + /// + /// Initializes a new instance of the class. + /// + /// The value representing this object. + private PlaylistId(Guid value) : base(value) + { + } + + /// + /// Creates a new instance of the class. + /// + /// The created instance. + public static PlaylistId CreateUnique() + { + return new PlaylistId(Guid.NewGuid()); + } + + /// + /// Creates a new instance of the class, from a pre-existing . + /// + /// The value used to create the instance. + /// The created instance. + public static PlaylistId Create(Guid value) + { + return new PlaylistId(value); + } + + /// + /// Gets the list of items that define equality of the object. + /// + /// A list of items defining the equality. + public override IEnumerable GetEqualityComponents() + { + yield return Value; + } +} diff --git a/src/Lumina.Domain/Core/BoundedContexts/SchedulingBoundedContext/ExternalIdentifiers/UserManagementBoundedContext/UserAggregate/UserId.cs b/src/Lumina.Domain/Core/BoundedContexts/SchedulingBoundedContext/ExternalIdentifiers/UserManagementBoundedContext/UserAggregate/UserId.cs index 8af9c718..271b3e7e 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/SchedulingBoundedContext/ExternalIdentifiers/UserManagementBoundedContext/UserAggregate/UserId.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/SchedulingBoundedContext/ExternalIdentifiers/UserManagementBoundedContext/UserAggregate/UserId.cs @@ -8,7 +8,7 @@ using System.Diagnostics; namespace Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ExternalIdentifiers.UserManagementBoundedContext.UserAggregate; /// -/// Value object for the Id of a user, duplicated from the UserManagement bounded context to keep the cross bounded context references decoupled. +/// Value Object for the Id of a user, duplicated from the UserManagement bounded context to keep the cross bounded context references decoupled. /// [DebuggerDisplay("{Value}")] public sealed class UserId : EntityId diff --git a/src/Lumina.Domain/Core/BoundedContexts/UserManagementBoundedContext/UserSettingsAggregate/UserSettings.cs b/src/Lumina.Domain/Core/BoundedContexts/UserManagementBoundedContext/UserSettingsAggregate/UserSettings.cs index 59f22083..3e75c2e9 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/UserManagementBoundedContext/UserSettingsAggregate/UserSettings.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/UserManagementBoundedContext/UserSettingsAggregate/UserSettings.cs @@ -1,9 +1,9 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Models.Core; using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserSettingsAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.Playback; using System.Diagnostics; #endregion @@ -23,6 +23,22 @@ public class UserSettings : AggregateRoot private const bool DEFAULT_AGGREGATE_ARTWORK_WHEN_MISSING = false; private const bool DEFAULT_SHOULD_RENDER_PDF_AS_IMAGES = false; private const bool DEFAULT_SHOULD_PRESERVE_BOOK_STYLES = true; + private const bool DEFAULT_SHOULD_KEEP_DOWNLOADING_WHILE_PAUSED = true; + private const bool DEFAULT_SHOULD_AUTOPLAY = true; + private const bool DEFAULT_IS_GAPLESS_PLAYBACK_ENABLED = true; + private const ReplayGainMode DEFAULT_REPLAY_GAIN_MODE = ReplayGainMode.Off; + private const PlaybackStreamingQuality DEFAULT_STREAMING_QUALITY = PlaybackStreamingQuality.Auto; + private const VuMeterOrientation DEFAULT_VU_METER_ORIENTATION = VuMeterOrientation.Vertical; + private const int DEFAULT_VU_METER_SEGMENT_COUNT = 12; + private const int DEFAULT_VU_METER_SEGMENT_GAP = 1; + private const double DEFAULT_VU_METER_MEDIUM_THRESHOLD = 0.6; + private const double DEFAULT_VU_METER_HIGH_THRESHOLD = 0.8; + private const bool DEFAULT_VU_METER_SHOW_PEAK = true; + private const int DEFAULT_VU_METER_PEAK_HOLD_DURATION_IN_MILLISECONDS = 650; + private const double DEFAULT_VU_METER_RELEASE_PER_SECOND = 3.0; + private const double DEFAULT_VU_METER_PEAK_RELEASE_PER_SECOND = 0.65; + private const double DEFAULT_VOLUME = 1.0; + private const bool DEFAULT_IS_MUTED = false; /// /// Gets the object representing the unique identifier of the user that owns these settings. @@ -72,6 +88,86 @@ public class UserSettings : AggregateRoot /// public bool ShouldPreserveBookStyles { get; private set; } + /// + /// Gets whether the player keeps downloading a track while playback is paused, or not, up to the entire file. + /// + public bool ShouldKeepDownloadingWhilePaused { get; private set; } + + /// + /// Gets whether the player continues playback at the end of an album or artist, or not. + /// + public bool ShouldAutoplay { get; private set; } + + /// + /// Gets whether the player transitions between consecutive tracks without a gap, or not. + /// + public bool IsGaplessPlaybackEnabled { get; private set; } + + /// + /// Gets the way ReplayGain normalization is applied to the tracks the user plays. + /// + public ReplayGainMode ReplayGainMode { get; private set; } + + /// + /// Gets the quality cap applied to the audio the server normalizes for the user. + /// + public PlaybackStreamingQuality StreamingQuality { get; private set; } + + /// + /// Gets the direction in which each channel of the VU meter of the audio player grows. + /// + public VuMeterOrientation VuMeterOrientation { get; private set; } + + /// + /// Gets the number of segments each channel of the VU meter is divided into. + /// + public int VuMeterSegmentCount { get; private set; } + + /// + /// Gets the gap, in pixels, between the segments and the channels of the VU meter. + /// + public int VuMeterSegmentGap { get; private set; } + + /// + /// Gets the level, between 0 and 1, above which a segment of the VU meter is drawn with its medium state. + /// + public double VuMeterMediumThreshold { get; private set; } + + /// + /// Gets the level, between 0 and 1, above which a segment of the VU meter is drawn with its high state. + /// + public double VuMeterHighThreshold { get; private set; } + + /// + /// Gets whether the VU meter holds the peak level of each channel after it falls, or not. + /// + public bool VuMeterShowPeak { get; private set; } + + /// + /// Gets the time, in milliseconds, a peak of the VU meter is held before it starts falling. + /// + public int VuMeterPeakHoldDurationInMilliseconds { get; private set; } + + /// + /// Gets the number of level units the display of the VU meter falls per second when the input level drops. + /// + public double VuMeterReleasePerSecond { get; private set; } + + /// + /// Gets the number of level units the peak of the VU meter falls per second after its hold time elapsed. + /// + public double VuMeterPeakReleasePerSecond { get; private set; } + + /// + /// Gets the last volume the player reported for the user. It is written automatically by the player, and is not part of the settings the user edits. + /// + public double Volume { get; private set; } + + /// + /// Gets the last mute state the player reported for the user. It is written automatically by the player, and is not part of the settings the user edits. + /// + public bool IsMuted { get; private set; } + /// /// Initializes a new instance of the class. /// @@ -85,6 +181,22 @@ public class UserSettings : AggregateRoot /// Whether the artwork of the media library items is aggregated from multiple providers, when it is missing, or not. /// Whether PDF books are rendered as page images for the user, or not. /// Whether the styles of the book content are preserved when it is rendered for the user, or not. + /// Whether the player keeps downloading a track while playback is paused, or not. + /// Whether the player continues playback at the end of an album or artist, or not. + /// Whether the player transitions between consecutive tracks without a gap, or not. + /// The way ReplayGain normalization is applied to the tracks the user plays. + /// The quality cap applied to the audio the server normalizes for the user. + /// The direction in which each channel of the VU meter of the audio player grows. + /// The number of segments each channel of the VU meter is divided into. + /// The gap, in pixels, between the segments and the channels of the VU meter. + /// The level above which a segment of the VU meter is drawn with its medium state. + /// The level above which a segment of the VU meter is drawn with its high state. + /// Whether the VU meter holds the peak level of each channel after it falls, or not. + /// The time a peak of the VU meter is held before it starts falling. + /// The number of level units the display of the VU meter falls per second when the input level drops. + /// The number of level units the peak of the VU meter falls per second after its hold time elapsed. + /// The last volume the player reported for the user. + /// The last mute state the player reported for the user. private UserSettings( UserSettingsId id, UserId userId, @@ -95,7 +207,23 @@ public class UserSettings : AggregateRoot bool shouldAggregateMetadataWhenMissing, bool shouldAggregateArtworkWhenMissing, bool shouldRenderPdfAsImages, - bool shouldPreserveBookStyles) : base(id) + bool shouldPreserveBookStyles, + bool shouldKeepDownloadingWhilePaused, + bool shouldAutoplay, + bool isGaplessPlaybackEnabled, + ReplayGainMode replayGainMode, + PlaybackStreamingQuality streamingQuality, + VuMeterOrientation vuMeterOrientation, + int vuMeterSegmentCount, + int vuMeterSegmentGap, + double vuMeterMediumThreshold, + double vuMeterHighThreshold, + bool vuMeterShowPeak, + int vuMeterPeakHoldDurationInMilliseconds, + double vuMeterReleasePerSecond, + double vuMeterPeakReleasePerSecond, + double volume, + bool isMuted) : base(id) { UserId = userId; IsPaginationEnabled = isPaginationEnabled; @@ -106,6 +234,22 @@ public class UserSettings : AggregateRoot ShouldAggregateArtworkWhenMissing = shouldAggregateArtworkWhenMissing; ShouldRenderPdfAsImages = shouldRenderPdfAsImages; ShouldPreserveBookStyles = shouldPreserveBookStyles; + ShouldKeepDownloadingWhilePaused = shouldKeepDownloadingWhilePaused; + ShouldAutoplay = shouldAutoplay; + IsGaplessPlaybackEnabled = isGaplessPlaybackEnabled; + ReplayGainMode = replayGainMode; + StreamingQuality = streamingQuality; + VuMeterOrientation = vuMeterOrientation; + VuMeterSegmentCount = vuMeterSegmentCount; + VuMeterSegmentGap = vuMeterSegmentGap; + VuMeterMediumThreshold = vuMeterMediumThreshold; + VuMeterHighThreshold = vuMeterHighThreshold; + VuMeterShowPeak = vuMeterShowPeak; + VuMeterPeakHoldDurationInMilliseconds = vuMeterPeakHoldDurationInMilliseconds; + VuMeterReleasePerSecond = vuMeterReleasePerSecond; + VuMeterPeakReleasePerSecond = vuMeterPeakReleasePerSecond; + Volume = volume; + IsMuted = isMuted; } /// @@ -117,15 +261,31 @@ public class UserSettings : AggregateRoot public static Result Create() { return Create( - UserId.CreateUnique(), - DEFAULT_IS_PAGINATION_ENABLED, - DEFAULT_ITEMS_PER_PAGE, - DEFAULT_IGNORE_THE_PREFIX_FOR_ALPHA_PICKER, - DEFAULT_IS_THEME_CACHING_ENABLED, - DEFAULT_AGGREGATE_METADATA_WHEN_MISSING, + UserId.CreateUnique(), + DEFAULT_IS_PAGINATION_ENABLED, + DEFAULT_ITEMS_PER_PAGE, + DEFAULT_IGNORE_THE_PREFIX_FOR_ALPHA_PICKER, + DEFAULT_IS_THEME_CACHING_ENABLED, + DEFAULT_AGGREGATE_METADATA_WHEN_MISSING, DEFAULT_AGGREGATE_ARTWORK_WHEN_MISSING, DEFAULT_SHOULD_RENDER_PDF_AS_IMAGES, - DEFAULT_SHOULD_PRESERVE_BOOK_STYLES + DEFAULT_SHOULD_PRESERVE_BOOK_STYLES, + DEFAULT_SHOULD_KEEP_DOWNLOADING_WHILE_PAUSED, + DEFAULT_SHOULD_AUTOPLAY, + DEFAULT_IS_GAPLESS_PLAYBACK_ENABLED, + DEFAULT_REPLAY_GAIN_MODE, + DEFAULT_STREAMING_QUALITY, + DEFAULT_VU_METER_ORIENTATION, + DEFAULT_VU_METER_SEGMENT_COUNT, + DEFAULT_VU_METER_SEGMENT_GAP, + DEFAULT_VU_METER_MEDIUM_THRESHOLD, + DEFAULT_VU_METER_HIGH_THRESHOLD, + DEFAULT_VU_METER_SHOW_PEAK, + DEFAULT_VU_METER_PEAK_HOLD_DURATION_IN_MILLISECONDS, + DEFAULT_VU_METER_RELEASE_PER_SECOND, + DEFAULT_VU_METER_PEAK_RELEASE_PER_SECOND, + DEFAULT_VOLUME, + DEFAULT_IS_MUTED ); } @@ -139,15 +299,31 @@ public class UserSettings : AggregateRoot public static Result Create(UserId userId) { return Create( - userId, - DEFAULT_IS_PAGINATION_ENABLED, - DEFAULT_ITEMS_PER_PAGE, - DEFAULT_IGNORE_THE_PREFIX_FOR_ALPHA_PICKER, - DEFAULT_IS_THEME_CACHING_ENABLED, - DEFAULT_AGGREGATE_METADATA_WHEN_MISSING, + userId, + DEFAULT_IS_PAGINATION_ENABLED, + DEFAULT_ITEMS_PER_PAGE, + DEFAULT_IGNORE_THE_PREFIX_FOR_ALPHA_PICKER, + DEFAULT_IS_THEME_CACHING_ENABLED, + DEFAULT_AGGREGATE_METADATA_WHEN_MISSING, DEFAULT_AGGREGATE_ARTWORK_WHEN_MISSING, DEFAULT_SHOULD_RENDER_PDF_AS_IMAGES, - DEFAULT_SHOULD_PRESERVE_BOOK_STYLES + DEFAULT_SHOULD_PRESERVE_BOOK_STYLES, + DEFAULT_SHOULD_KEEP_DOWNLOADING_WHILE_PAUSED, + DEFAULT_SHOULD_AUTOPLAY, + DEFAULT_IS_GAPLESS_PLAYBACK_ENABLED, + DEFAULT_REPLAY_GAIN_MODE, + DEFAULT_STREAMING_QUALITY, + DEFAULT_VU_METER_ORIENTATION, + DEFAULT_VU_METER_SEGMENT_COUNT, + DEFAULT_VU_METER_SEGMENT_GAP, + DEFAULT_VU_METER_MEDIUM_THRESHOLD, + DEFAULT_VU_METER_HIGH_THRESHOLD, + DEFAULT_VU_METER_SHOW_PEAK, + DEFAULT_VU_METER_PEAK_HOLD_DURATION_IN_MILLISECONDS, + DEFAULT_VU_METER_RELEASE_PER_SECOND, + DEFAULT_VU_METER_PEAK_RELEASE_PER_SECOND, + DEFAULT_VOLUME, + DEFAULT_IS_MUTED ); } @@ -163,6 +339,22 @@ public class UserSettings : AggregateRoot /// Whether the artwork of the media library items is aggregated from multiple providers, when it is missing, or not. /// Whether PDF books are rendered as page images for the user, or not. /// Whether the styles of the book content are preserved when it is rendered for the user, or not. + /// Whether the player keeps downloading a track while playback is paused, or not. + /// Whether the player continues playback at the end of an album or artist, or not. + /// Whether the player transitions between consecutive tracks without a gap, or not. + /// The way ReplayGain normalization is applied to the tracks the user plays. + /// The quality cap applied to the audio the server normalizes for the user. + /// The direction in which each channel of the VU meter of the audio player grows. + /// The number of segments each channel of the VU meter is divided into. + /// The gap, in pixels, between the segments and the channels of the VU meter. + /// The level above which a segment of the VU meter is drawn with its medium state. + /// The level above which a segment of the VU meter is drawn with its high state. + /// Whether the VU meter holds the peak level of each channel after it falls, or not. + /// The time a peak of the VU meter is held before it starts falling. + /// The number of level units the display of the VU meter falls per second when the input level drops. + /// The number of level units the peak of the VU meter falls per second after its hold time elapsed. + /// The last volume the player reported for the user. + /// The last mute state the player reported for the user. /// /// An containing either a successfully created , or an error message. /// @@ -175,11 +367,24 @@ public class UserSettings : AggregateRoot bool shouldAggregateMetadataWhenMissing, bool shouldAggregateArtworkWhenMissing, bool shouldRenderPdfAsImages, - bool shouldPreserveBookStyles) + bool shouldPreserveBookStyles, + bool shouldKeepDownloadingWhilePaused, + bool shouldAutoplay, + bool isGaplessPlaybackEnabled, + ReplayGainMode replayGainMode, + PlaybackStreamingQuality streamingQuality, + VuMeterOrientation vuMeterOrientation, + int vuMeterSegmentCount, + int vuMeterSegmentGap, + double vuMeterMediumThreshold, + double vuMeterHighThreshold, + bool vuMeterShowPeak, + int vuMeterPeakHoldDurationInMilliseconds, + double vuMeterReleasePerSecond, + double vuMeterPeakReleasePerSecond, + double volume, + bool isMuted) { - if (itemsPerPage <= 0) - return Errors.UserSettings.ItemsPerPageMustBeGreaterThanZero; - return new UserSettings( UserSettingsId.CreateUnique(), userId, @@ -190,7 +395,23 @@ public class UserSettings : AggregateRoot shouldAggregateMetadataWhenMissing, shouldAggregateArtworkWhenMissing, shouldRenderPdfAsImages, - shouldPreserveBookStyles); + shouldPreserveBookStyles, + shouldKeepDownloadingWhilePaused, + shouldAutoplay, + isGaplessPlaybackEnabled, + replayGainMode, + streamingQuality, + vuMeterOrientation, + vuMeterSegmentCount, + vuMeterSegmentGap, + vuMeterMediumThreshold, + vuMeterHighThreshold, + vuMeterShowPeak, + vuMeterPeakHoldDurationInMilliseconds, + vuMeterReleasePerSecond, + vuMeterPeakReleasePerSecond, + volume, + isMuted); } /// @@ -206,6 +427,22 @@ public class UserSettings : AggregateRoot /// Whether the artwork of the media library items is aggregated from multiple providers, when it is missing, or not. /// Whether PDF books are rendered as page images for the user, or not. /// Whether the styles of the book content are preserved when it is rendered for the user, or not. + /// Whether the player keeps downloading a track while playback is paused, or not. + /// Whether the player continues playback at the end of an album or artist, or not. + /// Whether the player transitions between consecutive tracks without a gap, or not. + /// The way ReplayGain normalization is applied to the tracks the user plays. + /// The quality cap applied to the audio the server normalizes for the user. + /// The direction in which each channel of the VU meter of the audio player grows. + /// The number of segments each channel of the VU meter is divided into. + /// The gap, in pixels, between the segments and the channels of the VU meter. + /// The level above which a segment of the VU meter is drawn with its medium state. + /// The level above which a segment of the VU meter is drawn with its high state. + /// Whether the VU meter holds the peak level of each channel after it falls, or not. + /// The time a peak of the VU meter is held before it starts falling. + /// The number of level units the display of the VU meter falls per second when the input level drops. + /// The number of level units the peak of the VU meter falls per second after its hold time elapsed. + /// The last volume the player reported for the user. + /// The last mute state the player reported for the user. /// /// An containing either a successfully created , or an error message. /// @@ -219,17 +456,60 @@ public class UserSettings : AggregateRoot bool shouldAggregateMetadataWhenMissing, bool shouldAggregateArtworkWhenMissing, bool shouldRenderPdfAsImages, - bool shouldPreserveBookStyles) + bool shouldPreserveBookStyles, + bool shouldKeepDownloadingWhilePaused, + bool shouldAutoplay, + bool isGaplessPlaybackEnabled, + ReplayGainMode replayGainMode, + PlaybackStreamingQuality streamingQuality, + VuMeterOrientation vuMeterOrientation, + int vuMeterSegmentCount, + int vuMeterSegmentGap, + double vuMeterMediumThreshold, + double vuMeterHighThreshold, + bool vuMeterShowPeak, + int vuMeterPeakHoldDurationInMilliseconds, + double vuMeterReleasePerSecond, + double vuMeterPeakReleasePerSecond, + double volume, + bool isMuted) { - if (itemsPerPage <= 0) - return Errors.UserSettings.ItemsPerPageMustBeGreaterThanZero; - - return new UserSettings(id, userId, isPaginationEnabled, itemsPerPage, shouldIgnoreThePrefixForAlphaPicker, isThemeCachingEnabled, shouldAggregateMetadataWhenMissing, shouldAggregateArtworkWhenMissing, shouldRenderPdfAsImages, shouldPreserveBookStyles); + return new UserSettings( + id, + userId, + isPaginationEnabled, + itemsPerPage, + shouldIgnoreThePrefixForAlphaPicker, + isThemeCachingEnabled, + shouldAggregateMetadataWhenMissing, + shouldAggregateArtworkWhenMissing, + shouldRenderPdfAsImages, + shouldPreserveBookStyles, + shouldKeepDownloadingWhilePaused, + shouldAutoplay, + isGaplessPlaybackEnabled, + replayGainMode, + streamingQuality, + vuMeterOrientation, + vuMeterSegmentCount, + vuMeterSegmentGap, + vuMeterMediumThreshold, + vuMeterHighThreshold, + vuMeterShowPeak, + vuMeterPeakHoldDurationInMilliseconds, + vuMeterReleasePerSecond, + vuMeterPeakReleasePerSecond, + volume, + isMuted); } /// /// Updates the settings of the user. /// + /// + /// The playback state the player reports automatically (the volume and the mute state) is not part of the settings the user edits, so + /// this method neither accepts nor changes it. + /// /// Whether pagination is enabled for the user, or not. /// The number of library items displayed per page when pagination is enabled. /// Whether the "The" prefix of library item titles is ignored by the alpha picker, or not. @@ -238,6 +518,20 @@ public class UserSettings : AggregateRoot /// Whether the artwork of the media library items is aggregated from multiple providers, when it is missing, or not. /// Whether PDF books are rendered as page images for the user, or not. /// Whether the styles of the book content are preserved when it is rendered for the user, or not. + /// Whether the player keeps downloading a track while playback is paused, or not. + /// Whether the player continues playback at the end of an album or artist, or not. + /// Whether the player transitions between consecutive tracks without a gap, or not. + /// The way ReplayGain normalization is applied to the tracks the user plays. + /// The quality cap applied to the audio the server normalizes for the user. + /// The direction in which each channel of the VU meter of the audio player grows. + /// The number of segments each channel of the VU meter is divided into. + /// The gap, in pixels, between the segments and the channels of the VU meter. + /// The level above which a segment of the VU meter is drawn with its medium state. + /// The level above which a segment of the VU meter is drawn with its high state. + /// Whether the VU meter holds the peak level of each channel after it falls, or not. + /// The time a peak of the VU meter is held before it starts falling. + /// The number of level units the display of the VU meter falls per second when the input level drops. + /// The number of level units the peak of the VU meter falls per second after its hold time elapsed. /// An representing either a successful update, or an error. public Result UpdateSettings( bool isPaginationEnabled, @@ -247,11 +541,22 @@ public class UserSettings : AggregateRoot bool shouldAggregateMetadataWhenMissing, bool shouldAggregateArtworkWhenMissing, bool shouldRenderPdfAsImages, - bool shouldPreserveBookStyles) + bool shouldPreserveBookStyles, + bool shouldKeepDownloadingWhilePaused, + bool shouldAutoplay, + bool isGaplessPlaybackEnabled, + ReplayGainMode replayGainMode, + PlaybackStreamingQuality streamingQuality, + VuMeterOrientation vuMeterOrientation, + int vuMeterSegmentCount, + int vuMeterSegmentGap, + double vuMeterMediumThreshold, + double vuMeterHighThreshold, + bool vuMeterShowPeak, + int vuMeterPeakHoldDurationInMilliseconds, + double vuMeterReleasePerSecond, + double vuMeterPeakReleasePerSecond) { - if (itemsPerPage <= 0) - return Errors.UserSettings.ItemsPerPageMustBeGreaterThanZero; - IsPaginationEnabled = isPaginationEnabled; ItemsPerPage = itemsPerPage; ShouldIgnoreThePrefixForAlphaPicker = shouldIgnoreThePrefixForAlphaPicker; @@ -260,6 +565,33 @@ public class UserSettings : AggregateRoot ShouldAggregateArtworkWhenMissing = shouldAggregateArtworkWhenMissing; ShouldRenderPdfAsImages = shouldRenderPdfAsImages; ShouldPreserveBookStyles = shouldPreserveBookStyles; + ShouldKeepDownloadingWhilePaused = shouldKeepDownloadingWhilePaused; + ShouldAutoplay = shouldAutoplay; + IsGaplessPlaybackEnabled = isGaplessPlaybackEnabled; + ReplayGainMode = replayGainMode; + StreamingQuality = streamingQuality; + VuMeterOrientation = vuMeterOrientation; + VuMeterSegmentCount = vuMeterSegmentCount; + VuMeterSegmentGap = vuMeterSegmentGap; + VuMeterMediumThreshold = vuMeterMediumThreshold; + VuMeterHighThreshold = vuMeterHighThreshold; + VuMeterShowPeak = vuMeterShowPeak; + VuMeterPeakHoldDurationInMilliseconds = vuMeterPeakHoldDurationInMilliseconds; + VuMeterReleasePerSecond = vuMeterReleasePerSecond; + VuMeterPeakReleasePerSecond = vuMeterPeakReleasePerSecond; + return Result.Updated; + } + + /// + /// Updates the playback state the player reports automatically. + /// + /// The last volume the player reported for the user. + /// The last mute state the player reported for the user. + /// An representing either a successful update, or an error. + public Result UpdatePlaybackState(double volume, bool isMuted) + { + Volume = volume; + IsMuted = isMuted; return Result.Updated; } } diff --git a/src/Lumina.Infrastructure/Common/Caching/TranscodingCachePaths.cs b/src/Lumina.Infrastructure/Common/Caching/TranscodingCachePaths.cs new file mode 100644 index 00000000..29877a13 --- /dev/null +++ b/src/Lumina.Infrastructure/Common/Caching/TranscodingCachePaths.cs @@ -0,0 +1,275 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.IO; +using System.Security.Cryptography; +using System.Text; +using System.Threading; +#endregion + +namespace Lumina.Infrastructure.Common.Caching; + +/// +/// Provides the location, the ownership marker and the permissions of the temporary directory into which the audio normalization pipeline writes the normalized audio. +/// +internal static class TranscodingCachePaths +{ + /// + /// The name of the temporary directory that is used when no cache directory is configured. + /// + public const string DEFAULT_DIRECTORY_NAME = "lumina-transcoding-cache"; + + /// + /// The name of the file that marks a directory as a normalized audio cache created and owned by this application. + /// + public const string CACHE_MARKER_FILE_NAME = ".lumina-transcoding-cache"; + + /// + /// The prefix of the temporary directories of the normalization jobs that have not been published to the cache yet. + /// + public const string TEMPORARY_DIRECTORY_PREFIX = "tmp-"; + + /// + /// The prefix of the tombstone directories that were detached from the cache and are waiting to be deleted. + /// + public const string DELETION_DIRECTORY_PREFIX = "del-"; + + private const int CACHE_ID_HEX_LENGTH = 64; + private const UnixFileMode PRIVATE_DIRECTORY_MODE = UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute; + private const UnixFileMode PRIVATE_FILE_MODE = UnixFileMode.UserRead | UnixFileMode.UserWrite; + private const int USER_SUFFIX_LENGTH = 16; + + /// + /// Gets the absolute path of the directory into which the audio normalization pipeline writes the normalized audio of the tracks. + /// + /// + /// The configured cache directory, relative to the application base directory when not rooted, or to use a private directory + /// under the system temporary directory. The default directory is scoped to the operating system account that runs the process. + /// + /// The absolute path of the transcoding cache directory. + public static string GetRootDirectory(string? configuredDirectory) + { + if (!string.IsNullOrWhiteSpace(configuredDirectory)) + { + string trimmedDirectory = configuredDirectory.Trim(); + string absoluteDirectory = Path.IsPathRooted(trimmedDirectory) + ? trimmedDirectory + : Path.Combine(AppContext.BaseDirectory, trimmedDirectory); + return Path.GetFullPath(absoluteDirectory); + } + return Path.Combine(Path.GetTempPath(), DEFAULT_DIRECTORY_NAME + "-" + GetUserSuffix()); + } + + /// + /// Checks whether a directory carries the marker of a normalized audio cache created by this application. + /// + /// The absolute path of the directory to check. + /// when the directory carries the cache marker, otherwise . + public static bool HasCacheMarker(string directoryPath) + { + return File.Exists(Path.Combine(directoryPath, CACHE_MARKER_FILE_NAME)); + } + + /// + /// Writes the marker that records the directory as a normalized audio cache created and owned by this application. + /// + /// The absolute path of the directory to mark. + /// + /// The marker is an ownership signal, not a lock: it is written once, and its presence is what allows a later startup to clean the directory. A directory + /// without the marker is never cleaned, so a cache directory that was configured by mistake can never lose data that does not belong to this application. + /// + public static void WriteCacheMarker(string directoryPath) + { + if (HasCacheMarker(directoryPath)) + return; + File.WriteAllText(Path.Combine(directoryPath, CACHE_MARKER_FILE_NAME), "Lumina normalized audio cache." + Environment.NewLine); + } + + /// + /// Checks whether an entry name belongs to the namespace of the normalized audio cache. + /// + /// The name of the entry, without its directory. + /// when the name is a cache identifier, a temporary directory name or a deletion tombstone name, otherwise . + public static bool IsCacheEntryName(string entryName) + { + if (string.IsNullOrEmpty(entryName)) + return false; + return IsValidCacheId(entryName) || + entryName.StartsWith(TEMPORARY_DIRECTORY_PREFIX, StringComparison.Ordinal) || + entryName.StartsWith(DELETION_DIRECTORY_PREFIX, StringComparison.Ordinal); + } + + /// + /// Checks whether a value is a well formed opaque cache identifier. + /// + /// The value to check. + /// when the value is a well formed cache identifier, otherwise . + public static bool IsValidCacheId(string cacheId) + { + if (string.IsNullOrEmpty(cacheId) || cacheId.Length != CACHE_ID_HEX_LENGTH) + return false; + foreach (char character in cacheId) + if (!char.IsAsciiHexDigitLower(character)) + return false; + return true; + } + + /// + /// Removes the entries of a directory that belong to the namespace of the normalized audio cache, and leaves every other entry untouched. + /// + /// The absolute path of the cache directory. + /// Cancellation token that can be used to stop the execution. + /// + /// The cache directory itself is never deleted, and entries that do not carry a cache identifier, a temporary directory name or a deletion tombstone + /// name are never inspected. This makes the startup cleanup safe even when the configured directory is not one this application created. + /// + /// The cleanup was canceled. + /// An entry could not be deleted. + /// An entry could not be deleted because access was denied. + public static void ClearCacheEntries(string directoryPath, CancellationToken cancellationToken) + { + foreach (string entryPath in Directory.GetDirectories(directoryPath)) + { + cancellationToken.ThrowIfCancellationRequested(); + if (!IsCacheEntryName(Path.GetFileName(entryPath))) + continue; + DirectoryInfo entryDirectory = new(entryPath); + // A cache entry is never a link. A link left under a cache like name is deleted as a link, so the deletion can never be redirected outside the cache. + if (entryDirectory.LinkTarget is not null) + entryDirectory.Delete(); + else + DeleteDirectoryRecursive(entryPath, cancellationToken); + } + } + + /// + /// Deletes a directory and everything it contains. + /// + /// The directory to delete. + /// Cancellation token that can be used to stop the execution. + /// The deletion was canceled. + /// A file or directory could not be deleted. + /// A file or directory could not be deleted because access was denied. + private static void DeleteDirectoryRecursive(string directoryPath, CancellationToken cancellationToken) + { + cancellationToken.ThrowIfCancellationRequested(); + foreach (string filePath in Directory.EnumerateFiles(directoryPath)) + { + cancellationToken.ThrowIfCancellationRequested(); + File.Delete(filePath); + } + foreach (string childDirectoryPath in Directory.EnumerateDirectories(directoryPath)) + { + cancellationToken.ThrowIfCancellationRequested(); + DirectoryInfo childDirectory = new(childDirectoryPath); + // A link is deleted as a link, so a tampered entry can never make the cleanup follow it outside the cache. + if (childDirectory.LinkTarget is not null) + childDirectory.Delete(); + else + DeleteDirectoryRecursive(childDirectoryPath, cancellationToken); + } + cancellationToken.ThrowIfCancellationRequested(); + Directory.Delete(directoryPath); + } + + /// + /// Verifies that an existing cache directory is not a symbolic link and tightens its permissions to the private mode on Unix. + /// + /// The absolute path of the cache directory. + /// The path is a symbolic link or cannot be inspected. + /// The directory is owned by another user or cannot be changed. + public static void RestrictPermissions(string directoryPath) + { + DirectoryInfo directoryInformation = new(directoryPath); + // A symbolic link is rejected even when its target does not exist, so CreateDirectory can never be redirected outside the intended path. + if (directoryInformation.LinkTarget is not null) + throw new IOException("The normalized audio cache directory is a symbolic link."); + + // On Unix a directory that already exists is not changed by CreateDirectory, and a directory planted by another user under a predictable name in + // the shared temporary directory would otherwise be reused with its own mode. Tightening it fails when the directory is not owned by this + // account, which makes the caller treat the cache as unavailable instead of using a directory it does not control. + if (!OperatingSystem.IsWindows() && directoryInformation.Exists) + File.SetUnixFileMode(directoryPath, PRIVATE_DIRECTORY_MODE); + } + + /// + /// Tightens the permissions of a file the cache created to owner read and write on Unix. + /// + /// The absolute path of the file. + /// The file permissions could not be changed. + /// The file is owned by another user or cannot be changed. + public static void RestrictFilePermissions(string filePath) + { + // Windows inherits the ACL of the private cache directory, so only the Unix mode bits need to be tightened here. + if (!OperatingSystem.IsWindows()) + File.SetUnixFileMode(filePath, PRIVATE_FILE_MODE); + } + + /// + /// Creates a directory with private permissions on the platforms that support them. + /// + /// The absolute path of the directory to create. + /// The directory could not be created. + /// The directory could not be created because access was denied. + public static void CreatePrivateDirectory(string directoryPath) + { + if (OperatingSystem.IsWindows()) + { + Directory.CreateDirectory(directoryPath); + return; + } + Directory.CreateDirectory(directoryPath, PRIVATE_DIRECTORY_MODE); + // CreateDirectory does not change an existing directory, so the mode is applied again after the directory is known to exist. + File.SetUnixFileMode(directoryPath, PRIVATE_DIRECTORY_MODE); + } + + /// + /// Creates the cache directory when it does not exist, or tightens an existing one, with private permissions on the platforms that support them. + /// + /// The absolute path of the cache directory. + /// + /// A directory created by this method is marked as owned by this application. An existing directory is never marked, so an operator supplied directory + /// is adopted only by the startup component, and only when it is empty. + /// + /// The directory could not be created, or the path is a symbolic link. + /// The directory could not be created or changed because access was denied. + public static void EnsureDirectoryExists(string directoryPath) + { + RestrictPermissions(directoryPath); + bool isCreated = !Directory.Exists(directoryPath); + CreatePrivateDirectory(directoryPath); + if (isCreated) + WriteCacheMarker(directoryPath); + } + + /// + /// Deletes a directory, and reports whether it was deleted. + /// + /// The directory to delete. + /// when the directory no longer exists, otherwise . + public static bool TryDeleteDirectory(string directoryPath) + { + try + { + if (Directory.Exists(directoryPath)) + Directory.Delete(directoryPath, recursive: true); + return true; + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) + { + return false; + } + } + + /// + /// Gets a short, file name safe suffix of the operating system account that runs the process, so the default directory is not shared between users. + /// + /// The account suffix used in the default cache directory name. + private static string GetUserSuffix() + { + string userIdentity = Environment.UserName; + if (string.IsNullOrWhiteSpace(userIdentity)) + userIdentity = "default"; + byte[] identityHash = SHA256.HashData(Encoding.UTF8.GetBytes(userIdentity)); + return Convert.ToHexString(identityHash).ToLowerInvariant()[..USER_SUFFIX_LENGTH]; + } +} diff --git a/src/Lumina.Infrastructure/Common/DependencyInjection/InfrastructureLayerServices.cs b/src/Lumina.Infrastructure/Common/DependencyInjection/InfrastructureLayerServices.cs index 10e7c307..b44909f7 100644 --- a/src/Lumina.Infrastructure/Common/DependencyInjection/InfrastructureLayerServices.cs +++ b/src/Lumina.Infrastructure/Common/DependencyInjection/InfrastructureLayerServices.cs @@ -2,6 +2,7 @@ using Lumina.Application.Common.DomainEvents; using Lumina.Application.Common.Infrastructure.Authentication; using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Infrastructure.Authorization.Policies.ConsumptionActivity; using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; using Lumina.Application.Common.Infrastructure.Authorization.Policies.Over18; using Lumina.Application.Common.Infrastructure.Models.DTO.Configuration; @@ -13,6 +14,7 @@ using Lumina.Application.Common.Infrastructure.Themes; using Lumina.Application.Common.Infrastructure.Time; using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artwork; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback; using Lumina.Application.Core.MediaLibrary.Management.Progress; using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Artwork; using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading; @@ -29,6 +31,7 @@ using Lumina.Infrastructure.Common.Networking; using Lumina.Infrastructure.Core.Authentication; using Lumina.Infrastructure.Core.Authorization; using Lumina.Infrastructure.Core.Authorization.Policies.Common.Factory; +using Lumina.Infrastructure.Core.Authorization.Policies.ConsumptionActivity; using Lumina.Infrastructure.Core.Authorization.Policies.LibraryOwnership; using Lumina.Infrastructure.Core.Authorization.Policies.Over18; using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Cancellation; @@ -38,6 +41,7 @@ using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.WrittenCo using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Progress; using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Queue; using Lumina.Infrastructure.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artwork; +using Lumina.Infrastructure.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback; using Lumina.Infrastructure.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Artwork; using Lumina.Infrastructure.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading; using Lumina.Infrastructure.Core.Plugins; @@ -101,6 +105,7 @@ public static class InfrastructureLayerServices // Authorization. services.AddScoped(); services.AddScoped(); + services.AddScoped(); services.AddScoped(); services.AddScoped(); @@ -146,6 +151,26 @@ public static class InfrastructureLayerServices // Music artwork: stores the artwork of the albums into the internal media directory. services.AddScoped(); + // Music playback: decides, for a track and the capabilities a player advertises, whether the track is played as stored, + // repackaged into another container, or re-encoded into another codec. + services.AddSingleton(); + + // Music playback: issues and resolves the opaque delivery handles reported by a playback manifest, so the segment route never has to + // recompute the delivery decision, the quality cap or the source file identity from values that can change while the track plays. + services.AddSingleton(); + + // Music playback: records the outcome of the ffmpeg probe, so a missing binary or encoder is reported as unavailable for the affected formats. + services.AddSingleton(); + + // Music playback: produces the normalized (remuxed or transcoded) audio of a track with ffmpeg, caches it as fixed duration + // segments and serves it from the cache, bounded in concurrency, cancellable and capped in disk usage. The segment route of the + // playback stream surface is its consumer. + services.AddSingleton(); + + // Music playback: owns the normalized audio cache lifecycle and verifies the ffmpeg encoders at startup, so a missing or changed toolchain + // is recorded and reported as unavailable for the affected formats instead of surfacing as a per track playback failure. + services.AddHostedService(); + // Book reading: resolves the book reader plugins, extracts the books into a temporary directory, and serves their contents. // The enablement cache lets the reading service skip the per-request database read of the reader configurations. services.AddSingleton(); diff --git a/src/Lumina.Infrastructure/Common/DependencyInjection/SharedConfiguration.cs b/src/Lumina.Infrastructure/Common/DependencyInjection/SharedConfiguration.cs index afd1c2c7..ce2327d0 100644 --- a/src/Lumina.Infrastructure/Common/DependencyInjection/SharedConfiguration.cs +++ b/src/Lumina.Infrastructure/Common/DependencyInjection/SharedConfiguration.cs @@ -70,6 +70,11 @@ public static class SharedConfiguration .ValidateFluently() .ValidateOnStart(); + services.AddOptions() + .Bind(configuration.GetRequiredSection(TranscodingSettingsDto.SECTION_NAME)) + .ValidateFluently() + .ValidateOnStart(); + return services; } } diff --git a/src/Lumina.Infrastructure/Common/DomainEvents/DomainEventPublisher.cs b/src/Lumina.Infrastructure/Common/DomainEvents/DomainEventPublisher.cs index 3c472e9b..15b3cf34 100644 --- a/src/Lumina.Infrastructure/Common/DomainEvents/DomainEventPublisher.cs +++ b/src/Lumina.Infrastructure/Common/DomainEvents/DomainEventPublisher.cs @@ -32,7 +32,7 @@ public class DomainEventPublisher : IDomainEventPublisher /// Publishes the specified to all its registered handlers, in registration order. /// /// The domain event to publish. - /// Token to monitor for cancellation requests. + /// Cancellation token that can be used to stop the execution. /// A task that represents the asynchronous operation. public ValueTask PublishAsync(IDomainEvent domainEvent, CancellationToken cancellationToken = default) { @@ -54,7 +54,7 @@ public class DomainEventPublisher : IDomainEventPublisher /// The type of the domain event being dispatched. /// The domain event to dispatch. /// The provider used to resolve the domain event handlers. - /// Token to monitor for cancellation requests. + /// Cancellation token that can be used to stop the execution. /// A task that represents the asynchronous operation. private static async Task DispatchAsync(IDomainEvent domainEvent, IServiceProvider serviceProvider, CancellationToken cancellationToken) where TDomainEvent : IDomainEvent diff --git a/src/Lumina.Infrastructure/Common/Errors/Errors.Configuration.cs b/src/Lumina.Infrastructure/Common/Errors/Errors.Configuration.cs index d5aa5e0e..ff960a4d 100644 --- a/src/Lumina.Infrastructure/Common/Errors/Errors.Configuration.cs +++ b/src/Lumina.Infrastructure/Common/Errors/Errors.Configuration.cs @@ -33,5 +33,21 @@ public static partial class Errors public static Error ThemeMaxExpandedBytesMustBePositive => Error.Validation(description: nameof(ThemeMaxExpandedBytesMustBePositive)); public static Error ThemeMaxSingleFileBytesMustBePositive => Error.Validation(description: nameof(ThemeMaxSingleFileBytesMustBePositive)); public static Error ThemeMaxEntriesMustBePositive => Error.Validation(description: nameof(ThemeMaxEntriesMustBePositive)); + public static Error TranscodingFfmpegPathCannotBeEmpty => Error.Validation(description: nameof(TranscodingFfmpegPathCannotBeEmpty)); + public static Error TranscodingMaxConcurrentJobsMustBePositive => Error.Validation(description: nameof(TranscodingMaxConcurrentJobsMustBePositive)); + public static Error TranscodingMaxConcurrentJobsIsTooLarge => Error.Validation(description: nameof(TranscodingMaxConcurrentJobsIsTooLarge)); + public static Error TranscodingMaxConcurrentJobsPerUserMustBePositive => Error.Validation(description: nameof(TranscodingMaxConcurrentJobsPerUserMustBePositive)); + public static Error TranscodingMaxConcurrentJobsPerUserIsTooLarge => Error.Validation(description: nameof(TranscodingMaxConcurrentJobsPerUserIsTooLarge)); + public static Error TranscodingMaxConcurrentJobsPerUserExceedsGlobal => Error.Validation(description: nameof(TranscodingMaxConcurrentJobsPerUserExceedsGlobal)); + public static Error TranscodingMaxCacheBytesMustBePositive => Error.Validation(description: nameof(TranscodingMaxCacheBytesMustBePositive)); + public static Error TranscodingJobTimeoutMustBePositive => Error.Validation(description: nameof(TranscodingJobTimeoutMustBePositive)); + public static Error TranscodingJobTimeoutIsTooLong => Error.Validation(description: nameof(TranscodingJobTimeoutIsTooLong)); + public static Error TranscodingEvictionGraceSecondsMustBePositive => Error.Validation(description: nameof(TranscodingEvictionGraceSecondsMustBePositive)); + public static Error TranscodingEvictionGraceSecondsIsTooLong => Error.Validation(description: nameof(TranscodingEvictionGraceSecondsIsTooLong)); + public static Error TranscodingCacheDirectoryIsInvalid => Error.Validation(description: nameof(TranscodingCacheDirectoryIsInvalid)); + public static Error TranscodingCacheDirectoryIsInsideMediaRoot => Error.Validation(description: nameof(TranscodingCacheDirectoryIsInsideMediaRoot)); + public static Error TranscodingCacheDirectoryContainsMediaRoot => Error.Validation(description: nameof(TranscodingCacheDirectoryContainsMediaRoot)); + public static Error TranscodingCacheDirectoryIsUnsafeLocation => Error.Validation(description: nameof(TranscodingCacheDirectoryIsUnsafeLocation)); + public static Error TranscodingDefaultCacheDirectoryIsInsideMediaRoot => Error.Validation(description: nameof(TranscodingDefaultCacheDirectoryIsInsideMediaRoot)); } } diff --git a/src/Lumina.Infrastructure/Common/Models/DTO/Configuration/TranscodingSettingsDto.cs b/src/Lumina.Infrastructure/Common/Models/DTO/Configuration/TranscodingSettingsDto.cs new file mode 100644 index 00000000..140a1771 --- /dev/null +++ b/src/Lumina.Infrastructure/Common/Models/DTO/Configuration/TranscodingSettingsDto.cs @@ -0,0 +1,51 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Infrastructure.Common.Models.DTO.Configuration; + +/// +/// Data transfer object for deserializing the settings of the audio normalization pipeline. +/// +[DebuggerDisplay("Section name: {SECTION_NAME}")] +public sealed class TranscodingSettingsDto +{ + public const string SECTION_NAME = "TranscodingSettings"; + + /// + /// Gets or sets the file name or path of the ffmpeg binary, relative to the process search path when not rooted. + /// + public string FfmpegPath { get; set; } = "ffmpeg"; + + /// + /// Gets or sets the maximum number of normalization jobs that may run at the same time. + /// + public int MaxConcurrentJobs { get; set; } = 2; + + /// + /// Gets or sets the maximum number of normalization jobs a single user may have running at the same time. A production that was + /// started by another user can still be waited for, because it is shared by every request for the same track and delivery. + /// + public int MaxConcurrentJobsPerUser { get; set; } = 1; + + /// + /// Gets or sets the maximum total size of the normalized audio cache, in bytes. + /// + public long MaxCacheBytes { get; set; } = 2L * 1024 * 1024 * 1024; + + /// + /// Gets or sets the maximum duration of a single normalization job, in seconds, after which the job is stopped. + /// + public int JobTimeoutSeconds { get; set; } = 900; + + /// + /// Gets or sets the period, in seconds, during which a cache entry that was just produced or served is protected from eviction. + /// + public int EvictionGraceSeconds { get; set; } = 120; + + /// + /// Gets or sets the directory where normalized audio is cached, relative to the API base directory when not rooted. When absent or empty, a + /// private directory under the system temporary directory is used. + /// + public string? CacheDirectory { get; set; } +} diff --git a/src/Lumina.Infrastructure/Common/Models/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/NormalizedAudioFormatDto.cs b/src/Lumina.Infrastructure/Common/Models/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/NormalizedAudioFormatDto.cs new file mode 100644 index 00000000..996b3262 --- /dev/null +++ b/src/Lumina.Infrastructure/Common/Models/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/NormalizedAudioFormatDto.cs @@ -0,0 +1,24 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Infrastructure.Common.Models.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback; + +/// +/// Describes how a single container and codec combination of the audio normalization pipeline is muxed and, when it has to be re-encoded, encoded. +/// +/// The canonical container of the delivered audio. +/// The canonical codec of the delivered audio. +/// The name of the ffmpeg muxer that writes the container. +/// The file extension of a single segment, including the leading dot. +/// The name of the ffmpeg encoder used when the audio is transcoded. +/// Whether the codec is lossless, in which case an encoder bitrate cap does not apply. +[DebuggerDisplay("Container: {Container} Codec: {Codec} Muxer: {MuxerName}")] +internal sealed record NormalizedAudioFormatDto( + string Container, + string Codec, + string MuxerName, + string FileExtension, + string EncoderName, + bool IsLossless +); diff --git a/src/Lumina.Infrastructure/Common/Models/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/NormalizedTrackIndexDto.cs b/src/Lumina.Infrastructure/Common/Models/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/NormalizedTrackIndexDto.cs new file mode 100644 index 00000000..0190f027 --- /dev/null +++ b/src/Lumina.Infrastructure/Common/Models/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/NormalizedTrackIndexDto.cs @@ -0,0 +1,37 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.SharedKernel.Common.Enums.Playback; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Text.Json.Serialization; +#endregion + +namespace Lumina.Infrastructure.Common.Models.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback; + +/// +/// Represents the persisted description of a cached normalized track, which lets the cache be read without parsing the ffmpeg output again. +/// +/// The version of the index layout, so an index written by an older version is treated as a cache miss. +/// The Id of the track the cached audio belongs to, so a cache handle can be authorized against the track of the route. +/// The way the audio is delivered, which is a remux or a transcode. +/// The container of the delivered audio. +/// The codec of the delivered audio. +/// The duration of each segment of the delivered audio, in seconds. +/// +/// The duration of the produced and cached audio, in seconds, rounded up to the next second. It is the produced end rather than the probed duration, so +/// it always covers every produced segment. +/// +/// The segments that make up the delivered audio, in playback order. +[DebuggerDisplay("TrackId: {TrackId} Container: {Container} Codec: {Codec} Segments: {Segments.Count}")] +// The record is internal, so its primary constructor is not public. Marking it tells System.Text.Json to use it for the on disk index anyway. +[method: JsonConstructor] +internal sealed record NormalizedTrackIndexDto( + int Version, + Guid TrackId, + PlaybackDeliveryMode Mode, + string Container, + string Codec, + int SegmentDurationSeconds, + int DurationInSeconds, + IReadOnlyList Segments +); diff --git a/src/Lumina.Infrastructure/Common/Models/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/NormalizedTrackSegmentIndexDto.cs b/src/Lumina.Infrastructure/Common/Models/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/NormalizedTrackSegmentIndexDto.cs new file mode 100644 index 00000000..d9ae324c --- /dev/null +++ b/src/Lumina.Infrastructure/Common/Models/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/NormalizedTrackSegmentIndexDto.cs @@ -0,0 +1,25 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +using System.Text.Json.Serialization; +#endregion + +namespace Lumina.Infrastructure.Common.Models.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback; + +/// +/// Represents the persisted description of a single segment of a cached normalized track. +/// +/// The zero based position of the segment in the delivered audio. +/// The time, in seconds from the start of the track, at which the segment starts. +/// The duration of the segment, in seconds. +/// The file name of the segment inside the cache entry. +/// The length of the segment, in bytes. +[DebuggerDisplay("Index: {Index} StartSeconds: {StartSeconds} FileName: {FileName}")] +// The record is internal, so its primary constructor is not public. Marking it tells System.Text.Json to use it for the on disk index anyway. +[method: JsonConstructor] +internal sealed record NormalizedTrackSegmentIndexDto( + int Index, + decimal StartSeconds, + decimal DurationSeconds, + string FileName, + long Length +); diff --git a/src/Lumina.Infrastructure/Common/Models/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/TranscodingCacheEntryDto.cs b/src/Lumina.Infrastructure/Common/Models/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/TranscodingCacheEntryDto.cs new file mode 100644 index 00000000..588a6c79 --- /dev/null +++ b/src/Lumina.Infrastructure/Common/Models/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/TranscodingCacheEntryDto.cs @@ -0,0 +1,21 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Infrastructure.Common.Models.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback; + +/// +/// Represents a single entry of the normalized audio cache, used to enforce the cache size limit. +/// +/// The absolute path of the directory that holds the entry. +/// The total size of the entry, in bytes. +/// The date and time, in UTC, when the entry was last produced or served. +/// The date and time, in UTC, when the entry was produced or, for an entry found on disk, the earliest representable time. +[DebuggerDisplay("Path: {Path} Size: {Size}")] +internal sealed record TranscodingCacheEntryDto( + string Path, + long Size, + DateTime LastUsedUtc, + DateTime ProducedAtUtc +); diff --git a/src/Lumina.Infrastructure/Common/Validators/TranscodingSettingsDtoValidator.cs b/src/Lumina.Infrastructure/Common/Validators/TranscodingSettingsDtoValidator.cs new file mode 100644 index 00000000..7ad7a3db --- /dev/null +++ b/src/Lumina.Infrastructure/Common/Validators/TranscodingSettingsDtoValidator.cs @@ -0,0 +1,304 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Infrastructure.Models.DTO.Configuration; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Utilities; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; +using Lumina.Infrastructure.Common.Caching; +using Lumina.Infrastructure.Common.Models.DTO.Configuration; +using Microsoft.Extensions.Options; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +#endregion + +namespace Lumina.Infrastructure.Common.Validators; + +/// +/// Validates the needed validation rules for the TranscodingSettings application configuration settings section. +/// +public class TranscodingSettingsDtoValidator : AbstractValidator +{ + private const int MAX_CONCURRENT_JOBS = 64; + private const int MAX_JOB_TIMEOUT_SECONDS = 86400; + private const int MAX_EVICTION_GRACE_SECONDS = 86400; + + private static readonly StringComparison s_pathComparison = OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal; + + private readonly IPathService _pathService; + private readonly string _mediaRootDirectory; + private readonly string[] _conflictingDirectories; + + /// + /// Initializes a new instance of the class. + /// + /// The media settings, used to reject a cache directory that would be served by the media route. + /// The plugin settings, used to reject a cache directory that would overlap the plugins directory. + /// The service used to check whether two directories overlap. + public TranscodingSettingsDtoValidator(IOptions mediaSettings, IOptions pluginsSettings, IPathService pathService) + { + _pathService = pathService; + _mediaRootDirectory = Path.GetFullPath(Path.Combine(AppContext.BaseDirectory, mediaSettings.Value.RootDirectory)); + _conflictingDirectories = BuildConflictingDirectories(pluginsSettings.Value); + + RuleFor(settings => settings.FfmpegPath) + .NotEmpty() + .WithError(Errors.Errors.Configuration.TranscodingFfmpegPathCannotBeEmpty); + + RuleFor(settings => settings.MaxConcurrentJobs) + .GreaterThan(0) + .WithError(Errors.Errors.Configuration.TranscodingMaxConcurrentJobsMustBePositive); + + RuleFor(settings => settings.MaxConcurrentJobs) + .Must(maxConcurrentJobs => maxConcurrentJobs <= MAX_CONCURRENT_JOBS) + .WithError(Errors.Errors.Configuration.TranscodingMaxConcurrentJobsIsTooLarge); + + RuleFor(settings => settings.MaxConcurrentJobsPerUser) + .GreaterThan(0) + .WithError(Errors.Errors.Configuration.TranscodingMaxConcurrentJobsPerUserMustBePositive); + + RuleFor(settings => settings.MaxConcurrentJobsPerUser) + .Must(maxConcurrentJobsPerUser => maxConcurrentJobsPerUser <= MAX_CONCURRENT_JOBS) + .WithError(Errors.Errors.Configuration.TranscodingMaxConcurrentJobsPerUserIsTooLarge); + + // A per-user limit above the global one can never be reached, and would hide a misconfiguration that looks like a working cap. + RuleFor(settings => settings.MaxConcurrentJobsPerUser) + .Must((settings, maxConcurrentJobsPerUser) => maxConcurrentJobsPerUser <= settings.MaxConcurrentJobs) + .WithError(Errors.Errors.Configuration.TranscodingMaxConcurrentJobsPerUserExceedsGlobal); + + RuleFor(settings => settings.MaxCacheBytes) + .GreaterThan(0) + .WithError(Errors.Errors.Configuration.TranscodingMaxCacheBytesMustBePositive); + + RuleFor(settings => settings.JobTimeoutSeconds) + .GreaterThan(0) + .WithError(Errors.Errors.Configuration.TranscodingJobTimeoutMustBePositive); + + // CancellationTokenSource(TimeSpan) cannot represent an arbitrarily large delay, and a job that may run for days is a configuration error. + RuleFor(settings => settings.JobTimeoutSeconds) + .Must(jobTimeoutSeconds => jobTimeoutSeconds <= MAX_JOB_TIMEOUT_SECONDS) + .WithError(Errors.Errors.Configuration.TranscodingJobTimeoutIsTooLong); + + RuleFor(settings => settings.EvictionGraceSeconds) + .GreaterThan(0) + .WithError(Errors.Errors.Configuration.TranscodingEvictionGraceSecondsMustBePositive); + + RuleFor(settings => settings.EvictionGraceSeconds) + .Must(evictionGraceSeconds => evictionGraceSeconds <= MAX_EVICTION_GRACE_SECONDS) + .WithError(Errors.Errors.Configuration.TranscodingEvictionGraceSecondsIsTooLong); + + RuleFor(settings => settings.CacheDirectory) + .Must(BeAValidDirectoryPath) + .WithError(Errors.Errors.Configuration.TranscodingCacheDirectoryIsInvalid) + .When(settings => !string.IsNullOrWhiteSpace(settings.CacheDirectory)); + + // A malformed path is reported by the rule above, so the rules below must not try to resolve it: Path.GetFullPath would throw and abort + // startup with a raw exception instead of a configuration error. + RuleFor(settings => settings.CacheDirectory) + .Must(BeConfiguredDirectoryOutsideMediaRoot) + .WithError(Errors.Errors.Configuration.TranscodingCacheDirectoryIsInsideMediaRoot) + .When(settings => !string.IsNullOrWhiteSpace(settings.CacheDirectory) && BeAValidDirectoryPath(settings.CacheDirectory)); + + // The reverse containment is just as destructive: a cache directory that contains the media root would delete the media when it is cleaned. + RuleFor(settings => settings.CacheDirectory) + .Must(BeConfiguredDirectoryNotContainingMediaRoot) + .WithError(Errors.Errors.Configuration.TranscodingCacheDirectoryContainsMediaRoot) + .When(settings => !string.IsNullOrWhiteSpace(settings.CacheDirectory) && BeAValidDirectoryPath(settings.CacheDirectory)); + + // The cache directory is cleaned at startup, so it must never resolve to a location whose cleanup would damage the application or the host. + RuleFor(settings => settings.CacheDirectory) + .Must(BeInSafeLocation) + .WithError(Errors.Errors.Configuration.TranscodingCacheDirectoryIsUnsafeLocation) + .When(settings => !string.IsNullOrWhiteSpace(settings.CacheDirectory) && BeAValidDirectoryPath(settings.CacheDirectory)); + + // When no directory is configured the service uses a per-user directory under the system temporary directory. A failure of that default is a + // different configuration problem from a CacheDirectory the operator chose, so it is reported with its own error and never names CacheDirectory. + RuleFor(settings => settings.CacheDirectory) + .Must(_ => BeDefaultDirectoryOutsideMediaRoot()) + .WithError(Errors.Errors.Configuration.TranscodingDefaultCacheDirectoryIsInsideMediaRoot) + .When(settings => string.IsNullOrWhiteSpace(settings.CacheDirectory)); + } + + /// + /// Checks whether the provided cache directory is a path the file system accepts. + /// + /// The configured cache directory, or when the default is used. + /// when the path is valid, otherwise . + private static bool BeAValidDirectoryPath(string? cacheDirectory) + { + if (string.IsNullOrWhiteSpace(cacheDirectory)) + return true; + try + { + Path.GetFullPath(cacheDirectory); + return true; + } + catch (Exception exception) when (exception is ArgumentException or NotSupportedException or PathTooLongException) + { + return false; + } + } + + /// + /// Checks whether the configured cache directory is outside the media root, which is served without authentication at the media route. + /// + /// The configured cache directory. It is already known to be a valid path. + /// when the cache is outside the media root, otherwise . + private bool BeConfiguredDirectoryOutsideMediaRoot(string? cacheDirectory) + { + try + { + return !IsSameOrWithin(TranscodingCachePaths.GetRootDirectory(cacheDirectory), _mediaRootDirectory); + } + catch (Exception exception) when (exception is ArgumentException or NotSupportedException or PathTooLongException) + { + // The validity rule owns the malformed path error; this rule never turns it into an unhandled startup exception. + return true; + } + } + + /// + /// Checks whether the configured cache directory does not contain the media root. + /// + /// The configured cache directory. It is already known to be a valid path. + /// when the cache does not contain the media root, otherwise . + private bool BeConfiguredDirectoryNotContainingMediaRoot(string? cacheDirectory) + { + try + { + return !IsSameOrWithin(_mediaRootDirectory, TranscodingCachePaths.GetRootDirectory(cacheDirectory)); + } + catch (Exception exception) when (exception is ArgumentException or NotSupportedException or PathTooLongException) + { + // The validity rule owns the malformed path error; this rule never turns it into an unhandled startup exception. + return true; + } + } + + /// + /// Checks whether the configured cache directory is a location whose cleanup cannot damage the application or the host. + /// + /// The configured cache directory. It is already known to be a valid path. + /// when the location is safe, otherwise . + private bool BeInSafeLocation(string? cacheDirectory) + { + try + { + string resolvedCacheDirectory = TranscodingCachePaths.GetRootDirectory(cacheDirectory); + if (IsFileSystemRoot(resolvedCacheDirectory)) + return false; + // The cache must never be the application base directory or one of its ancestors, because cleaning it would remove the application itself. + if (IsSameOrWithin(AppContext.BaseDirectory, resolvedCacheDirectory)) + return false; + // The logs and plugins directories are managed by the application, so the cache must not overlap them in either direction. + foreach (string conflictingDirectory in _conflictingDirectories) + if (IsSameOrWithin(resolvedCacheDirectory, conflictingDirectory) || IsSameOrWithin(conflictingDirectory, resolvedCacheDirectory)) + return false; + return true; + } + catch (Exception exception) when (exception is ArgumentException or NotSupportedException or PathTooLongException) + { + // The validity rule owns the malformed path error; this rule never turns it into an unhandled startup exception. + return true; + } + } + + /// + /// Checks whether the default cache directory, used when none is configured, is outside the media root. + /// + /// when the default cache is outside the media root, otherwise . + private bool BeDefaultDirectoryOutsideMediaRoot() + { + try + { + return !IsSameOrWithin(TranscodingCachePaths.GetRootDirectory(configuredDirectory: null), _mediaRootDirectory); + } + catch (Exception exception) when (exception is ArgumentException or NotSupportedException or PathTooLongException) + { + // A temporary directory that cannot be resolved is reported by the startup initializer; it is not a media root containment error. + return true; + } + } + + /// + /// Checks whether a path is equal to, or is located inside, another path. + /// + /// The path to check. + /// The path that must contain, or be equal to, the checked path. + /// when the path is equal to or inside the parent path, otherwise . + private bool IsSameOrWithin(string path, string parentPath) + { + string normalizedPath = NormalizePath(path); + string normalizedParentPath = NormalizePath(parentPath); + if (string.Equals(normalizedPath, normalizedParentPath, s_pathComparison)) + return true; + return _pathService.IsPathWithin(normalizedPath, normalizedParentPath); + } + + /// + /// Checks whether a path is the root of a file system, or of a volume, instead of a directory inside it. + /// + /// The absolute path to check. + /// when the path is a file system root, otherwise . + private static bool IsFileSystemRoot(string path) + { + string normalizedPath = NormalizePath(path); + string? rootPath = Path.GetPathRoot(normalizedPath); + return rootPath is not null && string.Equals(normalizedPath, rootPath, s_pathComparison); + } + + /// + /// Gets the full form of a path, without a trailing separator unless the path itself is the root of a file system or volume. + /// + /// The path to normalize. + /// The normalized absolute path. + private static string NormalizePath(string path) + { + string fullPath = Path.GetFullPath(path); + string? rootPath = Path.GetPathRoot(fullPath); + // The root must keep its trailing separator, otherwise a drive root such as "C:\" degenerates into the drive relative path "C:". + if (rootPath is null || fullPath.Length <= rootPath.Length) + return fullPath; + return fullPath.TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar); + } + + /// + /// Gets the directories that the cache directory must never overlap: the logs directory and the plugins directory. + /// + /// The plugin settings, whose directory is resolved against the application base directory. + /// The absolute paths of the directories the cache must not overlap. + private static string[] BuildConflictingDirectories(PluginsSettingsDto pluginsSettings) + { + List conflictingDirectories = []; + if (!string.IsNullOrWhiteSpace(pluginsSettings.Directory)) + AddConflictingDirectory(conflictingDirectories, Path.Combine(AppContext.BaseDirectory, pluginsSettings.Directory)); + // The local log path is always the logs directory of the application base directory; the environment variable and the container path cover + // the other two ways the log path is selected at startup. + AddConflictingDirectory(conflictingDirectories, Path.Combine(AppContext.BaseDirectory, "logs")); + AddConflictingDirectory(conflictingDirectories, Environment.GetEnvironmentVariable("LOG_PATH")); + if (string.Equals(Environment.GetEnvironmentVariable("DOTNET_RUNNING_IN_CONTAINER"), "true", StringComparison.OrdinalIgnoreCase)) + AddConflictingDirectory(conflictingDirectories, "/logs"); + return [.. conflictingDirectories]; + } + + /// + /// Adds the full form of a directory to the list of conflicting directories, when it can be resolved and is not already listed. + /// + /// The list of conflicting directories to add to. + /// The directory to add, or when it is not configured. + private static void AddConflictingDirectory(List conflictingDirectories, string? directory) + { + if (string.IsNullOrWhiteSpace(directory)) + return; + try + { + string resolvedDirectory = NormalizePath(directory); + if (!conflictingDirectories.Contains(resolvedDirectory, StringComparer.FromComparison(s_pathComparison))) + conflictingDirectories.Add(resolvedDirectory); + } + catch (Exception exception) when (exception is ArgumentException or NotSupportedException or PathTooLongException) + { + // A malformed log path is reported by the logging configuration, not by the cache validation. + } + } +} diff --git a/src/Lumina.Infrastructure/Core/Authorization/Policies/ConsumptionActivity/ConsumptionActivityAccessPolicy.cs b/src/Lumina.Infrastructure/Core/Authorization/Policies/ConsumptionActivity/ConsumptionActivityAccessPolicy.cs new file mode 100644 index 00000000..7ee4977d --- /dev/null +++ b/src/Lumina.Infrastructure/Core/Authorization/Policies/ConsumptionActivity/ConsumptionActivityAccessPolicy.cs @@ -0,0 +1,51 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Infrastructure.Authorization.Policies.Common.Base; +using Lumina.Application.Common.Infrastructure.Authorization.Policies.ConsumptionActivity; +using System; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Infrastructure.Core.Authorization.Policies.ConsumptionActivity; + +/// +/// Authorization policy that checks whether a user can access the consumption activity of a user: admins can access any user's consumption activity, +/// while other users can only access their own. +/// +public class ConsumptionActivityAccessPolicy : IConsumptionActivityAccessPolicy +{ + private readonly IAuthorizationService _authorizationService; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for authorization related functionality. + public ConsumptionActivityAccessPolicy(IAuthorizationService authorizationService) + { + _authorizationService = authorizationService; + } + + /// + /// Evaluates the policy for the user identified by against the consumption activity of the user identified in + /// . + /// + /// The unique identifier of the user for which to evaluate the policy. + /// The context carrying the Id of the user whose consumption activity is being accessed. + /// Cancellation token that can be used to stop the execution. + /// if the user is an admin or accesses their own consumption activity, otherwise. + public async Task EvaluateAsync(Guid userId, PolicyContext? context, CancellationToken cancellationToken) + { + // An empty user id is a defaulted value, not a real user, so it must never match another empty id. + if (userId == Guid.Empty) + return false; + if (context is not ConsumptionActivityAccessPolicyContext consumptionActivityContext) + return false; + if (consumptionActivityContext.TargetUserId == Guid.Empty) + return false; + if (consumptionActivityContext.TargetUserId == userId) // A user can access their own consumption activity. + return true; + // Admins can access consumption activities all the time. + return await _authorizationService.IsInRoleAsync(userId, AuthorizationRoles.ADMIN, cancellationToken).ConfigureAwait(false); + } +} diff --git a/src/Lumina.Infrastructure/Core/Authorization/Policies/LibraryOwnership/LibraryOwnershipPolicy.cs b/src/Lumina.Infrastructure/Core/Authorization/Policies/LibraryOwnership/LibraryOwnershipPolicy.cs index c3269050..5dfec779 100644 --- a/src/Lumina.Infrastructure/Core/Authorization/Policies/LibraryOwnership/LibraryOwnershipPolicy.cs +++ b/src/Lumina.Infrastructure/Core/Authorization/Policies/LibraryOwnership/LibraryOwnershipPolicy.cs @@ -1,11 +1,13 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; using Lumina.Application.Common.DataAccess.Entities.UsersManagement; using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Infrastructure.Authorization; using Lumina.Application.Common.Infrastructure.Authorization.Policies.Common.Base; using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; using Lumina.Domain.Common.Primitives; using System; +using System.Collections.Generic; +using System.Linq; using System.Threading; using System.Threading.Tasks; #endregion @@ -18,6 +20,10 @@ namespace Lumina.Infrastructure.Core.Authorization.Policies.LibraryOwnership; public class LibraryOwnershipPolicy : ILibraryOwnershipPolicy { private readonly IUnitOfWork _unitOfWork; + // The policy is registered per request, so this is a per-request cache keyed by the user that was loaded. It is not shared between requests, and the key prevents a reused policy instance from answering for a different user. + private Guid? _loadedUserId; + private bool _canAccessAllLibraries; + private HashSet _ownedLibraryIds = []; /// /// Initializes a new instance of the class. @@ -40,17 +46,24 @@ public class LibraryOwnershipPolicy : ILibraryOwnershipPolicy if (context is not LibraryOwnershipPolicyContext libraryContext) return false; - // Admins can access any media library. - Result getUserResult = await _unitOfWork.UserRepository.GetByIdAsync(userId, cancellationToken: cancellationToken).ConfigureAwait(false); - if (getUserResult.IsFailure || getUserResult.Value is null) - return false; - if (getUserResult.Value.UserRole?.Role.RoleName == "Admin") - return true; + // The policy is scoped to one request, so the user graph, including the libraries the user owns, is read once and every library of that request is answered from the same set. + if (_loadedUserId != userId) + { + Result getUserResult = await _unitOfWork.UserRepository.GetByIdAsync(userId, cancellationToken: cancellationToken).ConfigureAwait(false); + if (getUserResult.IsFailure || getUserResult.Value is null) + { + _loadedUserId = userId; + _canAccessAllLibraries = false; + _ownedLibraryIds = []; + return false; + } + // Admins can access any media library. + _canAccessAllLibraries = getUserResult.Value.UserRole?.Role.RoleName == AuthorizationRoles.ADMIN; + // The user graph already carries the libraries owned by this user, so answering the policy needs no second library read. + _ownedLibraryIds = [.. getUserResult.Value.Libraries.Select(library => library.Id)]; + _loadedUserId = userId; + } - // Regular users can only access the media libraries they own. - Result getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(libraryContext.LibraryId, cancellationToken: cancellationToken).ConfigureAwait(false); - if (getLibraryResult.IsFailure || getLibraryResult.Value is null) - return false; - return getLibraryResult.Value.UserId == userId; + return _canAccessAllLibraries || _ownedLibraryIds.Contains(libraryContext.LibraryId); } } diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Metadata/AudioContainerResolver.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Metadata/AudioContainerResolver.cs new file mode 100644 index 00000000..e0054c32 --- /dev/null +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Metadata/AudioContainerResolver.cs @@ -0,0 +1,57 @@ +#region ========================================================================= USING ===================================================================================== +using System; +#endregion + +namespace Lumina.Infrastructure.Core.MediaLibrary.AudioLibrary.MusicLibrary.Metadata; + +/// +/// Resolves the canonical name of the container of an audio file from the concrete type the tagging library parsed it as. +/// +internal static class AudioContainerResolver +{ + /// + /// Resolves the container of the audio file parsed by . + /// + /// The parsed audio file whose container is resolved. + /// The canonical name of the container, for example MP3, FLAC, OGG, AAC, MP4 or WAV, or when the container cannot be recognized. + public static string? Resolve(TagLib.File tagFile) + { + // The concrete type of the parsed file is the most reliable description of its container, because it is chosen by the parser from the + // actual bytes of the file, while the mime type only describes the extension. Containers that share a parser (for example the Opus and + // Vorbis streams parsed by the Ogg parser) are reported under the name of their container, and the codec column carries the difference. + return tagFile switch + { + TagLib.Mpeg.File => "MP3", + TagLib.Flac.File => "FLAC", + TagLib.Mpeg4.File => "MP4", + TagLib.Aac.File => "AAC", + TagLib.Ogg.File => "OGG", + TagLib.Riff.File => "WAV", + TagLib.Aiff.File => "AIFF", + TagLib.Ape.File => "APE", + TagLib.WavPack.File => "WAVPACK", + TagLib.Asf.File => "WMA", + TagLib.Dsf.File => "DSF", + TagLib.Matroska.File => "MATROSKA", + TagLib.MusePack.File => "MPC", + TagLib.Audible.File => "AA", + _ => ResolveFromMimeType(tagFile.MimeType) + }; + } + + /// + /// Resolves the container from the mime type reported by the tagging library, for the containers that have no dedicated parser. + /// + /// The mime type reported by the tagging library. + /// The name of the container, or when it cannot be derived. + public static string? ResolveFromMimeType(string? mimeType) + { + if (string.IsNullOrWhiteSpace(mimeType)) + return null; + + // The library reports its mime types with the "taglib/" prefix, so only the last segment names the container. + string[] segments = mimeType.Split('/', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); + string? container = segments.Length > 0 ? segments[^1] : null; + return string.IsNullOrWhiteSpace(container) ? null : container.ToUpperInvariant(); + } +} diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Metadata/MusicMetadataAggregator.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Metadata/MusicMetadataAggregator.cs index 000eb03c..6a335bc1 100644 --- a/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Metadata/MusicMetadataAggregator.cs +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Metadata/MusicMetadataAggregator.cs @@ -111,6 +111,7 @@ internal static class MusicMetadataAggregator First(first.Channels, second.Channels), First(first.BitDepth, second.BitDepth), First(first.AudioCodec, second.AudioCodec), + First(first.Container, second.Container), First(first.Bitrate, second.Bitrate), First(first.MusicBrainzRecordingId, second.MusicBrainzRecordingId), First(first.MusicBrainzTrackId, second.MusicBrainzTrackId), diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackDeliveryHandleService.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackDeliveryHandleService.cs new file mode 100644 index 00000000..1ae2e490 --- /dev/null +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackDeliveryHandleService.cs @@ -0,0 +1,251 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Threading; +#endregion + +namespace Lumina.Infrastructure.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback; + +/// +/// Issues and resolves the opaque delivery handles of the playback manifest, which bind a normalized delivery to the user, the track and the inputs the delivery was declared with. +/// +/// +/// The handles are process local, like the normalized audio cache they address. An API process must therefore keep handling both the manifest and +/// the segments of a track for a handle to resolve, which is the deployment the cache already requires: a single API process per cache directory. +/// A handle expires after a bounded lifetime, and the registry is bounded both globally and per user. Expired entries are removed from a queue in +/// issue order, so the sweep is amortized constant time and does not scan every handle. A repeated manifest for the same delivery inputs reuses the +/// handle that already exists for them, so reloading a manifest does not grow the registry. +/// +internal sealed class PlaybackDeliveryHandleService : IPlaybackDeliveryHandleService +{ + private const int MAX_DELIVERIES = 20_000; + private const int MAX_DELIVERIES_PER_USER = 64; + private static readonly TimeSpan s_deliveryLifetime = TimeSpan.FromHours(12); + + private readonly Lock _deliveryLock = new(); + // These dictionaries share one logical invariant: a delivery handle is split across the delivery map, its signature map, its per-user queue and count, + // and the global expiry queue. ConcurrentDictionary would make each collection thread-safe on its own, but not the multi-step issue, reuse, evict and remove sequences, + // which must see all of them consistently. The Lock is held only for short, O(1), non-awaiting work, so replacing these collections with concurrent ones would add + // complexity without removing the lock. Do not "fix" this without redesigning the state into one atomically updated map. + private readonly Dictionary _deliveries = []; + private readonly Dictionary _deliveryIdsBySignature = []; + private readonly Dictionary> _deliveryIdsByUser = []; + private readonly Dictionary _deliveryCountsByUser = []; + private readonly Queue<(string DeliveryId, DateTimeOffset ExpiresAtUtc)> _expiryQueue = []; + + /// + /// Issues an opaque handle for a delivery, which the playback manifest reports so its segments can be addressed by that handle. + /// + /// The delivery, its source file identity, its quality cap and its user. + /// The opaque delivery handle. + public string IssueDeliveryId(PlaybackDeliveryHandleDto delivery) + { + string signature = BuildSignature(delivery); + lock (_deliveryLock) + { + DateTimeOffset now = DateTimeOffset.UtcNow; + RemoveExpiredDeliveries(now); + if (_deliveryIdsBySignature.TryGetValue(signature, out string? existingDeliveryId) + && _deliveries.TryGetValue(existingDeliveryId, out StoredDelivery? existingDelivery) + && existingDelivery.ExpiresAtUtc > now) + return existingDeliveryId; + if (existingDeliveryId is not null) + RemoveDelivery(existingDeliveryId); + + EnforceUserLimit(delivery.Request.UserId); + EnforceGlobalLimit(); + + // The handle is a random opaque value, not a derived one, so it cannot be computed from the track or the file by a caller. + string deliveryId = Guid.NewGuid().ToString("N"); + DateTimeOffset expiresAtUtc = now.Add(s_deliveryLifetime); + _deliveries[deliveryId] = new StoredDelivery(delivery, signature, expiresAtUtc); + _deliveryIdsBySignature[signature] = deliveryId; + _deliveryCountsByUser[delivery.Request.UserId] = _deliveryCountsByUser.GetValueOrDefault(delivery.Request.UserId) + 1; + if (!_deliveryIdsByUser.TryGetValue(delivery.Request.UserId, out Queue? userDeliveryIds)) + { + userDeliveryIds = []; + _deliveryIdsByUser[delivery.Request.UserId] = userDeliveryIds; + } + userDeliveryIds.Enqueue(deliveryId); + _expiryQueue.Enqueue((deliveryId, expiresAtUtc)); + return deliveryId; + } + } + + /// + /// Resolves the delivery a handle addresses, after verifying that it was issued to the provided user and describes the provided track. + /// + /// The opaque delivery handle reported by the playback manifest. + /// The Id of the current user, which the handle must have been issued to. + /// The Id of the track named by the route, which the handle must describe. + /// + /// An containing either the delivery, or when the handle + /// is unknown, expired, or belongs to another user or track. + /// + public Result GetDelivery(string? deliveryId, Guid userId, Guid trackId) + { + if (string.IsNullOrWhiteSpace(deliveryId)) + return Errors.Playback.PlaybackDeliveryNotFound; + + lock (_deliveryLock) + { + if (!_deliveries.TryGetValue(deliveryId, out StoredDelivery? entry)) + return Errors.Playback.PlaybackDeliveryNotFound; + if (entry.ExpiresAtUtc <= DateTimeOffset.UtcNow) + { + RemoveDelivery(deliveryId); + return Errors.Playback.PlaybackDeliveryNotFound; + } + // A handle is not a capability: it is only valid for the user it was issued to and the track it describes, so a leaked handle + // cannot be used to read another user's track or another track of the same user. + if (entry.Delivery.Request.UserId != userId || entry.Delivery.Request.TrackId != trackId) + return Errors.Playback.PlaybackDeliveryNotFound; + return entry.Delivery; + } + } + + /// + /// Enforces the per-user handle limit by evicting the oldest handles of that user. + /// + /// The Id of the user whose handles are bounded. + private void EnforceUserLimit(Guid userId) + { + while (_deliveryCountsByUser.GetValueOrDefault(userId) >= MAX_DELIVERIES_PER_USER) + if (!TryEvictOldestForUser(userId)) + break; + } + + /// + /// Enforces the global handle limit by evicting the oldest handle. + /// + private void EnforceGlobalLimit() + { + while (_deliveries.Count >= MAX_DELIVERIES) + if (!TryEvictOldestDelivery()) + break; + } + + /// + /// Evicts the oldest handle that is still registered for a user. + /// + /// The Id of the user whose oldest handle is evicted. + /// when a handle was evicted, otherwise . + private bool TryEvictOldestForUser(Guid userId) + { + if (!_deliveryIdsByUser.TryGetValue(userId, out Queue? userDeliveryIds)) + return false; + while (userDeliveryIds.Count > 0) + { + string deliveryId = userDeliveryIds.Dequeue(); + if (!_deliveries.ContainsKey(deliveryId)) + continue; + RemoveDelivery(deliveryId); + return true; + } + _deliveryIdsByUser.Remove(userId); + return false; + } + + /// + /// Evicts the oldest handle that is still registered, using the expiry queue as the age order. + /// + /// when a handle was evicted, otherwise . + private bool TryEvictOldestDelivery() + { + while (_expiryQueue.Count > 0) + { + (string deliveryId, DateTimeOffset expiresAtUtc) = _expiryQueue.Dequeue(); + if (!_deliveries.TryGetValue(deliveryId, out StoredDelivery? storedDelivery) || storedDelivery.ExpiresAtUtc != expiresAtUtc) + continue; + RemoveDelivery(deliveryId); + return true; + } + return false; + } + + /// + /// Removes the deliveries whose lifetime ended, in expiry order, so the sweep does not scan the registry. + /// + /// The current time, in UTC. + private void RemoveExpiredDeliveries(DateTimeOffset now) + { + while (_expiryQueue.Count > 0) + { + (string deliveryId, DateTimeOffset expiresAtUtc) = _expiryQueue.Peek(); + if (expiresAtUtc > now) + return; + _expiryQueue.Dequeue(); + if (_deliveries.TryGetValue(deliveryId, out StoredDelivery? storedDelivery) && storedDelivery.ExpiresAtUtc == expiresAtUtc) + RemoveDelivery(deliveryId); + } + } + + /// + /// Removes one delivery and its signature and per-user accounting. + /// + /// The opaque handle of the delivery to remove. + private void RemoveDelivery(string deliveryId) + { + if (!_deliveries.Remove(deliveryId, out StoredDelivery? storedDelivery)) + return; + if (_deliveryIdsBySignature.TryGetValue(storedDelivery.Signature, out string? mappedDeliveryId) && mappedDeliveryId == deliveryId) + _deliveryIdsBySignature.Remove(storedDelivery.Signature); + if (_deliveryCountsByUser.TryGetValue(storedDelivery.Delivery.Request.UserId, out int count)) + { + if (count <= 1) + _deliveryCountsByUser.Remove(storedDelivery.Delivery.Request.UserId); + else + _deliveryCountsByUser[storedDelivery.Delivery.Request.UserId] = count - 1; + } + } + + /// + /// Builds the key that identifies a delivery for de-duplication, from every input that changes the handle's meaning. + /// + /// The delivery to key. + /// The signature of the delivery. + private static string BuildSignature(PlaybackDeliveryHandleDto delivery) + { + return string.Join('\u001F', new string[] + { + delivery.Request.UserId.ToString("N"), + delivery.Request.TrackId.ToString("N"), + delivery.LibraryId.ToString("N"), + delivery.AlbumId.ToString("N"), + delivery.ArtistId.ToString("N"), + ((int)delivery.Request.Mode).ToString(CultureInfo.InvariantCulture), + ((int)delivery.Shape).ToString(CultureInfo.InvariantCulture), + delivery.Request.SourceContainer ?? string.Empty, + delivery.Request.Container, + delivery.Request.Codec, + delivery.Request.SegmentDurationSeconds.ToString(CultureInfo.InvariantCulture), + delivery.Request.DurationInSeconds.ToString(CultureInfo.InvariantCulture), + delivery.Request.Bitrate?.ToString(CultureInfo.InvariantCulture) ?? string.Empty, + delivery.Request.SampleRate.ToString(CultureInfo.InvariantCulture), + delivery.Request.Channels.ToString(CultureInfo.InvariantCulture), + delivery.Request.BitDepth?.ToString(CultureInfo.InvariantCulture) ?? string.Empty, + ((int)delivery.Request.Quality).ToString(CultureInfo.InvariantCulture), + delivery.Request.SourcePath, + delivery.Request.SourceLength.ToString(CultureInfo.InvariantCulture), + delivery.Request.SourceLastModifiedUtc.Ticks.ToString(CultureInfo.InvariantCulture), + string.Join('\u001E', delivery.Request.AllowedRoots) + }); + } + + /// + /// A registered delivery, its de-duplication signature and its expiry. + /// + /// The delivery the handle addresses. + /// The signature of every input that changes the handle's meaning. + /// The time, in UTC, after which the handle is no longer accepted. + private sealed record StoredDelivery( + PlaybackDeliveryHandleDto Delivery, + string Signature, + DateTimeOffset ExpiresAtUtc + ); +} diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackFormatCatalog.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackFormatCatalog.cs new file mode 100644 index 00000000..8a1fe34f --- /dev/null +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackFormatCatalog.cs @@ -0,0 +1,102 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Infrastructure.Common.Models.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback; +using System; +using System.Collections.Frozen; +using System.Collections.Generic; +using System.Linq; +#endregion + +namespace Lumina.Infrastructure.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback; + +/// +/// The single catalog of the audio formats the server can produce, shared by the playback delivery decision and the audio normalization pipeline. +/// +/// +/// The order of is significant: the first appearance of a codec is its transcode preference, and the order of the containers of a +/// codec is the order in which the server prefers to produce it. Both the delivery decision and the normalization pipeline derive their tables from this +/// catalog, so a format can never be promised in a manifest without also being implementable by the pipeline. +/// +internal static class PlaybackFormatCatalog +{ + /// + /// Gets the formats the server can produce, in the order of the transcode codec preference and, within a codec, of the container preference. + /// + public static IReadOnlyList Formats { get; } = + [ + new("MP4", "AAC", "mp4", ".m4a", "aac", false), + new("AAC", "AAC", "adts", ".aac", "aac", false), + new("OGG", "OPUS", "ogg", ".ogg", "libopus", false), + new("MP3", "MP3", "mp3", ".mp3", "libmp3lame", false), + new("OGG", "VORBIS", "ogg", ".ogg", "libvorbis", false), + new("FLAC", "FLAC", "flac", ".flac", "flac", true), + new("WAV", "PCM", "wav", ".wav", "pcm_s16le", true) + ]; + + /// + /// Gets the formats the server can produce, keyed by their canonical container and codec pair. + /// + public static FrozenDictionary FormatsByPair { get; } = BuildFormatsByPair(); + + /// + /// Gets the containers the server can produce each codec in, in order of preference. + /// + public static FrozenDictionary> ProducibleContainersByCodec { get; } = BuildProducibleContainersByCodec(); + + /// + /// Gets the codecs the server can produce, in order of preference. + /// + public static IReadOnlyList TranscodeCodecPreference { get; } = BuildTranscodeCodecPreference(); + + /// + /// Builds the key of a canonical container and codec pair. + /// + /// The container of the audio. + /// The codec of the audio. + /// The canonical key of the pair. + public static string BuildPairKey(string container, string codec) + { + return (container ?? string.Empty).Trim().ToUpperInvariant() + "/" + (codec ?? string.Empty).Trim().ToUpperInvariant(); + } + + /// + /// Builds the map of the producible formats, keyed by their canonical container and codec pair. + /// + /// The producible formats, keyed by their canonical pair. + private static FrozenDictionary BuildFormatsByPair() + { + return Formats.ToFrozenDictionary(format => BuildPairKey(format.Container, format.Codec), StringComparer.OrdinalIgnoreCase); + } + + /// + /// Builds the map of the containers the server can produce each codec in, preserving the order of the catalog. + /// + /// The containers of each producible codec, in order of preference. + private static FrozenDictionary> BuildProducibleContainersByCodec() + { + Dictionary> containersByCodec = new(StringComparer.OrdinalIgnoreCase); + foreach (NormalizedAudioFormatDto format in Formats) + { + if (!containersByCodec.TryGetValue(format.Codec, out List? containers)) + { + containers = []; + containersByCodec[format.Codec] = containers; + } + if (!containers.Contains(format.Container, StringComparer.OrdinalIgnoreCase)) + containers.Add(format.Container); + } + return containersByCodec.ToFrozenDictionary(entry => entry.Key, entry => (IReadOnlyList)entry.Value, StringComparer.OrdinalIgnoreCase); + } + + /// + /// Builds the codecs the server can produce, preserving the order in which they first appear in the catalog. + /// + /// The producible codecs, in order of preference. + private static IReadOnlyList BuildTranscodeCodecPreference() + { + List codecs = []; + foreach (NormalizedAudioFormatDto format in Formats) + if (!codecs.Contains(format.Codec, StringComparer.OrdinalIgnoreCase)) + codecs.Add(format.Codec); + return codecs; + } +} diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackFormatService.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackFormatService.cs new file mode 100644 index 00000000..61df12f3 --- /dev/null +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackFormatService.cs @@ -0,0 +1,165 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.SharedKernel.Common.Enums.Playback; +using System; +using System.Collections.Generic; +using System.Linq; +#endregion + +namespace Lumina.Infrastructure.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback; + +/// +/// Service that decides whether the audio of a track can be played as stored by a player, or has to be repackaged into another container (remuxed) or re-encoded into another codec (transcoded). +/// +/// +/// The decision uses the container and the codec of the stored probe result together with the container and codec pairs the player advertises it can demux and decode directly: +/// a pair the player advertises as stored is a direct play, a codec the player decodes but a container it cannot demux is a remux into a container it can demux, and a codec the player cannot decode +/// is a transcode to the most preferred codec the server can produce and the player advertises. Everything that is not a direct play is delivered as fixed duration, time addressed segments, so that seeking never requires mapping a byte range to a time. +/// +internal sealed class PlaybackFormatService : IPlaybackFormatService +{ + // The duration of each segment of a normalized (remuxed or transcoded) delivery, in seconds: short enough to seek quickly, long enough to keep the request overhead low. + private const int SEGMENT_DURATION_SECONDS = 6; + + /// + /// Decides how the audio of a track, described by , is delivered to a player that advertises . + /// + /// The container and codec of the audio of the track, read from its stored probe result. + /// The container and codec combinations the player advertises it can demux and decode directly. + /// + /// An containing either the delivery decision, or an error when the server cannot produce any format the player advertises it supports. + /// + public Result DecideDelivery(PlaybackSourceFormatDto sourceFormat, IReadOnlyList capabilities) + { + string container = CanonicalizeContainer(sourceFormat.Container); + string codec = CanonicalizeCodec(sourceFormat.Codec); + + // Direct play: the player can demux the stored container and decode the stored codec, so the file is delivered unchanged, and it is addressed and seeked by byte range. + // The delivered container and codec are the stored ones, not the player's. + if (IsFormatAdvertised(capabilities, container, codec)) + return new PlaybackDeliveryDecisionDto(PlaybackDeliveryMode.DirectPlay, container, codec, PlaybackDeliveryShape.ByteRangeSeekable, 0); + + // Remux: the player can decode the stored codec but has no demuxer for the stored container, so the codec is repackaged + // into a container the server can produce and the player can demux, without re-encoding it; the normalized output is delivered as time addressed segments. + PlaybackCapabilityDto? remuxFormat = SelectFormatForCodec(capabilities, codec); + if (remuxFormat is not null) + return new PlaybackDeliveryDecisionDto(PlaybackDeliveryMode.Remux, remuxFormat.Container, remuxFormat.Codec, PlaybackDeliveryShape.TimeAddressedSegments, SEGMENT_DURATION_SECONDS); + + // Transcode: the player cannot decode the stored codec, so the audio is re-encoded into the most preferred codec the server can produce and the player advertises, + // and the normalized output is delivered as time addressed segments. + PlaybackCapabilityDto? transcodeFormat = SelectTranscodeFormat(capabilities); + if (transcodeFormat is null) + return Errors.Playback.NoSupportedPlaybackFormat; + + return new PlaybackDeliveryDecisionDto(PlaybackDeliveryMode.Transcode, transcodeFormat.Container, transcodeFormat.Codec, PlaybackDeliveryShape.TimeAddressedSegments, SEGMENT_DURATION_SECONDS); + } + + /// + /// Checks whether the player advertises the provided and as a combination it can demux and decode directly. + /// + /// The capabilities advertised by the player. + /// The canonical container that is looked for. + /// The canonical codec that is looked for. + /// when the player advertises the combination, otherwise . + private static bool IsFormatAdvertised(IReadOnlyList capabilities, string container, string codec) + { + if (container.Length == 0 || codec.Length == 0) + return false; + + return capabilities.Any(capability => + string.Equals(CanonicalizeContainer(capability.Container), container, StringComparison.OrdinalIgnoreCase) + && string.Equals(CanonicalizeCodec(capability.Codec), codec, StringComparison.OrdinalIgnoreCase)); + } + + /// + /// Selects the container the server produces the provided in, preferring the server's canonical one, among the containers the player advertises it can demux for that codec. + /// + /// The capabilities advertised by the player. + /// The canonical codec that is delivered. + /// + /// The container and codec the server delivers in, or when the server cannot produce the codec in any container the player advertises it can demux. + /// + private static PlaybackCapabilityDto? SelectFormatForCodec(IReadOnlyList capabilities, string codec) + { + if (codec.Length == 0 || !PlaybackFormatCatalog.ProducibleContainersByCodec.TryGetValue(codec, out IReadOnlyList? producibleContainers)) + return null; + + IReadOnlyList advertisedContainers = [.. capabilities + .Where(capability => string.Equals(CanonicalizeCodec(capability.Codec), codec, StringComparison.OrdinalIgnoreCase)) + .Select(capability => CanonicalizeContainer(capability.Container))]; + + // The delivered container is one of the server's own containers, chosen as the first one the player advertises: the player + // only selects among the containers the server knows, so a container the player names never reaches the transcoder itself. + foreach (string producibleContainer in producibleContainers) + if (advertisedContainers.Contains(producibleContainer, StringComparer.OrdinalIgnoreCase)) + return new PlaybackCapabilityDto(producibleContainer, codec); + + return null; + } + + /// + /// Selects the most preferred codec the server can produce that the player advertises it can decode. + /// + /// The capabilities advertised by the player. + /// The preferred producible container and codec, or when the player supports no producible codec. + private static PlaybackCapabilityDto? SelectTranscodeFormat(IReadOnlyList capabilities) + { + foreach (string preferredCodec in PlaybackFormatCatalog.TranscodeCodecPreference) + { + PlaybackCapabilityDto? format = SelectFormatForCodec(capabilities, preferredCodec); + if (format is not null) + return format; + } + + return null; + } + + /// + /// Canonicalizes the container of an audio file, so that containers compare regardless of casing. + /// + /// The container to canonicalize. + /// The canonical container, or an empty string when there is none. + private static string CanonicalizeContainer(string? container) + { + return string.IsNullOrWhiteSpace(container) ? string.Empty : container.Trim().ToUpperInvariant(); + } + + /// + /// Canonicalizes the codec of an audio file, mapping the free form descriptions reported by the probe to the canonical codec + /// names the players advertise, and leaving a description it does not recognize as unplayable. + /// + /// The codec to canonicalize. + /// The canonical codec, or an empty string when there is none. + private static string CanonicalizeCodec(string? codec) + { + if (string.IsNullOrWhiteSpace(codec)) + return string.Empty; + + // The probe reports the codec as the description the tagging library parsed from the file, for example "MPEG-1 Layer 3" rather than "MP3", + // so the known descriptions are recognized by their distinctive token, most specific ones first. The MPEG layer is matched by its layer number only, + // so MPEG-1 Layer 1 and Layer 2 are not mistaken for MP3, and a description that names no recognizable codec is left as it is, + // which keeps it from matching any advertised codec and forces a transcode. + string normalized = codec.Trim().ToUpperInvariant(); + if (normalized.Contains("VORBIS", StringComparison.Ordinal)) + return "VORBIS"; + if (normalized.Contains("OPUS", StringComparison.Ordinal)) + return "OPUS"; + if (normalized.Contains("FLAC", StringComparison.Ordinal)) + return "FLAC"; + if (normalized.Contains("ALAC", StringComparison.Ordinal) || normalized.Contains("APPLE LOSSLESS", StringComparison.Ordinal)) + return "ALAC"; + if (normalized.Contains("AAC", StringComparison.Ordinal)) + return "AAC"; + if (normalized.Contains("MP3", StringComparison.Ordinal) || normalized.Contains("LAYER 3", StringComparison.Ordinal) || normalized.Contains("LAYER III", StringComparison.Ordinal)) + return "MP3"; + if (normalized.Contains("PCM", StringComparison.Ordinal) || normalized.Contains("UNCOMPRESSED", StringComparison.Ordinal) || normalized.Contains("LINEAR", StringComparison.Ordinal)) + return "PCM"; + if (normalized.Contains("WINDOWS MEDIA", StringComparison.Ordinal) || normalized.Contains("WMA", StringComparison.Ordinal)) + return "WMA"; + + return normalized; + } +} diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/TrackNormalizationService.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/TrackNormalizationService.cs new file mode 100644 index 00000000..1ac540be --- /dev/null +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/TrackNormalizationService.cs @@ -0,0 +1,1472 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; +using Lumina.Domain.SharedKernel.Common.Enums.Playback; +using Lumina.Infrastructure.Common.Caching; +using Lumina.Infrastructure.Common.Models.DTO.Configuration; +using Lumina.Infrastructure.Common.Models.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; +using System; +using System.Collections.Concurrent; +using System.Collections.Frozen; +using System.Collections.Generic; +using System.ComponentModel; +using System.Diagnostics; +using System.Globalization; +using System.IO; +using System.Linq; +using System.Security.Cryptography; +using System.Text; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Infrastructure.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback; + +/// +/// Service that produces the normalized audio of a track with ffmpeg, caches it as fixed duration segments and serves it from the cache. +/// +/// +/// The normalized audio is written to a temporary directory that is wiped when the application starts. The number of jobs that run at the same time is +/// bounded, and a request that finds every slot occupied is reported as busy instead of being queued, so client requests cannot accumulate behind the +/// running jobs. Every child process is stopped when the application exits, and every job has a bounded duration. A production is shared by every request +/// for the same track and delivery: a request that disconnects stops waiting but does not stop the production, so repeated aborts converge to a cached entry. +/// A production is atomic: the entry is published only after ffmpeg finishes the whole track, so the first request waits for a complete production; the +/// produced segments are then served from the cache without buffering them into memory. The total size of the cache, including the output of the jobs that +/// are still running, is accounted for by a process wide coordinator, which evicts the least recently used entries that are neither freshly produced nor +/// being read. The command line is always built as a list of arguments, with the input protocol restricted to the file protocol, so a file path is never +/// interpolated into a command string and a probed file can never fetch a remote URL. Every component of a source path below a content location is checked +/// for reparse points, and ffmpeg consumes a private snapshot copied from the opened handle, so a path that is swapped after the open cannot redirect the +/// bytes that are transcoded. +/// +internal sealed class TrackNormalizationService : ITrackNormalizationService, IDisposable +{ + private const string CACHE_INDEX_FILE_NAME = "index.json"; + private const string SEGMENT_LIST_FILE_NAME = "segments.csv"; + private const string SOURCE_SNAPSHOT_FILE_NAME = "source"; + private const string SEGMENT_FILE_PREFIX = "segment-"; + private const string SEGMENT_FILE_NAME_PATTERN = SEGMENT_FILE_PREFIX + "%06d"; + private const string AUDIO_STREAM_MAP = "0:a:0"; + private const string NO_METADATA_MAP = "-1"; + private const string COPY_CODEC = "copy"; + private const string FILE_PROTOCOL = "file"; + private const long MAX_CACHE_INDEX_BYTES = 4 * 1024 * 1024; + private const long MAX_SEGMENT_LIST_BYTES = 4 * 1024 * 1024; + private const int CACHE_INDEX_VERSION = 2; + private const int MAX_SEGMENT_COUNT = 1_000_000; + private const int CACHE_SIZE_MONITOR_INTERVAL_MILLISECONDS = 500; + private const int PROCESS_EXIT_TIMEOUT_SECONDS = 5; + private const int PRODUCTION_DRAIN_TIMEOUT_SECONDS = 15; + private const int MAX_STANDARD_ERROR_CHARACTERS = 16 * 1024; + private const int AUTO_TRANSCODE_BITRATE_KBPS = 192; + private const int DEFAULT_SOURCE_BITRATE_KBPS = 320; + private const int DEFAULT_SAMPLE_RATE = 44100; + private const int DEFAULT_CHANNEL_COUNT = 2; + private const int DEFAULT_BIT_DEPTH = 16; + private const decimal FLAC_COMPRESSION_RATIO = 0.7m; + private const decimal REMUX_SIZE_MARGIN = 1.1m; + private const decimal SEGMENT_TIME_TOLERANCE_SECONDS = 0.001m; + private const decimal DURATION_TOLERANCE_MIN_SECONDS = 1m; + private const decimal DURATION_TOLERANCE_RATIO = 0.02m; + private const int MAX_TRACK_PROJECTIONS = 1024; + + // The demuxer of each container the probe can report. Pinning the demuxer stops ffmpeg from probing the content of the file and selecting a + // demuxer that can open a playlist or another indirection; the file protocol whitelist is the backstop for a container that is not listed here. + private static readonly FrozenDictionary s_sourceDemuxers = new Dictionary(StringComparer.OrdinalIgnoreCase) + { + ["MP3"] = "mp3", + ["FLAC"] = "flac", + ["MP4"] = "mov", + ["M4A"] = "mov", + ["AAC"] = "aac", + ["ADTS"] = "aac", + ["OGG"] = "ogg", + ["OPUS"] = "ogg", + ["VORBIS"] = "ogg", + ["WAV"] = "wav", + ["WAVE"] = "wav", + ["AIFF"] = "aiff", + ["APE"] = "ape", + ["WAVPACK"] = "wv", + ["WV"] = "wv", + ["WMA"] = "asf", + ["ASF"] = "asf", + ["DSF"] = "dsf", + ["MATROSKA"] = "matroska", + ["MKA"] = "matroska", + ["WEBM"] = "matroska", + ["MPC"] = "mpc", + ["AA"] = "aa" + }.ToFrozenDictionary(StringComparer.OrdinalIgnoreCase); + + // The index is server written, but a tampered file is still parsed defensively: MaxDepth bounds the recursion of the deserializer. + private static readonly JsonSerializerOptions s_indexJsonOptions = new(JsonSerializerDefaults.Web) + { + PropertyNameCaseInsensitive = true, + MaxDepth = 8 + }; + + // The productions are shared by every request of the process for the same cache entry, so a request that disconnects never cancels the work that + // another request, or a later retry, is waiting for. The key includes the cache root, because two service instances configured with different cache + // directories must never join each other's production. A completed production is removed from the registry; a later request reads the cache instead. + private static readonly ConcurrentDictionary<(string CacheRoot, string CacheId), Lazy>>> s_normalizationJobs = new(); + + private readonly TranscodingSettingsDto _settings; + private readonly ILogger _logger; + private readonly IPathService _pathService; + private readonly TranscodingCacheCoordinator _cache; + private readonly TranscodingToolchainStatus _toolchainStatus; + private readonly TimeSpan _evictionGracePeriod; + private readonly TimeSpan _touchThrottleInterval; + private readonly SemaphoreSlim _jobSlots; + private readonly ConcurrentDictionary _runningProcesses = new(); + // The projection of a cache index is reused between segment requests, so a cached track is not re-projected for every segment. The bound keeps + // the retained metadata small; a cleared cache is repopulated lazily from the index on the next request. + private readonly ConcurrentDictionary<(string CacheRoot, string CacheId), NormalizedTrackDto> _trackProjections = new(); + private readonly CancellationTokenSource _shutdownCancellation = new(); + private readonly Lock _lifecycleSync = new(); + // The global job slots are shared, but one user must not be able to take all of them and block another user's playback. These two fields guard + // the per-user admission count; they are not part of the cache identity, because a production is shared by every user that requests it. + private readonly Lock _userProductionLock = new(); + private readonly Dictionary _activeProductionsPerUser = []; + private readonly ManualResetEventSlim _productionsDrained = new(initialState: true); + private readonly string _cacheRoot; + private int _activeProductionCount; + // Written under _lifecycleSync by Dispose and read without the lock by the request paths through Volatile.Read, so the write is observed promptly. + private bool _isDisposed; + + /// + /// Initializes a new instance of the class. + /// + /// The audio normalization configuration options. + /// The logger for this service. + /// The service used to validate that a cached segment is inside its cache entry. + /// The status that records whether the ffmpeg toolchain found at startup can produce a format. + public TrackNormalizationService(IOptions options, ILogger logger, IPathService pathService, TranscodingToolchainStatus toolchainStatus) + { + _settings = options.Value; + _logger = logger; + _pathService = pathService; + _toolchainStatus = toolchainStatus; + _jobSlots = new SemaphoreSlim(_settings.MaxConcurrentJobs, _settings.MaxConcurrentJobs); + _evictionGracePeriod = TimeSpan.FromSeconds(_settings.EvictionGraceSeconds); + // A touch is written at most every quarter of the eviction grace period, so a stream that opens many segments does not rewrite the cache + // entry for every request while an actively used entry stays protected from eviction. + _touchThrottleInterval = TimeSpan.FromSeconds(Math.Clamp(_settings.EvictionGraceSeconds / 4.0, 0.25, 30)); + _cacheRoot = TranscodingCachePaths.GetRootDirectory(_settings.CacheDirectory); + _cache = TranscodingCacheCoordinator.AcquireForRoot(_cacheRoot); + // A killed process must never outlive the application, so every child process that is still running is stopped when the process exits. The + // subscription is removed when the service is disposed, so a host that is shut down in the same process does not keep this instance rooted. + AppDomain.CurrentDomain.ProcessExit += OnApplicationStopping; + } + + /// + /// Gets the normalized audio of a track from the cache, or produces it and caches it when it is not cached yet. + /// + /// The track, the delivery decision, the source file and the quality cap the normalized audio is produced with. + /// Cancellation token that can be used to stop the execution. + /// An containing either the cached normalized audio of the track, or an error message. + /// + /// Thrown when is canceled while the caller is waiting. The production continues in the background, so this is a + /// disconnect signal and must not be treated as a production failure. + /// + public async Task> GetOrCreateNormalizedTrackAsync(NormalizedTrackRequestDto request, CancellationToken cancellationToken) + { + // Dispose sets _isDisposed under _lifecycleSync, but taking that lock on every request would serialize this hot path. The flag is therefore read + // without the lock. Volatile.Read keeps the read from being cached in a register, so a request observes the disposal flag once it is set and + // fails fast instead of using resources that Dispose has already released. + if (Volatile.Read(ref _isDisposed)) + return Errors.Playback.NormalizationUnavailable; + if (request.TrackId == Guid.Empty) + return Errors.Playback.NormalizationFailed; + if (request.UserId == Guid.Empty) + return Errors.Playback.NormalizationFailed; + if (string.IsNullOrWhiteSpace(request.SourcePath)) + return Errors.Music.TrackPathCannotBeEmpty; + // The caller authorizes the request, and the service re-validates the source path against the content locations carried by the request. A path + // that is outside every allowed root is reported as not found, never as a path error, so no file system detail is disclosed. + if (request.AllowedRoots is null || request.AllowedRoots.Count == 0 || !IsPathAllowed(request.SourcePath, request.AllowedRoots)) + return Errors.Music.TrackFileNotFound; + // Normalization only exists for audio the player cannot play as stored, so a direct play never reaches the pipeline. + if (request.Mode == PlaybackDeliveryMode.DirectPlay) + return Errors.Playback.NormalizationIsNotRequiredForDirectPlay; + if (request.SegmentDurationSeconds <= 0) + return Errors.Playback.SegmentDurationMustBePositive; + if (request.DurationInSeconds <= 0) + return Errors.Playback.TrackDurationMustBePositive; + // A delivery decision that names a pair the catalog does not implement is a disagreement between two server side tables. It must never be + // reported as a limitation of the player, which is what the forbidden NoSupportedPlaybackFormat means. + if (!PlaybackFormatCatalog.FormatsByPair.TryGetValue(PlaybackFormatCatalog.BuildPairKey(request.Container, request.Codec), out NormalizedAudioFormatDto? format)) + return Errors.Playback.PlaybackFormatNotImplemented; + + FileInfo sourceFile; + long sourceLength; + DateTime sourceLastModifiedUtc; + try + { + sourceFile = new FileInfo(request.SourcePath); + if (!sourceFile.Exists) + return Errors.Music.TrackFileNotFound; + // The length and the modification time of the source are read once, while the file is known to exist, and are used both for the cache + // identity and for the size estimate, so a file that disappears between two reads can never surface as an unhandled exception. + sourceLength = sourceFile.Length; + sourceLastModifiedUtc = sourceFile.LastWriteTimeUtc; + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException or NotSupportedException) + { + return Errors.Music.TrackFileNotFound; // A file that cannot be read is indistinguishable, to the caller, from a file that does not exist. + } + + // The delivery was declared against a specific version of the source file. A file that changed since then would produce a new cache + // entry with a different identity, so its segments would be mixed with the segments of the declared delivery. It is rejected instead. + if (request.SourceLength != sourceLength || request.SourceLastModifiedUtc != sourceLastModifiedUtc) + return Errors.Playback.PlaybackDeliveryChanged; + + string cacheId = BuildCacheId(request, sourceFile.FullName, sourceLength, sourceLastModifiedUtc, format); + // The entry is touched before its index is read, so that a cache hit can never race an eviction that is deciding on the entry at the same time: + // an eviction that runs after the touch sees the entry as recently used, and one that ran before the touch makes the read miss and produce anew. + _cache.Touch(cacheId, _touchThrottleInterval); + if (TryReadCachedTrack(cacheId, out NormalizedTrackDto? cachedTrack) && cachedTrack is not null && cachedTrack.TrackId == request.TrackId) + return cachedTrack; + + // The production is shared by every request for this cache entry and is not tied to this request's token. This request only waits for it, so a + // disconnect stops this caller from waiting without destroying the work, and the next request either joins the same production or reads its result. + (string CacheRoot, string CacheId) normalizationJobKey = (_cacheRoot, cacheId); + // ExecutionAndPublication makes the factory run exactly once when several requests race to create the same job. + Lazy>> normalizationJob = s_normalizationJobs.GetOrAdd( + normalizationJobKey, + createdJobKey => new Lazy>>( + () => ProduceAsync(cacheId, request, format, sourceLength, sourceLastModifiedUtc), + LazyThreadSafetyMode.ExecutionAndPublication)); + Task> normalizationTask = normalizationJob.Value; + // Remove the job from the static registry when it finishes, so a completed result is not kept in memory forever. + _ = normalizationTask.ContinueWith( + completedTask => RemoveNormalizationJob(normalizationJobKey, normalizationJob), + CancellationToken.None, + TaskContinuationOptions.ExecuteSynchronously, + TaskScheduler.Default); + + return await normalizationTask.WaitAsync(cancellationToken).ConfigureAwait(false); + } + + /// + /// Opens a read stream over a single segment of a cached normalized track, after verifying that the entry belongs to the provided track. + /// + /// The opaque identifier of the cached entry that holds the normalized audio. + /// The Id of the track the caller authorized and whose segment is opened. + /// The zero based position of the segment in the delivered audio. + /// + /// An containing either a read stream over the segment, or an error message. The caller owns the returned stream. + /// + public Result OpenNormalizedSegment(string cacheId, Guid trackId, int segmentIndex) + { + // This runs for every segment request and must not take _lifecycleSync. Dispose writes _isDisposed under that lock, and Volatile.Read makes this + // lock free check observe the write instead of a value cached in a register, so segments stop being served as soon as the service is disposed. + if (Volatile.Read(ref _isDisposed)) + return Errors.Playback.NormalizationUnavailable; + if (trackId == Guid.Empty || !TranscodingCacheCoordinator.IsValidCacheId(cacheId) || segmentIndex < 0) + return Errors.Playback.NormalizedTrackCacheEntryNotFound; + + // The lease is acquired before the index is read, so that an eviction that runs concurrently can never delete the entry between the read and + // the moment the segment stream starts. The lease is handed over to the stream and released when the caller disposes it. + TranscodingCacheReaderLease lease = _cache.AcquireReaderLease(cacheId); + bool isLeaseTransferred = false; + try + { + if (!TryReadIndex(cacheId, out NormalizedTrackIndexDto? index) || index is null) + return Errors.Playback.NormalizedTrackCacheEntryNotFound; + + // The cache handle is not a capability: it is derived from the track and can be computed by anyone who knows the track. The entry is bound + // to the track it was produced for, so a handle can only ever serve the track the caller authorized against the route. + if (index.TrackId != trackId) + return Errors.Music.TrackNotFound; + + NormalizedTrackSegmentIndexDto? segment = index.Segments.FirstOrDefault(candidate => candidate.Index == segmentIndex); + if (segment is null) + return Errors.Playback.NormalizedTrackCacheEntryNotFound; + + string cachePath = Path.Combine(_cacheRoot, cacheId); + string segmentPath = Path.Combine(cachePath, segment.FileName); + // The file name comes from the cache index, which only the server writes, but the resolved path is still confined to the cache entry so that a + // tampered index can never be used to read a file outside it. + if (!_pathService.IsPathWithin(segmentPath, cachePath)) + return Errors.Playback.NormalizedTrackCacheEntryNotFound; + // A cache entry is never reached through a reparse point. The index is only written by this application, but a tampered cache entry must not be + // able to redirect a segment outside the cache root. + if (HasReparsePointBelow(_cacheRoot, segmentPath)) + return Errors.Playback.NormalizedTrackCacheEntryNotFound; + + FileInfo segmentFile = new(segmentPath); + if (!segmentFile.Exists || segmentFile.Length != segment.Length) + return Errors.Playback.NormalizedTrackCacheEntryNotFound; + + _cache.Touch(cacheId, _touchThrottleInterval); + // A published entry is immutable, so every reader can share the file. Delete sharing is not granted: replacement is coordinated through the + // lease and the publication lock, never by deleting a file under a reader. + FileStream fileStream = new(segmentPath, FileMode.Open, FileAccess.Read, FileShare.Read, 81920, useAsync: true); + try + { + // The handle is checked against the length from the index and against the reparse points again, so a file or an ancestor swapped between + // the check and the open is never handed to the caller. + if (fileStream.Length != segment.Length || HasReparsePointBelow(_cacheRoot, segmentPath)) + { + fileStream.Dispose(); + return Errors.Playback.NormalizedTrackCacheEntryNotFound; + } + } + catch + { + fileStream.Dispose(); + throw; + } + TranscodingCacheLeaseStream leaseStream = new(fileStream, lease); + isLeaseTransferred = true; + return Result.Success(leaseStream); + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException or NotSupportedException) + { + return Errors.Playback.NormalizedTrackCacheEntryNotFound; + } + finally + { + if (!isLeaseTransferred) + lease.Dispose(); + } + } + + /// + /// Opens the stored audio file of a track after re-validating that it is inside an allowed root, and re-checks the opened handle. + /// + /// + /// The caller has already authorized the request, but the path is still validated here as defense in depth. Every component between an allowed root and + /// the leaf is rejected when it is a reparse point, so a symbolic link inside a content location can never redirect the file outside it. The file is then + /// opened, and the opened handle is checked against the allowed roots and against the length and modification time the cache identity was built from. + /// The caller copies the opened handle into a private snapshot before the transcoder runs, so the transcoder reads exactly the bytes that were validated, + /// even when the path is replaced afterwards. The length is read from the handle; the modification time is a path based, best effort comparison. + /// + /// The request whose source path and allowed roots are validated. + /// The length of the stored audio file of the track, in bytes, read when the cache identity was built. + /// The date and time, in UTC, when the stored audio file of the track was last modified, read when the cache identity was built. + /// An containing either an open read stream over the authorized source file, or an error message. The caller owns the stream. + private Result OpenAuthorizedSource(NormalizedTrackRequestDto request, long sourceLength, DateTime sourceLastModifiedUtc) + { + try + { + FileInfo sourceFile = new(request.SourcePath); + if (!sourceFile.Exists || !IsPathAllowed(sourceFile.FullName, request.AllowedRoots)) + return Errors.Music.TrackFileNotFound; + + string resolvedPath = sourceFile.FullName; + FileStream sourceStream = new(resolvedPath, FileMode.Open, FileAccess.Read, FileShare.Read, 81920, useAsync: true); + try + { + // The file is checked again after it has been opened, so a path that was swapped between the FileInfo read and the open is never handed + // to the transcoder. The length is read from the handle itself; the modification time must also still match the value the cache identity was built from. + FileInfo openedFile = new(resolvedPath); + if (!openedFile.Exists || + !IsPathAllowed(openedFile.FullName, request.AllowedRoots) || + sourceStream.Length != sourceLength || + openedFile.LastWriteTimeUtc != sourceLastModifiedUtc) + { + sourceStream.Dispose(); + return Errors.Music.TrackFileNotFound; + } + + return sourceStream; + } + catch + { + sourceStream.Dispose(); + throw; + } + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException or NotSupportedException) + { + return Errors.Music.TrackFileNotFound; + } + } + + /// + /// Checks whether a path is inside at least one of the allowed roots, without crossing a reparse point below that root. + /// + /// The path to check. + /// The roots the path is allowed to be inside. + /// when the path is inside an allowed root and no component below that root is a reparse point, otherwise . + private bool IsPathAllowed(string path, IReadOnlyList allowedRoots) + { + foreach (string allowedRoot in allowedRoots) + { + if (string.IsNullOrWhiteSpace(allowedRoot) || !_pathService.IsPathWithin(path, allowedRoot)) + continue; + // A reparse point inside the content location fails closed instead of being resolved, because its target is outside the root the caller authorized. + return !HasReparsePointBelow(allowedRoot, path); + } + return false; + } + + /// + /// Checks whether any component of a path below a root is a reparse point. + /// + /// The root below which the components are checked. + /// The path inside the root whose components are checked. + /// when a component below the root is a reparse point, otherwise . + private static bool HasReparsePointBelow(string rootPath, string path) + { + string normalizedRootPath = Path.GetFullPath(rootPath); + string normalizedPath = Path.GetFullPath(path); + string relativePath = Path.GetRelativePath(normalizedRootPath, normalizedPath); + if (relativePath == ".") + return false; + string currentPath = normalizedRootPath; + foreach (string segment in relativePath.Split([Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar], StringSplitOptions.RemoveEmptyEntries)) + { + // The lexical containment check already succeeded, so a relative escape means the two paths disagree; the file is rejected rather than trusted. + if (segment == "..") + return true; + if (segment == ".") + continue; + currentPath = Path.Combine(currentPath, segment); + if ((File.GetAttributes(currentPath) & FileAttributes.ReparsePoint) == FileAttributes.ReparsePoint) + return true; + } + return false; + } + + /// + /// Admits a production to the service lifetime, so that shutdown cancels it and disposes the process lifetime resources only after it has left. + /// + /// The opaque identifier of the cache entry. + /// The track, the delivery decision and the quality cap the normalized audio is produced with. + /// The container and codec combination the normalized audio is produced in. + /// The length of the stored audio file of the track, in bytes. + /// The date and time, in UTC, when the stored audio file of the track was last modified. + /// An containing either the normalized audio of the track, or an error message. + private async Task> ProduceAsync(string cacheId, NormalizedTrackRequestDto request, NormalizedAudioFormatDto format, long sourceLength, DateTime sourceLastModifiedUtc) + { + // The global job slots are shared by every user, so a user who starts many productions at once could occupy all of them and make + // another user's playback fail. The per-user admission happens before the production is registered, and a request that joins a + // production another user already started does not reach this method, so a shared production is never charged twice. + if (!TryAcquireUserProductionSlot(request.UserId)) + return Errors.Playback.NormalizationUnavailable; + + try + { + lock (_lifecycleSync) + { + // A production that arrives after shutdown has started must not touch the cancellation source, the job slots or the coordinator, because shutdown may already have disposed them. + if (_isDisposed) + return Errors.Playback.NormalizationUnavailable; + // Dispose waits on _productionsDrained before it releases the coordinator and job slots. Counting the production here closes the race + // between the disposal check above and the resources being released while the production is still using them. + _activeProductionCount++; + if (_activeProductionCount == 1) + _productionsDrained.Reset(); + } + + try + { + return await ProduceCoreAsync(cacheId, request, format, sourceLength, sourceLastModifiedUtc).ConfigureAwait(false); + } + finally + { + lock (_lifecycleSync) + { + _activeProductionCount--; + if (_activeProductionCount == 0) + _productionsDrained.Set(); + } + } + } + finally + { + ReleaseUserProductionSlot(request.UserId); + } + } + + /// + /// Reserves one of the per-user production slots before a production is admitted, so one user can never occupy every global job slot. + /// + /// The Id of the user whose request starts the production. + /// when the slot was reserved, otherwise. + private bool TryAcquireUserProductionSlot(Guid userId) + { + lock (_userProductionLock) + { + if (userId == Guid.Empty) + return false; + int activeProductions = _activeProductionsPerUser.GetValueOrDefault(userId); + if (activeProductions >= _settings.MaxConcurrentJobsPerUser) + return false; + _activeProductionsPerUser[userId] = activeProductions + 1; + return true; + } + } + + /// + /// Releases a per-user production slot that was reserved by . + /// + /// The Id of the user whose production ended. + private void ReleaseUserProductionSlot(Guid userId) + { + lock (_userProductionLock) + { + if (!_activeProductionsPerUser.TryGetValue(userId, out int activeProductions)) + return; + if (activeProductions <= 1) + _activeProductionsPerUser.Remove(userId); + else + _activeProductionsPerUser[userId] = activeProductions - 1; + } + } + + /// + /// Produces the normalized audio of a track in the background, independent of any request that waits for it. + /// + /// The opaque identifier of the cache entry. + /// The track, the delivery decision and the quality cap the normalized audio is produced with. + /// The container and codec combination the normalized audio is produced in. + /// The length of the stored audio file of the track, in bytes. + /// The date and time, in UTC, when the stored audio file of the track was last modified. + /// An containing either the normalized audio of the track, or an error message. + private async Task> ProduceCoreAsync(string cacheId, NormalizedTrackRequestDto request, NormalizedAudioFormatDto format, long sourceLength, DateTime sourceLastModifiedUtc) + { + CancellationToken cancellationToken = _shutdownCancellation.Token; + + // The startup initializer owns the cache directory, but the service re-ensures it before every production so a directory removed at runtime or a + // failed startup wipe cannot turn into an unhandled exception or a partial write. + try + { + TranscodingCachePaths.EnsureDirectoryExists(_cacheRoot); + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) + { + _logger.LogError(exception, "The normalized audio cache directory '{CacheDirectory}' is not available for track {TrackId} in cache entry {CacheId}.", _cacheRoot, request.TrackId, cacheId); + return Errors.Playback.NormalizationUnavailable; + } + + try + { + // A production is admitted immediately or reported as busy. Queueing a task per distinct request would let a client saturate the pipeline + // and outlive its own timeout, while a started production is still allowed to outlive every disconnected waiter. + if (!_jobSlots.Wait(0)) + return Errors.Playback.NormalizationUnavailable; + try + { + // Another production for the same entry may have finished while this one was created, so the cache is checked again before spendingan admitted slot on work that is already done. + if (TryReadCachedTrack(cacheId, out NormalizedTrackDto? cachedTrack) && cachedTrack is not null && cachedTrack.TrackId == request.TrackId) + { + _cache.Touch(cacheId, _touchThrottleInterval); + return cachedTrack; + } + + // A cached entry is served even when the toolchain is broken, but a new production needs a usable ffmpeg and, for a transcode, the + // encoder of the delivery format. The startup probe recorded what is missing, so this is reported as unavailable instead of failing per track. + if (!_toolchainStatus.IsTranscoderAvailable || (request.Mode == PlaybackDeliveryMode.Transcode && !_toolchainStatus.IsEncoderAvailable(format.EncoderName))) + return Errors.Playback.NormalizationUnavailable; + + long estimatedSize = EstimateOutputSize(request, format); + if (!_cache.TryReserve(estimatedSize, _settings.MaxCacheBytes, _evictionGracePeriod, out TranscodingCacheReservation? reservation) || reservation is null) + return Errors.Playback.NormalizationCacheLimitExceeded; + + using (reservation) + return await NormalizeAsync(cacheId, request, format, sourceLength, sourceLastModifiedUtc, reservation, cancellationToken).ConfigureAwait(false); + } + finally + { + _jobSlots.Release(); + } + } + catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) + { + return Errors.Playback.NormalizationUnavailable; // The application is stopping, so the production cannot finish; it is reported instead of being left as an unobserved cancellation. + } + catch (Exception exception) + { + // The production is shared by requests that are no longer necessarily waiting, so every failure is turned into a result and observed here. + _logger.LogError(exception, "The normalized audio of track {TrackId} in cache entry {CacheId} could not be produced.", request.TrackId, cacheId); + return Errors.Playback.NormalizationFailed; + } + } + + /// + /// Produces the normalized audio of a track into a temporary directory, persists its index and asks the coordinator to publish it into the cache. + /// + /// The opaque identifier of the cache entry. + /// The track, the delivery decision and the quality cap the normalized audio is produced with. + /// The container and codec combination the normalized audio is produced in. + /// The length of the stored audio file of the track, in bytes. + /// The date and time, in UTC, when the stored audio file of the track was last modified. + /// The capacity the job reserved in the cache. + /// Cancellation token that can be used to stop the execution. + /// An containing either the normalized audio of the track, or an error message. + private async Task> NormalizeAsync(string cacheId, NormalizedTrackRequestDto request, NormalizedAudioFormatDto format, long sourceLength, DateTime sourceLastModifiedUtc, TranscodingCacheReservation reservation, CancellationToken cancellationToken) + { + string temporaryPath = Path.Combine(_cacheRoot, TranscodingCachePaths.TEMPORARY_DIRECTORY_PREFIX + Guid.NewGuid().ToString("N")); + string segmentListPath = Path.Combine(temporaryPath, SEGMENT_LIST_FILE_NAME); + + // The source is opened and re-validated here, immediately before the transcoder runs, and copied into a private snapshot that the transcoder reads. + // The snapshot is written from the validated handle, so the transcoder consumes exactly the bytes that were validated even when the path is replaced. + Result openResult = OpenAuthorizedSource(request, sourceLength, sourceLastModifiedUtc); + if (openResult.IsFailure) + return openResult.Errors; + + using (FileStream sourceStream = openResult.Value) + { + try + { + TranscodingCachePaths.CreatePrivateDirectory(temporaryPath); + string snapshotPath = Path.Combine(temporaryPath, SOURCE_SNAPSHOT_FILE_NAME); + bool isSnapshotComplete; + // The copy is bounded by the job timeout as well, so a source that never finishes reading cannot hold a job slot indefinitely. + using (CancellationTokenSource snapshotTimeoutCancellationTokenSource = new(TimeSpan.FromSeconds(_settings.JobTimeoutSeconds))) + { + using (CancellationTokenSource snapshotCancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, snapshotTimeoutCancellationTokenSource.Token)) + { + try + { + isSnapshotComplete = await CopySourceSnapshotAsync(sourceStream, snapshotPath, sourceLength, snapshotCancellationTokenSource.Token).ConfigureAwait(false); + } + catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested) + { + return Errors.Playback.NormalizationTimedOut; + } + } + } + if (!isSnapshotComplete) + return Errors.Music.TrackFileNotFound; + + Result runResult; + try + { + runResult = await RunFfmpegAsync(cacheId, request, snapshotPath, format, temporaryPath, segmentListPath, reservation, cancellationToken).ConfigureAwait(false); + } + finally + { + // The snapshot is not part of the cache entry; it is removed before the entry is moved or the temporary directory is cleaned. + TryDeleteFile(snapshotPath); + } + if (runResult.IsFailure) + return runResult.Errors; + NormalizedTrackIndexDto index = runResult.Value; + // The csv is only an intermediate of the production; it is not part of the published entry and is never read again. + TryDeleteFile(segmentListPath); + // The entries are created under a private root, but each produced file is tightened as well instead of relying on the directory mode alone. + foreach (NormalizedTrackSegmentIndexDto segment in index.Segments) + TranscodingCachePaths.RestrictFilePermissions(Path.Combine(temporaryPath, segment.FileName)); + + // The index is written before the entry is published, so a cache hit never has to parse the ffmpeg output or probe the segments again. + string indexJson = JsonSerializer.Serialize(index, s_indexJsonOptions); + string temporaryIndexPath = Path.Combine(temporaryPath, CACHE_INDEX_FILE_NAME); + await File.WriteAllTextAsync(temporaryIndexPath, indexJson, cancellationToken).ConfigureAwait(false); + TranscodingCachePaths.RestrictFilePermissions(temporaryIndexPath); + // The segments were stat'ed by the index parser, so the size is the parsed lengths plus the index file instead of another walk of the entry. + long entrySize = index.Segments.Sum(segment => segment.Length) + Encoding.UTF8.GetByteCount(indexJson); + FileInfo remainingSegmentList = new(segmentListPath); + if (remainingSegmentList.Exists) + entrySize += remainingSegmentList.Length; + // The coordinator replaces the previous directory, moves this one into place and registers its index under one lock, so a concurrent + // eviction can never delete the freshly published entry and a reader is never served a mix of two productions. + if (!reservation.TryComplete(cacheId, temporaryPath, entrySize, index, _settings.MaxCacheBytes, _evictionGracePeriod, out bool isKeptOverCapacity, out bool isEntryInUse)) + { + if (isEntryInUse) + return Errors.Playback.NormalizationUnavailable; + return Errors.Playback.NormalizationFailed; + } + if (isKeptOverCapacity) + _logger.LogWarning("The normalized audio of track {TrackId} in cache entry {CacheId} was produced successfully but exceeds the configured normalized audio cache limit. It is kept readable and will be evicted when it is no longer in use.", request.TrackId, cacheId); + + return GetOrCreateTrackProjection(cacheId, index); + } + catch (OperationCanceledException) + { + throw; + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException or JsonException or NotSupportedException) + { + _logger.LogWarning(exception, "The normalized audio of track {TrackId} in cache entry {CacheId} could not be cached.", request.TrackId, cacheId); + return Errors.Playback.NormalizationFailed; + } + finally + { + if (Directory.Exists(temporaryPath)) + TranscodingCachePaths.TryDeleteDirectory(temporaryPath); + } + } + } + + /// + /// Copies the validated source stream into a private snapshot file, so the transcoder reads exactly the bytes that were validated. + /// + /// The open, validated stream over the stored audio file of the track. + /// The path of the snapshot file to create. + /// The expected length of the source file, in bytes. + /// Cancellation token that can be used to stop the execution. + /// when the whole source was copied, otherwise . + private static async Task CopySourceSnapshotAsync(FileStream sourceStream, string snapshotPath, long expectedLength, CancellationToken cancellationToken) + { + using (FileStream snapshotStream = new(snapshotPath, FileMode.CreateNew, FileAccess.Write, FileShare.None, 81920, useAsync: true)) + await sourceStream.CopyToAsync(snapshotStream, cancellationToken).ConfigureAwait(false); + // The snapshot is read from the open handle, so the comparison detects a source that was truncated or grew after the handle was validated. + return new FileInfo(snapshotPath).Length == expectedLength; + } + + /// + /// Runs ffmpeg to write the normalized audio of a track into a temporary directory, and builds the index of the produced segments. + /// + /// The track, the delivery decision and the quality cap the normalized audio is produced with. + /// The path of the private snapshot of the stored audio file, which was copied from the validated handle. + /// The container and codec combination the normalized audio is produced in. + /// The temporary directory the normalized audio is written into. + /// The file into which ffmpeg writes the list of produced segments. + /// The capacity the job reserved in the cache. + /// Cancellation token that can be used to stop the execution. + /// An containing either the index of the produced segments, or an error message. + private async Task> RunFfmpegAsync(string cacheId, NormalizedTrackRequestDto request, string inputPath, NormalizedAudioFormatDto format, string temporaryPath, string segmentListPath, TranscodingCacheReservation reservation, CancellationToken cancellationToken) + { + using Process process = new(); + process.StartInfo = new ProcessStartInfo + { + FileName = _settings.FfmpegPath, + UseShellExecute = false, + CreateNoWindow = true, + RedirectStandardError = true, + RedirectStandardOutput = false + }; + foreach (string argument in BuildArguments(request, inputPath, format, temporaryPath, segmentListPath)) + process.StartInfo.ArgumentList.Add(argument); + + try + { + if (!process.Start()) + return Errors.Playback.NormalizationFailed; + } + catch (Exception exception) when (exception is Win32Exception or InvalidOperationException or IOException) + { + _logger.LogError(exception, "The audio transcoder for track {TrackId} in cache entry {CacheId} could not be started.", request.TrackId, cacheId); + return Errors.Playback.NormalizationUnavailable; + } + + // The process is registered so the application exit handler can kill it even if the host stops without reaching this method's finally. + _runningProcesses[process.Id] = process; + try + { + // Start draining stderr before waiting. A child that fills the pipe buffer blocks until it is read, so waiting for the exit first could deadlock. + Task standardErrorTask = ReadBoundedStandardErrorAsync(process.StandardError); + using CancellationTokenSource timeoutCancellationTokenSource = new(TimeSpan.FromSeconds(_settings.JobTimeoutSeconds)); + using CancellationTokenSource linkedCancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, timeoutCancellationTokenSource.Token); + // The callback kills ffmpeg as soon as the token fires, so a cancellation or timeout stops the child even while this thread is awaiting its + // exit. The catch below only observes the exit that the callback caused. + using CancellationTokenRegistration cancellationRegistration = linkedCancellationTokenSource.Token.Register(() => KillProcess(process)); + using CancellationTokenSource monitorCancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(linkedCancellationTokenSource.Token); + TranscodingOutputSizeTracker outputSizeTracker = new(temporaryPath, SEGMENT_FILE_PREFIX, format.FileExtension, SEGMENT_LIST_FILE_NAME); + Task monitorTask = MonitorOutputSizeAsync(cacheId, request.TrackId, outputSizeTracker, reservation, process, monitorCancellationTokenSource.Token); + try + { + await process.WaitForExitAsync(linkedCancellationTokenSource.Token).ConfigureAwait(false); + } + catch (OperationCanceledException) + { + KillProcess(process); + // The cancellation callback fired the kill without waiting. The exit is observed asynchronously here, so the temporary directory is + // cleaned up after the child has actually stopped, without pinning the thread that triggered the cancellation. + using CancellationTokenSource exitCancellationTokenSource = new(TimeSpan.FromSeconds(PROCESS_EXIT_TIMEOUT_SECONDS)); + try + { + await process.WaitForExitAsync(exitCancellationTokenSource.Token).ConfigureAwait(false); + } + catch (OperationCanceledException) + { + _logger.LogDebug("The audio transcoder did not exit within the process exit timeout."); + } + } + finally + { + // The monitor loops until it is canceled. Stop it before awaiting it, or a job that finished normally would wait forever. + monitorCancellationTokenSource.Cancel(); + } + + bool isCacheLimitExceeded = await monitorTask.ConfigureAwait(false); + // The read is bounded: a process that was killed but did not exit would otherwise keep the pipe open and park the job slot. + string standardError = await AwaitStandardErrorAsync(standardErrorTask).ConfigureAwait(false); + cancellationToken.ThrowIfCancellationRequested(); + if (isCacheLimitExceeded) + return Errors.Playback.NormalizationCacheLimitExceeded; + if (timeoutCancellationTokenSource.IsCancellationRequested) + return Errors.Playback.NormalizationTimedOut; + if (process.ExitCode != 0) + { + _logger.LogWarning("The audio transcoder for track {TrackId} in cache entry {CacheId} exited with code {ExitCode}.", request.TrackId, cacheId, process.ExitCode); + if (!string.IsNullOrWhiteSpace(standardError)) + { + // The bounded stderr can contain the source path and media metadata. It is only written at Debug and never returned to a client. + string diagnostic = RedactPath(RedactPath(standardError, inputPath), request.SourcePath); + _logger.LogDebug("The audio transcoder for track {TrackId} in cache entry {CacheId} reported: {StandardError}", request.TrackId, cacheId, diagnostic); + } + return Errors.Playback.NormalizationFailed; + } + + return ParseSegmentIndex(cacheId, segmentListPath, temporaryPath, request, format); + } + finally + { + _runningProcesses.TryRemove(process.Id, out _); + KillProcess(process); + } + } + + /// + /// Builds the argument list of a single ffmpeg invocation, with one argument per list entry, so a path is never interpolated into a command line. + /// + /// The track, the delivery decision and the quality cap the normalized audio is produced with. + /// The path of the private snapshot of the stored audio file, which was copied from the validated handle. + /// The container and codec combination the normalized audio is produced in. + /// The temporary directory the normalized audio is written into. + /// The file into which ffmpeg writes the list of produced segments. + /// The argument list of the ffmpeg invocation. + private static IReadOnlyList BuildArguments(NormalizedTrackRequestDto request, string inputPath, NormalizedAudioFormatDto format, string temporaryPath, string segmentListPath) + { + List arguments = + [ + "-hide_banner", + "-loglevel", "error", + "-nostdin", + "-y", + "-protocol_whitelist", FILE_PROTOCOL + ]; + + // The demuxer is pinned to the container the probe stored, so ffmpeg never probes the content of the file and never selects a demuxer that + // can follow a playlist or another indirection. A container that is not known is still limited to the file protocol by the whitelist above. + if (TryResolveSourceDemuxer(request.SourceContainer, out string sourceDemuxer)) + { + arguments.Add("-f"); + arguments.Add(sourceDemuxer); + } + + arguments.AddRange( + [ + "-i", inputPath, + "-map", AUDIO_STREAM_MAP, + "-vn", + "-sn", + "-dn", + "-map_metadata", NO_METADATA_MAP + ]); + + // A remux only repackages the stored codec, while a transcode re-encodes it and applies the streaming quality cap when the codec is lossy. + arguments.Add("-c:a"); + if (request.Mode == PlaybackDeliveryMode.Remux) + arguments.Add(COPY_CODEC); + else + { + arguments.Add(format.EncoderName); + // A lossy transcode always carries an explicit bitrate, including Auto, so the emitted stream and the cache size estimate use the same number. + if (!format.IsLossless) + { + arguments.Add("-b:a"); + arguments.Add(GetTargetBitrateKbps(request.Quality).ToString(CultureInfo.InvariantCulture) + "k"); + } + } + + arguments.AddRange( + [ + "-f", "segment", + "-segment_time", request.SegmentDurationSeconds.ToString(CultureInfo.InvariantCulture), + "-segment_format", format.MuxerName + ]); + + // MP4 writes the moov atom at the end by default, so a client that starts reading a segment before it is fully fetched would stall. The segments + // are written as files, so the muxer can move the atom to the front of each one. + if (string.Equals(format.MuxerName, "mp4", StringComparison.OrdinalIgnoreCase)) + { + arguments.Add("-segment_format_options"); + arguments.Add("movflags=+faststart"); + } + + arguments.AddRange( + [ + "-segment_start_number", "0", + "-reset_timestamps", "1", + "-segment_list", segmentListPath, + "-segment_list_type", "csv", + Path.Combine(temporaryPath, SEGMENT_FILE_NAME_PATTERN + format.FileExtension) + ]); + return arguments; + } + + /// + /// Parses the segment list ffmpeg wrote and turns it into the persisted index of the normalized audio. + /// + /// + /// Every line must describe a complete, readable segment. A malformed line is a hard failure instead of a skipped segment, because skipping a line + /// would produce an index over audio that has a hole in it. The index of a segment is taken from the number in its generated file name, and the + /// numbers must form a contiguous sequence starting at zero, so a missing segment can never be silently renumbered. A trailing segment with an empty + /// time range, which ffmpeg can emit when the last frame ends exactly on a segment boundary, is discarded instead of being indexed. The produced + /// duration is compared with the probed duration only for a shortfall, which is the truncation case; a production that is longer than the probe is + /// kept and logged, because a probe that estimates a duration from the bitrate can underestimate a variable bitrate file. The duration recorded in the + /// index is the produced end, rounded up to the next second, so the seek map of the cache entry always covers every produced segment. + /// + /// The opaque identifier of the cache entry. + /// The file into which ffmpeg wrote the list of produced segments. + /// The temporary directory the normalized audio was written into. + /// The track, the delivery decision and the quality cap the normalized audio was produced with. + /// The container and codec combination the normalized audio was produced in. + /// + /// An containing either the index of the produced segments, or an error message. + /// + private Result ParseSegmentIndex(string cacheId, string segmentListPath, string temporaryPath, NormalizedTrackRequestDto request, NormalizedAudioFormatDto format) + { + if (!File.Exists(segmentListPath)) + return Errors.Playback.NormalizationFailed; + if (new FileInfo(segmentListPath).Length > MAX_SEGMENT_LIST_BYTES) + return Errors.Playback.NormalizationFailed; + + List segments = []; + try + { + foreach (string line in File.ReadLines(segmentListPath)) + { + if (string.IsNullOrWhiteSpace(line)) + continue; + + // A csv entry is "file,start,end". The file name is generated by this application and never contains a comma, so the last two commas always delimit the two times. + int endSeparatorIndex = line.LastIndexOf(','); + if (endSeparatorIndex <= 0) + return Errors.Playback.NormalizationFailed; + int startSeparatorIndex = line.LastIndexOf(',', endSeparatorIndex - 1); + if (startSeparatorIndex <= 0) + return Errors.Playback.NormalizationFailed; + + string fileName = Path.GetFileName(line[..startSeparatorIndex].Trim()); + if (!TryGetSegmentNumber(fileName, format.FileExtension, out int segmentNumber)) + return Errors.Playback.NormalizationFailed; + + string startText = line[(startSeparatorIndex + 1)..endSeparatorIndex].Trim(); + string endText = line[(endSeparatorIndex + 1)..].Trim(); + if (!decimal.TryParse(startText, NumberStyles.Float, CultureInfo.InvariantCulture, out decimal startSeconds)) + return Errors.Playback.NormalizationFailed; + if (!decimal.TryParse(endText, NumberStyles.Float, CultureInfo.InvariantCulture, out decimal endSeconds)) + return Errors.Playback.NormalizationFailed; + if (startSeconds < 0 || endSeconds < startSeconds) + return Errors.Playback.NormalizationFailed; + + FileInfo segmentFile = new(Path.Combine(temporaryPath, fileName)); + decimal durationSeconds = endSeconds - startSeconds; + // ffmpeg can append a final segment whose time range is empty when the last frame ends exactly on a segment boundary. That segment is + // discarded after the list is sorted, but a zero duration anywhere else, or a missing or empty segment that is supposed to carry audio, is a malformed production. + if (durationSeconds == 0) + { + segments.Add(new NormalizedTrackSegmentIndexDto(segmentNumber, startSeconds, 0, fileName, segmentFile.Exists ? segmentFile.Length : 0)); + continue; + } + if (!segmentFile.Exists || segmentFile.Length <= 0) + return Errors.Playback.NormalizationFailed; + + segments.Add(new NormalizedTrackSegmentIndexDto(segmentNumber, startSeconds, durationSeconds, fileName, segmentFile.Length)); + } + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) + { + return Errors.Playback.NormalizationFailed; + } + + if (segments.Count == 0 || segments.Count > MAX_SEGMENT_COUNT) + return Errors.Playback.NormalizationFailed; + + // The number in the file name is the index, not the position of the line, and the numbers must be exactly the sequence from zero to count - 1. + // A gap, a duplicate or an out of order line would otherwise produce an index over audio that the player would map to the wrong time. + segments.Sort((left, right) => left.Index.CompareTo(right.Index)); + // The trailing segment with an empty time range carries no audio, so it is removed from the index and from the cache entry instead of being + // exposed as a segment that the player would seek to and find empty. + while (segments.Count > 0 && segments[^1].DurationSeconds == 0) + { + string trailingSegmentPath = Path.Combine(temporaryPath, segments[^1].FileName); + segments.RemoveAt(segments.Count - 1); + TryDeleteFile(trailingSegmentPath); + } + if (segments.Count == 0) + return Errors.Playback.NormalizationFailed; + + decimal previousEndSeconds = 0; + for (int position = 0; position < segments.Count; position++) + { + // A segment must start where the previous one ended, within the small tolerance of the csv times. Checking only that it does not start + // before the previous end would accept a leading gap or a gap in the middle of the track as long as the final end still matched. + decimal startDifferenceSeconds = segments[position].StartSeconds - previousEndSeconds; + if (segments[position].Index != position || + segments[position].DurationSeconds <= 0 || + startDifferenceSeconds < -SEGMENT_TIME_TOLERANCE_SECONDS || + startDifferenceSeconds > SEGMENT_TIME_TOLERANCE_SECONDS) + return Errors.Playback.NormalizationFailed; + previousEndSeconds = segments[position].StartSeconds + segments[position].DurationSeconds; + } + + // A shortfall is the truncation case this check exists for. A probe that estimates the duration from the bitrate can underestimate a variable + // bitrate file, so a production that is longer than the probe is accepted and logged instead of being rejected forever. + decimal expectedDurationSeconds = request.DurationInSeconds; + decimal durationToleranceSeconds = Math.Max(DURATION_TOLERANCE_MIN_SECONDS, expectedDurationSeconds * DURATION_TOLERANCE_RATIO); + if (previousEndSeconds < expectedDurationSeconds - durationToleranceSeconds) + return Errors.Playback.NormalizationFailed; + if (previousEndSeconds > expectedDurationSeconds + durationToleranceSeconds) + _logger.LogInformation("The normalized audio of track {TrackId} in cache entry {CacheId} is longer than the probed duration: produced {ProducedSeconds} seconds, probed {ExpectedSeconds} seconds. The production is kept because only a shortfall is treated as truncation.", request.TrackId, cacheId, previousEndSeconds, expectedDurationSeconds); + + // The index advertises the produced end, rounded up to the next second, instead of the probed duration. A probe can underestimate a variable + // bitrate file, and a seek map that is shorter than the audio would hide the tail of every segment after the underestimated end. + int producedDurationSeconds = previousEndSeconds >= int.MaxValue + ? int.MaxValue + : (int)Math.Ceiling(previousEndSeconds); + return new NormalizedTrackIndexDto(CACHE_INDEX_VERSION, request.TrackId, request.Mode, format.Container, format.Codec, request.SegmentDurationSeconds, producedDurationSeconds, segments); + } + + /// + /// Reads the persisted index of a cached normalized track, and validates that it is complete and that every segment it names still exists. + /// + /// The opaque identifier of the cache entry. + /// The index of the cached normalized track, when it could be read. + /// when a complete and consistent cache entry could be read, otherwise . + private bool TryReadIndex(string cacheId, out NormalizedTrackIndexDto? index) + { + index = null; + if (!TranscodingCacheCoordinator.IsValidCacheId(cacheId)) + return false; + + if (_cache.TryGetIndex(cacheId, out NormalizedTrackIndexDto? cachedIndex) && cachedIndex is not null) + { + index = cachedIndex; + return true; + } + + string cachePath = Path.Combine(_cacheRoot, cacheId); + string indexPath = Path.Combine(cachePath, CACHE_INDEX_FILE_NAME); + try + { + if (!File.Exists(indexPath)) + return false; + if (new FileInfo(indexPath).Length > MAX_CACHE_INDEX_BYTES) + return false; + + string indexJson = File.ReadAllText(indexPath); + NormalizedTrackIndexDto? storedIndex = JsonSerializer.Deserialize(indexJson, s_indexJsonOptions); + if (storedIndex is null || + storedIndex.Version != CACHE_INDEX_VERSION || + storedIndex.TrackId == Guid.Empty || + storedIndex.Mode is not (PlaybackDeliveryMode.Remux or PlaybackDeliveryMode.Transcode) || + storedIndex.SegmentDurationSeconds <= 0 || + storedIndex.DurationInSeconds <= 0 || + storedIndex.Segments is null || + storedIndex.Segments.Count == 0 || + storedIndex.Segments.Count > MAX_SEGMENT_COUNT || + !PlaybackFormatCatalog.FormatsByPair.TryGetValue(PlaybackFormatCatalog.BuildPairKey(storedIndex.Container, storedIndex.Codec), out NormalizedAudioFormatDto? format)) + return false; + + decimal previousEndSeconds = 0; + for (int position = 0; position < storedIndex.Segments.Count; position++) + { + NormalizedTrackSegmentIndexDto? segment = storedIndex.Segments[position]; + // The index must already be in playback order, name a supported generated file, describe a real segment and cover the track without a hole. + decimal startDifferenceSeconds = segment is null ? 0 : segment.StartSeconds - previousEndSeconds; + if (segment is null || + segment.Index != position || + !IsValidSegmentFileName(segment.FileName) || + !TryGetSegmentNumber(segment.FileName, format.FileExtension, out int segmentNumber) || + segmentNumber != position || + segment.StartSeconds < 0 || + segment.DurationSeconds <= 0 || + segment.Length <= 0 || + startDifferenceSeconds < -SEGMENT_TIME_TOLERANCE_SECONDS || + startDifferenceSeconds > SEGMENT_TIME_TOLERANCE_SECONDS || + !File.Exists(Path.Combine(cachePath, segment.FileName))) + return false; + previousEndSeconds = segment.StartSeconds + segment.DurationSeconds; + } + + // The advertised duration must cover the produced segments, otherwise a seek map built from the index would end before the audio does. New + // indexes are written with the produced end rounded up; an index that claims less is treated as a corrupt cache entry. + if (storedIndex.DurationInSeconds < previousEndSeconds) + return false; + + index = storedIndex; + _cache.SetIndex(cacheId, storedIndex); + return true; + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException or JsonException or NotSupportedException) + { + return false; + } + } + + /// + /// Reads a cached normalized track, when a complete cache entry for it exists. + /// + /// The opaque identifier of the cache entry. + /// The cached normalized track, when it could be read. + /// when a complete cache entry could be read, otherwise . + private bool TryReadCachedTrack(string cacheId, out NormalizedTrackDto? normalizedTrack) + { + normalizedTrack = null; + if (!TryReadIndex(cacheId, out NormalizedTrackIndexDto? index) || index is null) + return false; + + normalizedTrack = GetOrCreateTrackProjection(cacheId, index); + return true; + } + + /// + /// Projects a validated cache index once and reuses the projection for the following segment requests of the same cached track. + /// + /// The opaque identifier of the cache entry that holds the normalized audio. + /// The validated index of the cache entry. + /// The normalized track described by the index. + private NormalizedTrackDto GetOrCreateTrackProjection(string cacheId, NormalizedTrackIndexDto index) + { + (string CacheRoot, string CacheId) key = (_cacheRoot, cacheId); + if (_trackProjections.TryGetValue(key, out NormalizedTrackDto? existing) && existing.TrackId == index.TrackId) + return existing; + NormalizedTrackDto projection = CreateNormalizedTrackDto(cacheId, index); + // The projection is metadata only, but unbounded retention is not useful: when the bound is reached, the cache is dropped and rebuilt lazily. + if (_trackProjections.Count >= MAX_TRACK_PROJECTIONS) + _trackProjections.Clear(); + _trackProjections[key] = projection; + return projection; + } + + /// + /// Projects a validated cache index into the normalized track the caller receives. + /// + /// The opaque identifier of the cache entry that holds the normalized audio. + /// The validated index of the cache entry. + /// The normalized track described by the index. + private static NormalizedTrackDto CreateNormalizedTrackDto(string cacheId, NormalizedTrackIndexDto index) + { + return new NormalizedTrackDto( + index.TrackId, + cacheId, + index.Mode, + index.Container, + index.Codec, + index.SegmentDurationSeconds, + index.DurationInSeconds, + [.. index.Segments.Select(segment => new NormalizedTrackSegmentDto(segment.Index, segment.StartSeconds, segment.DurationSeconds, segment.Length))]); + } + + /// + /// Builds the opaque cache identifier of a normalized track, so that a replaced or changed source file, or another track, never reuses a stale entry. + /// + /// The track, the delivery decision and the quality cap the normalized audio is produced with. + /// The full path of the stored audio file of the track. + /// The length of the stored audio file of the track, in bytes. + /// The date and time, in UTC, when the stored audio file of the track was last modified. + /// The container and codec combination the normalized audio is produced in. + /// The opaque cache identifier. + private static string BuildCacheId(NormalizedTrackRequestDto request, string sourcePath, long sourceLength, DateTime sourceLastModifiedUtc, NormalizedAudioFormatDto format) + { + string identity = string.Join('\n', + [ + request.TrackId.ToString(), + sourcePath, + sourceLength.ToString(CultureInfo.InvariantCulture), + sourceLastModifiedUtc.Ticks.ToString(CultureInfo.InvariantCulture), + request.Mode.ToString(), + format.Container, + format.Codec, + request.SegmentDurationSeconds.ToString(CultureInfo.InvariantCulture), + request.DurationInSeconds.ToString(CultureInfo.InvariantCulture), + // The quality cap only changes the output of a lossy transcode. A remux only repackages the stored codec, and a lossless transcode is not + // capped, so including the quality for them would only create byte-identical entries that compete for the same cache budget. + request.Mode == PlaybackDeliveryMode.Transcode && !format.IsLossless ? request.Quality.ToString() : string.Empty + ]); + // The identity is hashed so the cache entry name is a fixed length file name even when the source path is long, and so the source path is not + // exposed by the directory listing of the cache. + return Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(identity))).ToLowerInvariant(); + } + + /// + /// Resolves the ffmpeg demuxer of a stored container, so that the input is never probed by content. + /// + /// The container of the stored audio file, as captured by the probe. + /// The ffmpeg demuxer of the container, when it is known. + /// when the container maps to a known demuxer, otherwise . + private static bool TryResolveSourceDemuxer(string? sourceContainer, out string sourceDemuxer) + { + sourceDemuxer = string.Empty; + if (string.IsNullOrWhiteSpace(sourceContainer)) + return false; + if (!s_sourceDemuxers.TryGetValue(sourceContainer.Trim(), out string? demuxer) || string.IsNullOrEmpty(demuxer)) + return false; + sourceDemuxer = demuxer; + return true; + } + + /// + /// Gets the bitrate cap, in kbps, of a streaming quality setting. + /// + /// The streaming quality cap of the current user. + /// The bitrate cap in kbps. uses the server default cap. + private static int GetTargetBitrateKbps(PlaybackStreamingQuality quality) + { + return quality switch + { + PlaybackStreamingQuality.Low => 96, + PlaybackStreamingQuality.Medium => 160, + PlaybackStreamingQuality.High => 320, + _ => AUTO_TRANSCODE_BITRATE_KBPS + }; + } + + /// + /// Estimates the size of the normalized audio, so that the cache is trimmed before a job starts instead of only after it finished. + /// + /// + /// A lossless delivery is estimated from the sample rate, the channel count and the bit depth of the stored audio, because a hi-res track can be + /// several times larger than the uncompressed stereo audio at 44.1 kHz and 16 bits. A FLAC stream is compressed, so its initial estimate is a fraction + /// of the uncompressed size. A remux of a lossy codec is estimated from the stored audio bitrate, not from the length of the source container, so a + /// large video file with a small audio stream is not rejected as too big for the cache. The cache monitor grows the reservation when the actual output needs more room. + /// + /// The delivery decision and the quality cap the normalized audio is produced with. + /// The container and codec combination the normalized audio is produced in. + /// The estimated size of the normalized audio, in bytes. + private static long EstimateOutputSize(NormalizedTrackRequestDto request, NormalizedAudioFormatDto format) + { + if (format.IsLossless) + { + int sampleRate = request.SampleRate > 0 ? request.SampleRate : DEFAULT_SAMPLE_RATE; + int channelCount = request.Channels > 0 ? request.Channels : DEFAULT_CHANNEL_COUNT; + // The PCM encoder of the pipeline writes 16 bit samples, while the FLAC encoder keeps the sample format of the source, so the delivered + // bit depth is used instead of the stored one for PCM. The FLAC estimate is a fraction of the uncompressed size, because the stream is compressed. + int bitDepth = string.Equals(format.Container, "WAV", StringComparison.OrdinalIgnoreCase) + ? DEFAULT_BIT_DEPTH + : request.BitDepth is > 0 ? request.BitDepth.Value : DEFAULT_BIT_DEPTH; + long uncompressedBytesPerSecond = (long)sampleRate * channelCount * bitDepth / 8; + decimal compressionRatio = string.Equals(format.Container, "FLAC", StringComparison.OrdinalIgnoreCase) ? FLAC_COMPRESSION_RATIO : 1m; + return Math.Max((long)(uncompressedBytesPerSecond * request.DurationInSeconds * compressionRatio), 1); + } + + if (request.Mode == PlaybackDeliveryMode.Remux) + { + int sourceBitrateKbps = request.Bitrate is > 0 ? request.Bitrate.Value : DEFAULT_SOURCE_BITRATE_KBPS; + decimal estimatedBytes = request.DurationInSeconds * sourceBitrateKbps * 1000m / 8m * REMUX_SIZE_MARGIN; + return Math.Max((long)estimatedBytes, 1); + } + + int bitrateKbps = GetTargetBitrateKbps(request.Quality); + return Math.Max((long)request.DurationInSeconds * bitrateKbps * 1000 / 8, 1); + } + + /// + /// Checks whether a generated segment file name has the expected prefix and extension, and extracts the segment number from it. + /// + /// The file name of the segment. + /// The expected file extension of the segment, including the leading dot. + /// The number encoded in the file name, when the name is valid. + /// when the file name is a valid generated segment name, otherwise . + private static bool TryGetSegmentNumber(string fileName, string fileExtension, out int segmentNumber) + { + segmentNumber = -1; + if (string.IsNullOrEmpty(fileName) || + !fileName.StartsWith(SEGMENT_FILE_PREFIX, StringComparison.Ordinal) || + !fileName.EndsWith(fileExtension, StringComparison.Ordinal)) + return false; + + string numberText = fileName[SEGMENT_FILE_PREFIX.Length..^fileExtension.Length]; + return numberText.Length > 0 && + int.TryParse(numberText, NumberStyles.None, CultureInfo.InvariantCulture, out segmentNumber) && + segmentNumber >= 0; + } + + /// + /// Checks whether a value is a plain file name of a produced segment. + /// + /// The value to check. + /// when the value is a plain segment file name, otherwise . + private static bool IsValidSegmentFileName(string fileName) + { + return !string.IsNullOrWhiteSpace(fileName) && + string.Equals(fileName, Path.GetFileName(fileName), StringComparison.Ordinal) && + !fileName.Contains(Path.DirectorySeparatorChar) && + !fileName.Contains(Path.AltDirectorySeparatorChar); + } + + /// + /// Monitors the size of the temporary directory of a running job and keeps its cache reservation in step with the bytes it has actually written. + /// + /// The opaque identifier of the cache entry. + /// The Id of the track whose audio is normalized. + /// The tracker of the output size of the job. + /// The capacity the job reserved in the cache. + /// The ffmpeg process of the job. + /// Cancellation token that can be used to stop the execution. + /// when the job was stopped because it could not reserve enough cache capacity, otherwise . + private async Task MonitorOutputSizeAsync(string cacheId, Guid trackId, TranscodingOutputSizeTracker outputSizeTracker, TranscodingCacheReservation reservation, Process process, CancellationToken cancellationToken) + { + try + { + while (true) + { + await Task.Delay(CACHE_SIZE_MONITOR_INTERVAL_MILLISECONDS, cancellationToken).ConfigureAwait(false); + long actualBytes = outputSizeTracker.GetCurrentSize(); + if (!reservation.TryUpdate(actualBytes, _settings.MaxCacheBytes, _evictionGracePeriod)) + { + _logger.LogWarning("A normalization job for track {TrackId} in cache entry {CacheId} could not reserve enough space in the normalized audio cache and was stopped.", trackId, cacheId); + KillProcess(process); + return true; + } + } + } + catch (OperationCanceledException) + { + return false; + } + } + + /// + /// Waits for the bounded standard error of a finished process, without pinning the job when the pipe never closes. + /// + /// The task that reads the bounded standard error of the process. + /// The bounded standard error, or an empty string when the pipe did not close within the bounded wait. + private static async Task AwaitStandardErrorAsync(Task standardErrorTask) + { + try + { + return await standardErrorTask.WaitAsync(TimeSpan.FromSeconds(PROCESS_EXIT_TIMEOUT_SECONDS)).ConfigureAwait(false); + } + catch (TimeoutException) + { + // A kill that did not take effect leaves the pipe open. The job is finished without a diagnostic instead of holding a job slot forever; the + // read task ends when the process is disposed and its standard error stream is closed. + return string.Empty; + } + } + + /// + /// Reads the standard error of a running process while keeping only its last few kilobytes, so a crafted input cannot make the server buffer an unbounded diagnostic string over the whole job timeout. + /// + /// The standard error stream of the process. + /// The bounded tail of the standard error of the process. + private static async Task ReadBoundedStandardErrorAsync(StreamReader standardError) + { + char[] buffer = new char[4096]; + StringBuilder boundedStandardError = new(); + try + { + int read; + while ((read = await standardError.ReadAsync(buffer, 0, buffer.Length).ConfigureAwait(false)) > 0) + { + boundedStandardError.Append(buffer, 0, read); + if (boundedStandardError.Length > MAX_STANDARD_ERROR_CHARACTERS * 2) + boundedStandardError.Remove(0, boundedStandardError.Length - MAX_STANDARD_ERROR_CHARACTERS); + } + } + catch (Exception exception) when (exception is IOException or ObjectDisposedException) + { + // The pipe is closed when the process is killed; the bytes read so far are still the useful diagnostic tail. + } + + if (boundedStandardError.Length > MAX_STANDARD_ERROR_CHARACTERS) + boundedStandardError.Remove(0, boundedStandardError.Length - MAX_STANDARD_ERROR_CHARACTERS); + return boundedStandardError.ToString(); + } + + /// + /// Replaces an absolute source path in a diagnostic message with a placeholder, so the path is not written to the application log. + /// + /// The diagnostic message. + /// The path to redact, or when there is none. + /// The diagnostic message with the path replaced. + private static string RedactPath(string diagnostic, string? path) + { + if (string.IsNullOrWhiteSpace(path)) + return diagnostic; + return diagnostic.Replace(path, "[source]", StringComparison.OrdinalIgnoreCase); + } + + /// + /// Removes a completed production from the shared registry, unless a newer production replaced it. + /// + /// The cache root and cache entry the production belongs to. + /// The production that completed. + private static void RemoveNormalizationJob((string CacheRoot, string CacheId) normalizationJobKey, Lazy>> normalizationJob) + { + if (s_normalizationJobs.TryGetValue(normalizationJobKey, out Lazy>>? currentJob) && ReferenceEquals(currentJob, normalizationJob)) + s_normalizationJobs.TryRemove(normalizationJobKey, out _); + } + + /// + /// Deletes a file, ignoring a file that is already gone or cannot be deleted. + /// + /// The file to delete. + private static void TryDeleteFile(string filePath) + { + try + { + if (File.Exists(filePath)) + File.Delete(filePath); + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) + { + // The trailing empty segment is not indexed, so a failed deletion only leaves a small unreferenced file in the cache entry. + } + } + + /// + /// Stops a child process and its descendants without waiting for it, so a cancellation callback is never blocked; the caller that awaits the process observes its exit. + /// + /// The process to stop. + private void KillProcess(Process process) + { + try + { + if (!process.HasExited) + process.Kill(entireProcessTree: true); + } + catch (Exception exception) when (exception is InvalidOperationException or NotSupportedException or Win32Exception) + { + _logger.LogDebug(exception, "The audio transcoder process could not be stopped."); + } + } + + /// + /// Stops every child process that is still running when the application exits, and cancels the productions that are still waiting for a job slot. + /// + /// The source of the event. + /// The event data. + private void OnApplicationStopping(object? sender, EventArgs eventArguments) + { + _shutdownCancellation.Cancel(); + foreach (Process process in _runningProcesses.Values) + KillProcess(process); + } + + /// + /// Releases the resources of the service when its host is disposed, including the process exit subscription that would otherwise keep it alive. + /// + /// + /// The cancellation source, the job slots and the cache coordinator are process lifetime resources that a production uses until it leaves. Shutdown + /// cancels and kills first, then waits a bounded time for every admitted production to leave before disposing them, so a production that is finishing + /// during shutdown still reports its Result instead of faulting on a disposed primitive or re-registering into a released coordinator. If the drain + /// times out the resources are intentionally left undisposed: the process is exiting and faulting the in-flight task would be worse. + /// + public void Dispose() + { + lock (_lifecycleSync) + { + if (_isDisposed) + return; + _isDisposed = true; + } + AppDomain.CurrentDomain.ProcessExit -= OnApplicationStopping; + OnApplicationStopping(this, EventArgs.Empty); + if (!_productionsDrained.Wait(TimeSpan.FromSeconds(PRODUCTION_DRAIN_TIMEOUT_SECONDS))) + { + _logger.LogWarning("The normalized audio productions did not drain within {DrainTimeoutSeconds} seconds during shutdown. The process lifetime resources are left undisposed.", PRODUCTION_DRAIN_TIMEOUT_SECONDS); + return; + } + _cache.Release(); + _jobSlots.Dispose(); + _shutdownCancellation.Dispose(); + _productionsDrained.Dispose(); + } +} diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/TranscodingCacheCoordinator.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/TranscodingCacheCoordinator.cs new file mode 100644 index 00000000..7eff1ad3 --- /dev/null +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/TranscodingCacheCoordinator.cs @@ -0,0 +1,591 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Infrastructure.Common.Caching; +using Lumina.Infrastructure.Common.Models.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback; +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Threading; +using System.Threading.Channels; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Infrastructure.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback; + +/// +/// Coordinates the process wide size accounting, eviction and reader protection of the normalized audio cache. +/// +/// +/// Every cached entry and every running normalization job of a cache root is accounted for under one lock, so the cache size limit is a global limit +/// instead of a per job limit. An entry is protected from eviction while a reader holds a lease on it, and for a grace period after it was produced or +/// last served, so an entry that a request is about to read is never deleted by another job. Replacing and registering a produced entry is atomic under +/// the same lock, so an eviction can never delete a freshly published entry. Directories are never deleted under the lock: an entry that is evicted or +/// replaced is renamed to a unique tombstone under the lock and deleted by a background sweeper, so serving a segment or opening a manifest never waits +/// for a recursive delete. The size limit is enforced against live entries: a tombstone occupies disk until the sweeper removes it. The coordinator is +/// shared by every service instance of the process that uses the same cache root. +/// +internal sealed class TranscodingCacheCoordinator +{ + private static readonly ConcurrentDictionary s_coordinators = new(StringComparer.Ordinal); + private static readonly Lock s_registrySync = new(); + + private readonly Lock _sync = new(); + private readonly string _cacheRoot; + private readonly Dictionary _entries = new(StringComparer.Ordinal); + private readonly Dictionary _reservations = new(StringComparer.Ordinal); + private readonly Dictionary _readerLeaseCounts = new(StringComparer.Ordinal); + // Read and written by request threads without _sync, so the index cache is a concurrent dictionary while the accounting dictionaries are guarded by _sync. + private readonly ConcurrentDictionary _indexCache = new(StringComparer.Ordinal); + // Entries that were over capacity but still leased. The last lease release hands them to the sweeper. + private readonly HashSet _pendingEvictions = new(StringComparer.Ordinal); + // Tombstones are consumed by one background reader, so a recursive delete never runs under _sync. + private readonly Channel _deletionQueue = Channel.CreateUnbounded(new UnboundedChannelOptions { SingleReader = true }); + // The value is unused. Lazy is the once-only gate: the first caller runs the cache walk outside _sync and every other caller waits for it. + private readonly Lazy _initialization; + private int _referenceCount; + + /// + /// Initializes a new instance of the class. + /// + /// The absolute path of the cache root the coordinator accounts for. + private TranscodingCacheCoordinator(string cacheRoot) + { + _cacheRoot = cacheRoot; + _initialization = new Lazy(InitializeCore, LazyThreadSafetyMode.ExecutionAndPublication); + _ = Task.Run(ProcessDeletionQueueAsync); + } + + /// + /// Acquires the coordinator of a cache root, which is shared by every service instance of the process that uses the same root. + /// + /// The absolute path of the cache root. + /// The coordinator of the cache root. The caller must call when it no longer uses it. + public static TranscodingCacheCoordinator AcquireForRoot(string cacheRoot) + { + string normalizedRoot = Path.GetFullPath(cacheRoot); + lock (s_registrySync) + { + // The registry is process wide because two service instances that use the same cache root must share the same size and lease accounting. + // The reference count keeps the coordinator alive until the last service instance is disposed. + if (!s_coordinators.TryGetValue(normalizedRoot, out TranscodingCacheCoordinator? coordinator)) + { + coordinator = new TranscodingCacheCoordinator(normalizedRoot); + s_coordinators[normalizedRoot] = coordinator; + } + coordinator._referenceCount++; + return coordinator; + } + } + + /// + /// Releases the caller's use of the coordinator, removing it from the process registry when the last caller releases it. + /// + public void Release() + { + bool isUnused; + lock (s_registrySync) + { + if (_referenceCount > 0) + _referenceCount--; + isUnused = _referenceCount == 0; + if (isUnused) + s_coordinators.Remove(_cacheRoot, out _); + } + + if (!isUnused) + return; + lock (_sync) + { + _entries.Clear(); + _reservations.Clear(); + _readerLeaseCounts.Clear(); + _pendingEvictions.Clear(); + _indexCache.Clear(); + } + // The sweeper drains the tombstones it already owns and then stops. A deletion that is still in flight is finished, and a tombstone left by a + // deletion that cannot complete is removed by the startup cleanup. + _deletionQueue.Writer.TryComplete(); + } + + /// + /// Checks whether a value is a well formed opaque cache identifier. + /// + /// The value to check. + /// when the value is a well formed cache identifier, otherwise . + public static bool IsValidCacheId(string cacheId) + { + return TranscodingCachePaths.IsValidCacheId(cacheId); + } + + /// + /// Reserves capacity for the output of a normalization job, after evicting the entries that may be evicted to make room for it. + /// + /// The estimated size of the output of the job, in bytes. + /// The maximum total size of the cache, in bytes. + /// The period during which a recently produced or served entry is protected from eviction. + /// The reservation of the job, when capacity could be reserved. + /// when capacity could be reserved, otherwise . + public bool TryReserve(long requestedBytes, long maxCacheBytes, TimeSpan gracePeriod, out TranscodingCacheReservation? reservation) + { + reservation = null; + if (requestedBytes <= 0 || maxCacheBytes <= 0) + return false; + EnsureInitialized(); + lock (_sync) + { + long currentSize = GetTotalSize(); + if (requestedBytes > maxCacheBytes || !TryMakeRoom(requestedBytes, currentSize, excludedCacheId: null, maxCacheBytes, gracePeriod)) + return false; + + string reservationId = Guid.NewGuid().ToString("N"); + _reservations[reservationId] = requestedBytes; + reservation = new TranscodingCacheReservation(this, reservationId); + return true; + } + } + + /// + /// Grows the reservation of a running job to the number of bytes it has actually written, after evicting entries when it has to grow. + /// + /// The identifier of the reservation. + /// The number of bytes the job has actually written, in bytes. + /// The maximum total size of the cache, in bytes. + /// The period during which a recently produced or served entry is protected from eviction. + /// when the reservation covers the actual size, otherwise . + public bool TryGrow(string reservationId, long actualBytes, long maxCacheBytes, TimeSpan gracePeriod) + { + if (actualBytes < 0) + return false; + EnsureInitialized(); + lock (_sync) + { + if (!_reservations.TryGetValue(reservationId, out long reservedBytes)) + return false; + // A reservation is never shrunk while the job runs: a size of zero read before the first byte is written, or a size that fluctuates + // while a file is being appended, must not hand the reserved capacity to another job that the running job then cannot reclaim. + if (actualBytes <= reservedBytes) + return true; + if (actualBytes > maxCacheBytes) + return false; + + long currentSize = GetTotalSize(); + long requiredAdditionalBytes = actualBytes - reservedBytes; + if (!TryMakeRoom(requiredAdditionalBytes, currentSize, excludedCacheId: null, maxCacheBytes, gracePeriod)) + return false; + + _reservations[reservationId] = actualBytes; + return true; + } + } + + /// + /// Publishes the cache entry a finished job produced, replacing any previous entry for the same identifier, and enforces the cache size limit. + /// + /// The identifier of the reservation. + /// The identifier of the produced cache entry. + /// The temporary directory that holds the complete produced entry. + /// The total size of the produced cache entry, in bytes. + /// The validated index of the produced cache entry. + /// The maximum total size of the cache, in bytes. + /// The period during which a recently produced or served entry is protected from eviction. + /// + /// when the produced entry still exceeds the cache limit after every unprotected entry was detached, so it is kept readable and + /// becomes eligible for eviction later. The caller should report the production as successful and log the over-budget state. + /// + /// + /// when a reader still holds the previous entry of the same cache identifier, so the replacement was not attempted and the + /// caller should report a retryable failure instead of a production failure. + /// + /// + /// when the produced entry is readable and may be served, otherwise when it was not published. + /// + public bool TryPublish(string reservationId, string cacheId, string temporaryPath, long size, NormalizedTrackIndexDto index, long maxCacheBytes, TimeSpan gracePeriod, out bool isKeptOverCapacity, out bool isEntryInUse) + { + isKeptOverCapacity = false; + isEntryInUse = false; + EnsureInitialized(); + lock (_sync) + { + // The reservation is consumed whether or not the entry is published, because the caller never releases it after this call. + _reservations.Remove(reservationId); + + // The previous directory cannot be replaced while a reader holds it on every platform, so the production is reported as retryable and the + // previous entry stays intact. The next request retries the production after the reader is gone. + if (IsLeased(cacheId)) + { + isEntryInUse = true; + return false; + } + + string cachePath = Path.Combine(_cacheRoot, cacheId); + if (_entries.TryGetValue(cacheId, out TranscodingCacheEntryDto? existingEntry)) + { + if (!TryDetachEntryForDeletion(cacheId, existingEntry)) + return false; + } + else if (!TryMoveToDeletion(cachePath)) + return false; + + _indexCache.TryRemove(cacheId, out _); + _pendingEvictions.Remove(cacheId); + try + { + Directory.Move(temporaryPath, cachePath); + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) + { + return false; + } + // Defense in depth against a directory that an external actor removed between the move and the registration. + if (!Directory.Exists(cachePath)) + return false; + + _entries[cacheId] = new TranscodingCacheEntryDto(cachePath, size, DateTime.UtcNow, DateTime.UtcNow); + _indexCache[cacheId] = index; + + long currentSize = GetTotalSize(); + if (currentSize <= maxCacheBytes) + return true; + if (TryMakeRoom(0, currentSize, cacheId, maxCacheBytes, gracePeriod)) + return true; + + // The entry does not fit even after every other unprotected entry was detached. It is kept readable and becomes eligible for eviction once + // its grace period ends, so a production that already consumed a full job is not discarded because the estimate was exceeded. + isKeptOverCapacity = true; + return true; + } + } + + /// + /// Releases the reservation of a job that did not produce a cache entry. + /// + /// The identifier of the reservation. + public void ReleaseReservation(string reservationId) + { + lock (_sync) + _reservations.Remove(reservationId); + } + + /// + /// Records that a cache entry was served, so that the least recently used eviction and the eviction grace period keep it for longer. + /// + /// The identifier of the cache entry. + /// + /// The minimum interval between two writes of the last use time. A value smaller than the eviction grace period keeps an actively used entry protected. + /// + public void Touch(string cacheId, TimeSpan throttleInterval) + { + EnsureInitialized(); + lock (_sync) + { + if (!_entries.TryGetValue(cacheId, out TranscodingCacheEntryDto? entry)) + return; + + DateTime nowUtc = DateTime.UtcNow; + // A stream opens a segment every few seconds, so writing the last use time on every request would needlessly serialize the coordinator. + if (nowUtc - entry.LastUsedUtc < throttleInterval) + return; + _entries[cacheId] = entry with { LastUsedUtc = nowUtc }; + } + } + + /// + /// Acquires a lease that prevents a cache entry from being evicted while a reader holds it. + /// + /// The identifier of the cache entry. + /// The lease, which must be disposed when the reader is done with the entry. + public TranscodingCacheReaderLease AcquireReaderLease(string cacheId) + { + EnsureInitialized(); + lock (_sync) + _readerLeaseCounts[cacheId] = _readerLeaseCounts.TryGetValue(cacheId, out int leaseCount) ? leaseCount + 1 : 1; + return new TranscodingCacheReaderLease(this, cacheId); + } + + /// + /// Gets the validated index of a cache entry, when it was already read and validated by this process. + /// + /// The identifier of the cache entry. + /// The validated index of the cache entry, when it is cached. + /// when the validated index is cached, otherwise . + public bool TryGetIndex(string cacheId, out NormalizedTrackIndexDto? index) + { + return _indexCache.TryGetValue(cacheId, out index); + } + + /// + /// Caches the validated index of a cache entry, so serving its segments does not re-read and re-validate the whole index on every request. + /// + /// The identifier of the cache entry. + /// The validated index of the cache entry. + public void SetIndex(string cacheId, NormalizedTrackIndexDto index) + { + _indexCache[cacheId] = index; + } + + /// + /// Releases a lease that a reader held on a cache entry. + /// + /// The identifier of the cache entry. + internal void ReleaseReaderLease(string cacheId) + { + lock (_sync) + { + if (!_readerLeaseCounts.TryGetValue(cacheId, out int leaseCount)) + return; + if (leaseCount > 1) + { + _readerLeaseCounts[cacheId] = leaseCount - 1; + return; + } + + _readerLeaseCounts.Remove(cacheId); + // An entry that could not be evicted while a reader was using it is detached only after the last reader is gone. The actual deletion is + // performed by the sweeper, outside this lock, so releasing a segment stream never waits for a recursive delete. + if (_pendingEvictions.Contains(cacheId) && _entries.TryGetValue(cacheId, out TranscodingCacheEntryDto? entry)) + { + _pendingEvictions.Remove(cacheId); + if (!TryDetachEntryForDeletion(cacheId, entry)) + _pendingEvictions.Add(cacheId); + } + } + } + + /// + /// Gets the total size of a directory, in bytes, without letting a file that disappears mid-walk discard the rest of the measurement. + /// + /// The directory whose size is computed. + /// The total size of the directory, in bytes. + internal static long GetDirectorySize(string directoryPath) + { + long size = 0; + Stack pendingDirectories = new(); + pendingDirectories.Push(directoryPath); + while (pendingDirectories.Count > 0) + { + string currentDirectory = pendingDirectories.Pop(); + try + { + using (IEnumerator fileEnumerator = Directory.EnumerateFiles(currentDirectory).GetEnumerator()) + { + while (true) + { + bool hasNextFile; + try + { + hasNextFile = fileEnumerator.MoveNext(); + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) + { + break; + } + if (!hasNextFile) + break; + + try + { + size += new FileInfo(fileEnumerator.Current).Length; + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) + { + // A file that disappears between enumeration and its size read is not counted; the walk continues with the next one. + } + } + } + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) + { + // A directory that cannot be opened is skipped; the rest of the cache is still measured. + } + + try + { + using (IEnumerator directoryEnumerator = Directory.EnumerateDirectories(currentDirectory).GetEnumerator()) + { + while (true) + { + bool hasNextDirectory; + try + { + hasNextDirectory = directoryEnumerator.MoveNext(); + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) + { + break; + } + if (!hasNextDirectory) + break; + pendingDirectories.Push(directoryEnumerator.Current); + } + } + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) + { + // A directory that cannot be enumerated is skipped; the rest of the cache is still measured. + } + } + return size; + } + + /// + /// Runs the once-only initialization of the entries that already exist in the cache root, outside the coordinator lock. + /// + private void EnsureInitialized() + { + _ = _initialization.Value; + } + + /// + /// Reads the entries that already exist in the cache root, so a cache that survived a restart is still accounted for. + /// + /// when the accounting was populated. + /// + /// The walk of the cache root happens outside the coordinator lock, because it stats every file of every entry. The result is published under the lock, + /// so a request never blocks a manifest or a segment open behind the walk. + /// + private bool InitializeCore() + { + Dictionary entries = new(StringComparer.Ordinal); + List tombstones = []; + if (Directory.Exists(_cacheRoot)) + { + try + { + foreach (string directoryPath in Directory.EnumerateDirectories(_cacheRoot)) + { + string cacheId = Path.GetFileName(directoryPath); + if (cacheId.StartsWith(TranscodingCachePaths.DELETION_DIRECTORY_PREFIX, StringComparison.Ordinal)) + { + // A tombstone left by a previous coordinator of the same process is handed to the sweeper instead of being accounted for. + tombstones.Add(directoryPath); + continue; + } + if (!IsValidCacheId(cacheId)) + continue; + entries[cacheId] = new TranscodingCacheEntryDto(directoryPath, GetDirectorySize(directoryPath), Directory.GetLastWriteTimeUtc(directoryPath), DateTime.MinValue); + } + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) + { + // A cache that cannot be enumerated is treated as empty for this run instead of being retried on every request. + } + } + + lock (_sync) + foreach (KeyValuePair entry in entries) + _entries[entry.Key] = entry.Value; + foreach (string tombstonePath in tombstones) + _deletionQueue.Writer.TryWrite(tombstonePath); + return true; + } + + /// + /// Gets the combined size of the cached entries and the reservations of the running jobs, in bytes. + /// + /// The combined size of the cached entries and the reservations, in bytes. + private long GetTotalSize() + { + long entriesSize = _entries.Values.Sum(entry => entry.Size); + long reservationsSize = _reservations.Values.Sum(); + return entriesSize + reservationsSize; + } + + /// + /// Detaches the least recently used unprotected entries until the required number of bytes fits under the cache size limit. + /// + /// The number of additional bytes that must fit. + /// The current combined size of the entries and reservations, in bytes. + /// The cache entry that must never be evicted by this pass, or when none is excluded. + /// The maximum total size of the cache, in bytes. + /// The period during which a recently produced or served entry is protected from eviction. + /// when the required number of bytes fits, otherwise . + private bool TryMakeRoom(long requiredBytes, long currentSize, string? excludedCacheId, long maxCacheBytes, TimeSpan gracePeriod) + { + if (currentSize + requiredBytes <= maxCacheBytes) + return true; + + DateTime nowUtc = DateTime.UtcNow; + foreach (TranscodingCacheEntryDto entry in _entries.Values.OrderBy(entry => entry.LastUsedUtc).ToList()) + { + string cacheId = Path.GetFileName(entry.Path); + if (string.Equals(cacheId, excludedCacheId, StringComparison.Ordinal)) + continue; + + DateTime lastActivityUtc = entry.LastUsedUtc > entry.ProducedAtUtc ? entry.LastUsedUtc : entry.ProducedAtUtc; + if (nowUtc - lastActivityUtc < gracePeriod) + continue; + if (IsLeased(cacheId)) + { + // A reader holds the entry, so it is detached when the last lease is released instead of failing the deletion under the lock. + _pendingEvictions.Add(cacheId); + continue; + } + if (!TryDetachEntryForDeletion(cacheId, entry)) + continue; + currentSize -= entry.Size; + if (currentSize + requiredBytes <= maxCacheBytes) + return true; + } + return currentSize + requiredBytes <= maxCacheBytes; + } + + /// + /// Checks whether a reader currently holds a cache entry. + /// + /// The identifier of the cache entry. + /// when at least one reader holds the entry, otherwise . + private bool IsLeased(string cacheId) + { + return _readerLeaseCounts.TryGetValue(cacheId, out int leaseCount) && leaseCount > 0; + } + + /// + /// Removes an entry from the cache accounting and schedules its directory for deletion. + /// + /// The identifier of the cache entry. + /// The entry to detach. + /// when the entry was detached, otherwise when its directory could not be renamed. + private bool TryDetachEntryForDeletion(string cacheId, TranscodingCacheEntryDto entry) + { + if (!TryMoveToDeletion(entry.Path)) + return false; + _entries.Remove(cacheId); + _pendingEvictions.Remove(cacheId); + _indexCache.TryRemove(cacheId, out _); + return true; + } + + /// + /// Moves a directory out of the live cache and schedules it for deletion. + /// + /// The directory to detach. + /// when the directory was detached or no longer exists, otherwise . + private bool TryMoveToDeletion(string directoryPath) + { + if (!Directory.Exists(directoryPath)) + return true; + string deletionPath = Path.Combine(_cacheRoot, TranscodingCachePaths.DELETION_DIRECTORY_PREFIX + Guid.NewGuid().ToString("N")); + try + { + // A rename is a metadata operation, so it stays fast under the lock even for an entry with thousands of segments. + Directory.Move(directoryPath, deletionPath); + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) + { + return false; + } + // A tombstone that cannot be enqueued because the coordinator was released is removed by the startup cleanup. + _deletionQueue.Writer.TryWrite(deletionPath); + return true; + } + + /// + /// Deletes the directories that were detached from the cache. + /// + private async Task ProcessDeletionQueueAsync() + { + await foreach (string directoryPath in _deletionQueue.Reader.ReadAllAsync().ConfigureAwait(false)) + TranscodingCachePaths.TryDeleteDirectory(directoryPath); + } +} diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/TranscodingCacheLeaseStream.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/TranscodingCacheLeaseStream.cs new file mode 100644 index 00000000..09478ec1 --- /dev/null +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/TranscodingCacheLeaseStream.cs @@ -0,0 +1,222 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.IO; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Infrastructure.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback; + +/// +/// A read stream over a cached segment that keeps the reader lease of its cache entry until the stream is disposed. +/// +internal sealed class TranscodingCacheLeaseStream : Stream +{ + private readonly Stream _innerStream; + private readonly TranscodingCacheReaderLease _lease; + private bool _isDisposed; + + /// + /// Gets whether the stream supports reading. + /// + public override bool CanRead => _innerStream.CanRead; + + /// + /// Gets whether the stream supports seeking. + /// + public override bool CanSeek => _innerStream.CanSeek; + + /// + /// Gets whether the stream supports writing. + /// + public override bool CanWrite => _innerStream.CanWrite; + + /// + /// Gets the length of the stream, in bytes. + /// + public override long Length => _innerStream.Length; + + /// + /// Gets or sets the position within the stream. + /// + public override long Position + { + get { return _innerStream.Position; } + set { _innerStream.Position = value; } + } + + /// + /// Initializes a new instance of the class. + /// + /// The stream over the cached segment. + /// The reader lease that protects the cache entry of the segment. + internal TranscodingCacheLeaseStream(Stream innerStream, TranscodingCacheReaderLease lease) + { + _innerStream = innerStream; + _lease = lease; + } + + /// + /// Clears the buffers of the stream. + /// + public override void Flush() + { + _innerStream.Flush(); + } + + /// + /// Reads a block of bytes from the stream. + /// + /// The buffer to read into. + /// The offset in the buffer at which to start writing. + /// The maximum number of bytes to read. + /// The number of bytes read. + public override int Read(byte[] buffer, int offset, int count) + { + return _innerStream.Read(buffer, offset, count); + } + + /// + /// Reads a block of bytes from the stream. + /// + /// The buffer to read into. + /// The number of bytes read. + public override int Read(Span buffer) + { + return _innerStream.Read(buffer); + } + + /// + /// Reads a block of bytes from the stream asynchronously. + /// + /// The buffer to read into. + /// The offset in the buffer at which to start writing. + /// The maximum number of bytes to read. + /// Cancellation token that can be used to stop the execution. + /// The number of bytes read. + public override Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) + { + // The memory based overload is the one the inner stream should implement, so the array overload only adapts to it. + return _innerStream.ReadAsync(buffer.AsMemory(offset, count), cancellationToken).AsTask(); + } + + /// + /// Reads a block of bytes from the stream asynchronously. + /// + /// The buffer to read into. + /// Cancellation token that can be used to stop the execution. + /// The number of bytes read. + public override ValueTask ReadAsync(Memory buffer, CancellationToken cancellationToken = default) + { + return _innerStream.ReadAsync(buffer, cancellationToken); + } + + /// + /// Sets the position within the stream. + /// + /// The offset relative to . + /// The reference point used to obtain the new position. + /// The new position within the stream. + public override long Seek(long offset, SeekOrigin origin) + { + return _innerStream.Seek(offset, origin); + } + + /// + /// Sets the length of the stream. + /// + /// The new length of the stream, in bytes. + public override void SetLength(long value) + { + _innerStream.SetLength(value); + } + + /// + /// Writes a block of bytes to the stream. + /// + /// The buffer to write from. + /// The offset in the buffer at which to start reading. + /// The number of bytes to write. + public override void Write(byte[] buffer, int offset, int count) + { + _innerStream.Write(buffer, offset, count); + } + + /// + /// Writes a block of bytes to the stream. + /// + /// The buffer to write from. + public override void Write(ReadOnlySpan buffer) + { + _innerStream.Write(buffer); + } + + /// + /// Writes a block of bytes to the stream asynchronously. + /// + /// The buffer to write from. + /// The offset in the buffer at which to start reading. + /// The number of bytes to write. + /// Cancellation token that can be used to stop the execution. + /// A task that represents the asynchronous write operation. + public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) + { + // The memory based overload is the one the inner stream should implement, so the array overload only adapts to it. + return _innerStream.WriteAsync(buffer.AsMemory(offset, count), cancellationToken).AsTask(); + } + + /// + /// Writes a block of bytes to the stream asynchronously. + /// + /// The buffer to write from. + /// Cancellation token that can be used to stop the execution. + /// A task that represents the asynchronous write operation. + public override ValueTask WriteAsync(ReadOnlyMemory buffer, CancellationToken cancellationToken = default) + { + return _innerStream.WriteAsync(buffer, cancellationToken); + } + + /// + /// Releases the inner stream and the reader lease. + /// + /// Whether the method is called from the method. + protected override void Dispose(bool disposing) + { + if (disposing && !_isDisposed) + { + _isDisposed = true; + try + { + _innerStream.Dispose(); + } + finally + { + // The lease must be released even when disposing the stream throws, otherwise the entry stays protected from eviction forever. + _lease.Dispose(); + } + } + base.Dispose(disposing); + } + + /// + /// Releases the inner stream and the reader lease asynchronously. + /// + /// A task that represents the asynchronous dispose operation. + public override async ValueTask DisposeAsync() + { + if (!_isDisposed) + { + _isDisposed = true; + try + { + await _innerStream.DisposeAsync().ConfigureAwait(false); + } + finally + { + // The lease must be released even when disposing the stream throws, otherwise the entry stays protected from eviction forever. + _lease.Dispose(); + } + } + await base.DisposeAsync().ConfigureAwait(false); + } +} diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/TranscodingCacheReaderLease.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/TranscodingCacheReaderLease.cs new file mode 100644 index 00000000..070246f6 --- /dev/null +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/TranscodingCacheReaderLease.cs @@ -0,0 +1,39 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Infrastructure.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback; + +/// +/// Represents a reader's lease on a cache entry, which keeps the entry from being evicted until the lease is released. +/// +[DebuggerDisplay("CacheId: {_cacheId}")] +internal sealed class TranscodingCacheReaderLease : IDisposable +{ + private readonly TranscodingCacheCoordinator _coordinator; + private readonly string _cacheId; + private bool _isDisposed; + + /// + /// Initializes a new instance of the class. + /// + /// The coordinator that accounts for the lease. + /// The identifier of the cache entry the lease holds. + internal TranscodingCacheReaderLease(TranscodingCacheCoordinator coordinator, string cacheId) + { + _coordinator = coordinator; + _cacheId = cacheId; + } + + /// + /// Releases the lease, so the cache entry may be evicted again. + /// + public void Dispose() + { + if (_isDisposed) + return; + _isDisposed = true; + _coordinator.ReleaseReaderLease(_cacheId); + } +} diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/TranscodingCacheReservation.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/TranscodingCacheReservation.cs new file mode 100644 index 00000000..6e7114f1 --- /dev/null +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/TranscodingCacheReservation.cs @@ -0,0 +1,84 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Infrastructure.Common.Models.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback; +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Infrastructure.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback; + +/// +/// Represents the capacity a running normalization job reserved in the normalized audio cache, until it either produces an entry or is aborted. +/// +[DebuggerDisplay("Id: {Id}")] +internal sealed class TranscodingCacheReservation : IDisposable +{ + private readonly TranscodingCacheCoordinator _coordinator; + private bool _isCompleted; + private bool _isDisposed; + + /// + /// Gets the identifier of the reservation. + /// + internal string Id { get; } + + /// + /// Initializes a new instance of the class. + /// + /// The coordinator that accounts for the reservation. + /// The identifier of the reservation. + internal TranscodingCacheReservation(TranscodingCacheCoordinator coordinator, string id) + { + _coordinator = coordinator; + Id = id; + } + + /// + /// Updates the reservation to the number of bytes the job has actually written, growing it when the output is larger than the estimate. + /// + /// The number of bytes the job has actually written, in bytes. + /// The maximum total size of the cache, in bytes. + /// The period during which a recently produced or served entry is protected from eviction. + /// when the reservation covers the actual size, otherwise . + public bool TryUpdate(long actualBytes, long maxCacheBytes, TimeSpan gracePeriod) + { + if (_isCompleted || _isDisposed) + return false; + return _coordinator.TryGrow(Id, actualBytes, maxCacheBytes, gracePeriod); + } + + /// + /// Replaces the reservation with the produced cache entry. + /// + /// The identifier of the produced cache entry. + /// The temporary directory that holds the complete produced entry. + /// The total size of the produced cache entry, in bytes. + /// The validated index of the produced cache entry. + /// The maximum total size of the cache, in bytes. + /// The period during which a recently produced or served entry is protected from eviction. + /// when the produced entry remains readable even though it exceeds the cache limit, otherwise . + /// when a reader still holds the previous entry of the same cache identifier, so the replacement was not attempted. + /// when the produced entry is readable and may be served, otherwise when it was not published. + public bool TryComplete(string cacheId, string temporaryPath, long size, NormalizedTrackIndexDto index, long maxCacheBytes, TimeSpan gracePeriod, out bool isKeptOverCapacity, out bool isEntryInUse) + { + isKeptOverCapacity = false; + isEntryInUse = false; + if (_isCompleted || _isDisposed) + return false; + bool isCompleted = _coordinator.TryPublish(Id, cacheId, temporaryPath, size, index, maxCacheBytes, gracePeriod, out isKeptOverCapacity, out isEntryInUse); + // The reservation is consumed even when the produced entry had to be removed, so it is never released a second time. + _isCompleted = true; + return isCompleted; + } + + /// + /// Releases the reservation when the job did not produce a cache entry. + /// + public void Dispose() + { + if (_isDisposed) + return; + _isDisposed = true; + if (!_isCompleted) + _coordinator.ReleaseReservation(Id); + } +} diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/TranscodingOutputSizeTracker.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/TranscodingOutputSizeTracker.cs new file mode 100644 index 00000000..1e5870ba --- /dev/null +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/TranscodingOutputSizeTracker.cs @@ -0,0 +1,125 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.IO; +#endregion + +namespace Lumina.Infrastructure.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback; + +/// +/// Tracks the size of the temporary output of a running normalization job without walking the growing directory on every monitor tick. +/// +/// +/// Segment files are written in sequence and only the last one grows. The tracker discovers each new segment once, keeps the size of the completed +/// segments, and only re-stats the current segment and the segment list on every tick, so the monitor stays O(1) per tick instead of O(n). +/// +internal sealed class TranscodingOutputSizeTracker +{ + private readonly string _directoryPath; + private readonly string _segmentFilePrefix; + private readonly string _segmentFileExtension; + private readonly string _segmentListPath; + private long _totalBytes; + private long _segmentListLength; + private long _lastSegmentLength; + private int _nextSegmentIndex; + private string? _lastSegmentPath; + + /// + /// Initializes a new instance of the class. + /// + /// The temporary directory the job writes into. + /// The prefix of the generated segment file names. + /// The file extension of a segment, including the leading dot. + /// The file name of the segment list written by ffmpeg. + internal TranscodingOutputSizeTracker(string directoryPath, string segmentFilePrefix, string segmentFileExtension, string segmentListFileName) + { + _directoryPath = directoryPath; + _segmentFilePrefix = segmentFilePrefix; + _segmentFileExtension = segmentFileExtension; + _segmentListPath = Path.Combine(directoryPath, segmentListFileName); + } + + /// + /// Gets the current total size of the produced output, in bytes. + /// + /// The current total size of the produced output, in bytes. + public long GetCurrentSize() + { + // The previous tick's last segment may have grown before a new segment was started, so it is measured before new files are discovered. + RecalculateLastSegment(); + RecalculateSegmentList(); + DiscoverNewSegments(); + RecalculateLastSegment(); + return _totalBytes; + } + + /// + /// Updates the total with the growth of the segment that is currently being written, when there is one. + /// + private void RecalculateLastSegment() + { + if (_lastSegmentPath is null) + return; + long currentLength = GetFileLength(_lastSegmentPath, _lastSegmentLength); + _totalBytes += currentLength - _lastSegmentLength; + _lastSegmentLength = currentLength; + } + + /// + /// Updates the total with the growth of the segment list. + /// + private void RecalculateSegmentList() + { + long currentLength = GetFileLength(_segmentListPath, _segmentListLength); + _totalBytes += currentLength - _segmentListLength; + _segmentListLength = currentLength; + } + + /// + /// Adds every segment that has appeared since the previous tick, in sequence, and leaves the last one as the growing segment. + /// + private void DiscoverNewSegments() + { + while (true) + { + string segmentPath = Path.Combine(_directoryPath, $"{_segmentFilePrefix}{_nextSegmentIndex:D6}{_segmentFileExtension}"); + FileInfo segmentFile = new(segmentPath); + if (!segmentFile.Exists) + return; + + long segmentLength; + try + { + segmentLength = segmentFile.Length; + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) + { + return; // A file that cannot be measured yet is retried on the next tick. + } + + _totalBytes += segmentLength; + _lastSegmentPath = segmentPath; + _lastSegmentLength = segmentLength; + _nextSegmentIndex++; + } + } + + /// + /// Gets the length of a file, falling back to its last known length when it cannot currently be measured. + /// + /// The file to measure. + /// The length to use when the file cannot be measured. + /// The current or fallback length of the file, in bytes. + private static long GetFileLength(string filePath, long fallbackLength) + { + try + { + FileInfo file = new(filePath); + return file.Exists ? file.Length : fallbackLength; + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) + { + return fallbackLength; + } + } +} diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/TranscodingStartupInitializer.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/TranscodingStartupInitializer.cs new file mode 100644 index 00000000..93b69bc7 --- /dev/null +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/TranscodingStartupInitializer.cs @@ -0,0 +1,228 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Infrastructure.Common.Caching; +using Lumina.Infrastructure.Common.Models.DTO.Configuration; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Infrastructure.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback; + +/// +/// Startup component that owns the normalized audio cache lifecycle and verifies the ffmpeg toolchain before any playback request is served. +/// +/// +/// The cache is cleaned and recreated with private permissions at startup, and the configured ffmpeg binary is probed for the encoders the catalog uses. The +/// cleanup only removes the entries the cache itself owns, and only from a directory that carries the cache marker or was empty, so a configured directory +/// that belongs to something else is never wiped. The cleanup is bounded, so a slow or network backed cache directory cannot delay host readiness without +/// limit. The probe outcome is recorded in , so normalized playback reports that it is unavailable for the affected +/// formats instead of failing per track. A failure of either step is logged and does not abort the host, so direct playback of the rest of the application +/// keeps working. +/// +internal sealed class TranscodingStartupInitializer : IHostedService +{ + private const int CACHE_CLEANUP_TIMEOUT_SECONDS = 30; + private const int FFMPEG_PROBE_TIMEOUT_SECONDS = 10; + + private readonly TranscodingSettingsDto _settings; + private readonly TranscodingToolchainStatus _toolchainStatus; + private readonly ILogger _logger; + + /// + /// Initializes a new instance of the class. + /// + /// The audio normalization configuration options. + /// The status that records the outcome of the ffmpeg probe for the normalization service. + /// The logger for this startup component. + public TranscodingStartupInitializer(IOptions options, TranscodingToolchainStatus toolchainStatus, ILogger logger) + { + _settings = options.Value; + _toolchainStatus = toolchainStatus; + _logger = logger; + } + + /// + /// Cleans and recreates the cache directory, then probes the ffmpeg binary for the encoders the pipeline uses. + /// + /// Cancellation token that can be used to stop the execution. + /// A task that represents the asynchronous startup operation. + public async Task StartAsync(CancellationToken cancellationToken) + { + try + { + string cacheDirectory = TranscodingCachePaths.GetRootDirectory(_settings.CacheDirectory); + if (Directory.Exists(cacheDirectory)) + { + // The permissions are verified before the directory is inspected, so a directory planted by another account is never used or cleaned. + TranscodingCachePaths.RestrictPermissions(cacheDirectory); + if (TranscodingCachePaths.HasCacheMarker(cacheDirectory)) + { + // Only the entries the cache itself owns are removed, so a directory that was configured by mistake can never lose unrelated data. + // The cleanup is bounded and cancellable, because a network backed cache directory must not delay host readiness forever. + using (CancellationTokenSource cleanupTimeoutCancellationTokenSource = new(TimeSpan.FromSeconds(CACHE_CLEANUP_TIMEOUT_SECONDS))) + { + using (CancellationTokenSource linkedCleanupCancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, cleanupTimeoutCancellationTokenSource.Token)) + { + try + { + TranscodingCachePaths.ClearCacheEntries(cacheDirectory, linkedCleanupCancellationTokenSource.Token); + } + catch (OperationCanceledException) + { + if (!cancellationToken.IsCancellationRequested) + _logger.LogWarning("The normalized audio cache cleanup did not finish within {CleanupTimeoutSeconds} seconds. Whatever remains is accounted for by the coordinator and is removed by the next cleanup.", CACHE_CLEANUP_TIMEOUT_SECONDS); + } + } + } + } + else if (!Directory.EnumerateFileSystemEntries(cacheDirectory).Any()) + TranscodingCachePaths.WriteCacheMarker(cacheDirectory); // An empty directory is adopted, so a cache directory created ahead of the first run works without manual preparation. + else // A non-empty directory without the marker was not created by this application. It is never wiped, because only the operator can tell whether its entries are safe to remove. + throw new IOException("The configured normalized audio cache directory exists, is not empty and does not carry the Lumina cache marker, so it was not wiped."); + } + else + TranscodingCachePaths.EnsureDirectoryExists(cacheDirectory); + _logger.LogInformation("The normalized audio cache uses the directory '{CacheDirectory}'.", cacheDirectory); + } + catch (Exception exception) + { + // A locked file, a read-only volume or a directory owned by another account must not stop the whole application; the coordinator accounts + // for whatever remains and the service reports normalized playback as unavailable when the directory still cannot be used. + _logger.LogError(exception, "The normalized audio cache could not be initialized (configured directory: '{CacheDirectory}'). Normalized playback may be unavailable.", _settings.CacheDirectory ?? "(default)"); + } + + try + { + await ProbeFfmpegAsync(cancellationToken).ConfigureAwait(false); + } + catch (Exception exception) + { + // The startup component promises never to abort the host, so an unexpected probe failure is contained and reported here. + _toolchainStatus.RecordUnavailable(); + _logger.LogError(exception, "The ffmpeg startup probe failed unexpectedly. Normalized playback may be unavailable."); + } + } + + /// + /// Stops the startup component, which has no resources of its own to release. + /// + /// Cancellation token that can be used to stop the execution. + /// A completed task. + public Task StopAsync(CancellationToken cancellationToken) + { + return Task.CompletedTask; + } + + /// + /// Probes the ffmpeg binary for the encoders the catalog can produce, without failing the host when it is missing or incomplete. + /// + /// Cancellation token that can be used to stop the execution. + /// A task that represents the asynchronous probe. + private async Task ProbeFfmpegAsync(CancellationToken cancellationToken) + { + try + { + using Process process = new(); + process.StartInfo = new ProcessStartInfo + { + FileName = _settings.FfmpegPath, + UseShellExecute = false, + CreateNoWindow = true, + RedirectStandardOutput = true, + RedirectStandardError = true + }; + process.StartInfo.ArgumentList.Add("-hide_banner"); + process.StartInfo.ArgumentList.Add("-encoders"); + + if (!process.Start()) + { + _toolchainStatus.RecordUnavailable(); + _logger.LogWarning("The ffmpeg binary '{FfmpegPath}' could not be started. Normalized playback will be unavailable.", _settings.FfmpegPath); + return; + } + + using CancellationTokenSource timeoutCancellationTokenSource = new(TimeSpan.FromSeconds(FFMPEG_PROBE_TIMEOUT_SECONDS)); + // The probe has two cancellation reasons: the host startup token and the probe timeout. Linking them gives the process wait and the pipe reads + // one token that means "this probe is over" for either reason. The parameter alone could not stop the reads on a timeout, and the timeout alone would ignore host shutdown. + using CancellationTokenSource linkedCancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, timeoutCancellationTokenSource.Token); + // Drain both pipes while the process runs. A child that fills a pipe buffer blocks until it is read, so waiting for exit first could deadlock. + // The linked token stops the reads as well, so a probe timeout or host shutdown does not leave them running against a killed child. + Task standardOutputTask = process.StandardOutput.ReadToEndAsync(linkedCancellationTokenSource.Token); + Task standardErrorTask = process.StandardError.ReadToEndAsync(linkedCancellationTokenSource.Token); + try + { + await process.WaitForExitAsync(linkedCancellationTokenSource.Token).ConfigureAwait(false); + } + catch (OperationCanceledException) + { + try + { + if (!process.HasExited) + process.Kill(entireProcessTree: true); + } + catch (Exception killException) when (killException is Win32Exception or InvalidOperationException or NotSupportedException) + { + _logger.LogDebug(killException, "The ffmpeg startup probe process could not be stopped."); + } + if (!cancellationToken.IsCancellationRequested) + _logger.LogWarning("The ffmpeg binary '{FfmpegPath}' did not respond to the startup probe.", _settings.FfmpegPath); + _toolchainStatus.RecordUnavailable(); + return; + } + + string encoderListing = await standardOutputTask.ConfigureAwait(false); + await standardErrorTask.ConfigureAwait(false); + if (process.ExitCode != 0) + { + _toolchainStatus.RecordUnavailable(); + _logger.LogWarning("The ffmpeg binary '{FfmpegPath}' exited with code {ExitCode} during the startup probe. Normalized playback may be unavailable.", _settings.FfmpegPath, process.ExitCode); + return; + } + + IReadOnlyList requiredEncoders = [.. PlaybackFormatCatalog.Formats + .Select(format => format.EncoderName) + .Distinct(StringComparer.OrdinalIgnoreCase)]; + List missingEncoders = [.. requiredEncoders.Where(encoder => !ContainsEncoder(encoderListing, encoder))]; + if (missingEncoders.Count > 0) + { + // An unpinned distribution package can change the encoder set without changing the application build, so this is reported at startup instead of surfacing as a per track playback failure. + _toolchainStatus.RecordMissingEncoders(missingEncoders); + _logger.LogError("The ffmpeg binary '{FfmpegPath}' is missing the encoders {MissingEncoders}. Normalized playback for those formats will be unavailable.", _settings.FfmpegPath, string.Join(", ", missingEncoders)); + return; + } + _toolchainStatus.RecordAvailable(); + _logger.LogInformation("The ffmpeg binary '{FfmpegPath}' provides every encoder the normalized audio pipeline uses.", _settings.FfmpegPath); + } + catch (Exception exception) when (exception is Win32Exception or InvalidOperationException or IOException or UnauthorizedAccessException or NotSupportedException) + { + _toolchainStatus.RecordUnavailable(); + _logger.LogWarning(exception, "The ffmpeg binary '{FfmpegPath}' could not be probed. Normalized playback will be unavailable.", _settings.FfmpegPath); + } + } + + /// + /// Checks whether the encoder listing of ffmpeg contains the provided encoder name. + /// + /// The output of the ffmpeg encoder listing. + /// The encoder name to look for. + /// when the encoder is listed, otherwise . + private static bool ContainsEncoder(string encoderListing, string encoderName) + { + foreach (string line in encoderListing.Split('\n')) + { + string[] tokens = line.Split([' ', '\t'], StringSplitOptions.RemoveEmptyEntries); + // An encoder line is " "; the encoder name is always the second token. + if (tokens.Length >= 2 && string.Equals(tokens[1], encoderName, StringComparison.OrdinalIgnoreCase)) + return true; + } + return false; + } +} diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/TranscodingToolchainStatus.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/TranscodingToolchainStatus.cs new file mode 100644 index 00000000..d6e0e717 --- /dev/null +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/TranscodingToolchainStatus.cs @@ -0,0 +1,73 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Collections.Frozen; +using System.Collections.Generic; +using System.Linq; +#endregion + +namespace Lumina.Infrastructure.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback; + +/// +/// Records the outcome of the ffmpeg startup probe, so a missing toolchain or encoder is reported as a retryable unavailability instead of a production failure. +/// +/// +/// The status starts as available, because a request that arrives before the probe completes is better served by attempting the work than by rejecting it. The +/// probe replaces the status with its outcome, and every later production consults it before it spends a job slot. +/// +internal sealed class TranscodingToolchainStatus +{ + // The startup probe writes these fields and request threads read them without a lock, so volatile makes each write visible to the readers. + private volatile bool _isTranscoderAvailable = true; + private volatile FrozenSet _missingEncoders = []; + + /// + /// Initializes a new instance of the class, which starts as available until the startup probe records its outcome. + /// + public TranscodingToolchainStatus() + { + } + + /// + /// Gets a value indicating whether the ffmpeg binary can run at all. + /// + public bool IsTranscoderAvailable => _isTranscoderAvailable; + + /// + /// Records that the probe found a usable ffmpeg binary with every encoder the catalog needs. + /// + public void RecordAvailable() + { + // The set is cleared before the availability flag, so a reader never observes a missing encoder together with a fresh successful probe. + _missingEncoders = []; + _isTranscoderAvailable = true; + } + + /// + /// Records that the ffmpeg binary could not be started or did not answer the probe. + /// + public void RecordUnavailable() + { + _isTranscoderAvailable = false; + _missingEncoders = []; + } + + /// + /// Records that ffmpeg runs, but that some of the encoders the catalog needs are missing. + /// + /// The names of the encoders the startup probe did not find. + public void RecordMissingEncoders(IEnumerable missingEncoders) + { + _missingEncoders = missingEncoders.ToFrozenSet(StringComparer.OrdinalIgnoreCase); + _isTranscoderAvailable = true; + } + + /// + /// Checks whether an encoder can be used for a lossy or lossless transcode. + /// + /// The name of the ffmpeg encoder the delivery format needs. + /// when ffmpeg runs and the encoder was found, otherwise . + public bool IsEncoderAvailable(string encoderName) + { + return _isTranscoderAvailable && !_missingEncoders.Contains(encoderName); + } +} diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicMediaLibraryScanItemMaterializer.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicMediaLibraryScanItemMaterializer.cs index 1eaf37a6..7c23fbe0 100644 --- a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicMediaLibraryScanItemMaterializer.cs +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicMediaLibraryScanItemMaterializer.cs @@ -306,6 +306,7 @@ internal sealed class MusicMediaLibraryScanItemMaterializer : IMediaLibraryScanI Channels = stagedItem.Channels, BitDepth = stagedItem.BitDepth, AudioCodec = stagedItem.AudioCodec, + Container = stagedItem.Container, Bitrate = stagedItem.Bitrate, AcoustId = stagedItem.AcoustId, ReplayGainTrackGain = stagedItem.ReplayGainTrackGain, diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicMetadataExtractionJob.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicMetadataExtractionJob.cs index f96b6d29..f04ffff6 100644 --- a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicMetadataExtractionJob.cs +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicMetadataExtractionJob.cs @@ -17,6 +17,7 @@ using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.Library using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Infrastructure.Core.MediaLibrary.AudioLibrary.MusicLibrary.Metadata; using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Common; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; @@ -232,6 +233,7 @@ internal sealed class MusicMetadataExtractionJob : MediaLibraryScanJob, IMusicMe int channels = 0; int? bitDepth = null; string? audioCodec = null; + string? container = null; int? bitrate = null; string? acoustId = null; decimal? replayGainTrackGain = null; @@ -242,64 +244,71 @@ internal sealed class MusicMetadataExtractionJob : MediaLibraryScanJob, IMusicMe try { - using (TagLib.File tagFile = TagLib.File.Create(path)) + // A file that is itself a link is not read, so its target outside the content locations is never opened. A linked directory is a separate + // discovery level concern, so this is a defense in depth for the leaf file rather than a complete containment guarantee. + if (!IsReparsePoint(path)) { - TagLib.Tag tag = tagFile.Tag; - if (!string.IsNullOrWhiteSpace(tag.Title)) - trackTitle = tag.Title; - if (!string.IsNullOrWhiteSpace(tag.Album)) - releaseName = tag.Album; - // The album artist is preferred over the track artist, because it is the artist the release belongs to. - string? tagArtist = !string.IsNullOrWhiteSpace(tag.FirstAlbumArtist) ? tag.FirstAlbumArtist : tag.FirstPerformer; - if (!string.IsNullOrWhiteSpace(tagArtist)) - artistName = tagArtist; - if (tag.Track > 0) - trackNumber = (int)tag.Track; - if (tag.Disc > 0) - discNumber = (int)tag.Disc; - if (tag.Year > 0) - releaseYear = (int)tag.Year; + using (TagLib.File tagFile = TagLib.File.Create(path)) + { + TagLib.Tag tag = tagFile.Tag; + if (!string.IsNullOrWhiteSpace(tag.Title)) + trackTitle = tag.Title; + if (!string.IsNullOrWhiteSpace(tag.Album)) + releaseName = tag.Album; + // The album artist is preferred over the track artist, because it is the artist the release belongs to. + string? tagArtist = !string.IsNullOrWhiteSpace(tag.FirstAlbumArtist) ? tag.FirstAlbumArtist : tag.FirstPerformer; + if (!string.IsNullOrWhiteSpace(tagArtist)) + artistName = tagArtist; + if (tag.Track > 0) + trackNumber = (int)tag.Track; + if (tag.Disc > 0) + discNumber = (int)tag.Disc; + if (tag.Year > 0) + releaseYear = (int)tag.Year; - TagLib.Properties audioProperties = tagFile.Properties; - durationInSeconds = (int)audioProperties.Duration.TotalSeconds; - sampleRate = audioProperties.AudioSampleRate; - channels = audioProperties.AudioChannels; - if (audioProperties.BitsPerSample > 0) - bitDepth = audioProperties.BitsPerSample; - if (audioProperties.AudioBitrate > 0) - bitrate = audioProperties.AudioBitrate; - if (!string.IsNullOrWhiteSpace(audioProperties.Description)) - audioCodec = audioProperties.Description; + TagLib.Properties audioProperties = tagFile.Properties; + durationInSeconds = (int)audioProperties.Duration.TotalSeconds; + sampleRate = audioProperties.AudioSampleRate; + channels = audioProperties.AudioChannels; + // The container is the format of the file itself, so it is resolved from the concrete type of the parsed file and not from its tags. + container = AudioContainerResolver.Resolve(tagFile); + if (audioProperties.BitsPerSample > 0) + bitDepth = audioProperties.BitsPerSample; + if (audioProperties.AudioBitrate > 0) + bitrate = audioProperties.AudioBitrate; + if (!string.IsNullOrWhiteSpace(audioProperties.Description)) + audioCodec = audioProperties.Description; - // The text frames of the ID3v2 tag are read once for the whole file, so that the extended tag lookups below do not walk all the frames - // of the tag again for every key. - IReadOnlyDictionary id3v2ExtendedFields = GetId3v2ExtendedFields(tagFile); + // The text frames of the ID3v2 tag are read once for the whole file, so that the extended tag lookups below do not walk all the frames + // of the tag again for every key. + IReadOnlyDictionary id3v2ExtendedFields = GetId3v2ExtendedFields(tagFile); - // The MusicBrainz identifiers written by taggers like Picard are read here, so that the enrichment can look the items up directly, - // instead of guessing them through searches. The work identifier and title are not exposed as properties by the tagging library, so - // they are read from the extended tags of the container, and they only serve as a fallback for recordings that MusicBrainz leaves unlinked to a work. - musicBrainzArtistId = ParseGuid(tag.MusicBrainzArtistId); - musicBrainzReleaseArtistId = ParseGuid(tag.MusicBrainzReleaseArtistId); - musicBrainzReleaseGroupId = ParseGuid(tag.MusicBrainzReleaseGroupId); - musicBrainzReleaseId = ParseGuid(tag.MusicBrainzReleaseId); - musicBrainzRecordingId = ParseGuid(tag.MusicBrainzTrackId); - musicBrainzTrackId = ParseGuid(GetExtendedField(tagFile, id3v2ExtendedFields, "MusicBrainz Release Track Id", "MUSICBRAINZ_RELEASETRACKID")); - musicBrainzWorkId = ParseGuid(GetExtendedField(tagFile, id3v2ExtendedFields, "MusicBrainz Work Id", "MUSICBRAINZ_WORKID")); - string? extendedWorkTitle = GetExtendedField(tagFile, id3v2ExtendedFields, "WORK", "MUSICBRAINZ_WORK"); - if (!string.IsNullOrWhiteSpace(extendedWorkTitle)) - workTitle = extendedWorkTitle; + // The MusicBrainz identifiers written by taggers like Picard are read here, so that the enrichment can look the items up directly, + // instead of guessing them through searches. The work identifier and title are not exposed as properties by the tagging library, so + // they are read from the extended tags of the container, and they only serve as a fallback for recordings that MusicBrainz leaves unlinked to a work. + musicBrainzArtistId = ParseGuid(tag.MusicBrainzArtistId); + musicBrainzReleaseArtistId = ParseGuid(tag.MusicBrainzReleaseArtistId); + musicBrainzReleaseGroupId = ParseGuid(tag.MusicBrainzReleaseGroupId); + musicBrainzReleaseId = ParseGuid(tag.MusicBrainzReleaseId); + musicBrainzRecordingId = ParseGuid(tag.MusicBrainzTrackId); + musicBrainzTrackId = ParseGuid(GetExtendedField(tagFile, id3v2ExtendedFields, "MusicBrainz Release Track Id", "MUSICBRAINZ_RELEASETRACKID")); + musicBrainzWorkId = ParseGuid(GetExtendedField(tagFile, id3v2ExtendedFields, "MusicBrainz Work Id", "MUSICBRAINZ_WORKID")); + string? extendedWorkTitle = GetExtendedField(tagFile, id3v2ExtendedFields, "WORK", "MUSICBRAINZ_WORK"); + if (!string.IsNullOrWhiteSpace(extendedWorkTitle)) + workTitle = extendedWorkTitle; - // The AcoustID, the moods and the ReplayGain values written by taggers like Picard are read here as well. The moods can be a single - // slash separated value or several distinct values, depending on the container, so all of them are read and split before being de-duplicated. - acoustId = GetExtendedField(tagFile, id3v2ExtendedFields, "Acoustid Id", "ACOUSTID_ID"); - moods = [.. GetExtendedFields(tagFile, id3v2ExtendedFields, "mood", "MOOD", "MOODS") - .SelectMany(mood => mood.Split('/', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)) - .Where(mood => !string.IsNullOrWhiteSpace(mood)) - .Distinct(StringComparer.OrdinalIgnoreCase)]; - replayGainTrackGain = ParseDecimal(GetExtendedField(tagFile, id3v2ExtendedFields, "REPLAYGAIN_TRACK_GAIN", "replaygain_track_gain")); - replayGainTrackPeak = ParseDecimal(GetExtendedField(tagFile, id3v2ExtendedFields, "REPLAYGAIN_TRACK_PEAK", "replaygain_track_peak")); - replayGainAlbumGain = ParseDecimal(GetExtendedField(tagFile, id3v2ExtendedFields, "REPLAYGAIN_ALBUM_GAIN", "replaygain_album_gain")); - replayGainAlbumPeak = ParseDecimal(GetExtendedField(tagFile, id3v2ExtendedFields, "REPLAYGAIN_ALBUM_PEAK", "replaygain_album_peak")); + // The AcoustID, the moods and the ReplayGain values written by taggers like Picard are read here as well. The moods can be a single + // slash separated value or several distinct values, depending on the container, so all of them are read and split before being de-duplicated. + acoustId = GetExtendedField(tagFile, id3v2ExtendedFields, "Acoustid Id", "ACOUSTID_ID"); + moods = [.. GetExtendedFields(tagFile, id3v2ExtendedFields, "mood", "MOOD", "MOODS") + .SelectMany(mood => mood.Split('/', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)) + .Where(mood => !string.IsNullOrWhiteSpace(mood)) + .Distinct(StringComparer.OrdinalIgnoreCase)]; + replayGainTrackGain = ParseDecimal(GetExtendedField(tagFile, id3v2ExtendedFields, "REPLAYGAIN_TRACK_GAIN", "replaygain_track_gain")); + replayGainTrackPeak = ParseDecimal(GetExtendedField(tagFile, id3v2ExtendedFields, "REPLAYGAIN_TRACK_PEAK", "replaygain_track_peak")); + replayGainAlbumGain = ParseDecimal(GetExtendedField(tagFile, id3v2ExtendedFields, "REPLAYGAIN_ALBUM_GAIN", "replaygain_album_gain")); + replayGainAlbumPeak = ParseDecimal(GetExtendedField(tagFile, id3v2ExtendedFields, "REPLAYGAIN_ALBUM_PEAK", "replaygain_album_peak")); + } } } catch (Exception exception) when (exception is TagLib.CorruptFileException or TagLib.UnsupportedFormatException or IOException or UnauthorizedAccessException) @@ -330,6 +339,7 @@ internal sealed class MusicMetadataExtractionJob : MediaLibraryScanJob, IMusicMe Channels = channels, BitDepth = bitDepth, AudioCodec = audioCodec, + Container = container, Bitrate = bitrate, AcoustId = acoustId, ReplayGainTrackGain = replayGainTrackGain, @@ -348,6 +358,17 @@ internal sealed class MusicMetadataExtractionJob : MediaLibraryScanJob, IMusicMe }; } + /// + /// Determines whether the file stored at is a reparse point, such as a symbolic link. + /// + /// The file system path of the file to check. + /// when the file is a reparse point, otherwise . + private static bool IsReparsePoint(string path) + { + // This only detects a leaf file that is itself a link; a linked directory encountered during discovery is not caught here. + return (File.GetAttributes(path) & FileAttributes.ReparsePoint) == FileAttributes.ReparsePoint; + } + /// /// Parses the provided tag as a globally unique identifier. /// diff --git a/src/Lumina.Infrastructure/Core/Plugins/PluginSettingsStore.cs b/src/Lumina.Infrastructure/Core/Plugins/PluginSettingsStore.cs index 75aa4ff8..b4413224 100644 --- a/src/Lumina.Infrastructure/Core/Plugins/PluginSettingsStore.cs +++ b/src/Lumina.Infrastructure/Core/Plugins/PluginSettingsStore.cs @@ -37,7 +37,7 @@ internal sealed class PluginSettingsStore : IPluginSettingsStore /// Gets the settings persisted by the host for the plugin identified by . /// /// The unique identifier of the plugin whose settings are read. - /// Cancellation token that can be used to cancel the operation. + /// Cancellation token that can be used to stop the execution. /// The persisted settings keyed by setting key, or when no settings were persisted for the plugin. public async Task?> GetSettingsAsync(Guid pluginId, CancellationToken cancellationToken) { diff --git a/src/Lumina.Infrastructure/Core/Scheduling/Execution/IScheduledJobCycleTicker.cs b/src/Lumina.Infrastructure/Core/Scheduling/Execution/IScheduledJobCycleTicker.cs index b25a91a3..5278f302 100644 --- a/src/Lumina.Infrastructure/Core/Scheduling/Execution/IScheduledJobCycleTicker.cs +++ b/src/Lumina.Infrastructure/Core/Scheduling/Execution/IScheduledJobCycleTicker.cs @@ -26,7 +26,7 @@ internal interface IScheduledJobCycleTicker : IDisposable /// /// Waits until the next tick of the ticker, or until the ticker is disposed or is cancelled. /// - /// Cancellation token that can be used to stop the wait. + /// Cancellation token that can be used to stop the execution. /// when a tick occurred; when the ticker was disposed before the next tick. ValueTask WaitForNextTickAsync(CancellationToken cancellationToken); } diff --git a/src/Lumina.Infrastructure/Core/Scheduling/Execution/PeriodicScheduledJobCycleTicker.cs b/src/Lumina.Infrastructure/Core/Scheduling/Execution/PeriodicScheduledJobCycleTicker.cs index b7c788ff..7ea258a1 100644 --- a/src/Lumina.Infrastructure/Core/Scheduling/Execution/PeriodicScheduledJobCycleTicker.cs +++ b/src/Lumina.Infrastructure/Core/Scheduling/Execution/PeriodicScheduledJobCycleTicker.cs @@ -36,7 +36,7 @@ internal sealed class PeriodicScheduledJobCycleTicker : IScheduledJobCycleTicker /// /// Waits until the next tick of the ticker, or until the ticker is disposed or is cancelled. /// - /// Cancellation token that can be used to stop the wait. + /// Cancellation token that can be used to stop the execution. /// when a tick occurred; when the ticker was disposed before the next tick. public ValueTask WaitForNextTickAsync(CancellationToken cancellationToken) { diff --git a/src/Lumina.Infrastructure/Core/Scheduling/Notifications/ScheduledJobsHub.cs b/src/Lumina.Infrastructure/Core/Scheduling/Notifications/ScheduledJobsHub.cs index 5d498ecb..491e0c38 100644 --- a/src/Lumina.Infrastructure/Core/Scheduling/Notifications/ScheduledJobsHub.cs +++ b/src/Lumina.Infrastructure/Core/Scheduling/Notifications/ScheduledJobsHub.cs @@ -2,6 +2,7 @@ using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.SignalR; using Microsoft.Extensions.DependencyInjection; +using Lumina.Application.Common.Infrastructure.Authorization; using System; using System.Security.Claims; using System.Threading; @@ -60,6 +61,6 @@ public class ScheduledJobsHub : Hub { await using AsyncServiceScope scope = _serviceScopeFactory.CreateAsyncScope(); ApplicationAuthorizationService authorizationService = scope.ServiceProvider.GetRequiredService(); - return await authorizationService.IsInRoleAsync(userId, "Admin", CancellationToken.None).ConfigureAwait(false); + return await authorizationService.IsInRoleAsync(userId, AuthorizationRoles.ADMIN, CancellationToken.None).ConfigureAwait(false); } } diff --git a/src/Lumina.Infrastructure/Core/Themes/ThemeMimeTypes.cs b/src/Lumina.Infrastructure/Core/Themes/ThemeMimeTypes.cs index 12b00303..7ea04b74 100644 --- a/src/Lumina.Infrastructure/Core/Themes/ThemeMimeTypes.cs +++ b/src/Lumina.Infrastructure/Core/Themes/ThemeMimeTypes.cs @@ -1,5 +1,6 @@ #region ========================================================================= USING ===================================================================================== using System; +using System.Collections.Frozen; using System.Collections.Generic; using System.IO; #endregion @@ -11,25 +12,25 @@ namespace Lumina.Infrastructure.Core.Themes; /// internal static class ThemeMimeTypes { - private static readonly Dictionary s_mimeByExtension = new(StringComparer.OrdinalIgnoreCase) + private static readonly FrozenDictionary s_fileExtensionToMimeType = new Dictionary { - [".htm"] = "text/html", - [".html"] = "text/html", - [".css"] = "text/css", - [".js"] = "application/javascript", - [".json"] = "application/json", - [".png"] = "image/png", - [".jpg"] = "image/jpeg", - [".jpeg"] = "image/jpeg", - [".gif"] = "image/gif", - [".webp"] = "image/webp", - [".svg"] = "image/svg+xml", - [".ico"] = "image/x-icon", - [".woff"] = "font/woff", - [".woff2"] = "font/woff2", - [".ttf"] = "font/ttf", - [".txt"] = "text/plain" - }; + { ".htm", "text/html" }, + { ".html", "text/html" }, + { ".css", "text/css" }, + { ".js", "application/javascript" }, + { ".json", "application/json" }, + { ".png", "image/png" }, + { ".jpg", "image/jpeg" }, + { ".jpeg", "image/jpeg" }, + { ".gif", "image/gif" }, + { ".webp", "image/webp" }, + { ".svg", "image/svg+xml" }, + { ".ico", "image/x-icon" }, + { ".woff", "font/woff" }, + { ".woff2", "font/woff2" }, + { ".ttf", "font/ttf" }, + { ".txt", "text/plain" } + }.ToFrozenDictionary(StringComparer.OrdinalIgnoreCase); /// /// Gets the MIME content type of a file based on its extension. @@ -38,6 +39,6 @@ internal static class ThemeMimeTypes /// The MIME content type, or application/octet-stream when the extension is unknown. public static string GetMimeType(string filePath) { - return s_mimeByExtension.TryGetValue(Path.GetExtension(filePath), out string? mimeType) ? mimeType : "application/octet-stream"; + return s_fileExtensionToMimeType.TryGetValue(Path.GetExtension(filePath), out string? mimeType) ? mimeType : "application/octet-stream"; } } diff --git a/src/Lumina.Infrastructure/Lumina.Infrastructure.csproj b/src/Lumina.Infrastructure/Lumina.Infrastructure.csproj index 1ffd9bd4..68c0bb03 100644 --- a/src/Lumina.Infrastructure/Lumina.Infrastructure.csproj +++ b/src/Lumina.Infrastructure/Lumina.Infrastructure.csproj @@ -26,6 +26,7 @@ + diff --git a/src/Lumina.Infrastructure/appsettings.shared.json b/src/Lumina.Infrastructure/appsettings.shared.json index dfeb872c..59f643fd 100644 --- a/src/Lumina.Infrastructure/appsettings.shared.json +++ b/src/Lumina.Infrastructure/appsettings.shared.json @@ -17,6 +17,15 @@ "MaxSingleFileBytes": 6291456, "MaxEntries": 250 }, + "TranscodingSettings": { + "FfmpegPath": "ffmpeg", + "MaxConcurrentJobs": 2, + "MaxConcurrentJobsPerUser": 1, + "MaxCacheBytes": 2147483648, + "JobTimeoutSeconds": 900, + "EvictionGraceSeconds": 120, + "CacheDirectory": null + }, "ConnectionStrings": { "DefaultConnection": "Server=;Database=;User Id=;Password=;" }, diff --git a/src/Lumina.Plugins.Contracts/Core/Plugins/IPluginSettingsStore.cs b/src/Lumina.Plugins.Contracts/Core/Plugins/IPluginSettingsStore.cs index e3b6dac2..dc6e9213 100644 --- a/src/Lumina.Plugins.Contracts/Core/Plugins/IPluginSettingsStore.cs +++ b/src/Lumina.Plugins.Contracts/Core/Plugins/IPluginSettingsStore.cs @@ -16,7 +16,7 @@ public interface IPluginSettingsStore /// Gets the settings persisted by the host for the plugin identified by . /// /// The unique identifier of the plugin whose settings are read. - /// Cancellation token that can be used to cancel the operation. + /// Cancellation token that can be used to stop the execution. /// The persisted settings keyed by setting key, or when no settings were persisted for the plugin. Task?> GetSettingsAsync(Guid pluginId, CancellationToken cancellationToken); } diff --git a/src/Lumina.Presentation.Api/Common/DependencyInjection/PresentationApiLayerServices.cs b/src/Lumina.Presentation.Api/Common/DependencyInjection/PresentationApiLayerServices.cs index b5a4de98..7a8823db 100644 --- a/src/Lumina.Presentation.Api/Common/DependencyInjection/PresentationApiLayerServices.cs +++ b/src/Lumina.Presentation.Api/Common/DependencyInjection/PresentationApiLayerServices.cs @@ -17,6 +17,7 @@ using Microsoft.IdentityModel.Tokens; using System; using System.Diagnostics.CodeAnalysis; using System.Linq; +using System.Security.Claims; using System.Text; using System.Text.Json.Serialization; using System.Threading.RateLimiting; @@ -31,6 +32,9 @@ namespace Lumina.Presentation.Api.Common.DependencyInjection; [ExcludeFromCodeCoverage] public static class PresentationApiLayerServices { + public const string AUTHENTICATION_RATE_LIMIT_POLICY = "authenticationPolicy"; + public const string TRACK_STREAM_RATE_LIMIT_POLICY = "trackStreamPolicy"; + /// /// Registers the services of the Presentation Api layer into the Dependency Injection container. /// @@ -94,7 +98,7 @@ public static class PresentationApiLayerServices await onRejectedContext.HttpContext.Response.WriteAsJsonAsync(problem, cancellationToken); }; - rateLimiterOptions.AddPolicy("authenticationPolicy", httpContext => + rateLimiterOptions.AddPolicy(AUTHENTICATION_RATE_LIMIT_POLICY, httpContext => { string clientIp = httpContext.Request.Headers["X-Forwarded-For"] // First check forwarded headers, in case this is behind a reverse proxy. .FirstOrDefault()?.Split(',')[0].Trim() // Take first IP, if multiple available, to avoid IP spoofing attempts, @@ -110,6 +114,20 @@ public static class PresentationApiLayerServices AutoReplenishment = true // Automatically reset rate limiter tokens. }); }); + rateLimiterOptions.AddPolicy(TRACK_STREAM_RATE_LIMIT_POLICY, httpContext => + { + // The track stream is limited per user, so that a single user cannot hold an unbounded number of long lived audio streams open at once. + // This is deliberately not the login policy: it is a concurrency limit, partitioned per authenticated user, not a per IP attempt window. + string userId = httpContext.User.FindFirst(ClaimTypes.NameIdentifier)?.Value ?? "anonymous"; + return RateLimitPartition.GetConcurrencyLimiter( + partitionKey: $"trackStream_{userId}", + factory: _ => new ConcurrencyLimiterOptions + { + PermitLimit = 4, // Allow 4 concurrent audio streams per user. + QueueLimit = 0, // Don't queue requests, a request beyond the limit is rejected instead of waiting. + QueueProcessingOrder = QueueProcessingOrder.OldestFirst + }); + }); }); // Add authentication and specify the JWT scheme to check tokens against. diff --git a/src/Lumina.Presentation.Api/Common/HealthChecks/DatabaseHealthCheck.cs b/src/Lumina.Presentation.Api/Common/HealthChecks/DatabaseHealthCheck.cs index 9ff53c7d..8f2c1a6a 100644 --- a/src/Lumina.Presentation.Api/Common/HealthChecks/DatabaseHealthCheck.cs +++ b/src/Lumina.Presentation.Api/Common/HealthChecks/DatabaseHealthCheck.cs @@ -29,7 +29,7 @@ public class DatabaseHealthCheck : IHealthCheck /// Checks whether the database can be reached. /// /// The health check context. - /// Token to monitor for cancellation requests. + /// Cancellation token that can be used to stop the execution. /// A task that represents the asynchronous operation, containing the health check result. public virtual async Task CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken) { diff --git a/src/Lumina.Presentation.Api/Common/Http/SkipEventualConsistencyMetadata.cs b/src/Lumina.Presentation.Api/Common/Http/SkipEventualConsistencyMetadata.cs new file mode 100644 index 00000000..ba878a82 --- /dev/null +++ b/src/Lumina.Presentation.Api/Common/Http/SkipEventualConsistencyMetadata.cs @@ -0,0 +1,8 @@ +namespace Lumina.Presentation.Api.Common.Http; + +/// +/// Marker metadata that opts an endpoint out of the eventual consistency pipeline, so that a long lived response (for example a track stream) never holds the request's database transaction open. +/// +public sealed class SkipEventualConsistencyMetadata +{ +} diff --git a/src/Lumina.Presentation.Api/Common/Middlewares/EventualConsistencyMiddleware.cs b/src/Lumina.Presentation.Api/Common/Middlewares/EventualConsistencyMiddleware.cs index 7f16b977..9d04b5a3 100644 --- a/src/Lumina.Presentation.Api/Common/Middlewares/EventualConsistencyMiddleware.cs +++ b/src/Lumina.Presentation.Api/Common/Middlewares/EventualConsistencyMiddleware.cs @@ -1,18 +1,20 @@ #region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.UoW; using Lumina.Application.Common.DomainEvents; -using Lumina.DataAccess.Core.UoW; using Lumina.Domain.Common.Events; using Lumina.Domain.Common.Exceptions; +using Lumina.Presentation.Api.Common.Http; using Microsoft.AspNetCore.Http; -using Microsoft.EntityFrameworkCore.Storage; using Microsoft.Extensions.Logging; +using System; +using System.Threading; using System.Threading.Tasks; #endregion namespace Lumina.Presentation.Api.Common.Middlewares; /// -/// Middleware that ensures eventual consistency by handling domain events and publishing them after the request has completed successfully. +/// Middleware that owns the request transaction, committing it and publishing the queued domain events after a successful request, and rolling it back otherwise. /// public class EventualConsistencyMiddleware { @@ -35,28 +37,39 @@ public class EventualConsistencyMiddleware /// /// The current HTTP context. /// The domain event publisher used to publish events. - /// The database context used to manage the transaction. + /// Injected unit of work that owns the request transaction. /// In memory queue containing the queued domain events. - public async Task InvokeAsync(HttpContext context, IDomainEventPublisher domainEventPublisher, LuminaDbContext dbContext, IDomainEventsQueue domainEventQueue) + public async Task InvokeAsync(HttpContext context, IDomainEventPublisher domainEventPublisher, IUnitOfWork unitOfWork, IDomainEventsQueue domainEventQueue) { - // begin a new database transaction - this will wrap any database operations performed during this HTTP request in an atomic operation - IDbContextTransaction transaction = await dbContext.Database.BeginTransactionAsync(context.RequestAborted).ConfigureAwait(false); - // register an action to be executed once the response is completed (the user already received a response for the request) + // Endpoints that serve long lived responses (for example a track stream) opt out through endpoint metadata, so that their response never + // holds the request's database transaction open; the opt out is metadata based, so it follows the endpoint even when its route changes. + if (context.GetEndpoint()?.Metadata.GetMetadata() is not null) + { + await _next(context).ConfigureAwait(false); + return; + } + + // Begin a new database transaction - this will wrap any database operations performed during this HTTP request in an atomic operation. + await unitOfWork.BeginTransactionAsync(context.RequestAborted).ConfigureAwait(false); + // Register an action to be executed once the response is completed (the user already received a response for the request). context.Response.OnCompleted(async () => { try { - // only proceed if the response status code indicates success + // Only proceed if the response status code indicates success. The request abort token is deliberately not consulted here: + // it can already be cancelled when the callback runs, even though the operation completed successfully, and refusing to + // commit then would discard a write whose success response was already sent. An aborted request is instead reported as a + // non-success status by the exception handling middleware. if (context.Response.StatusCode >= 200 && context.Response.StatusCode < 300) { - // commit the transaction: because some domain events trigger jobs that end up being processed in background hosted services, and those are + // Commit the transaction: because some domain events trigger jobs that end up being processed in background hosted services, and those are // singletons that require their own DI scope to be created, any changes made on the DbContext in this HTTP scope would not be seen on the // DbContext created in the background service scope, because the transaction is not yet committed here; therefor, the transaction needs to be - // committed first, before any domain events are fired - // see docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0002.md for details: - await transaction.CommitAsync().ConfigureAwait(false); + // committed first, before any domain events are fired. + // See docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0002.md for details: + await unitOfWork.CommitTransactionAsync(CancellationToken.None).ConfigureAwait(false); - // check if domain events exist in the channel queue and publish them + // Check if domain events exist in the channel queue and publish them. while (domainEventQueue.TryDequeue(out IDomainEvent? nextEvent)) await domainEventPublisher.PublishAsync(nextEvent); } @@ -65,10 +78,23 @@ public class EventualConsistencyMiddleware { _logger.LogCritical(ex, "Failed to perform eventual consistency"); } + catch (Exception ex) // The response is already complete, so this failure cannot reach the client. It is logged, and the transaction is still closed by the rollback below. + { + _logger.LogError(ex, "Failed to complete the request transaction for {Path}", context.Request.Path); + } finally { - // DisposeAsync automatically roles back any changes, if a call to CommitAsync was not performed prior - await transaction.DisposeAsync().ConfigureAwait(false); + // A commit or a rollback clears the transaction, so this only closes one that the failure above left open. It runs for + // every response, including the non-success one that never attempted a commit. Rollback must never throw out of the + // completion callback, and must never mask the failure that is already being handled. + try + { + await unitOfWork.RollbackTransactionAsync(CancellationToken.None).ConfigureAwait(false); + } + catch (Exception ex) + { + _logger.LogError(ex, "Failed to roll back the request transaction for {Path}", context.Request.Path); + } } }); await _next(context).ConfigureAwait(false); diff --git a/src/Lumina.Presentation.Api/Common/Middlewares/ExceptionHandlingMiddleware.cs b/src/Lumina.Presentation.Api/Common/Middlewares/ExceptionHandlingMiddleware.cs index d24f2e22..ec7ac12a 100644 --- a/src/Lumina.Presentation.Api/Common/Middlewares/ExceptionHandlingMiddleware.cs +++ b/src/Lumina.Presentation.Api/Common/Middlewares/ExceptionHandlingMiddleware.cs @@ -41,12 +41,16 @@ public class ExceptionHandlingMiddleware } catch (OperationCanceledException) { - // the request was aborted, so there is no client left to write a response to + // The request was aborted, so there is no client left to write a response to. The status is still set to a non-success value, + // because the eventual consistency middleware decides whether to commit from it, and the writes of an aborted request must be + // rolled back instead of being reported as a success. + if (!context.Response.HasStarted) + context.Response.StatusCode = StatusCodes.Status499ClientClosedRequest; throw; } catch (Exception ex) { - // once the response has started, it is no longer possible to replace it with a ProblemDetails response + // Once the response has started, it is no longer possible to replace it with a ProblemDetails response. if (context.Response.HasStarted) throw; _logger.LogError(ex, "Unhandled exception occurred while processing request {Method} {Path}", context.Request.Method, context.Request.Path); diff --git a/src/Lumina.Presentation.Api/Common/Utilities/MimeTypes.cs b/src/Lumina.Presentation.Api/Common/MimeTypes/ImageMimeTypes.cs similarity index 90% rename from src/Lumina.Presentation.Api/Common/Utilities/MimeTypes.cs rename to src/Lumina.Presentation.Api/Common/MimeTypes/ImageMimeTypes.cs index c68cee65..af1205a5 100644 --- a/src/Lumina.Presentation.Api/Common/Utilities/MimeTypes.cs +++ b/src/Lumina.Presentation.Api/Common/MimeTypes/ImageMimeTypes.cs @@ -4,12 +4,12 @@ using System.Collections.Frozen; using System.Collections.Generic; #endregion -namespace Lumina.Presentation.Api.Common.Utilities; +namespace Lumina.Presentation.Api.Common.MimeTypes; /// -/// Utility class for converting from domain image types to known image mime types. +/// Resolves the MIME content type of image types. /// -public static class MimeTypes +public static class ImageMimeTypes { private static readonly FrozenDictionary s_imageTypeToMimeType = new Dictionary { diff --git a/src/Lumina.Presentation.Api/Common/MimeTypes/MusicMimeTypes.cs b/src/Lumina.Presentation.Api/Common/MimeTypes/MusicMimeTypes.cs new file mode 100644 index 00000000..50cbda20 --- /dev/null +++ b/src/Lumina.Presentation.Api/Common/MimeTypes/MusicMimeTypes.cs @@ -0,0 +1,68 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; +using System; +using System.Collections.Frozen; +using System.Collections.Generic; +#endregion + +namespace Lumina.Presentation.Api.Common.MimeTypes; + +/// +/// Resolves the MIME content type of audio file formats. +/// +public static class MusicMimeTypes +{ + private static readonly FrozenDictionary s_audioFileFormatToMimeType = new Dictionary + { + { AudioFileFormat.MP3, "audio/mpeg" }, + { AudioFileFormat.FLAC, "audio/flac" }, + { AudioFileFormat.M4A, "audio/mp4" }, + { AudioFileFormat.AAC, "audio/aac" }, + { AudioFileFormat.OGG, "audio/ogg" }, + { AudioFileFormat.OPUS, "audio/ogg" }, + { AudioFileFormat.WAV, "audio/wav" }, + { AudioFileFormat.WMA, "audio/x-ms-wma" }, + { AudioFileFormat.AIFF, "audio/aiff" }, + { AudioFileFormat.APE, "audio/x-ape" }, + { AudioFileFormat.WAVPACK, "audio/x-wavpack" }, + { AudioFileFormat.DSF, "audio/x-dsf" }, + { AudioFileFormat.DFF, "audio/x-dff" }, + { AudioFileFormat.MATROSKA, "audio/x-matroska" } + }.ToFrozenDictionary(); + + // Container names are mapped to the file format enumeration instead of to their own media type strings, so the media type table above stays the + // single source of truth and a new format only needs one entry. + private static readonly FrozenDictionary s_containerToAudioFileFormat = new Dictionary(StringComparer.OrdinalIgnoreCase) + { + { "MP3", AudioFileFormat.MP3 }, + { "FLAC", AudioFileFormat.FLAC }, + { "MP4", AudioFileFormat.M4A }, + { "M4A", AudioFileFormat.M4A }, + { "AAC", AudioFileFormat.AAC }, + { "OGG", AudioFileFormat.OGG }, + { "OPUS", AudioFileFormat.OPUS }, + { "WAV", AudioFileFormat.WAV } + }.ToFrozenDictionary(StringComparer.OrdinalIgnoreCase); + + /// + /// Gets the MIME content type of . + /// + /// The audio file format for which to get the MIME content type. + /// The MIME content type of , or application/octet-stream when the format is unknown. + public static string GetMimeType(AudioFileFormat format) + { + return s_audioFileFormatToMimeType.TryGetValue(format, out string? mimeType) ? mimeType : "application/octet-stream"; + } + + /// + /// Gets the MIME content type of an audio container, as named by the delivery decision of a playback manifest. + /// + /// The canonical container of the delivered audio, for example MP4, AAC, OGG, MP3, FLAC or WAV. + /// The MIME content type of , or application/octet-stream when the container is unknown. + public static string GetContainerMimeType(string? container) + { + return !string.IsNullOrWhiteSpace(container) && s_containerToAudioFileFormat.TryGetValue(container.Trim(), out AudioFileFormat format) + ? GetMimeType(format) + : "application/octet-stream"; + } +} diff --git a/src/Lumina.Presentation.Api/Common/Routes/Favorites/ApiRoutes.Favorites.cs b/src/Lumina.Presentation.Api/Common/Routes/Favorites/ApiRoutes.Favorites.cs new file mode 100644 index 00000000..4b4c95f3 --- /dev/null +++ b/src/Lumina.Presentation.Api/Common/Routes/Favorites/ApiRoutes.Favorites.cs @@ -0,0 +1,18 @@ +namespace Lumina.Presentation.Api.Common.Routes.Favorites; + +/// +/// Class for the collection of the favorite routes of the API. +/// +public static partial class ApiRoutes +{ + /// + /// Routes for the favorites of the current user. + /// + 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"; + } +} diff --git a/src/Lumina.Presentation.Api/Common/Routes/Library/AudioLibrary/MusicLibrary/ApiRoutes.Tracks.cs b/src/Lumina.Presentation.Api/Common/Routes/Library/AudioLibrary/MusicLibrary/ApiRoutes.Tracks.cs index b17a5043..a61fb46c 100644 --- a/src/Lumina.Presentation.Api/Common/Routes/Library/AudioLibrary/MusicLibrary/ApiRoutes.Tracks.cs +++ b/src/Lumina.Presentation.Api/Common/Routes/Library/AudioLibrary/MusicLibrary/ApiRoutes.Tracks.cs @@ -12,7 +12,11 @@ public static partial class ApiRoutes { public const string ADD_TRACK = "/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks"; public const string GET_TRACK_BY_ID = "/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}"; + public const string SHUFFLE_TRACKS = "/libraries/{libraryId}/tracks/shuffle"; public const string UPDATE_TRACK = "/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}"; public const string DELETE_TRACK = "/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}"; + public const string STREAM_TRACK = "/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}/stream"; + public const string STREAM_TRACK_SEGMENT = "/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}/stream/deliveries/{deliveryId}/segments/{segmentIndex}"; + public const string GET_PLAYBACK_MANIFEST = "/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}/playback-manifest"; } } diff --git a/src/Lumina.Presentation.Api/Common/Routes/Library/Statistics/ApiRoutes.LibraryStatistics.cs b/src/Lumina.Presentation.Api/Common/Routes/Library/Statistics/ApiRoutes.LibraryStatistics.cs new file mode 100644 index 00000000..2eb93dc2 --- /dev/null +++ b/src/Lumina.Presentation.Api/Common/Routes/Library/Statistics/ApiRoutes.LibraryStatistics.cs @@ -0,0 +1,33 @@ +namespace Lumina.Presentation.Api.Common.Routes.Library.Statistics; + +/// +/// Class for the collection of the library statistics routes of the API. +/// +public static partial class ApiRoutes +{ + /// + /// Routes for the consumption history, consumption statistics, and resume points of the current user, of another user, and of every user. + /// + public static class LibraryStatistics + { + public const string GET_RECENTLY_CONSUMED = "/users/me/consumption-history/recently-consumed"; + public const string GET_MOST_CONSUMED = "/users/me/consumption-history/most-consumed"; + public const string GET_CONSUMPTION_STATISTICS = "/users/me/consumption-statistics"; + public const string GET_TAG_CONSUMPTION = "/users/me/consumption-statistics/tags"; + public const string GET_GENRE_CONSUMPTION = "/users/me/consumption-statistics/genres"; + public const string GET_USER_RECENTLY_CONSUMED = "/users/{userId}/consumption-history/recently-consumed"; + public const string GET_USER_MOST_CONSUMED = "/users/{userId}/consumption-history/most-consumed"; + public const string GET_USER_CONSUMPTION_STATISTICS = "/users/{userId}/consumption-statistics"; + public const string GET_USER_TAG_CONSUMPTION = "/users/{userId}/consumption-statistics/tags"; + public const string GET_USER_GENRE_CONSUMPTION = "/users/{userId}/consumption-statistics/genres"; + public const string GET_ALL_USERS_CONSUMPTION_STATISTICS = "/users/consumption-statistics"; + public const string DELETE_CONSUMPTION_RECORD = "/users/me/consumption-history/{recordId}"; + public const string DELETE_USER_CONSUMPTION_RECORD = "/users/{userId}/consumption-history/{recordId}"; + public const string DELETE_CONSUMPTION_ITEM_HISTORY = "/users/me/consumption-history/media-items/{mediaKind}/{mediaItemId}/{libraryId}"; + public const string DELETE_USER_CONSUMPTION_ITEM_HISTORY = "/users/{userId}/consumption-history/media-items/{mediaKind}/{mediaItemId}/{libraryId}"; + public const string CLEAR_CONSUMPTION_HISTORY = "/users/me/consumption-history"; + public const string CLEAR_USER_CONSUMPTION_HISTORY = "/users/{userId}/consumption-history"; + public const string CLEAR_RESUME_POINTS = "/users/me/media-resume-points"; + public const string CLEAR_USER_RESUME_POINTS = "/users/{userId}/media-resume-points"; + } +} diff --git a/src/Lumina.Presentation.Api/Common/Routes/MediaConsumption/ApiRoutes.MediaConsumption.cs b/src/Lumina.Presentation.Api/Common/Routes/MediaConsumption/ApiRoutes.MediaConsumption.cs new file mode 100644 index 00000000..980e4eaa --- /dev/null +++ b/src/Lumina.Presentation.Api/Common/Routes/MediaConsumption/ApiRoutes.MediaConsumption.cs @@ -0,0 +1,20 @@ +namespace Lumina.Presentation.Api.Common.Routes.MediaConsumption; + +/// +/// Class for the collection of the media consumption routes of the API. +/// +public static partial class ApiRoutes +{ + /// + /// Routes for the media consumption lifecycle, records, and resume points of the current user. + /// + public static class MediaConsumption + { + public const string START_CONSUMPTION = "/libraries/{libraryId}/media-items/{mediaKind}/{mediaItemId}/consumption-records"; + public const string GET_CONSUMPTION_RECORD = "/users/me/consumption-records/{recordId}"; + public const string REPORT_CONSUMPTION_PROGRESS = "/users/me/consumption-records/{recordId}/progress"; + public const string COMPLETE_CONSUMPTION = "/users/me/consumption-records/{recordId}/complete"; + public const string STOP_CONSUMPTION = "/users/me/consumption-records/{recordId}/stop"; + public const string GET_RESUME_POINT = "/users/me/media-resume-points/{mediaKind}/{mediaItemId}"; + } +} diff --git a/src/Lumina.Presentation.Api/Common/Routes/Playlists/ApiRoutes.Playlists.cs b/src/Lumina.Presentation.Api/Common/Routes/Playlists/ApiRoutes.Playlists.cs new file mode 100644 index 00000000..6c26c625 --- /dev/null +++ b/src/Lumina.Presentation.Api/Common/Routes/Playlists/ApiRoutes.Playlists.cs @@ -0,0 +1,24 @@ +namespace Lumina.Presentation.Api.Common.Routes.Playlists; + +/// +/// Class for the collection of the playlist routes of the API. +/// +public static partial class ApiRoutes +{ + /// + /// Routes for the playlists of the current user. + /// + public static class Playlists + { + public const string GET_PLAYLISTS = "/users/me/playlists"; + public const string CREATE_PLAYLIST = "/users/me/playlists"; + public const string GET_PLAYLIST = "/users/me/playlists/{playlistId}"; + public const string UPDATE_PLAYLIST = "/users/me/playlists/{playlistId}"; + public const string DELETE_PLAYLIST = "/users/me/playlists/{playlistId}"; + public const string ADD_PLAYLIST_ENTRY = "/users/me/playlists/{playlistId}/entries"; + public const string ADD_PLAYLIST_ENTRIES = "/users/me/playlists/{playlistId}/entries-batch"; + public const string ADD_PLAYLIST_SCOPE_ENTRIES = "/users/me/playlists/{playlistId}/entries-scope"; + public const string REMOVE_PLAYLIST_ENTRY = "/users/me/playlists/{playlistId}/entries/{playlistEntryId}"; + public const string MOVE_PLAYLIST_ENTRY = "/users/me/playlists/{playlistId}/entries/{playlistEntryId}/move"; + } +} diff --git a/src/Lumina.Presentation.Api/Common/Routes/UsersManagement/ApiRoutes.Users.cs b/src/Lumina.Presentation.Api/Common/Routes/UsersManagement/ApiRoutes.Users.cs index 1be6e11b..3a24a202 100644 --- a/src/Lumina.Presentation.Api/Common/Routes/UsersManagement/ApiRoutes.Users.cs +++ b/src/Lumina.Presentation.Api/Common/Routes/UsersManagement/ApiRoutes.Users.cs @@ -13,5 +13,7 @@ public static partial class ApiRoutes public const string GET_USER_BY_ID = "/users/{id}"; public const string GET_USER_SETTINGS = "/users/me/settings"; // uses "me" because it is always for the currently authenticated user public const string UPDATE_USER_SETTINGS = "/users/me/settings"; + public const string GET_PLAYBACK_STATE = "/users/me/settings/playback-state"; + public const string UPDATE_PLAYBACK_STATE = "/users/me/settings/playback-state"; } } diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Admin/Authorization/Roles/GetRoles/GetRolesEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Admin/Authorization/Roles/GetRoles/GetRolesEndpointSummary.cs index 54b5b52d..2fbfc6de 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Admin/Authorization/Roles/GetRoles/GetRolesEndpointSummary.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Admin/Authorization/Roles/GetRoles/GetRolesEndpointSummary.cs @@ -1,5 +1,6 @@ #region ========================================================================= USING ===================================================================================== using FastEndpoints; +using Lumina.Application.Common.Infrastructure.Authorization; using Lumina.Contracts.Responses.Authorization; using System; using System.Diagnostics.CodeAnalysis; @@ -23,7 +24,7 @@ public class GetRolesEndpointSummary : Summary Response(200, "The authorization roles are returned.", example: new[] { - new RoleResponse(Id: Guid.NewGuid(), "Admin") + new RoleResponse(Id: Guid.NewGuid(), AuthorizationRoles.ADMIN) }); Response(401, "Authentication required.", "application/problem+json", diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Common/BaseEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Common/BaseEndpoint.cs index 2074be09..fb6404fb 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Common/BaseEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Common/BaseEndpoint.cs @@ -45,16 +45,20 @@ public abstract class BaseEndpoint : Endpoint extensionsDictionary = []; - int statusCode = error.Type switch - { - ErrorType.Validation => StatusCodes.Status400BadRequest, - ErrorType.Unauthorized => StatusCodes.Status403Forbidden, // DO NOT return Status401Unauthorized, that actually means lack of valid authentication credentials (not logged in) - ErrorType.Failure => StatusCodes.Status403Forbidden, - ErrorType.Forbidden => StatusCodes.Status403Forbidden, - ErrorType.NotFound => StatusCodes.Status404NotFound, - ErrorType.Conflict => StatusCodes.Status409Conflict, - _ => StatusCodes.Status500InternalServerError, - }; + // A resource that is temporarily unavailable is a transient condition of the server, not an unexpected failure, so it is reported as + // unavailable rather than as an internal error. A client can retry it, and the playback player does. + int statusCode = error is ResourceUnavailableError + ? StatusCodes.Status503ServiceUnavailable + : error.Type switch + { + ErrorType.Validation => StatusCodes.Status400BadRequest, + ErrorType.Unauthorized => StatusCodes.Status403Forbidden, // DO NOT return Status401Unauthorized, that actually means lack of valid authentication credentials (not logged in) + ErrorType.Failure => StatusCodes.Status403Forbidden, + ErrorType.Forbidden => StatusCodes.Status403Forbidden, + ErrorType.NotFound => StatusCodes.Status404NotFound, + ErrorType.Conflict => StatusCodes.Status409Conflict, + _ => StatusCodes.Status500InternalServerError, + }; extensionsDictionary["traceId"] = Activity.Current?.Id ?? HttpContext.TraceIdentifier; @@ -79,15 +83,11 @@ public abstract class BaseEndpoint : Endpoint +/// A response result that writes an owned stream to the response without buffering it and releases the stream once the response is complete. +/// +/// +/// The result owns the stream, so a lease protected resource that is served through it is always released, including when the client disconnects +/// before the whole content was written. Unlike a result built from bytes, it never materializes the content in memory. +/// +public sealed class DisposingStreamResult : IResult +{ + private readonly Stream _content; + private readonly string _contentType; + private readonly long? _contentLength; + + /// + /// Initializes a new instance of the class. + /// + /// The stream to write, which this result owns and releases after the response is complete. + /// The media type of the content. + /// The length of the content, in bytes, or when it is not known in advance. + public DisposingStreamResult(Stream content, string contentType, long? contentLength) + { + _content = content; + _contentType = contentType; + _contentLength = contentLength; + } + + /// + /// Writes the content stream to the response. + /// + /// The HTTP context of the request being answered. + public async Task ExecuteAsync(HttpContext httpContext) + { + if (_contentLength.HasValue) + httpContext.Response.ContentLength = _contentLength.Value; + httpContext.Response.ContentType = _contentType; + await using (_content) + await _content.CopyToAsync(httpContext.Response.Body, httpContext.RequestAborted).ConfigureAwait(false); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Favorites/AddFavorite/AddFavoriteEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Favorites/AddFavorite/AddFavoriteEndpoint.cs new file mode 100644 index 00000000..c73555ea --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Favorites/AddFavorite/AddFavoriteEndpoint.cs @@ -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; + +/// +/// API endpoint for the /users/me/favorites route, for adding a favorite. +/// +/// +/// Uses "me" because it is always for the currently authenticated user. +/// +public class AddFavoriteEndpoint : BaseEndpoint +{ + private readonly ICommandHandler> _addFavoriteCommandHandler; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for handling add favorite commands. + public AddFavoriteEndpoint(ICommandHandler> addFavoriteCommandHandler) + { + _addFavoriteCommandHandler = addFavoriteCommandHandler; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(FastEndpoints.Http.POST); + Routes(ApiRoutes.Favorites.ADD_FAVORITE); + Version(1); + DontCatchExceptions(); + } + + /// + /// Marks a media item as a favorite of the current user. + /// + /// The request containing the kind and the Id of the media item to favorite. + /// Cancellation token that can be used to stop the execution. + public override async Task 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 result = await _addFavoriteCommandHandler.HandleAsync(request.ToCommand(), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Ok(success), Problem); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Favorites/AddFavorite/AddFavoriteEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Favorites/AddFavorite/AddFavoriteEndpointSummary.cs new file mode 100644 index 00000000..0acb9aa3 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Favorites/AddFavorite/AddFavoriteEndpointSummary.cs @@ -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; + +/// +/// Class used for providing a textual description for the API endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class AddFavoriteEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + 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(response => response.Id, "The Id of the favorite."); + ResponseParam(response => response.MediaKind, "The kind of the favorited media item."); + ResponseParam(response => response.MediaItemId, "The Id of the favorited media item."); + ResponseParam(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 + { + { + "General.Validation", new[] + { + "FavoriteMediaKindIsInvalid", + "FavoriteMediaItemIdCannotBeEmpty", + "FavoriteMediaKindIsNotSupported" + } + } + }, + traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00" + } + ); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Favorites/GetFavoriteStatus/GetFavoriteStatusEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Favorites/GetFavoriteStatus/GetFavoriteStatusEndpoint.cs new file mode 100644 index 00000000..1f719ac1 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Favorites/GetFavoriteStatus/GetFavoriteStatusEndpoint.cs @@ -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; + +/// +/// API endpoint for the /users/me/favorites/status route. +/// +/// +/// Uses "me" because it is always for the currently authenticated user. +/// +public class GetFavoriteStatusEndpoint : BaseEndpoint +{ + private readonly IQueryHandler> _getFavoriteStatusQueryHandler; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for handling get favorite status queries. + public GetFavoriteStatusEndpoint(IQueryHandler> getFavoriteStatusQueryHandler) + { + _getFavoriteStatusQueryHandler = getFavoriteStatusQueryHandler; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(FastEndpoints.Http.GET); + Routes(ApiRoutes.Favorites.GET_FAVORITE_STATUS); + Version(1); + DontCatchExceptions(); + } + + /// + /// Finds out which media items of one kind are favorites of the current user. + /// + /// The request containing the media kind and the Ids of the media items to check. + /// Cancellation token that can be used to stop the execution. + public override async Task 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 result = await _getFavoriteStatusQueryHandler.HandleAsync(request.ToQuery(), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Ok(success), Problem); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Favorites/GetFavoriteStatus/GetFavoriteStatusEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Favorites/GetFavoriteStatus/GetFavoriteStatusEndpointSummary.cs new file mode 100644 index 00000000..32d3bb79 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Favorites/GetFavoriteStatus/GetFavoriteStatusEndpointSummary.cs @@ -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; + +/// +/// Class used for providing a textual description for the API endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class GetFavoriteStatusEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + 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(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 + { + { + "General.Validation", new[] + { + "FavoriteMediaKindIsInvalid", + "FavoriteMediaItemIdsCannotBeEmpty", + "FavoriteMediaItemIdsExceedMaximumCount", + "FavoriteMediaItemIdCannotBeEmpty" + } + } + }, + traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00" + } + ); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Favorites/GetFavorites/GetFavoritesEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Favorites/GetFavorites/GetFavoritesEndpoint.cs new file mode 100644 index 00000000..23c60218 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Favorites/GetFavorites/GetFavoritesEndpoint.cs @@ -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; + +/// +/// API endpoint for the /users/me/favorites route, for getting the favorites. +/// +/// +/// Uses "me" because it is always for the currently authenticated user. +/// +public class GetFavoritesEndpoint : BaseEndpoint +{ + private readonly IQueryHandler>> _getFavoritesQueryHandler; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for handling get favorites queries. + public GetFavoritesEndpoint(IQueryHandler>> getFavoritesQueryHandler) + { + _getFavoritesQueryHandler = getFavoritesQueryHandler; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(FastEndpoints.Http.GET); + Routes(ApiRoutes.Favorites.GET_FAVORITES); + Version(1); + DontCatchExceptions(); + } + + /// + /// Gets a page of the favorites of the current user. + /// + /// The request containing the optional media kind filter and the page bounds. + /// Cancellation token that can be used to stop the execution. + public override async Task 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> result = await _getFavoritesQueryHandler.HandleAsync(request.ToQuery(), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Ok(success), Problem); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Favorites/GetFavorites/GetFavoritesEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Favorites/GetFavorites/GetFavoritesEndpointSummary.cs new file mode 100644 index 00000000..34ebcc92 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Favorites/GetFavorites/GetFavoritesEndpointSummary.cs @@ -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; + +/// +/// Class used for providing a textual description for the API endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class GetFavoritesEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + 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>(response => response.Data, "The favorites of the requested page, from the most recently favorited."); + ResponseParam>(response => response.CurrentPage, "The current page number."); + ResponseParam>(response => response.PerPage, "The number of favorites retrieved per page."); + ResponseParam>(response => response.Count, "The total number of favorites that match the filter."); + ResponseParam>(response => response.NumberOfPages, "The total number of pages."); + + ResponseParam(response => response.MediaKind, "The kind of the favorited media item."); + ResponseParam(response => response.MediaItemId, "The Id of the favorited media item."); + ResponseParam(response => response.IsAvailable, "Whether the media item still exists and its library is accessible to the current user."); + ResponseParam(response => response.LibraryId, "The Id of the media library that contains the media item."); + ResponseParam(response => response.Title, "The title of the media item."); + ResponseParam(response => response.CollectionId, "The Id of the collection that contains the media item, or the empty Guid when there is none."); + ResponseParam(response => response.CollectionTitle, "The title of the collection that contains the media item, or an empty string when there is none."); + ResponseParam(response => response.CreatorId, "The Id of the creator of the media item, or the empty Guid when there is none."); + ResponseParam(response => response.CreatorName, "The name of the creator of the media item, or an empty string when there is none."); + ResponseParam(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 + { + 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 + { + { + "General.Validation", new[] + { + "FavoriteMediaKindIsInvalid" + } + } + }, + traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00" + } + ); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Favorites/RemoveFavorite/RemoveFavoriteEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Favorites/RemoveFavorite/RemoveFavoriteEndpoint.cs new file mode 100644 index 00000000..5cce0411 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Favorites/RemoveFavorite/RemoveFavoriteEndpoint.cs @@ -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; + +/// +/// API endpoint for the /users/me/favorites/{mediaKind}/{mediaItemId} route. +/// +/// +/// Uses "me" because it is always for the currently authenticated user. +/// +public class RemoveFavoriteEndpoint : BaseEndpoint +{ + private readonly ICommandHandler> _removeFavoriteCommandHandler; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for handling remove favorite commands. + public RemoveFavoriteEndpoint(ICommandHandler> removeFavoriteCommandHandler) + { + _removeFavoriteCommandHandler = removeFavoriteCommandHandler; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(FastEndpoints.Http.DELETE); + Routes(ApiRoutes.Favorites.REMOVE_FAVORITE); + Version(1); + DontCatchExceptions(); + } + + /// + /// Removes a media item from the favorites of the current user. + /// + /// The request object. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(FastEndpoints.EmptyRequest request, CancellationToken cancellationToken) + { + // The 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 result = await _removeFavoriteCommandHandler.HandleAsync(new RemoveFavoriteCommand(mediaKind, mediaItemId), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Ok(success), Problem); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Favorites/RemoveFavorite/RemoveFavoriteEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Favorites/RemoveFavorite/RemoveFavoriteEndpointSummary.cs new file mode 100644 index 00000000..559e4b2a --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Favorites/RemoveFavorite/RemoveFavoriteEndpointSummary.cs @@ -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; + +/// +/// Class used for providing a textual description for the API endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class RemoveFavoriteEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + 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 + { + { + "General.Validation", new[] + { + "FavoriteMediaKindIsInvalid", + "FavoriteMediaItemIdCannotBeEmpty" + } + } + }, + traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00" + } + ); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Thumbnails/GetThumbnail/GetThumbnailEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Thumbnails/GetThumbnail/GetThumbnailEndpoint.cs index 91e37b15..4940e42d 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Thumbnails/GetThumbnail/GetThumbnailEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Thumbnails/GetThumbnail/GetThumbnailEndpoint.cs @@ -7,8 +7,8 @@ using Lumina.Application.Core.FileSystemManagement.Thumbnails.Queries.GetThumbna using Lumina.Contracts.Requests.FileSystemManagement.Thumbnails; using Lumina.Contracts.Responses.FileSystemManagement.Thumbnails; using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Common.MimeTypes; using Lumina.Presentation.Api.Common.Routes.FileSystemManagement; -using Lumina.Presentation.Api.Common.Utilities; using Lumina.Presentation.Api.Core.Endpoints.Common; using Microsoft.AspNetCore.Http; using System.Threading; @@ -52,6 +52,6 @@ public class GetThumbnailEndpoint : BaseEndpoint public override async Task ExecuteAsync(GetThumbnailRequest request, CancellationToken cancellationToken) { Result result = await _getThumbnailQueryHandler.HandleAsync(request.ToQuery(), cancellationToken).ConfigureAwait(false); - return result.Match(success => TypedResults.File(success.Bytes, MimeTypes.GetMimeType(success.Type)), Problem); + return result.Match(success => TypedResults.File(success.Bytes, ImageMimeTypes.GetMimeType(success.Type)), Problem); } } diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/AddAlbum/AddAlbumEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/AddAlbum/AddAlbumEndpointSummary.cs index fedd2b40..b7e28e68 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/AddAlbum/AddAlbumEndpointSummary.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/AddAlbum/AddAlbumEndpointSummary.cs @@ -340,6 +340,7 @@ public class AddAlbumEndpointSummary : Summary(r => r.Id, "The Id of the album."); ResponseParam(r => r.ArtistId, "The Id of the artist the album belongs to."); + ResponseParam(r => r.ArtistName, "The name of the artist the album belongs to."); ResponseParam(r => r.LibraryId, "The Id of the media library the album belongs to."); ResponseParam(r => r.Metadata!.Title, "The title of the album."); ResponseParam(r => r.Metadata!.OriginalTitle, "The original title of the album, if applicable."); @@ -380,6 +381,7 @@ public class AddAlbumEndpointSummary : Summary ResponseParam(r => r.Id, "The Id of the album."); ResponseParam(r => r.ArtistId, "The Id of the artist the album belongs to."); + ResponseParam(r => r.ArtistName, "The name of the artist the album belongs to."); ResponseParam(r => r.LibraryId, "The Id of the media library the album belongs to."); ResponseParam(r => r.Metadata!.Title, "The title of the album."); ResponseParam(r => r.Metadata!.OriginalTitle, "The original title of the album, if applicable."); @@ -72,6 +73,7 @@ public class GetAlbumEndpointSummary : Summary example: new AlbumResponse( Id: Guid.NewGuid(), ArtistId: Guid.NewGuid(), + ArtistName: "Queen", LibraryId: Guid.NewGuid(), Metadata: new MusicAlbumMetadataDto( Title: "A Night at the Opera", @@ -152,6 +154,7 @@ public class GetAlbumEndpointSummary : Summary AlbumId: Guid.NewGuid(), LibraryId: Guid.NewGuid(), Path: "/music/queen/a-night-at-the-opera/01-bohemian-rhapsody.flac", + Container: "FLAC", Metadata: new( Title: "Bohemian Rhapsody", OriginalTitle: "Bohemian Rhapsody", @@ -244,6 +247,7 @@ public class GetAlbumEndpointSummary : Summary AlbumId: Guid.NewGuid(), LibraryId: Guid.NewGuid(), Path: "/music/queen/a-night-at-the-opera/07-youre-my-best-friend.flac", + Container: "FLAC", Metadata: new( Title: "You're My Best Friend", OriginalTitle: "You're My Best Friend", diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/GetAlbumTracks/GetAlbumTracksEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/GetAlbumTracks/GetAlbumTracksEndpointSummary.cs index e9c3f688..55af03b5 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/GetAlbumTracks/GetAlbumTracksEndpointSummary.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/GetAlbumTracks/GetAlbumTracksEndpointSummary.cs @@ -33,6 +33,7 @@ public class GetAlbumTracksEndpointSummary : Summary(r => r.AlbumId, "The Id of the album the track belongs to."); ResponseParam(r => r.LibraryId, "The Id of the media library the track belongs to."); ResponseParam(r => r.Path, "The file system path of the track."); + ResponseParam(r => r.Container, "The container of the audio file of the track, if applicable."); ResponseParam(r => r.Metadata!.Title, "The title of the track."); ResponseParam(r => r.Metadata!.OriginalTitle, "The original title of the track, if applicable."); ResponseParam(r => r.Metadata!.Description, "The description of the track, if applicable."); @@ -80,6 +81,7 @@ public class GetAlbumTracksEndpointSummary : Summary(r => r.Id, "The Id of the album."); ResponseParam(r => r.ArtistId, "The Id of the artist the album belongs to."); + ResponseParam(r => r.ArtistName, "The name of the artist the album belongs to."); ResponseParam(r => r.LibraryId, "The Id of the media library the album belongs to."); ResponseParam(r => r.Metadata!.Title, "The title of the album."); ResponseParam(r => r.Metadata!.OriginalTitle, "The original title of the album, if applicable."); @@ -184,6 +185,7 @@ public class UpdateAlbumEndpointSummary : Summary new( Id: Guid.NewGuid(), ArtistId: Guid.NewGuid(), + ArtistName: "Queen", LibraryId: Guid.NewGuid(), Metadata: new( Title: "A Night at the Opera", @@ -123,6 +124,7 @@ public class GetArtistEndpointSummary : Summary AlbumId: Guid.NewGuid(), LibraryId: Guid.NewGuid(), Path: "/music/queen/a-night-at-the-opera/01-bohemian-rhapsody.flac", + Container: "FLAC", Metadata: new( Title: "Bohemian Rhapsody", OriginalTitle: "Bohemian Rhapsody", diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetArtistAlbums/GetArtistAlbumsEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetArtistAlbums/GetArtistAlbumsEndpointSummary.cs index 4d4546b0..56419539 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetArtistAlbums/GetArtistAlbumsEndpointSummary.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetArtistAlbums/GetArtistAlbumsEndpointSummary.cs @@ -32,6 +32,7 @@ public class GetArtistAlbumsEndpointSummary : Summary(r => r.Id, "The Id of the album."); ResponseParam(r => r.ArtistId, "The Id of the artist the album belongs to."); + ResponseParam(r => r.ArtistName, "The name of the artist the album belongs to."); ResponseParam(r => r.LibraryId, "The Id of the media library the album belongs to."); ResponseParam(r => r.Metadata!.Title, "The title of the album."); ResponseParam(r => r.Metadata!.OriginalTitle, "The original title of the album, if applicable."); @@ -74,6 +75,7 @@ public class GetArtistAlbumsEndpointSummary : Summary(r => r.AlbumId, "The Id of the album the track belongs to."); ResponseParam(r => r.LibraryId, "The Id of the media library the track belongs to."); ResponseParam(r => r.Path, "The file system path of the track."); + ResponseParam(r => r.Container, "The container of the audio file of the track, if applicable."); ResponseParam(r => r.Metadata!.Title, "The title of the track."); ResponseParam(r => r.Metadata!.OriginalTitle, "The original title of the track, if applicable."); ResponseParam(r => r.Metadata!.Description, "The description of the track, if applicable."); @@ -215,6 +216,7 @@ public class AddTrackEndpointSummary : Summary +/// API endpoint for the /libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}/playback-manifest route. +/// +public class GetPlaybackManifestEndpoint : BaseEndpoint +{ + private readonly IQueryHandler> _getPlaybackManifestQueryHandler; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for handling get playback manifest queries. + public GetPlaybackManifestEndpoint(IQueryHandler> getPlaybackManifestQueryHandler) + { + _getPlaybackManifestQueryHandler = getPlaybackManifestQueryHandler; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(Http.GET); + Routes(ApiRoutes.Tracks.GET_PLAYBACK_MANIFEST); + Version(1); + DontCatchExceptions(); + } + + /// + /// Gets the playback manifest of the track identified by the route. + /// + /// The request object. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(EmptyRequest request, CancellationToken cancellationToken) + { + // Take unique identifiers from the route. + string? libraryId = HttpContext.Request.RouteValues["libraryId"]?.ToString(); + string? artistId = HttpContext.Request.RouteValues["artistId"]?.ToString(); + string? albumId = HttpContext.Request.RouteValues["albumId"]?.ToString(); + string? trackId = HttpContext.Request.RouteValues["trackId"]?.ToString(); + // The capabilities the player advertises are optional; an absent parameter is an empty value, which the handler treats as no capabilities. + string capabilities = HttpContext.Request.Query["capabilities"].ToString(); + // The stream path is filled in from the stream route itself, so that the manifest and the stream can never disagree on the shape of the route. + // It is kept relative, without a host, a scheme or the version prefix, so that a client reaches the stream through its own application. + string streamPath = ApiRoutes.Tracks.STREAM_TRACK + .Replace("{libraryId}", libraryId, StringComparison.Ordinal) + .Replace("{artistId}", artistId, StringComparison.Ordinal) + .Replace("{albumId}", albumId, StringComparison.Ordinal) + .Replace("{trackId}", trackId, StringComparison.Ordinal); + // The segment route is filled in from the same route values, and its delivery handle and segment index placeholders are kept for the player + // to expand, so the manifest and the segment route can never disagree on the shape of the path either. The delivery handle is what binds + // the segments to the delivery this manifest declared; the capabilities are not repeated in the path. + string segmentStreamPathTemplate = ApiRoutes.Tracks.STREAM_TRACK_SEGMENT + .Replace("{libraryId}", libraryId, StringComparison.Ordinal) + .Replace("{artistId}", artistId, StringComparison.Ordinal) + .Replace("{albumId}", albumId, StringComparison.Ordinal) + .Replace("{trackId}", trackId, StringComparison.Ordinal); + GetPlaybackManifestQuery query = new(libraryId, artistId, albumId, trackId, capabilities, streamPath, segmentStreamPathTemplate); + Result result = await _getPlaybackManifestQueryHandler.HandleAsync(query, cancellationToken).ConfigureAwait(false); + return result.Match(success => + { + // The manifest carries delivery metadata specific to the authenticated user, so no intermediary may store it and every response varies by + // the bearer token that authorized it. + HttpContext.Response.Headers["Cache-Control"] = "private, no-store"; + HttpContext.Response.Headers["Vary"] = "Authorization"; + return TypedResults.Ok(success); + }, Problem); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetPlaybackManifest/GetPlaybackManifestEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetPlaybackManifest/GetPlaybackManifestEndpointSummary.cs new file mode 100644 index 00000000..14e54f8f --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetPlaybackManifest/GetPlaybackManifestEndpointSummary.cs @@ -0,0 +1,165 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Playback; +using Lumina.Domain.SharedKernel.Common.Enums.Playback; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.GetPlaybackManifest; + +/// +/// Class used for providing a textual description for the API endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class GetPlaybackManifestEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public GetPlaybackManifestEndpointSummary() + { + Summary = "Retrieves the playback manifest of a track."; + Description = "Retrieves the playback manifest of a track, containing the format of its stored audio, the delivery the server decided on for the requesting player, and the path of its stream. The player advertises the container and codec pairs it can demux and decode directly in the optional capabilities query parameter, as a comma separated list of container/codec pairs; when the parameter is absent, empty or lists no valid pair, the default capabilities of the bundled player apply. The manifest is returned to an Admin, who can build the manifest of the tracks of all libraries, or to the owner of the library of the track."; + + ResponseParam(r => r.TrackId, "The Id of the track the manifest describes."); + ResponseParam(r => r.DurationInSeconds, "The duration of the audio of the track, in seconds."); + ResponseParam(r => r.SourceContainer, "The container of the stored audio file of the track, for example MP3, FLAC, OGG, AAC, MP4 or WAV."); + ResponseParam(r => r.SourceCodec, "The codec of the stored audio of the track."); + ResponseParam(r => r.SampleRate, "The sample rate of the audio of the track, in Hz."); + ResponseParam(r => r.Channels, "The number of audio channels of the track."); + ResponseParam(r => r.BitDepth, "The bit depth of the audio of the track, if applicable."); + ResponseParam(r => r.ReplayGainTrackGain, "The ReplayGain track gain of the track, in decibels, if applicable."); + ResponseParam(r => r.ReplayGainTrackPeak, "The ReplayGain track peak of the track, if applicable."); + ResponseParam(r => r.ReplayGainAlbumGain, "The ReplayGain album gain of the track, in decibels, if applicable."); + ResponseParam(r => r.ReplayGainAlbumPeak, "The ReplayGain album peak of the track, if applicable."); + ResponseParam(r => r.IsDirectPlay, "Whether the player can play the stored audio as it is, without the server changing its container or its codec."); + ResponseParam(r => r.DeliveryContainer, "The container of the audio the server delivers, when the delivery is not a direct play."); + ResponseParam(r => r.DeliveryCodec, "The codec of the audio the server delivers, when the delivery is not a direct play."); + ResponseParam(r => r.DeliveryShape, "The shape the delivered audio is addressed and seeked by, when the delivery is not a direct play."); + ResponseParam(r => r.SegmentDurationSeconds, "The duration of each segment of the delivered audio, in seconds, when the delivery is addressed as time addressed segments."); + ResponseParam(r => r.IsSeekable, "Whether the delivered audio can be seeked by the player."); + ResponseParam(r => r.StreamPath, "The path of the track stream, relative to the API, without a host or a scheme."); + ResponseParam(r => r.DeliveryId, "The opaque handle of the normalized delivery, which the segment route accepts. Null for a direct play."); + ResponseParam(r => r.SegmentStreamPathTemplate, "The path template of the segment route of the normalized delivery, relative to the API, with {deliveryId} and {segmentIndex} placeholders. Null for a direct play."); + + Response(200, "The playback manifest of the track is returned.", + example: new PlaybackManifestResponse( + TrackId: Guid.Parse("9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f"), + DurationInSeconds: 354, + SourceContainer: "FLAC", + SourceCodec: "FLAC", + SampleRate: 44100, + Channels: 2, + BitDepth: 16, + ReplayGainTrackGain: -7.5m, + ReplayGainTrackPeak: 0.9877m, + ReplayGainAlbumGain: -6.8m, + ReplayGainAlbumPeak: 0.9999m, + IsDirectPlay: false, + DeliveryContainer: "MP3", + DeliveryCodec: "MP3", + DeliveryShape: PlaybackDeliveryShape.TimeAddressedSegments, + SegmentDurationSeconds: 6, + IsSeekable: true, + StreamPath: "/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/albums/e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f/tracks/9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f/stream", + DeliveryId: "8f14e45fceea167a5a36dedd4bea2543", + SegmentStreamPathTemplate: "/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/albums/e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f/tracks/9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f/stream/deliveries/{deliveryId}/segments/{segmentIndex}" + ) + ); + + Response(401, "Authentication required.", "application/problem+json", + example: new[] + { + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "Authentication failed", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}/playback-manifest" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token has expired", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}/playback-manifest" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token is invalid", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}/playback-manifest" + } + } + ); + + Response(403, "The request failed because the user making the request is not an Admin, or the owner of the media library, or because the server cannot produce any format the player advertises it supports.", "application/problem+json", + example: new[] + { + new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.4", + title = "General.Unauthorized", + status = 403, + detail = "NotAuthorized", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}/playback-manifest", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + }, + new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.4", + title = "General.Forbidden", + status = 403, + detail = "NoSupportedPlaybackFormat", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}/playback-manifest", + traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00" + } + } + ); + + Response(404, "The request failed because the track or its media library does not exist, or the track does not belong to the library, album and artist named by the route.", "application/problem+json", + example: new[] + { + new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.5", + title = "General.NotFound", + status = 404, + detail = "TrackNotFound", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}/playback-manifest", + traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00" + } + } + ); + + Response(422, "The request did not pass validation checks.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc4918#section-11.2", + title = "General.Validation", + status = 422, + detail = "OneOrMoreValidationErrorsOccurred", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}/playback-manifest", + errors = new Dictionary + { + { + "General.Validation", new[] + { + "LibraryIdCannotBeEmpty", + "ArtistIdCannotBeEmpty", + "AlbumIdCannotBeEmpty", + "TrackIdCannotBeEmpty" + } + } + }, + traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00" + } + ); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetTrack/GetTrackEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetTrack/GetTrackEndpointSummary.cs index 5061be39..56968c3e 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetTrack/GetTrackEndpointSummary.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetTrack/GetTrackEndpointSummary.cs @@ -33,6 +33,7 @@ public class GetTrackEndpointSummary : Summary ResponseParam(r => r.AlbumId, "The Id of the album the track belongs to."); ResponseParam(r => r.LibraryId, "The Id of the media library the track belongs to."); ResponseParam(r => r.Path, "The file system path of the track."); + ResponseParam(r => r.Container, "The container of the audio file of the track, if applicable."); ResponseParam(r => r.Metadata!.Title, "The title of the track."); ResponseParam(r => r.Metadata!.OriginalTitle, "The original title of the track, if applicable."); ResponseParam(r => r.Metadata!.Description, "The description of the track, if applicable."); @@ -78,6 +79,7 @@ public class GetTrackEndpointSummary : Summary AlbumId: Guid.NewGuid(), LibraryId: Guid.NewGuid(), Path: "/music/queen/a-night-at-the-opera/01-bohemian-rhapsody.flac", + Container: "FLAC", Metadata: new MusicTrackMetadataDto( Title: "Bohemian Rhapsody", OriginalTitle: "Bohemian Rhapsody", diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetTrackSegment/GetTrackSegmentEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetTrackSegment/GetTrackSegmentEndpoint.cs new file mode 100644 index 00000000..00b1e85a --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetTrackSegment/GetTrackSegmentEndpoint.cs @@ -0,0 +1,93 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Queries.GetTrackSegment; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Common.DependencyInjection; +using Lumina.Presentation.Api.Common.Http; +using Lumina.Presentation.Api.Common.MimeTypes; +using Lumina.Presentation.Api.Common.Routes.Library.AudioLibrary.MusicLibrary; +using Lumina.Presentation.Api.Core.Endpoints.Common; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System.Globalization; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.GetTrackSegment; + +/// +/// API endpoint for the /libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}/stream/deliveries/{deliveryId}/segments/{segmentIndex} route. +/// +public class GetTrackSegmentEndpoint : BaseEndpoint +{ + // The name is repeated in the web client application, which is a separate project that keeps its own contracts, so both sides must change together. + private const string SEGMENT_COUNT_HEADER_NAME = "X-Lumina-Segment-Count"; + private const string SEGMENT_START_SECONDS_HEADER_NAME = "X-Segment-Start-Seconds"; + private const string TRACK_DURATION_SECONDS_HEADER_NAME = "X-Lumina-Track-Duration-Seconds"; + + private readonly IQueryHandler> _getTrackSegmentQueryHandler; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for handling get track segment queries. + public GetTrackSegmentEndpoint(IQueryHandler> getTrackSegmentQueryHandler) + { + _getTrackSegmentQueryHandler = getTrackSegmentQueryHandler; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(Http.GET); + Routes(ApiRoutes.Tracks.STREAM_TRACK_SEGMENT); + Version(1); + DontCatchExceptions(); + // The segment stream is limited per user with the same concurrency limiter as the track stream, and it is excluded from the eventual + // consistency pipeline, because a long lived response would otherwise hold the request's database transaction open for its whole duration. + Options(builder => builder + .RequireRateLimiting(PresentationApiLayerServices.TRACK_STREAM_RATE_LIMIT_POLICY) + .WithMetadata(new SkipEventualConsistencyMetadata())); + } + + /// + /// Streams one segment of the normalized audio of the track identified by the route. + /// + /// The request object. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(EmptyRequest request, CancellationToken cancellationToken) + { + // Take unique identifiers and the segment index from the route. + string? libraryId = HttpContext.Request.RouteValues["libraryId"]?.ToString(); + string? artistId = HttpContext.Request.RouteValues["artistId"]?.ToString(); + string? albumId = HttpContext.Request.RouteValues["albumId"]?.ToString(); + string? trackId = HttpContext.Request.RouteValues["trackId"]?.ToString(); + string? deliveryId = HttpContext.Request.RouteValues["deliveryId"]?.ToString(); + string? segmentIndex = HttpContext.Request.RouteValues["segmentIndex"]?.ToString(); + GetTrackSegmentQuery query = new(libraryId, artistId, albumId, trackId, deliveryId, segmentIndex); + Result result = await _getTrackSegmentQueryHandler.HandleAsync(query, cancellationToken).ConfigureAwait(false); + if (result.IsFailure) + return Problem(result.Errors); + + // The produced segment is private to the authenticated user and is served from a temporary cache, so it must never be stored by an + // intermediary, and content sniffing stays disabled, so a segment can never be interpreted as active content. + HttpContext.Response.Headers["X-Content-Type-Options"] = "nosniff"; + HttpContext.Response.Headers["Cache-Control"] = "private, no-store"; + HttpContext.Response.Headers["Vary"] = "Authorization"; + // The count lets the player stop at the end of the production instead of probing for it with a request that cannot be told apart + // from a track that was deleted or moved. It is sent on every segment, because any segment can be the first one a player fetches. + HttpContext.Response.Headers[SEGMENT_COUNT_HEADER_NAME] = result.Value.SegmentCount.ToString(); + // The real start of the segment, because ffmpeg cuts at the first packet at or after a segment boundary and a container can number its + // frames from the start of the track. The player offsets the packets by this value instead of assuming an exact multiple of the duration. + HttpContext.Response.Headers[SEGMENT_START_SECONDS_HEADER_NAME] = result.Value.StartSeconds.ToString(CultureInfo.InvariantCulture); + // The produced duration can differ from the probed duration, so the player uses this value for its timeline and progress bar. + HttpContext.Response.Headers[TRACK_DURATION_SECONDS_HEADER_NAME] = result.Value.DurationInSeconds.ToString(CultureInfo.InvariantCulture); + // The length comes from the index of the production, so the response is length delimited without reading the segment into memory first. + return new DisposingStreamResult(result.Value.Content, MusicMimeTypes.GetContainerMimeType(result.Value.Container), result.Value.Length); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetTrackSegment/GetTrackSegmentEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetTrackSegment/GetTrackSegmentEndpointSummary.cs new file mode 100644 index 00000000..342dc56a --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetTrackSegment/GetTrackSegmentEndpointSummary.cs @@ -0,0 +1,145 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.GetTrackSegment; + +/// +/// Class used for providing a textual description for the API endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class GetTrackSegmentEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public GetTrackSegmentEndpointSummary() + { + Summary = "Streams one segment of the normalized audio of a track."; + Description = "Streams a single fixed duration segment of the normalized audio of the track identified by the route. A track that is not a direct play is delivered as fixed duration, time addressed segments, so a player seeks by segment index and never maps a byte range to a time. The delivery handle is the opaque value the playback manifest reports in its deliveryId, and the segment index is zero based; together they name a segment of exactly the delivery the manifest declared, including its quality cap and the source file version it was declared for. Library ownership is re-evaluated on every request, while track membership and content locations are those captured at manifest time, so a deleted track row whose file remains can stay streamable until the handle expires. The first request for a track may wait for the whole normalized audio to be produced and cached. The segment is streamed to an Admin, who can stream the tracks of all libraries, or to the owner of the library of the track."; + + Response(200, "The requested segment is streamed, with the media type of the delivered container, or application/octet-stream when the container is not an audio type, with the length of the segment as its content length, and with the segment count and its exact start time on the track timeline as the X-Lumina-Segment-Count and X-Segment-Start-Seconds headers.", "*/*"); + + Response(401, "Authentication required.", "application/problem+json", + example: new[] + { + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "Authentication failed", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}/stream/deliveries/8f14e45fceea167a5a36dedd4bea2543/segments/0" + } + } + ); + + Response(403, "The request failed because the user making the request is not an Admin, or the owner of the media library.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.4", + title = "General.Unauthorized", + status = 403, + detail = "NotAuthorized", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}/stream/deliveries/8f14e45fceea167a5a36dedd4bea2543/segments/0", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + } + ); + + Response(404, "The request failed because the delivery handle is unknown, expired, or was issued to another user or track, the track or its media library does not exist, the track does not belong to the library, album and artist named by the route, the audio file of the track is outside the content locations of its library, missing, or unreadable, or the requested segment does not exist. Only the NormalizedTrackSegmentNotFound detail means the end of the normalized audio; every other not found detail is a playback failure.", "application/problem+json", + example: new[] + { + new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.5", + title = "General.NotFound", + status = 404, + detail = "TrackNotFound", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}/stream/deliveries/8f14e45fceea167a5a36dedd4bea2543/segments/0", + traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00" + }, + new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.5", + title = "General.NotFound", + status = 404, + detail = "PlaybackDeliveryNotFound", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}/stream/deliveries/8f14e45fceea167a5a36dedd4bea2543/segments/0", + traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00" + }, + new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.5", + title = "General.NotFound", + status = 404, + detail = "NormalizedTrackSegmentNotFound", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}/stream/deliveries/8f14e45fceea167a5a36dedd4bea2543/segments/999", + traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00" + }, + new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.5", + title = "General.NotFound", + status = 404, + detail = "NormalizedTrackCacheEntryNotFound", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}/stream/deliveries/8f14e45fceea167a5a36dedd4bea2543/segments/999", + traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00" + } + } + ); + + Response(409, "The delivery handle does not describe time addressed segments, or the source file changed since the manifest declared the delivery. The player must request the playback manifest again.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.10", + title = "General.Conflict", + status = 409, + detail = "PlaybackDeliveryChanged", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}/stream/deliveries/8f14e45fceea167a5a36dedd4bea2543/segments/0", + traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00" + } + ); + + Response(422, "The request did not pass validation checks.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc4918#section-11.2", + title = "General.Validation", + status = 422, + detail = "OneOrMoreValidationErrorsOccurred", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}/stream/deliveries/not-a-handle/segments/-1", + errors = new Dictionary + { + { + "General.Validation", new[] + { + "LibraryIdCannotBeEmpty", + "ArtistIdCannotBeEmpty", + "AlbumIdCannotBeEmpty", + "TrackIdCannotBeEmpty", + "DeliveryIdCannotBeEmpty", + "DeliveryIdIsInvalid", + "SegmentIndexMustBeValid" + } + } + }, + traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00" + } + ); + + Response(503, "Every normalization job slot, globally or for this user, is in use. The condition is transient and the request can be retried.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.6.4", + title = "General.ResourceUnavailable", + status = 503, + detail = "NormalizationUnavailable", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}/stream/deliveries/8f14e45fceea167a5a36dedd4bea2543/segments/0", + traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00" + } + ); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetTrackStream/GetTrackStreamEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetTrackStream/GetTrackStreamEndpoint.cs new file mode 100644 index 00000000..5e930410 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetTrackStream/GetTrackStreamEndpoint.cs @@ -0,0 +1,86 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Application.Common.CQRS; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Queries.GetTrackStream; +using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Common.DependencyInjection; +using Lumina.Presentation.Api.Common.Http; +using Lumina.Presentation.Api.Common.MimeTypes; +using Lumina.Presentation.Api.Common.Routes.Library.AudioLibrary.MusicLibrary; +using Lumina.Presentation.Api.Core.Endpoints.Common; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using Microsoft.Net.Http.Headers; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.GetTrackStream; + +/// +/// API endpoint for the /libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}/stream route. +/// +public class GetTrackStreamEndpoint : BaseEndpoint +{ + private readonly IQueryHandler> _getTrackStreamQueryHandler; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for handling get track stream queries. + public GetTrackStreamEndpoint(IQueryHandler> getTrackStreamQueryHandler) + { + _getTrackStreamQueryHandler = getTrackStreamQueryHandler; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(Http.GET); + Routes(ApiRoutes.Tracks.STREAM_TRACK); + Version(1); + DontCatchExceptions(); + // The stream is limited per user with a concurrency limiter (never with the login rate limit policy), and it is excluded from the eventual + // consistency pipeline, because a long lived audio response would otherwise hold the request's database transaction open for its whole duration. + Options(builder => builder + .RequireRateLimiting(PresentationApiLayerServices.TRACK_STREAM_RATE_LIMIT_POLICY) + .WithMetadata(new SkipEventualConsistencyMetadata())); + } + + /// + /// Streams the audio file of the track identified by the route. + /// + /// The request object. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(EmptyRequest request, CancellationToken cancellationToken) + { + // Take unique identifiers from the route. + string? libraryId = HttpContext.Request.RouteValues["libraryId"]?.ToString(); + string? artistId = HttpContext.Request.RouteValues["artistId"]?.ToString(); + string? albumId = HttpContext.Request.RouteValues["albumId"]?.ToString(); + string? trackId = HttpContext.Request.RouteValues["trackId"]?.ToString(); + GetTrackStreamQuery query = new(libraryId, artistId, albumId, trackId); + Result result = await _getTrackStreamQueryHandler.HandleAsync(query, cancellationToken).ConfigureAwait(false); + if (result.IsFailure) + return Problem(result.Errors); + + // Audio is inert content, but it is still served with content sniffing disabled, so that a file with an unexpected extension is never interpreted as active content. + HttpContext.Response.Headers["X-Content-Type-Options"] = "nosniff"; + // The audio is private to the authenticated user and its bytes must never be stored by an intermediary, so it is not publicly cacheable and it varies by the bearer token. + HttpContext.Response.Headers["Cache-Control"] = "private"; + HttpContext.Response.Headers["Vary"] = "Authorization"; + + // The entity tag is derived from the size and the last modification time of the file, never from its path or its name, so no file system detail is exposed, and no download name is passed, so no Content-Disposition is emitted. + EntityTagHeaderValue entityTag = new($"\"{result.Value.LastModified.ToUnixTimeSeconds()}-{result.Value.Length}\""); + return TypedResults.PhysicalFile( + result.Value.Path, + MusicMimeTypes.GetMimeType(result.Value.Format), + fileDownloadName: null, + enableRangeProcessing: true, + lastModified: result.Value.LastModified, + entityTag: entityTag); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetTrackStream/GetTrackStreamEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetTrackStream/GetTrackStreamEndpointSummary.cs new file mode 100644 index 00000000..a6d03136 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetTrackStream/GetTrackStreamEndpointSummary.cs @@ -0,0 +1,138 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.GetTrackStream; + +/// +/// Class used for providing a textual description for the API endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class GetTrackStreamEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public GetTrackStreamEndpointSummary() + { + Summary = "Streams the audio file of a track."; + Description = "Streams the audio file of the track identified by the route, with HTTP range support, so that a player can start playback before the whole file is downloaded and can seek within it. The audio file is streamed to an Admin, who can stream the tracks of all libraries, or to the owner of the library of the track."; + + Response(200, "The audio file of the track is streamed, with the media type of the file when it is an audio type, or application/octet-stream otherwise, and with the length of the file as its content length.", "*/*"); + + Response(206, "The requested range of the audio file of the track is streamed, with the range in the Content-Range header and its length as the content length.", "*/*"); + + Response(401, "Authentication required.", "application/problem+json", + example: new[] + { + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "Authentication failed", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}/stream" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token has expired", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}/stream" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token is invalid", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}/stream" + } + } + ); + + Response(403, "The request failed because the user making the request is not an Admin, or the owner of the media library.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.4", + title = "General.Unauthorized", + status = 403, + detail = "NotAuthorized", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}/stream", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + } + ); + + Response(404, "The request failed because the track or its media library does not exist, the track does not belong to the library, album and artist named by the route, or the audio file of the track is outside the content locations of its library, missing, or unreadable.", "application/problem+json", + example: new[] + { + new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.5", + title = "General.NotFound", + status = 404, + detail = "TrackNotFound", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}/stream", + traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00" + }, + new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.5", + title = "General.NotFound", + status = 404, + detail = "LibraryNotFound", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}/stream", + traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00" + }, + new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.5", + title = "General.NotFound", + status = 404, + detail = "TrackFileNotFound", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}/stream", + traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00" + } + } + ); + + Response(416, "The request failed because the requested range is not satisfiable for the size of the audio file.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.17", + title = "RangeNotSatisfiable", + status = 416, + detail = "The requested range is not satisfiable.", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}/stream" + } + ); + + Response(422, "The request did not pass validation checks.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc4918#section-11.2", + title = "General.Validation", + status = 422, + detail = "OneOrMoreValidationErrorsOccurred", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}/stream", + errors = new Dictionary + { + { + "General.Validation", new[] + { + "LibraryIdCannotBeEmpty", + "ArtistIdCannotBeEmpty", + "AlbumIdCannotBeEmpty", + "TrackIdCannotBeEmpty" + } + } + }, + traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00" + } + ); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/ShuffleTracks/ShuffleTracksEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/ShuffleTracks/ShuffleTracksEndpoint.cs new file mode 100644 index 00000000..1bc850e5 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/ShuffleTracks/ShuffleTracksEndpoint.cs @@ -0,0 +1,58 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Queries.ShuffleTracks; +using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; +using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Common.Routes.Library.AudioLibrary.MusicLibrary; +using Lumina.Presentation.Api.Core.Endpoints.Common; +using Microsoft.AspNetCore.Http; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.ShuffleTracks; + +/// +/// API endpoint for the /libraries/{libraryId}/tracks/shuffle route. +/// +public class ShuffleTracksEndpoint : BaseEndpoint +{ + private readonly IQueryHandler>> _shuffleTracksQueryHandler; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for handling shuffle tracks queries. + public ShuffleTracksEndpoint(IQueryHandler>> shuffleTracksQueryHandler) + { + _shuffleTracksQueryHandler = shuffleTracksQueryHandler; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(Http.POST); + Routes(ApiRoutes.Tracks.SHUFFLE_TRACKS); + Version(1); + DontCatchExceptions(); + } + + /// + /// Draws a random selection of tracks of the library identified by the route. + /// + /// The request containing the selection size, the optional scope and the tracks to exclude. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(ShuffleTracksRequest request, CancellationToken cancellationToken) + { + // Take the unique identifier from the route. + string? libraryId = HttpContext.Request.RouteValues["libraryId"]?.ToString(); + Result> result = await _shuffleTracksQueryHandler.HandleAsync(request.ToQuery(libraryId), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Ok(success), Problem); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/ShuffleTracks/ShuffleTracksEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/ShuffleTracks/ShuffleTracksEndpointSummary.cs new file mode 100644 index 00000000..cfba7759 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/ShuffleTracks/ShuffleTracksEndpointSummary.cs @@ -0,0 +1,107 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; +using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.ShuffleTracks; + +/// +/// Class used for providing a textual description for the API endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class ShuffleTracksEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public ShuffleTracksEndpointSummary() + { + Summary = "Draws a random selection of tracks from a media library, an artist or an album."; + Description = "Returns uniformly random tracks from every track of the whole library, of one artist, or of one album, selected by the database itself. The client can pass the tracks it already queued to exclude them, so consecutive batches of a shuffle do not repeat a track. The request is returned to an Admin, who can shuffle all libraries, or to the owner of the library."; + + ExampleRequest = new ShuffleTracksRequest( + Count: 100, + ArtistId: null, + AlbumId: null, + ExcludedTrackIds: [Guid.NewGuid(), Guid.NewGuid()] + ); + + RequestParam(r => r.Count, "The maximum number of tracks to return, between 1 and 500."); + RequestParam(r => r.ArtistId, "The artist whose tracks are sampled. Optional."); + RequestParam(r => r.AlbumId, "The album whose tracks are sampled. Optional."); + RequestParam(r => r.ExcludedTrackIds, "The tracks that must not be returned. Optional."); + + ResponseParam(r => r.TrackId, "The Id of the track."); + ResponseParam(r => r.Title, "The title of the track."); + ResponseParam(r => r.DurationInSeconds, "The duration of the track in seconds."); + ResponseParam(r => r.AlbumId, "The Id of the album the track belongs to."); + ResponseParam(r => r.AlbumTitle, "The title of the album the track belongs to."); + ResponseParam(r => r.ArtistId, "The Id of the artist the album belongs to."); + ResponseParam(r => r.CoverPath, "The path of the cover of the album, if available."); + + Response(200, "The random selection of tracks is returned.", + example: new List + { + new( + TrackId: Guid.NewGuid(), + Title: "Bohemian Rhapsody", + DurationInSeconds: 354, + AlbumId: Guid.NewGuid(), + AlbumTitle: "A Night at the Opera", + ArtistId: Guid.NewGuid(), + CoverPath: "/music/queen/a-night-at-the-opera/cover.jpg" + ) + } + ); + + Response(401, "Authentication required.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "Authentication failed", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/tracks/shuffle" + } + ); + + Response(403, "The request failed because the user making the request is not an Admin, or the owner of the media library.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.4", + title = "General.Unauthorized", + status = 403, + detail = "NotAuthorized", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/tracks/shuffle", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + } + ); + + Response(422, "The request did not pass validation checks.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc4918#section-11.2", + title = "General.Validation", + status = 422, + detail = "OneOrMoreValidationErrorsOccurred", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/tracks/shuffle", + errors = new Dictionary + { + { + "General.Validation", new[] + { + "LibraryIdCannotBeEmpty", + "ShuffleTrackCountMustBeGreaterThanZero", + "ShuffleTrackCountMustBeAtMost500" + } + } + }, + traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00" + } + ); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/UpdateTrack/UpdateTrackEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/UpdateTrack/UpdateTrackEndpointSummary.cs index e873a6d6..6544de1b 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/UpdateTrack/UpdateTrackEndpointSummary.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/UpdateTrack/UpdateTrackEndpointSummary.cs @@ -31,7 +31,6 @@ public class UpdateTrackEndpointSummary : Summary r.Path, "The file system path of the track. Required."); RequestParam(r => r.Metadata, "The audio metadata of the track. Required."); RequestParam(r => r.Metadata!.Title, "The title of the track. Required."); RequestParam(r => r.Metadata!.OriginalTitle, "The original title of the track. Optional."); @@ -170,6 +168,7 @@ public class UpdateTrackEndpointSummary : Summary(r => r.AlbumId, "The Id of the album the track belongs to."); ResponseParam(r => r.LibraryId, "The Id of the media library the track belongs to."); ResponseParam(r => r.Path, "The file system path of the track."); + ResponseParam(r => r.Container, "The container of the audio file of the track, if applicable."); ResponseParam(r => r.Metadata!.Title, "The title of the track."); ResponseParam(r => r.Metadata!.OriginalTitle, "The original title of the track, if applicable."); ResponseParam(r => r.Metadata!.Description, "The description of the track, if applicable."); @@ -215,6 +214,7 @@ public class UpdateTrackEndpointSummary : Summary r.CanDownloadMetadataFromWeb, "Whether this media library should update the metadata of its elements from the web, or not. Optional."); RequestParam(r => r.ShouldSaveMetadataInMediaDirectories, "Whether this media library should copy the downloaded metadata into the media library content locations, or not. Optional."); RequestParam(r => r.ShouldSkipUnchangedDirectoriesDuringScan, "Whether this media library should skip the directories whose contents have not changed since the last scan, during the scan, or not. Optional."); + RequestParam(r => r.ShouldTrackConsumptionProgress, "Whether the consumption progress of the media library items should be tracked, or not. Optional, the default of the library type is used when absent."); + RequestParam(r => r.CompletionThresholdPercentage, "The percentage of a media library item that must be consumed for its session to be considered completed. Optional, the default of the library type is used when absent."); RequestParam(r => r.PathTemplateParts, "The ordered parts of the template describing the structure of the media library on disk. Optional, the ideal structure of the library type is used when absent."); ResponseParam(r => r.Id, "The unique identifier of the entity."); @@ -62,6 +66,8 @@ public class AddLibraryEndpointSummary : Summary(r => r.CanDownloadMetadataFromWeb, "Whether this media library should update the metadata of its elements from the web, or not."); ResponseParam(r => r.ShouldSaveMetadataInMediaDirectories, "Whether this media library should copy the downloaded metadata into the media library content locations, or not."); ResponseParam(r => r.ShouldSkipUnchangedDirectoriesDuringScan, "Whether this media library should skip the directories whose contents have not changed since the last scan, during the scan, or not."); + ResponseParam(r => r.ShouldTrackConsumptionProgress, "Whether the consumption progress of the media library items is tracked."); + ResponseParam(r => r.CompletionThresholdPercentage, "The percentage of a media library item that must be consumed for its session to be considered completed, when progress tracking is enabled."); ResponseParam(r => r.PathTemplateParts, "The ordered parts of the template describing the structure of the media library on disk."); ResponseParam(r => r.CreatedOnUtc, "The date and time when the entity was created."); ResponseParam(r => r.UpdatedOnUtc, "The date and time when the entity was last updated."); @@ -79,6 +85,8 @@ public class AddLibraryEndpointSummary : Summary(r => r.CanDownloadMetadataFromWeb, "Whether this media library should update the metadata of its elements from the web, or not."); ResponseParam(r => r.ShouldSaveMetadataInMediaDirectories, "Whether this media library should copy the downloaded metadata into the media library content locations, or not."); ResponseParam(r => r.ShouldSkipUnchangedDirectoriesDuringScan, "Whether this media library should skip the directories whose contents have not changed since the last scan, during the scan, or not."); + ResponseParam(r => r.ShouldTrackConsumptionProgress, "Whether the consumption progress of the media library items is tracked."); + ResponseParam(r => r.CompletionThresholdPercentage, "The percentage of a media library item that must be consumed for its session to be considered completed, when progress tracking is enabled."); ResponseParam(r => r.PathTemplateParts, "The ordered parts of the template describing the structure of the media library on disk."); ResponseParam(r => r.CreatedOnUtc, "The date and time when the entity was created."); ResponseParam(r => r.UpdatedOnUtc, "The date and time when the entity was last updated."); @@ -51,6 +53,8 @@ public class GetEnabledLibrariesEndpointSummary : Summary(r => r.CanDownloadMetadataFromWeb, "Whether this media library should update the metadata of its elements from the web, or not."); ResponseParam(r => r.ShouldSaveMetadataInMediaDirectories, "Whether this media library should copy the downloaded metadata into the media library content locations, or not."); ResponseParam(r => r.ShouldSkipUnchangedDirectoriesDuringScan, "Whether this media library should skip the directories whose contents have not changed since the last scan, during the scan, or not."); + ResponseParam(r => r.ShouldTrackConsumptionProgress, "Whether the consumption progress of the media library items is tracked."); + ResponseParam(r => r.CompletionThresholdPercentage, "The percentage of a media library item that must be consumed for its session to be considered completed, when progress tracking is enabled."); ResponseParam(r => r.PathTemplateParts, "The ordered parts of the template describing the structure of the media library on disk."); ResponseParam(r => r.CreatedOnUtc, "The date and time when the entity was created."); ResponseParam(r => r.UpdatedOnUtc, "The date and time when the entity was last updated."); @@ -51,6 +53,8 @@ public class GetLibrariesEndpointSummary : Summary(r => r.CanDownloadMetadataFromWeb, "Whether this media library should update the metadata of its elements from the web, or not."); ResponseParam(r => r.ShouldSaveMetadataInMediaDirectories, "Whether this media library should copy the downloaded metadata into the media library content locations, or not."); ResponseParam(r => r.ShouldSkipUnchangedDirectoriesDuringScan, "Whether this media library should skip the directories whose contents have not changed since the last scan, during the scan, or not."); + ResponseParam(r => r.ShouldTrackConsumptionProgress, "Whether the consumption progress of the media library items is tracked."); + ResponseParam(r => r.CompletionThresholdPercentage, "The percentage of a media library item that must be consumed for its session to be considered completed, when progress tracking is enabled."); ResponseParam(r => r.PathTemplateParts, "The ordered parts of the template describing the structure of the media library on disk."); ResponseParam(r => r.CreatedOnUtc, "The date and time when the entity was created."); ResponseParam(r => r.UpdatedOnUtc, "The date and time when the entity was last updated."); @@ -57,6 +59,8 @@ public class GetLibraryEndpointSummary : Summary r.CanDownloadMetadataFromWeb, "Whether this media library should update the metadata of its elements from the web, or not. Optional."); RequestParam(r => r.ShouldSaveMetadataInMediaDirectories, "Whether this media library should copy the downloaded metadata into the media library content locations, or not. Optional."); RequestParam(r => r.ShouldSkipUnchangedDirectoriesDuringScan, "Whether this media library should skip the directories whose contents have not changed since the last scan, during the scan, or not. Optional."); + RequestParam(r => r.ShouldTrackConsumptionProgress, "Whether the consumption progress of the media library items should be tracked, or not. Optional, the stored value is kept when absent."); + RequestParam(r => r.CompletionThresholdPercentage, "The percentage of a media library item that must be consumed for its session to be considered completed. Optional, the stored value is kept when absent."); RequestParam(r => r.PathTemplateParts, "The ordered parts of the template describing the structure of the media library on disk. Optional, the ideal structure of the library type is used when absent."); ResponseParam(r => r.Id, "The unique identifier of the entity."); @@ -66,6 +70,8 @@ public class UpdateLibraryEndpointSummary : Summary(r => r.CanDownloadMetadataFromWeb, "Whether this media library should update the metadata of its elements from the web, or not."); ResponseParam(r => r.ShouldSaveMetadataInMediaDirectories, "Whether this media library should copy the downloaded metadata into the media library content locations, or not."); ResponseParam(r => r.ShouldSkipUnchangedDirectoriesDuringScan, "Whether this media library should skip the directories whose contents have not changed since the last scan, during the scan, or not."); + ResponseParam(r => r.ShouldTrackConsumptionProgress, "Whether the consumption progress of the media library items is tracked."); + ResponseParam(r => r.CompletionThresholdPercentage, "The percentage of a media library item that must be consumed for its session to be considered completed, when progress tracking is enabled."); ResponseParam(r => r.PathTemplateParts, "The ordered parts of the template describing the structure of the media library on disk."); ResponseParam(r => r.CreatedOnUtc, "The date and time when the entity was created."); ResponseParam(r => r.UpdatedOnUtc, "The date and time when the entity was last updated."); @@ -83,6 +89,8 @@ public class UpdateLibraryEndpointSummary : Summary +/// API endpoint for the /users/me/consumption-history route. +/// +/// +/// Uses "me" because it is always for the currently authenticated user. +/// +public class ClearConsumptionHistoryEndpoint : BaseEndpoint +{ + private readonly ICommandHandler> _clearConsumptionHistoryCommandHandler; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for handling clear consumption history commands. + public ClearConsumptionHistoryEndpoint(ICommandHandler> clearConsumptionHistoryCommandHandler) + { + _clearConsumptionHistoryCommandHandler = clearConsumptionHistoryCommandHandler; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(FastEndpoints.Http.DELETE); + Routes(ApiRoutes.LibraryStatistics.CLEAR_CONSUMPTION_HISTORY); + Version(1); + DontCatchExceptions(); + } + + /// + /// Deletes every consumption record of the current user. + /// + /// The request object. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(FastEndpoints.EmptyRequest request, CancellationToken cancellationToken) + { + // The consumption history belongs to the authenticated user, so no intermediary may store any response of this route, including its problem + // responses, and every response varies by the bearer token that authorized it. + HttpContext.Response.Headers["Cache-Control"] = "private, no-store"; + HttpContext.Response.Headers.Append("Vary", "Authorization"); + Result result = await _clearConsumptionHistoryCommandHandler.HandleAsync(new ClearConsumptionHistoryCommand(TargetUserId: null), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Ok(success), Problem); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/ClearConsumptionHistory/ClearConsumptionHistoryEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/ClearConsumptionHistory/ClearConsumptionHistoryEndpointSummary.cs new file mode 100644 index 00000000..0f448eab --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/ClearConsumptionHistory/ClearConsumptionHistoryEndpointSummary.cs @@ -0,0 +1,70 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Library.Statistics.ClearConsumptionHistory; + +/// +/// Class used for providing a textual description for the API endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class ClearConsumptionHistoryEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public ClearConsumptionHistoryEndpointSummary() + { + Summary = "Deletes every consumption record of the current user."; + Description = "Deletes every recorded consumption session of the current user. The deletion is a hard delete, so the statistics and the history lists are empty as soon as it completes. Clearing an already empty history changes nothing and is not an error, so a retried clearance is safe; a concurrent write can still be rejected with a conflict. The resume points are not deleted: clearing the history and removing items from continue watching are separate user actions, and a user can keep their resume points after deleting their history. The history of another user is never deleted by this route."; + + Response(200, "The consumption history was successfully cleared."); + + 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/consumption-history" + }, + 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/consumption-history" + } + } + ); + + 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/consumption-history", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + } + ); + + Response(409, "The request failed because the deletion could not be stored, because the database is busy or locked, or because another request changed the same data after this request read it. Repeating the request is safe.", "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/consumption-history", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + } + ); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/ClearConsumptionHistory/ClearUserConsumptionHistoryEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/ClearConsumptionHistory/ClearUserConsumptionHistoryEndpoint.cs new file mode 100644 index 00000000..f99a9a1b --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/ClearConsumptionHistory/ClearUserConsumptionHistoryEndpoint.cs @@ -0,0 +1,58 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Core.MediaConsumption.Commands.ClearConsumptionHistory; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Common.Routes.Library.Statistics; +using Lumina.Presentation.Api.Core.Endpoints.Common; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Library.Statistics.ClearConsumptionHistory; + +/// +/// API endpoint for the /users/{userId}/consumption-history route. +/// +public class ClearUserConsumptionHistoryEndpoint : BaseEndpoint +{ + private readonly ICommandHandler> _clearConsumptionHistoryCommandHandler; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for handling clear consumption history commands. + public ClearUserConsumptionHistoryEndpoint(ICommandHandler> clearConsumptionHistoryCommandHandler) + { + _clearConsumptionHistoryCommandHandler = clearConsumptionHistoryCommandHandler; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(FastEndpoints.Http.DELETE); + Routes(ApiRoutes.LibraryStatistics.CLEAR_USER_CONSUMPTION_HISTORY); + Version(1); + DontCatchExceptions(); + } + + /// + /// Deletes every consumption record of a user. + /// + /// The request object. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(FastEndpoints.EmptyRequest request, CancellationToken cancellationToken) + { + // The consumption history belongs to the target user, and only that user or an Admin may read or delete it, 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.Append("Vary", "Authorization"); + // Take the target user from the route. The access policy in the command decides whether the caller is the target user or an admin, and a + // regular user targeting another user receives the same not authorized result as a route that names no accessible user. + string? targetUserId = HttpContext.Request.RouteValues["userId"]?.ToString(); + Result result = await _clearConsumptionHistoryCommandHandler.HandleAsync(new ClearConsumptionHistoryCommand(targetUserId), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Ok(success), Problem); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/ClearConsumptionHistory/ClearUserConsumptionHistoryEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/ClearConsumptionHistory/ClearUserConsumptionHistoryEndpointSummary.cs new file mode 100644 index 00000000..fe217434 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/ClearConsumptionHistory/ClearUserConsumptionHistoryEndpointSummary.cs @@ -0,0 +1,94 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Library.Statistics.ClearConsumptionHistory; + +/// +/// Class used for providing a textual description for the API endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class ClearUserConsumptionHistoryEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public ClearUserConsumptionHistoryEndpointSummary() + { + Summary = "Deletes every consumption record of a user."; + Description = "Deletes every recorded consumption session of a user. A user can clear only their own history, while an Admin can select any user with the userId route parameter; a regular user targeting another user receives the same not authorized result as a route that names no accessible user. The deletion is a hard delete, so the statistics and the history lists are empty as soon as it completes. Clearing an already empty history changes nothing and is not an error, so a retried clearance is safe; a concurrent write can still be rejected with a conflict. The resume points are not deleted: clearing the history and removing items from continue watching are separate user actions, and a user can keep their resume points after deleting their history."; + + Params["userId"] = "The Id of the user whose history is cleared. An Admin can name any user; a regular user can only name themselves."; + + Response(200, "The consumption history of the user was successfully cleared."); + + 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/{userId}/consumption-history" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token has expired", + instance = "/api/v1/users/{userId}/consumption-history" + } + } + ); + + Response(403, "The request failed because the authenticated request does not carry the identity of a user, or because the current user is neither the target user nor an Admin.", "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/{userId}/consumption-history", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + } + ); + + Response(409, "The request failed because the deletion could not be stored, because the database is busy or locked, or because another request changed the same data after this request read it. Repeating the request is safe.", "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/{userId}/consumption-history", + 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/{userId}/consumption-history", + errors = new Dictionary + { + { + "General.Validation", new[] + { + "TargetUserIdIsInvalid" + } + } + }, + traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00" + } + ); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/ClearResumePoints/ClearResumePointsEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/ClearResumePoints/ClearResumePointsEndpoint.cs new file mode 100644 index 00000000..6dfb746e --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/ClearResumePoints/ClearResumePointsEndpoint.cs @@ -0,0 +1,60 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.Mapping.MediaConsumption; +using Lumina.Application.Core.MediaConsumption.Commands.ClearResumePoints; +using Lumina.Contracts.Requests.MediaConsumption; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Common.Routes.Library.Statistics; +using Lumina.Presentation.Api.Core.Endpoints.Common; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Library.Statistics.ClearResumePoints; + +/// +/// API endpoint for the /users/me/media-resume-points route. +/// +/// +/// Uses "me" because it is always for the currently authenticated user. +/// +public class ClearResumePointsEndpoint : BaseEndpoint +{ + private readonly ICommandHandler> _clearResumePointsCommandHandler; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for handling clear resume points commands. + public ClearResumePointsEndpoint(ICommandHandler> clearResumePointsCommandHandler) + { + _clearResumePointsCommandHandler = clearResumePointsCommandHandler; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(FastEndpoints.Http.DELETE); + Routes(ApiRoutes.LibraryStatistics.CLEAR_RESUME_POINTS); + Version(1); + DontCatchExceptions(); + } + + /// + /// Deletes the resume points of the current user. + /// + /// The request containing the optional library filter. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(ClearResumePointsRequest request, CancellationToken cancellationToken) + { + // The resume points 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.Append("Vary", "Authorization"); + Result result = await _clearResumePointsCommandHandler.HandleAsync(request.ToCommand(targetUserId: null), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Ok(success), Problem); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/ClearResumePoints/ClearResumePointsEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/ClearResumePoints/ClearResumePointsEndpointSummary.cs new file mode 100644 index 00000000..d3ba9809 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/ClearResumePoints/ClearResumePointsEndpointSummary.cs @@ -0,0 +1,95 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Contracts.Requests.MediaConsumption; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Library.Statistics.ClearResumePoints; + +/// +/// Class used for providing a textual description for the API endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class ClearResumePointsEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public ClearResumePointsEndpointSummary() + { + Summary = "Deletes the resume points of the current user."; + Description = "Deletes the resume points of the current user, optionally limited to one media library with the libraryId query parameter. This only clears the continue watching list, while the recorded consumption history is kept, so the statistics and the history lists do not change. Deleting absent resume points changes nothing and is not an error, so a retried deletion is safe; a concurrent write can still be rejected with a conflict. The resume points of another user are never deleted by this route."; + + RequestParam(request => request.LibraryId, "The Id of the media library to restrict the deletion to. Optional."); + + Response(200, "The resume points were successfully deleted."); + + Response(401, "Authentication required.", "application/problem+json", + example: new[] + { + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "Authentication failed", + instance = "/api/v1/users/me/media-resume-points" + }, + 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/media-resume-points" + } + } + ); + + 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/media-resume-points", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + } + ); + + Response(409, "The request failed because the deletion could not be stored, because the database is busy or locked, or because another request changed the same data after this request read it. Repeating the request is safe.", "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/media-resume-points", + 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/media-resume-points", + errors = new Dictionary + { + { + "General.Validation", new[] + { + "LibraryIdCannotBeEmpty" + } + } + }, + traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00" + } + ); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/ClearResumePoints/ClearUserResumePointsEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/ClearResumePoints/ClearUserResumePointsEndpoint.cs new file mode 100644 index 00000000..478b01d8 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/ClearResumePoints/ClearUserResumePointsEndpoint.cs @@ -0,0 +1,60 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.Mapping.MediaConsumption; +using Lumina.Application.Core.MediaConsumption.Commands.ClearResumePoints; +using Lumina.Contracts.Requests.MediaConsumption; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Common.Routes.Library.Statistics; +using Lumina.Presentation.Api.Core.Endpoints.Common; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Library.Statistics.ClearResumePoints; + +/// +/// API endpoint for the /users/{userId}/media-resume-points route. +/// +public class ClearUserResumePointsEndpoint : BaseEndpoint +{ + private readonly ICommandHandler> _clearResumePointsCommandHandler; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for handling clear resume points commands. + public ClearUserResumePointsEndpoint(ICommandHandler> clearResumePointsCommandHandler) + { + _clearResumePointsCommandHandler = clearResumePointsCommandHandler; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(FastEndpoints.Http.DELETE); + Routes(ApiRoutes.LibraryStatistics.CLEAR_USER_RESUME_POINTS); + Version(1); + DontCatchExceptions(); + } + + /// + /// Deletes the resume points of a user. + /// + /// The request containing the optional library filter. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(ClearResumePointsRequest request, CancellationToken cancellationToken) + { + // The resume points belong to the target user, and only that user or an Admin may read or delete them, 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.Append("Vary", "Authorization"); + // Take the target user from the route. The access policy in the command decides whether the caller is the target user or an admin, and a + // regular user targeting another user receives the same not authorized result as a route that names no accessible user. + string? targetUserId = HttpContext.Request.RouteValues["userId"]?.ToString(); + Result result = await _clearResumePointsCommandHandler.HandleAsync(request.ToCommand(targetUserId), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Ok(success), Problem); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/ClearResumePoints/ClearUserResumePointsEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/ClearResumePoints/ClearUserResumePointsEndpointSummary.cs new file mode 100644 index 00000000..ecab050c --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/ClearResumePoints/ClearUserResumePointsEndpointSummary.cs @@ -0,0 +1,97 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Contracts.Requests.MediaConsumption; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Library.Statistics.ClearResumePoints; + +/// +/// Class used for providing a textual description for the API endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class ClearUserResumePointsEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public ClearUserResumePointsEndpointSummary() + { + Summary = "Deletes the resume points of a user."; + Description = "Deletes the resume points of a user, optionally limited to one media library with the libraryId query parameter. A user can clear only their own resume points, while an Admin can select any user with the userId route parameter; a regular user targeting another user receives the same not authorized result as a route that names no accessible user. This only clears the continue watching list, while the recorded consumption history is kept, so the statistics and the history lists do not change. Deleting absent resume points changes nothing and is not an error, so a retried deletion is safe; a concurrent write can still be rejected with a conflict."; + + Params["userId"] = "The Id of the user whose resume points are deleted. An Admin can name any user; a regular user can only name themselves."; + RequestParam(request => request.LibraryId, "The Id of the media library to restrict the deletion to. Optional."); + + Response(200, "The resume points of the user were successfully deleted."); + + Response(401, "Authentication required.", "application/problem+json", + example: new[] + { + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "Authentication failed", + instance = "/api/v1/users/{userId}/media-resume-points" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token has expired", + instance = "/api/v1/users/{userId}/media-resume-points" + } + } + ); + + Response(403, "The request failed because the authenticated request does not carry the identity of a user, or because the current user is neither the target user nor an Admin.", "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/{userId}/media-resume-points", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + } + ); + + Response(409, "The request failed because the deletion could not be stored, because the database is busy or locked, or because another request changed the same data after this request read it. Repeating the request is safe.", "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/{userId}/media-resume-points", + 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/{userId}/media-resume-points", + errors = new Dictionary + { + { + "General.Validation", new[] + { + "TargetUserIdIsInvalid", + "LibraryIdCannotBeEmpty" + } + } + }, + traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00" + } + ); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/DeleteConsumptionItemHistory/DeleteConsumptionItemHistoryEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/DeleteConsumptionItemHistory/DeleteConsumptionItemHistoryEndpoint.cs new file mode 100644 index 00000000..ccb8ccda --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/DeleteConsumptionItemHistory/DeleteConsumptionItemHistoryEndpoint.cs @@ -0,0 +1,60 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Core.MediaConsumption.Commands.DeleteConsumptionItemHistory; +using Lumina.Contracts.Requests.MediaConsumption; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Common.Routes.Library.Statistics; +using Lumina.Presentation.Api.Core.Endpoints.Common; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Library.Statistics.DeleteConsumptionItemHistory; + +/// +/// API endpoint for the /users/me/consumption-history/media-items/{mediaKind}/{mediaItemId}/{libraryId} route. +/// +/// +/// Uses "me" because it is always for the currently authenticated user. +/// +public class DeleteConsumptionItemHistoryEndpoint : BaseEndpoint +{ + private readonly ICommandHandler> _deleteConsumptionItemHistoryCommandHandler; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for handling delete consumption item history commands. + public DeleteConsumptionItemHistoryEndpoint(ICommandHandler> deleteConsumptionItemHistoryCommandHandler) + { + _deleteConsumptionItemHistoryCommandHandler = deleteConsumptionItemHistoryCommandHandler; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(FastEndpoints.Http.DELETE); + Routes(ApiRoutes.LibraryStatistics.DELETE_CONSUMPTION_ITEM_HISTORY); + Version(1); + DontCatchExceptions(); + } + + /// + /// Deletes every consumption record of a media item of the current user. + /// + /// The request containing the media item and its library. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(DeleteConsumptionItemHistoryRequest request, CancellationToken cancellationToken) + { + // The consumption records 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.Append("Vary", "Authorization"); + Result result = await _deleteConsumptionItemHistoryCommandHandler + .HandleAsync(new DeleteConsumptionItemHistoryCommand(TargetUserId: null, request.MediaKind, request.MediaItemId, request.LibraryId), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Ok(success), Problem); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/DeleteConsumptionItemHistory/DeleteConsumptionItemHistoryEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/DeleteConsumptionItemHistory/DeleteConsumptionItemHistoryEndpointSummary.cs new file mode 100644 index 00000000..56fcb2e6 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/DeleteConsumptionItemHistory/DeleteConsumptionItemHistoryEndpointSummary.cs @@ -0,0 +1,99 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Contracts.Requests.MediaConsumption; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Library.Statistics.DeleteConsumptionItemHistory; + +/// +/// Class used for providing a textual description for the API endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class DeleteConsumptionItemHistoryEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public DeleteConsumptionItemHistoryEndpointSummary() + { + Summary = "Deletes every consumption record of a media item of the current user."; + Description = "Deletes every recorded consumption session of one media item of the current user, in the library named by the route. The deletion covers every session of the item, independent of any date range, so the item disappears from the history consistently with clearing the whole history. Deleting an item that has no recorded session changes nothing and is not an error, so a retried deletion is safe; a concurrent write can still be rejected with a conflict. The resume point of the media item is not deleted: removing an item from the history and removing it from continue watching are separate user actions. The records of another user are never deleted by this route."; + + Params["mediaKind"] = "The kind of the consumed media item."; + Params["mediaItemId"] = "The Id of the consumed media item."; + Params["libraryId"] = "The Id of the media library that contains the media item."; + + Response(200, "The consumption records of the media item were successfully deleted."); + + Response(401, "Authentication required.", "application/problem+json", + example: new[] + { + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "Authentication failed", + instance = "/api/v1/users/me/consumption-history/media-items/MusicTrack/9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a" + }, + 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/consumption-history/media-items/MusicTrack/9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a" + } + } + ); + + 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/consumption-history/media-items/MusicTrack/9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + } + ); + + Response(409, "The request failed because the deletion could not be stored, because the database is busy or locked, or because another request changed the same data after this request read it. Repeating the request is safe.", "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/consumption-history/media-items/MusicTrack/9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a", + 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/consumption-history/media-items/MusicTrack/9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a", + errors = new Dictionary + { + { + "General.Validation", new[] + { + "UnsupportedMediaKind", + "MediaItemIdCannotBeEmpty", + "LibraryIdCannotBeEmpty" + } + } + }, + traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00" + } + ); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/DeleteConsumptionItemHistory/DeleteUserConsumptionItemHistoryEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/DeleteConsumptionItemHistory/DeleteUserConsumptionItemHistoryEndpoint.cs new file mode 100644 index 00000000..5b674a3b --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/DeleteConsumptionItemHistory/DeleteUserConsumptionItemHistoryEndpoint.cs @@ -0,0 +1,58 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Core.MediaConsumption.Commands.DeleteConsumptionItemHistory; +using Lumina.Contracts.Requests.MediaConsumption; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Common.Routes.Library.Statistics; +using Lumina.Presentation.Api.Core.Endpoints.Common; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Library.Statistics.DeleteConsumptionItemHistory; + +/// +/// API endpoint for the /users/{userId}/consumption-history/media-items/{mediaKind}/{mediaItemId}/{libraryId} route. +/// +public class DeleteUserConsumptionItemHistoryEndpoint : BaseEndpoint +{ + private readonly ICommandHandler> _deleteConsumptionItemHistoryCommandHandler; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for handling delete consumption item history commands. + public DeleteUserConsumptionItemHistoryEndpoint(ICommandHandler> deleteConsumptionItemHistoryCommandHandler) + { + _deleteConsumptionItemHistoryCommandHandler = deleteConsumptionItemHistoryCommandHandler; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(FastEndpoints.Http.DELETE); + Routes(ApiRoutes.LibraryStatistics.DELETE_USER_CONSUMPTION_ITEM_HISTORY); + Version(1); + DontCatchExceptions(); + } + + /// + /// Deletes every consumption record of a media item of a user. + /// + /// The request containing the media item and its library. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(DeleteConsumptionItemHistoryRequest request, CancellationToken cancellationToken) + { + // The consumption records belong to the target user, and only that user or an Admin may delete them, 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.Append("Vary", "Authorization"); + string? targetUserId = HttpContext.Request.RouteValues["userId"]?.ToString(); + Result result = await _deleteConsumptionItemHistoryCommandHandler + .HandleAsync(new DeleteConsumptionItemHistoryCommand(targetUserId, request.MediaKind, request.MediaItemId, request.LibraryId), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Ok(success), Problem); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/DeleteConsumptionItemHistory/DeleteUserConsumptionItemHistoryEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/DeleteConsumptionItemHistory/DeleteUserConsumptionItemHistoryEndpointSummary.cs new file mode 100644 index 00000000..1ccf64b4 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/DeleteConsumptionItemHistory/DeleteUserConsumptionItemHistoryEndpointSummary.cs @@ -0,0 +1,101 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Contracts.Requests.MediaConsumption; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Library.Statistics.DeleteConsumptionItemHistory; + +/// +/// Class used for providing a textual description for the API endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class DeleteUserConsumptionItemHistoryEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public DeleteUserConsumptionItemHistoryEndpointSummary() + { + Summary = "Deletes every consumption record of a media item of a user."; + Description = "Deletes every recorded consumption session of one media item of a user, in the library named by the route. The deletion covers every session of the item, independent of any date range, so the item disappears from the history consistently with clearing the whole history. A user can delete only their own history, while an Admin can select any user with the userId route parameter; a regular user targeting another user receives the same not authorized result as a route that names no accessible user. Deleting an item that has no recorded session changes nothing and is not an error, so a retried deletion is safe; a concurrent write can still be rejected with a conflict. The resume point of the media item is not deleted: removing an item from the history and removing it from continue watching are separate user actions."; + + Params["userId"] = "The Id of the user whose history is deleted. An Admin can name any user; a regular user can only name themselves."; + Params["mediaKind"] = "The kind of the consumed media item."; + Params["mediaItemId"] = "The Id of the consumed media item."; + Params["libraryId"] = "The Id of the media library that contains the media item."; + + Response(200, "The consumption records of the media item were successfully deleted."); + + Response(401, "Authentication required.", "application/problem+json", + example: new[] + { + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "Authentication failed", + instance = "/api/v1/users/1a2b3c4d-5e6f-4a1b-8c2d-3e4f5a6b7c8d/consumption-history/media-items/MusicTrack/9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token has expired", + instance = "/api/v1/users/1a2b3c4d-5e6f-4a1b-8c2d-3e4f5a6b7c8d/consumption-history/media-items/MusicTrack/9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a" + } + } + ); + + 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/1a2b3c4d-5e6f-4a1b-8c2d-3e4f5a6b7c8d/consumption-history/media-items/MusicTrack/9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + } + ); + + Response(409, "The request failed because the deletion could not be stored, because the database is busy or locked, or because another request changed the same data after this request read it. Repeating the request is safe.", "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/1a2b3c4d-5e6f-4a1b-8c2d-3e4f5a6b7c8d/consumption-history/media-items/MusicTrack/9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a", + 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/1a2b3c4d-5e6f-4a1b-8c2d-3e4f5a6b7c8d/consumption-history/media-items/MusicTrack/9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a", + errors = new Dictionary + { + { + "General.Validation", new[] + { + "TargetUserIdIsInvalid", + "UnsupportedMediaKind", + "MediaItemIdCannotBeEmpty", + "LibraryIdCannotBeEmpty" + } + } + }, + traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00" + } + ); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/DeleteConsumptionRecord/DeleteConsumptionRecordEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/DeleteConsumptionRecord/DeleteConsumptionRecordEndpoint.cs new file mode 100644 index 00000000..1fdb3c56 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/DeleteConsumptionRecord/DeleteConsumptionRecordEndpoint.cs @@ -0,0 +1,60 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Core.MediaConsumption.Commands.DeleteConsumptionRecord; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Common.Routes.Library.Statistics; +using Lumina.Presentation.Api.Core.Endpoints.Common; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Library.Statistics.DeleteConsumptionRecord; + +/// +/// API endpoint for the /users/me/consumption-history/{recordId} route. +/// +/// +/// Uses "me" because it is always for the currently authenticated user. +/// +public class DeleteConsumptionRecordEndpoint : BaseEndpoint +{ + private readonly ICommandHandler> _deleteConsumptionRecordCommandHandler; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for handling delete consumption record commands. + public DeleteConsumptionRecordEndpoint(ICommandHandler> deleteConsumptionRecordCommandHandler) + { + _deleteConsumptionRecordCommandHandler = deleteConsumptionRecordCommandHandler; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(FastEndpoints.Http.DELETE); + Routes(ApiRoutes.LibraryStatistics.DELETE_CONSUMPTION_RECORD); + Version(1); + DontCatchExceptions(); + } + + /// + /// Deletes one consumption record of the current user. + /// + /// The request object. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(FastEndpoints.EmptyRequest request, CancellationToken cancellationToken) + { + // The consumption record belongs to the authenticated user, so no intermediary may store any response of this route, including its problem + // responses, and every response varies by the bearer token that authorized it. + HttpContext.Response.Headers["Cache-Control"] = "private, no-store"; + HttpContext.Response.Headers.Append("Vary", "Authorization"); + // Take the unique identifier from the route, so that it cannot be replaced by a value supplied in the query string. + string? consumptionRecordId = HttpContext.Request.RouteValues["recordId"]?.ToString(); + Result result = await _deleteConsumptionRecordCommandHandler.HandleAsync(new DeleteConsumptionRecordCommand(consumptionRecordId, TargetUserId: null), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Ok(success), Problem); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/DeleteConsumptionRecord/DeleteConsumptionRecordEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/DeleteConsumptionRecord/DeleteConsumptionRecordEndpointSummary.cs new file mode 100644 index 00000000..87795baa --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/DeleteConsumptionRecord/DeleteConsumptionRecordEndpointSummary.cs @@ -0,0 +1,94 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Library.Statistics.DeleteConsumptionRecord; + +/// +/// Class used for providing a textual description for the API endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class DeleteConsumptionRecordEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public DeleteConsumptionRecordEndpointSummary() + { + Summary = "Deletes one consumption record of the current user."; + Description = "Deletes one recorded consumption session of the current user, named by the route. The deletion is a hard delete, so the session stops contributing to the statistics and to the history lists immediately. Deleting an absent record, or a record that was already deleted in another tab, changes nothing and is not an error, so a retried deletion is safe; a concurrent write can still be rejected with a conflict. The resume point of the media item is not deleted: removing a record from the history and removing an item from continue watching are separate user actions. The record of another user is never deleted by this route."; + + Params["recordId"] = "The Id of the consumption record to delete."; + + Response(200, "The consumption record was successfully deleted."); + + Response(401, "Authentication required.", "application/problem+json", + example: new[] + { + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "Authentication failed", + instance = "/api/v1/users/me/consumption-history/2c1b0a9f-8e7d-4c6b-5a4f-3e2d1c0b9a8f" + }, + 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/consumption-history/2c1b0a9f-8e7d-4c6b-5a4f-3e2d1c0b9a8f" + } + } + ); + + 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/consumption-history/2c1b0a9f-8e7d-4c6b-5a4f-3e2d1c0b9a8f", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + } + ); + + Response(409, "The request failed because the deletion could not be stored, because the database is busy or locked, or because another request changed the same data after this request read it. Repeating the request is safe.", "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/consumption-history/2c1b0a9f-8e7d-4c6b-5a4f-3e2d1c0b9a8f", + 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/consumption-history/2c1b0a9f-8e7d-4c6b-5a4f-3e2d1c0b9a8f", + errors = new Dictionary + { + { + "General.Validation", new[] + { + "ConsumptionRecordIdCannotBeEmpty" + } + } + }, + traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00" + } + ); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/DeleteConsumptionRecord/DeleteUserConsumptionRecordEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/DeleteConsumptionRecord/DeleteUserConsumptionRecordEndpoint.cs new file mode 100644 index 00000000..5b12acf5 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/DeleteConsumptionRecord/DeleteUserConsumptionRecordEndpoint.cs @@ -0,0 +1,60 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Core.MediaConsumption.Commands.DeleteConsumptionRecord; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Common.Routes.Library.Statistics; +using Lumina.Presentation.Api.Core.Endpoints.Common; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Library.Statistics.DeleteConsumptionRecord; + +/// +/// API endpoint for the /users/{userId}/consumption-history/{recordId} route. +/// +public class DeleteUserConsumptionRecordEndpoint : BaseEndpoint +{ + private readonly ICommandHandler> _deleteConsumptionRecordCommandHandler; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for handling delete consumption record commands. + public DeleteUserConsumptionRecordEndpoint(ICommandHandler> deleteConsumptionRecordCommandHandler) + { + _deleteConsumptionRecordCommandHandler = deleteConsumptionRecordCommandHandler; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(FastEndpoints.Http.DELETE); + Routes(ApiRoutes.LibraryStatistics.DELETE_USER_CONSUMPTION_RECORD); + Version(1); + DontCatchExceptions(); + } + + /// + /// Deletes one consumption record of a user. + /// + /// The request object. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(FastEndpoints.EmptyRequest request, CancellationToken cancellationToken) + { + // The consumption record belongs to the target user, and only that user or an Admin may read or delete it, 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.Append("Vary", "Authorization"); + // Take the unique identifiers from the route, so that they cannot be replaced by values supplied in the query string. + string? targetUserId = HttpContext.Request.RouteValues["userId"]?.ToString(); + string? consumptionRecordId = HttpContext.Request.RouteValues["recordId"]?.ToString(); + // The access policy in the command decides whether the caller is the target user or an admin, and a regular user targeting another user + // receives the same not authorized result as a route that names no accessible user. + Result result = await _deleteConsumptionRecordCommandHandler.HandleAsync(new DeleteConsumptionRecordCommand(consumptionRecordId, targetUserId), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Ok(success), Problem); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/DeleteConsumptionRecord/DeleteUserConsumptionRecordEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/DeleteConsumptionRecord/DeleteUserConsumptionRecordEndpointSummary.cs new file mode 100644 index 00000000..279c0bcb --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/DeleteConsumptionRecord/DeleteUserConsumptionRecordEndpointSummary.cs @@ -0,0 +1,96 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Library.Statistics.DeleteConsumptionRecord; + +/// +/// Class used for providing a textual description for the API endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class DeleteUserConsumptionRecordEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public DeleteUserConsumptionRecordEndpointSummary() + { + Summary = "Deletes one consumption record of a user."; + Description = "Deletes one recorded consumption session of a user, named by the route. A user can delete only their own records, while an Admin can select any user with the userId route parameter; a regular user targeting another user receives the same not authorized result as a route that names no accessible user. The deletion is a hard delete, so the session stops contributing to the statistics and to the history lists immediately. Deleting an absent record, or a record that was already deleted in another tab, changes nothing and is not an error, so a retried deletion is safe; a concurrent write can still be rejected with a conflict. The resume point of the media item is not deleted: removing a record from the history and removing an item from continue watching are separate user actions."; + + Params["userId"] = "The Id of the user whose record is deleted. An Admin can name any user; a regular user can only name themselves."; + Params["recordId"] = "The Id of the consumption record to delete."; + + Response(200, "The consumption record was successfully deleted."); + + Response(401, "Authentication required.", "application/problem+json", + example: new[] + { + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "Authentication failed", + instance = "/api/v1/users/{userId}/consumption-history/2c1b0a9f-8e7d-4c6b-5a4f-3e2d1c0b9a8f" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token has expired", + instance = "/api/v1/users/{userId}/consumption-history/2c1b0a9f-8e7d-4c6b-5a4f-3e2d1c0b9a8f" + } + } + ); + + Response(403, "The request failed because the authenticated request does not carry the identity of a user, or because the current user is neither the target user nor an Admin.", "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/{userId}/consumption-history/2c1b0a9f-8e7d-4c6b-5a4f-3e2d1c0b9a8f", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + } + ); + + Response(409, "The request failed because the deletion could not be stored, because the database is busy or locked, or because another request changed the same data after this request read it. Repeating the request is safe.", "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/{userId}/consumption-history/2c1b0a9f-8e7d-4c6b-5a4f-3e2d1c0b9a8f", + 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/{userId}/consumption-history/2c1b0a9f-8e7d-4c6b-5a4f-3e2d1c0b9a8f", + errors = new Dictionary + { + { + "General.Validation", new[] + { + "TargetUserIdIsInvalid", + "ConsumptionRecordIdCannotBeEmpty" + } + } + }, + traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00" + } + ); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetAllUsersConsumptionStatistics/GetAllUsersConsumptionStatisticsEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetAllUsersConsumptionStatistics/GetAllUsersConsumptionStatisticsEndpoint.cs new file mode 100644 index 00000000..5bfacbd2 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetAllUsersConsumptionStatistics/GetAllUsersConsumptionStatisticsEndpoint.cs @@ -0,0 +1,59 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.Mapping.MediaConsumption; +using Lumina.Application.Core.MediaConsumption.Queries.GetAllUsersConsumptionStatistics; +using Lumina.Contracts.Requests.MediaConsumption; +using Lumina.Contracts.Responses.MediaConsumption; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Common.Routes.Library.Statistics; +using Lumina.Presentation.Api.Core.Endpoints.Common; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Library.Statistics.GetAllUsersConsumptionStatistics; + +/// +/// API endpoint for the /users/consumption-statistics route. +/// +public class GetAllUsersConsumptionStatisticsEndpoint : BaseEndpoint +{ + private readonly IQueryHandler> _getAllUsersConsumptionStatisticsQueryHandler; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for handling get all users consumption statistics queries. + public GetAllUsersConsumptionStatisticsEndpoint(IQueryHandler> getAllUsersConsumptionStatisticsQueryHandler) + { + _getAllUsersConsumptionStatisticsQueryHandler = getAllUsersConsumptionStatisticsQueryHandler; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(FastEndpoints.Http.GET); + Routes(ApiRoutes.LibraryStatistics.GET_ALL_USERS_CONSUMPTION_STATISTICS); + Version(1); + DontCatchExceptions(); + } + + /// + /// Gets the consumption statistics of every user. + /// + /// The request containing the optional filters and the date range. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(GetAllUsersConsumptionStatisticsRequest request, CancellationToken cancellationToken) + { + // The consumption statistics belong to every user of the server, 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.Append("Vary", "Authorization"); + // The handler is the only place that checks the admin role, so a regular user receives the same not authorized result as any other protected administration route. + Result result = await _getAllUsersConsumptionStatisticsQueryHandler.HandleAsync(request.ToQuery(), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Ok(success), Problem); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetAllUsersConsumptionStatistics/GetAllUsersConsumptionStatisticsEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetAllUsersConsumptionStatistics/GetAllUsersConsumptionStatisticsEndpointSummary.cs new file mode 100644 index 00000000..975f397d --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetAllUsersConsumptionStatistics/GetAllUsersConsumptionStatisticsEndpointSummary.cs @@ -0,0 +1,198 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Contracts.Requests.MediaConsumption; +using Lumina.Contracts.Responses.MediaConsumption; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Library.Statistics.GetAllUsersConsumptionStatistics; + +/// +/// Class used for providing a textual description for the API endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class GetAllUsersConsumptionStatisticsEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public GetAllUsersConsumptionStatisticsEndpointSummary() + { + Summary = "Gets the consumption statistics of every user."; + Description = "Gets the consumption statistics of every user of the server, together with their combined totals, across every kind of media or restricted to one kind, one library, and a date range. Only an Admin can call this route; a regular user receives the same not authorized result as any other administration route. A session counts only when it completed, or when it reached the counting threshold of its media kind: 30 consecutive seconds of a music track or a podcast episode, 60 consecutive seconds of an audiobook, 3 consecutive minutes of a movie, a TV episode or a video, more than 5 consecutive pages of a book, or every view of a photo. The consumed duration totals every recorded session, including the sessions that do not count, while the counted, completed, and stopped session counts follow the counting rules. Each user summary carries its own breakdown by media kind, and the combined totals are derived from those summaries, so they can never disagree with the sum of the users."; + + ExampleRequest = new GetAllUsersConsumptionStatisticsRequest( + LibraryId: null, + MediaKind: null, + FromUtc: "2026-10-01T00:00:00Z", + ToUtc: "2026-10-31T23:59:59Z" + ); + + RequestParam(request => request.LibraryId, "The Id of the media library to restrict the statistics to. Optional."); + RequestParam(request => request.MediaKind, "The name of the kind of media to restrict the statistics to. Optional. Only the member names of the media kind enumeration are accepted."); + RequestParam(request => request.FromUtc, "The inclusive start of the date range. Optional."); + RequestParam(request => request.ToUtc, "The inclusive end of the date range. Optional."); + + ResponseParam(response => response.Total, "The combined consumption statistics of every user."); + ResponseParam(response => response.Users, "The consumption statistics of each user, ordered by user Id. Each summary carries the user Id and the same fields as a single user summary."); + ResponseParam(response => response.TotalConsumedDurationInSeconds, "The total duration consumed over every recorded session of every user, in seconds."); + ResponseParam(response => response.CountedSessionCount, "The number of recorded sessions of every user that count towards statistics."); + ResponseParam(response => response.CompletedSessionCount, "The number of recorded sessions of every user that completed."); + ResponseParam(response => response.StoppedSessionCount, "The number of recorded sessions of every user that stopped before they completed and count towards statistics."); + ResponseParam(response => response.CompletionRate, "The fraction of the counted sessions of every user that completed, between 0 and 1, or 0 when there is no counted session."); + ResponseParam(response => response.MediaKindSummaries, "The combined consumption statistics broken down by media kind."); + ResponseParam(response => response.UserId, "The Id of the user the summary belongs to."); + ResponseParam(response => response.TotalConsumedDurationInSeconds, "The total duration consumed over every recorded session of the user, in seconds."); + ResponseParam(response => response.CountedSessionCount, "The number of recorded sessions of the user that count towards statistics."); + ResponseParam(response => response.CompletedSessionCount, "The number of recorded sessions of the user that completed."); + ResponseParam(response => response.StoppedSessionCount, "The number of recorded sessions of the user that stopped before they completed and count towards statistics."); + ResponseParam(response => response.CompletionRate, "The fraction of the counted sessions of the user that completed, between 0 and 1."); + ResponseParam(response => response.MediaKindSummaries, "The consumption statistics of the user broken down by media kind."); + ResponseParam(response => response.MediaKind, "The kind of media the breakdown entry belongs to."); + ResponseParam(response => response.TotalConsumedDurationInSeconds, "The total duration consumed over every recorded session of the media kind, in seconds."); + ResponseParam(response => response.CountedSessionCount, "The number of recorded sessions of the media kind that count towards statistics."); + ResponseParam(response => response.CompletedSessionCount, "The number of recorded sessions of the media kind that completed."); + ResponseParam(response => response.StoppedSessionCount, "The number of recorded sessions of the media kind that stopped before they completed and count towards statistics."); + ResponseParam(response => response.CompletionRate, "The fraction of the counted sessions of the media kind that completed, between 0 and 1."); + + Response(statusCode: 200, description: "The consumption statistics of every user are returned.", contentType: "application/json", + example: new AllUsersConsumptionStatisticsResponse( + Total: new ConsumptionTotalsResponse( + TotalConsumedDurationInSeconds: 12874.5, + CountedSessionCount: 9, + CompletedSessionCount: 6, + StoppedSessionCount: 3, + CompletionRate: 0.6667, + MediaKindSummaries: + [ + new MediaKindConsumptionSummaryResponse( + MediaKind: MediaKind.MusicTrack, + TotalConsumedDurationInSeconds: 5554.5, + CountedSessionCount: 7, + CompletedSessionCount: 5, + StoppedSessionCount: 2, + CompletionRate: 0.7143 + ), + new MediaKindConsumptionSummaryResponse( + MediaKind: MediaKind.Book, + TotalConsumedDurationInSeconds: 7320, + CountedSessionCount: 2, + CompletedSessionCount: 1, + StoppedSessionCount: 1, + CompletionRate: 0.5 + ) + ] + ), + Users: + [ + new ConsumptionSummaryResponse( + UserId: Guid.Parse("1a2b3c4d-5e6f-4a1b-8c2d-3e4f5a6b7c8d"), + TotalConsumedDurationInSeconds: 8744.5, + CountedSessionCount: 6, + CompletedSessionCount: 4, + StoppedSessionCount: 2, + CompletionRate: 0.6667, + MediaKindSummaries: + [ + new MediaKindConsumptionSummaryResponse( + MediaKind: MediaKind.MusicTrack, + TotalConsumedDurationInSeconds: 1424.5, + CountedSessionCount: 4, + CompletedSessionCount: 3, + StoppedSessionCount: 1, + CompletionRate: 0.75 + ), + new MediaKindConsumptionSummaryResponse( + MediaKind: MediaKind.Book, + TotalConsumedDurationInSeconds: 7320, + CountedSessionCount: 2, + CompletedSessionCount: 1, + StoppedSessionCount: 1, + CompletionRate: 0.5 + ) + ] + ), + new ConsumptionSummaryResponse( + UserId: Guid.Parse("2b3c4d5e-6f70-4a1b-9c3d-4e5f6a7b8c9d"), + TotalConsumedDurationInSeconds: 4130, + CountedSessionCount: 3, + CompletedSessionCount: 2, + StoppedSessionCount: 1, + CompletionRate: 0.6667, + MediaKindSummaries: + [ + new MediaKindConsumptionSummaryResponse( + MediaKind: MediaKind.MusicTrack, + TotalConsumedDurationInSeconds: 4130, + CountedSessionCount: 3, + CompletedSessionCount: 2, + StoppedSessionCount: 1, + CompletionRate: 0.6667 + ) + ] + ) + ] + ) + ); + + 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/consumption-statistics" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token has expired", + instance = "/api/v1/users/consumption-statistics" + } + } + ); + + Response(403, "The request failed because the authenticated request does not carry the identity of a user, or because the current user is not an Admin.", "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/consumption-statistics", + 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/consumption-statistics", + errors = new Dictionary + { + { + "General.Validation", new[] + { + "LibraryIdCannotBeEmpty", + "UnsupportedMediaKind", + "ConsumptionDateRangeIsInvalid" + } + } + }, + traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00" + } + ); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetConsumptionStatistics/GetConsumptionStatisticsEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetConsumptionStatistics/GetConsumptionStatisticsEndpoint.cs new file mode 100644 index 00000000..2fa63318 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetConsumptionStatistics/GetConsumptionStatisticsEndpoint.cs @@ -0,0 +1,61 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.Mapping.MediaConsumption; +using Lumina.Application.Core.MediaConsumption.Queries.GetConsumptionStatistics; +using Lumina.Contracts.Requests.MediaConsumption; +using Lumina.Contracts.Responses.MediaConsumption; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Common.Routes.Library.Statistics; +using Lumina.Presentation.Api.Core.Endpoints.Common; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Library.Statistics.GetConsumptionStatistics; + +/// +/// API endpoint for the /users/me/consumption-statistics route. +/// +/// +/// Uses "me" because it is always for the currently authenticated user. +/// +public class GetConsumptionStatisticsEndpoint : BaseEndpoint +{ + private readonly IQueryHandler> _getConsumptionStatisticsQueryHandler; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for handling get consumption statistics queries. + public GetConsumptionStatisticsEndpoint(IQueryHandler> getConsumptionStatisticsQueryHandler) + { + _getConsumptionStatisticsQueryHandler = getConsumptionStatisticsQueryHandler; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(FastEndpoints.Http.GET); + Routes(ApiRoutes.LibraryStatistics.GET_CONSUMPTION_STATISTICS); + Version(1); + DontCatchExceptions(); + } + + /// + /// Gets the consumption statistics of the current user. + /// + /// The request containing the optional filters and the date range. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(GetConsumptionStatisticsRequest request, CancellationToken cancellationToken) + { + // The consumption statistics 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.Append("Vary", "Authorization"); + Result result = await _getConsumptionStatisticsQueryHandler.HandleAsync(request.ToQuery(targetUserId: null), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Ok(success), Problem); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetConsumptionStatistics/GetConsumptionStatisticsEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetConsumptionStatistics/GetConsumptionStatisticsEndpointSummary.cs new file mode 100644 index 00000000..0fa1d4ee --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetConsumptionStatistics/GetConsumptionStatisticsEndpointSummary.cs @@ -0,0 +1,140 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Contracts.Requests.MediaConsumption; +using Lumina.Contracts.Responses.MediaConsumption; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Library.Statistics.GetConsumptionStatistics; + +/// +/// Class used for providing a textual description for the API endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class GetConsumptionStatisticsEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public GetConsumptionStatisticsEndpointSummary() + { + Summary = "Gets the consumption statistics of the current user."; + Description = "Gets the consolidated consumption statistics of the current user, across every kind of media or restricted to one kind, one library, and a date range. A session counts only when it completed, or when it reached the counting threshold of its media kind: 30 consecutive seconds of a music track or a podcast episode, 60 consecutive seconds of an audiobook, 3 consecutive minutes of a movie, a TV episode or a video, more than 5 consecutive pages of a book, or every view of a photo. The consumed duration totals every recorded session, including the sessions that do not count, while the counted, completed, and stopped session counts follow the counting rules. The completion rate is the fraction of the counted sessions that completed. Music and book consumption are reported in the same summary, broken down by media kind. The statistics are derived from the recorded sessions, so deleting history changes them immediately. The statistics of another user are never returned by this route."; + + ExampleRequest = new GetConsumptionStatisticsRequest( + LibraryId: null, + MediaKind: null, + FromUtc: "2026-10-01T00:00:00Z", + ToUtc: "2026-10-31T23:59:59Z" + ); + + RequestParam(request => request.LibraryId, "The Id of the media library to restrict the statistics to. Optional."); + RequestParam(request => request.MediaKind, "The name of the kind of media to restrict the statistics to. Optional. Only the member names of the media kind enumeration are accepted."); + RequestParam(request => request.FromUtc, "The inclusive start of the date range. Optional."); + RequestParam(request => request.ToUtc, "The inclusive end of the date range. Optional."); + + ResponseParam(response => response.UserId, "The Id of the user the statistics belong to."); + ResponseParam(response => response.TotalConsumedDurationInSeconds, "The total duration consumed over every recorded session, in seconds."); + ResponseParam(response => response.CountedSessionCount, "The number of recorded sessions that count towards statistics."); + ResponseParam(response => response.CompletedSessionCount, "The number of recorded sessions that completed."); + ResponseParam(response => response.StoppedSessionCount, "The number of recorded sessions that stopped before they completed and count towards statistics."); + ResponseParam(response => response.CompletionRate, "The fraction of the counted sessions that completed, between 0 and 1, or 0 when there is no counted session."); + ResponseParam(response => response.MediaKindSummaries, "The consumption statistics broken down by media kind."); + ResponseParam(response => response.MediaKind, "The kind of media the breakdown entry belongs to."); + ResponseParam(response => response.TotalConsumedDurationInSeconds, "The total duration consumed over every recorded session of the media kind, in seconds."); + ResponseParam(response => response.CountedSessionCount, "The number of recorded sessions of the media kind that count towards statistics."); + ResponseParam(response => response.CompletedSessionCount, "The number of recorded sessions of the media kind that completed."); + ResponseParam(response => response.StoppedSessionCount, "The number of recorded sessions of the media kind that stopped before they completed and count towards statistics."); + ResponseParam(response => response.CompletionRate, "The fraction of the counted sessions of the media kind that completed, between 0 and 1."); + + Response(statusCode: 200, description: "The consumption statistics of the current user are returned.", contentType: "application/json", + example: new ConsumptionSummaryResponse( + UserId: Guid.Parse("1a2b3c4d-5e6f-4a1b-8c2d-3e4f5a6b7c8d"), + TotalConsumedDurationInSeconds: 8744.5, + CountedSessionCount: 6, + CompletedSessionCount: 4, + StoppedSessionCount: 2, + CompletionRate: 0.6667, + MediaKindSummaries: + [ + new MediaKindConsumptionSummaryResponse( + MediaKind: MediaKind.MusicTrack, + TotalConsumedDurationInSeconds: 1424.5, + CountedSessionCount: 4, + CompletedSessionCount: 3, + StoppedSessionCount: 1, + CompletionRate: 0.75 + ), + new MediaKindConsumptionSummaryResponse( + MediaKind: MediaKind.Book, + TotalConsumedDurationInSeconds: 7320, + CountedSessionCount: 2, + CompletedSessionCount: 1, + StoppedSessionCount: 1, + CompletionRate: 0.5 + ) + ] + ) + ); + + 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/consumption-statistics" + }, + 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/consumption-statistics" + } + } + ); + + 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/consumption-statistics", + 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/consumption-statistics", + errors = new Dictionary + { + { + "General.Validation", new[] + { + "LibraryIdCannotBeEmpty", + "UnsupportedMediaKind", + "ConsumptionDateRangeIsInvalid" + } + } + }, + traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00" + } + ); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetConsumptionStatistics/GetUserConsumptionStatisticsEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetConsumptionStatistics/GetUserConsumptionStatisticsEndpoint.cs new file mode 100644 index 00000000..2ddfb9f0 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetConsumptionStatistics/GetUserConsumptionStatisticsEndpoint.cs @@ -0,0 +1,61 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.Mapping.MediaConsumption; +using Lumina.Application.Core.MediaConsumption.Queries.GetConsumptionStatistics; +using Lumina.Contracts.Requests.MediaConsumption; +using Lumina.Contracts.Responses.MediaConsumption; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Common.Routes.Library.Statistics; +using Lumina.Presentation.Api.Core.Endpoints.Common; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Library.Statistics.GetConsumptionStatistics; + +/// +/// API endpoint for the /users/{userId}/consumption-statistics route. +/// +public class GetUserConsumptionStatisticsEndpoint : BaseEndpoint +{ + private readonly IQueryHandler> _getConsumptionStatisticsQueryHandler; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for handling get consumption statistics queries. + public GetUserConsumptionStatisticsEndpoint(IQueryHandler> getConsumptionStatisticsQueryHandler) + { + _getConsumptionStatisticsQueryHandler = getConsumptionStatisticsQueryHandler; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(FastEndpoints.Http.GET); + Routes(ApiRoutes.LibraryStatistics.GET_USER_CONSUMPTION_STATISTICS); + Version(1); + DontCatchExceptions(); + } + + /// + /// Gets the consumption statistics of a user. + /// + /// The request containing the optional filters and the date range. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(GetConsumptionStatisticsRequest request, CancellationToken cancellationToken) + { + // The consumption statistics belong to the target user, and only that user or an Admin may read them, 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.Append("Vary", "Authorization"); + // Take the target user from the route. The access policy in the query decides whether the caller is the target user or an admin, and a + // regular user targeting another user receives the same not authorized result as a route that names no accessible user. + string? targetUserId = HttpContext.Request.RouteValues["userId"]?.ToString(); + Result result = await _getConsumptionStatisticsQueryHandler.HandleAsync(request.ToQuery(targetUserId), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Ok(success), Problem); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetConsumptionStatistics/GetUserConsumptionStatisticsEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetConsumptionStatistics/GetUserConsumptionStatisticsEndpointSummary.cs new file mode 100644 index 00000000..9ffd43e8 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetConsumptionStatistics/GetUserConsumptionStatisticsEndpointSummary.cs @@ -0,0 +1,142 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Contracts.Requests.MediaConsumption; +using Lumina.Contracts.Responses.MediaConsumption; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Library.Statistics.GetConsumptionStatistics; + +/// +/// Class used for providing a textual description for the API endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class GetUserConsumptionStatisticsEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public GetUserConsumptionStatisticsEndpointSummary() + { + Summary = "Gets the consumption statistics of a user."; + Description = "Gets the consolidated consumption statistics of a user, across every kind of media or restricted to one kind, one library, and a date range. A user can read only their own statistics, while an Admin can select any user with the userId route parameter; a regular user targeting another user receives the same not authorized result as a route that names no accessible user. A session counts only when it completed, or when it reached the counting threshold of its media kind: 30 consecutive seconds of a music track or a podcast episode, 60 consecutive seconds of an audiobook, 3 consecutive minutes of a movie, a TV episode or a video, more than 5 consecutive pages of a book, or every view of a photo. The consumed duration totals every recorded session, including the sessions that do not count, while the counted, completed, and stopped session counts follow the counting rules. The completion rate is the fraction of the counted sessions that completed. Music and book consumption are reported in the same summary, broken down by media kind. The statistics are derived from the recorded sessions, so deleting history changes them immediately."; + + ExampleRequest = new GetConsumptionStatisticsRequest( + LibraryId: null, + MediaKind: null, + FromUtc: "2026-10-01T00:00:00Z", + ToUtc: "2026-10-31T23:59:59Z" + ); + + Params["userId"] = "The Id of the user whose statistics are retrieved. An Admin can name any user; a regular user can only name themselves."; + RequestParam(request => request.LibraryId, "The Id of the media library to restrict the statistics to. Optional."); + RequestParam(request => request.MediaKind, "The name of the kind of media to restrict the statistics to. Optional. Only the member names of the media kind enumeration are accepted."); + RequestParam(request => request.FromUtc, "The inclusive start of the date range. Optional."); + RequestParam(request => request.ToUtc, "The inclusive end of the date range. Optional."); + + ResponseParam(response => response.UserId, "The Id of the user the statistics belong to."); + ResponseParam(response => response.TotalConsumedDurationInSeconds, "The total duration consumed over every recorded session, in seconds."); + ResponseParam(response => response.CountedSessionCount, "The number of recorded sessions that count towards statistics."); + ResponseParam(response => response.CompletedSessionCount, "The number of recorded sessions that completed."); + ResponseParam(response => response.StoppedSessionCount, "The number of recorded sessions that stopped before they completed and count towards statistics."); + ResponseParam(response => response.CompletionRate, "The fraction of the counted sessions that completed, between 0 and 1, or 0 when there is no counted session."); + ResponseParam(response => response.MediaKindSummaries, "The consumption statistics broken down by media kind."); + ResponseParam(response => response.MediaKind, "The kind of media the breakdown entry belongs to."); + ResponseParam(response => response.TotalConsumedDurationInSeconds, "The total duration consumed over every recorded session of the media kind, in seconds."); + ResponseParam(response => response.CountedSessionCount, "The number of recorded sessions of the media kind that count towards statistics."); + ResponseParam(response => response.CompletedSessionCount, "The number of recorded sessions of the media kind that completed."); + ResponseParam(response => response.StoppedSessionCount, "The number of recorded sessions of the media kind that stopped before they completed and count towards statistics."); + ResponseParam(response => response.CompletionRate, "The fraction of the counted sessions of the media kind that completed, between 0 and 1."); + + Response(statusCode: 200, description: "The consumption statistics of the user are returned.", contentType: "application/json", + example: new ConsumptionSummaryResponse( + UserId: Guid.Parse("1a2b3c4d-5e6f-4a1b-8c2d-3e4f5a6b7c8d"), + TotalConsumedDurationInSeconds: 8744.5, + CountedSessionCount: 6, + CompletedSessionCount: 4, + StoppedSessionCount: 2, + CompletionRate: 0.6667, + MediaKindSummaries: + [ + new MediaKindConsumptionSummaryResponse( + MediaKind: MediaKind.MusicTrack, + TotalConsumedDurationInSeconds: 1424.5, + CountedSessionCount: 4, + CompletedSessionCount: 3, + StoppedSessionCount: 1, + CompletionRate: 0.75 + ), + new MediaKindConsumptionSummaryResponse( + MediaKind: MediaKind.Book, + TotalConsumedDurationInSeconds: 7320, + CountedSessionCount: 2, + CompletedSessionCount: 1, + StoppedSessionCount: 1, + CompletionRate: 0.5 + ) + ] + ) + ); + + 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/{userId}/consumption-statistics" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token has expired", + instance = "/api/v1/users/{userId}/consumption-statistics" + } + } + ); + + Response(403, "The request failed because the authenticated request does not carry the identity of a user, or because the current user is neither the target user nor an Admin.", "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/{userId}/consumption-statistics", + 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/{userId}/consumption-statistics", + errors = new Dictionary + { + { + "General.Validation", new[] + { + "TargetUserIdIsInvalid", + "LibraryIdCannotBeEmpty", + "UnsupportedMediaKind", + "ConsumptionDateRangeIsInvalid" + } + } + }, + traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00" + } + ); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetGenreConsumption/GetGenreConsumptionEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetGenreConsumption/GetGenreConsumptionEndpoint.cs new file mode 100644 index 00000000..79424078 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetGenreConsumption/GetGenreConsumptionEndpoint.cs @@ -0,0 +1,62 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.Mapping.MediaConsumption; +using Lumina.Application.Core.MediaConsumption.Queries.GetGenreConsumption; +using Lumina.Contracts.Requests.MediaConsumption; +using Lumina.Contracts.Responses.MediaConsumption; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Common.Routes.Library.Statistics; +using Lumina.Presentation.Api.Core.Endpoints.Common; +using Microsoft.AspNetCore.Http; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Library.Statistics.GetGenreConsumption; + +/// +/// API endpoint for the /users/me/consumption-statistics/genres route. +/// +/// +/// Uses "me" because it is always for the currently authenticated user. +/// +public class GetGenreConsumptionEndpoint : BaseEndpoint +{ + private readonly IQueryHandler>> _getGenreConsumptionQueryHandler; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for handling get genre consumption queries. + public GetGenreConsumptionEndpoint(IQueryHandler>> getGenreConsumptionQueryHandler) + { + _getGenreConsumptionQueryHandler = getGenreConsumptionQueryHandler; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(FastEndpoints.Http.GET); + Routes(ApiRoutes.LibraryStatistics.GET_GENRE_CONSUMPTION); + Version(1); + DontCatchExceptions(); + } + + /// + /// Gets the consumption statistics of the genres of the current user. + /// + /// The request containing the optional filters and the date range. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(GetGenreConsumptionRequest request, CancellationToken cancellationToken) + { + // The consumption statistics 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.Append("Vary", "Authorization"); + Result> result = await _getGenreConsumptionQueryHandler.HandleAsync(request.ToQuery(targetUserId: null), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Ok(success), Problem); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetGenreConsumption/GetGenreConsumptionEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetGenreConsumption/GetGenreConsumptionEndpointSummary.cs new file mode 100644 index 00000000..47153c04 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetGenreConsumption/GetGenreConsumptionEndpointSummary.cs @@ -0,0 +1,120 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Contracts.Requests.MediaConsumption; +using Lumina.Contracts.Responses.MediaConsumption; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Library.Statistics.GetGenreConsumption; + +/// +/// Class used for providing a textual description for the API endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class GetGenreConsumptionEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public GetGenreConsumptionEndpointSummary() + { + Summary = "Gets the consumption statistics of the genres of the current user."; + Description = "Gets the genres carried by the media items the current user consumed, grouped by lowercase name across every media kind, or restricted to one kind, one library, and a date range. Only an item with at least one session that counts towards statistics contributes, and each item contributes its genres once regardless of how many sessions it had, so a multi-genre item adds one to each of its genres, not one per session. The names are always lowercase and culture invariant, so a genre that is shared by a book and a track appears in one bucket. Genres of an item whose media item was deleted, or whose media library the user can no longer access, are not included, because their genres cannot be resolved, while their sessions still count in the summary. The statistics of another user are never returned by this route."; + + ExampleRequest = new GetGenreConsumptionRequest( + LibraryId: null, + MediaKind: null, + FromUtc: "2026-10-01T00:00:00.0000000Z", + ToUtc: "2026-10-31T23:59:59.0000000Z" + ); + + RequestParam(request => request.LibraryId, "The Id of the media library to restrict the statistics to. Optional."); + RequestParam(request => request.MediaKind, "The kind of media to restrict the statistics to. Optional."); + RequestParam(request => request.FromUtc, "The inclusive start of the date range. Optional."); + RequestParam(request => request.ToUtc, "The inclusive end of the date range. Optional."); + + ResponseParam(response => response.Name, "The lowercase name of the genre."); + ResponseParam(response => response.ConsumedItemCount, "The number of distinct media items that carry the genre and were consumed."); + ResponseParam(response => response.ConsumedDurationInSeconds, "The active duration consumed in the media items that carry the genre, in seconds."); + + Response>(statusCode: 200, description: "The consumption statistics of the genres of the current user are returned.", contentType: "application/json", + example: + [ + new GenreConsumptionResponse( + Name: "horror", + ConsumedItemCount: 3, + ConsumedDurationInSeconds: 5400 + ), + new GenreConsumptionResponse( + Name: "fantasy", + ConsumedItemCount: 2, + ConsumedDurationInSeconds: 7320 + ), + new GenreConsumptionResponse( + Name: "science fiction", + ConsumedItemCount: 1, + ConsumedDurationInSeconds: 1424.5 + ) + ] + ); + + 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/consumption-statistics/genres" + }, + 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/consumption-statistics/genres" + } + } + ); + + 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/consumption-statistics/genres", + 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/consumption-statistics/genres", + errors = new Dictionary + { + { + "General.Validation", new[] + { + "LibraryIdCannotBeEmpty", + "UnsupportedMediaKind", + "ConsumptionDateRangeIsInvalid" + } + } + }, + traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00" + } + ); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetGenreConsumption/GetUserGenreConsumptionEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetGenreConsumption/GetUserGenreConsumptionEndpoint.cs new file mode 100644 index 00000000..0103a081 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetGenreConsumption/GetUserGenreConsumptionEndpoint.cs @@ -0,0 +1,62 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.Mapping.MediaConsumption; +using Lumina.Application.Core.MediaConsumption.Queries.GetGenreConsumption; +using Lumina.Contracts.Requests.MediaConsumption; +using Lumina.Contracts.Responses.MediaConsumption; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Common.Routes.Library.Statistics; +using Lumina.Presentation.Api.Core.Endpoints.Common; +using Microsoft.AspNetCore.Http; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Library.Statistics.GetGenreConsumption; + +/// +/// API endpoint for the /users/{userId}/consumption-statistics/genres route. +/// +public class GetUserGenreConsumptionEndpoint : BaseEndpoint +{ + private readonly IQueryHandler>> _getGenreConsumptionQueryHandler; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for handling get genre consumption queries. + public GetUserGenreConsumptionEndpoint(IQueryHandler>> getGenreConsumptionQueryHandler) + { + _getGenreConsumptionQueryHandler = getGenreConsumptionQueryHandler; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(FastEndpoints.Http.GET); + Routes(ApiRoutes.LibraryStatistics.GET_USER_GENRE_CONSUMPTION); + Version(1); + DontCatchExceptions(); + } + + /// + /// Gets the consumption statistics of the genres of a user. + /// + /// The request containing the optional filters and the date range. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(GetGenreConsumptionRequest request, CancellationToken cancellationToken) + { + // The consumption statistics belong to the target user, and only that user or an Admin may read them, 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.Append("Vary", "Authorization"); + // Take the target user from the route. The access policy in the query decides whether the caller is the target user or an admin, and a + // regular user targeting another user receives the same not authorized result as a route that names no accessible user. + string? targetUserId = HttpContext.Request.RouteValues["userId"]?.ToString(); + Result> result = await _getGenreConsumptionQueryHandler.HandleAsync(request.ToQuery(targetUserId), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Ok(success), Problem); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetGenreConsumption/GetUserGenreConsumptionEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetGenreConsumption/GetUserGenreConsumptionEndpointSummary.cs new file mode 100644 index 00000000..818707d3 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetGenreConsumption/GetUserGenreConsumptionEndpointSummary.cs @@ -0,0 +1,122 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Contracts.Requests.MediaConsumption; +using Lumina.Contracts.Responses.MediaConsumption; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Library.Statistics.GetGenreConsumption; + +/// +/// Class used for providing a textual description for the API endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class GetUserGenreConsumptionEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public GetUserGenreConsumptionEndpointSummary() + { + Summary = "Gets the consumption statistics of the genres of a user."; + Description = "Gets the genres carried by the media items a user consumed, grouped by lowercase name across every media kind, or restricted to one kind, one library, and a date range. A user can read only their own statistics, while an Admin can select any user with the userId route parameter; a regular user targeting another user receives the same not authorized result as a route that names no accessible user. Only an item with at least one session that counts towards statistics contributes, and each item contributes its genres once regardless of how many sessions it had, so a multi-genre item adds one to each of its genres, not one per session. The names are always lowercase and culture invariant, so a genre that is shared by a book and a track appears in one bucket. Genres of an item whose media item was deleted, or whose media library the user can no longer access, are not included, because their genres cannot be resolved, while their sessions still count in the summary."; + + ExampleRequest = new GetGenreConsumptionRequest( + LibraryId: null, + MediaKind: null, + FromUtc: "2026-10-01T00:00:00.0000000Z", + ToUtc: "2026-10-31T23:59:59.0000000Z" + ); + + Params["userId"] = "The Id of the user whose statistics are retrieved. An Admin can name any user; a regular user can only name themselves."; + RequestParam(request => request.LibraryId, "The Id of the media library to restrict the statistics to. Optional."); + RequestParam(request => request.MediaKind, "The kind of media to restrict the statistics to. Optional."); + RequestParam(request => request.FromUtc, "The inclusive start of the date range. Optional."); + RequestParam(request => request.ToUtc, "The inclusive end of the date range. Optional."); + + ResponseParam(response => response.Name, "The lowercase name of the genre."); + ResponseParam(response => response.ConsumedItemCount, "The number of distinct media items that carry the genre and were consumed."); + ResponseParam(response => response.ConsumedDurationInSeconds, "The active duration consumed in the media items that carry the genre, in seconds."); + + Response>(statusCode: 200, description: "The consumption statistics of the genres of the user are returned.", contentType: "application/json", + example: + [ + new GenreConsumptionResponse( + Name: "horror", + ConsumedItemCount: 3, + ConsumedDurationInSeconds: 5400 + ), + new GenreConsumptionResponse( + Name: "fantasy", + ConsumedItemCount: 2, + ConsumedDurationInSeconds: 7320 + ), + new GenreConsumptionResponse( + Name: "science fiction", + ConsumedItemCount: 1, + ConsumedDurationInSeconds: 1424.5 + ) + ] + ); + + 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/{userId}/consumption-statistics/genres" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token has expired", + instance = "/api/v1/users/{userId}/consumption-statistics/genres" + } + } + ); + + Response(403, "The request failed because the authenticated request does not carry the identity of a user, or because the current user is neither the target user nor an Admin.", "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/{userId}/consumption-statistics/genres", + 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/{userId}/consumption-statistics/genres", + errors = new Dictionary + { + { + "General.Validation", new[] + { + "TargetUserIdIsInvalid", + "LibraryIdCannotBeEmpty", + "UnsupportedMediaKind", + "ConsumptionDateRangeIsInvalid" + } + } + }, + traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00" + } + ); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetMostConsumed/GetMostConsumedEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetMostConsumed/GetMostConsumedEndpoint.cs new file mode 100644 index 00000000..8c0e4117 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetMostConsumed/GetMostConsumedEndpoint.cs @@ -0,0 +1,62 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.Mapping.MediaConsumption; +using Lumina.Application.Core.MediaConsumption.Queries.GetMostConsumed; +using Lumina.Contracts.Requests.MediaConsumption; +using Lumina.Contracts.Responses.Common; +using Lumina.Contracts.Responses.MediaConsumption; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Common.Routes.Library.Statistics; +using Lumina.Presentation.Api.Core.Endpoints.Common; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Library.Statistics.GetMostConsumed; + +/// +/// API endpoint for the /users/me/consumption-history/most-consumed route. +/// +/// +/// Uses "me" because it is always for the currently authenticated user. +/// +public class GetMostConsumedEndpoint : BaseEndpoint +{ + private readonly IQueryHandler>> _getMostConsumedQueryHandler; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for handling get most consumed queries. + public GetMostConsumedEndpoint(IQueryHandler>> getMostConsumedQueryHandler) + { + _getMostConsumedQueryHandler = getMostConsumedQueryHandler; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(FastEndpoints.Http.GET); + Routes(ApiRoutes.LibraryStatistics.GET_MOST_CONSUMED); + Version(1); + DontCatchExceptions(); + } + + /// + /// Gets the most consumed media items of the current user. + /// + /// The request containing the optional filters and the page bounds. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(GetMostConsumedRequest request, CancellationToken cancellationToken) + { + // The consumption history belongs to the authenticated user, so no intermediary may store any response of this route, including its problem + // responses, and every response varies by the bearer token that authorized it. + HttpContext.Response.Headers["Cache-Control"] = "private, no-store"; + HttpContext.Response.Headers.Append("Vary", "Authorization"); + Result> result = await _getMostConsumedQueryHandler.HandleAsync(request.ToQuery(targetUserId: null), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Ok(success), Problem); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetMostConsumed/GetMostConsumedEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetMostConsumed/GetMostConsumedEndpointSummary.cs new file mode 100644 index 00000000..0c02ec57 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetMostConsumed/GetMostConsumedEndpointSummary.cs @@ -0,0 +1,160 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Contracts.Requests.MediaConsumption; +using Lumina.Contracts.Responses.Common; +using Lumina.Contracts.Responses.MediaConsumption; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Library.Statistics.GetMostConsumed; + +/// +/// Class used for providing a textual description for the API endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class GetMostConsumedEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public GetMostConsumedEndpointSummary() + { + Summary = "Gets the most consumed media items of the current user."; + Description = "Gets one page of the media items the current user consumed the most, across every kind of media or restricted to one kind, one library, and a date range. The items are ordered by the number of sessions that count towards statistics, then by the consumed duration, then by the last consumption date, and finally by the media item Id so the order is stable. Music and book sessions appear in the same list, and an item consumed many times appears once. An item whose sessions all fall below the counting threshold of its kind still appears in this list with a countedSessionCount of zero, but it is ordered after every item that has at least one counted session, so it normally appears on a later page. Each item carries the display details of the media item it references: the title, the collection, the creator and the cover art. An item 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 delete it from the history. The history of another user is never returned by this route."; + + ExampleRequest = new GetMostConsumedRequest( + LibraryId: null, + MediaKind: nameof(MediaKind.MusicTrack), + CurrentPage: 1, + PerPage: 50, + FromUtc: "2026-10-01T00:00:00Z", + ToUtc: "2026-10-31T23:59:59Z" + ); + + RequestParam(request => request.LibraryId, "The Id of the media library to restrict the history to. Optional."); + RequestParam(request => request.MediaKind, "The name of the kind of media to restrict the history to. Optional. Only the member names of the media kind enumeration are accepted."); + RequestParam(request => request.CurrentPage, "The one based page of media items to return. Optional."); + RequestParam(request => request.PerPage, "The number of media items per page. Optional."); + RequestParam(request => request.FromUtc, "The inclusive start of the date range. Optional."); + RequestParam(request => request.ToUtc, "The inclusive end of the date range. Optional."); + + ResponseParam>(response => response.Data, "The most consumed media items of the requested page, ordered by counted sessions, consumed duration, and last consumption date."); + ResponseParam>(response => response.CurrentPage, "The current page number."); + ResponseParam>(response => response.PerPage, "The number of media items retrieved per page."); + ResponseParam>(response => response.Count, "The total number of distinct media items that match the filters."); + ResponseParam>(response => response.NumberOfPages, "The total number of pages."); + ResponseParam(response => response.MediaKind, "The kind of the consumed media item."); + ResponseParam(response => response.MediaItemId, "The Id of the consumed media item."); + ResponseParam(response => response.LibraryId, "The Id of the media library that contains the media item."); + ResponseParam(response => response.IsAvailable, "Whether the media item still exists and its library is accessible to the current user."); + ResponseParam(response => response.Title, "The title of the media item, or an empty string when the item is not available."); + ResponseParam(response => response.CollectionTitle, "The title of the collection that contains the media item, or an empty string when there is none."); + ResponseParam(response => response.CreatorName, "The name of the creator of the media item, or an empty string when there is none."); + ResponseParam(response => response.CoverPath, "The path of the cover art of the media item, if available."); + ResponseParam(response => response.LastConsumedOnUtc, "The date and time when the media item was last consumed."); + ResponseParam(response => response.CountedSessionCount, "The number of consumption sessions of the media item that count towards statistics."); + ResponseParam(response => response.CompletedSessionCount, "The number of consumption sessions of the media item that completed."); + ResponseParam(response => response.ConsumedDurationInSeconds, "The active duration consumed in the media item, over all of its sessions, in seconds."); + + Response(200, "The most consumed media items of the current user are returned.", "application/json", + example: new PaginatedResponse + { + Data = + [ + new ConsumedItemResponse( + MediaKind: MediaKind.MusicTrack, + MediaItemId: Guid.Parse("9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f"), + LibraryId: Guid.Parse("3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a"), + IsAvailable: true, + Title: "The Show Must Go On", + CollectionTitle: "Innuendo", + CreatorName: "Queen", + CoverPath: "/artwork/albums/e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f/cover.jpg", + LastConsumedOnUtc: new DateTime(2026, 10, 24, 12, 12, 0, DateTimeKind.Utc), + CountedSessionCount: 4, + CompletedSessionCount: 3, + ConsumedDurationInSeconds: 1424.5 + ), + new ConsumedItemResponse( + MediaKind: MediaKind.Book, + MediaItemId: Guid.Parse("7a6b5c4d-3e2f-4a1b-8c9d-0e1f2a3b4c5d"), + LibraryId: Guid.Parse("6c7d8e9f-0a1b-4c2d-9e3f-4a5b6c7d8e9f"), + IsAvailable: true, + Title: "The Fellowship of the Ring", + CollectionTitle: string.Empty, + CreatorName: "J. R. R. Tolkien", + CoverPath: "/artwork/books/7a6b5c4d-3e2f-4a1b-8c9d-0e1f2a3b4c5d/cover.jpg", + LastConsumedOnUtc: new DateTime(2026, 10, 23, 20, 40, 0, DateTimeKind.Utc), + CountedSessionCount: 2, + CompletedSessionCount: 1, + ConsumedDurationInSeconds: 7320 + ) + ], + CurrentPage = 1, + PerPage = 50, + Count = 2, + NumberOfPages = 1 + } + ); + + Response(401, "Authentication required.", "application/problem+json", + example: new[] + { + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "Authentication failed", + instance = "/api/v1/users/me/consumption-history/most-consumed" + }, + 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/consumption-history/most-consumed" + } + } + ); + + 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/consumption-history/most-consumed", + 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/consumption-history/most-consumed", + errors = new Dictionary + { + { + "General.Validation", new[] + { + "LibraryIdCannotBeEmpty", + "UnsupportedMediaKind", + "ConsumptionDateRangeIsInvalid" + } + } + }, + traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00" + } + ); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetMostConsumed/GetUserMostConsumedEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetMostConsumed/GetUserMostConsumedEndpoint.cs new file mode 100644 index 00000000..ebb7a090 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetMostConsumed/GetUserMostConsumedEndpoint.cs @@ -0,0 +1,62 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.Mapping.MediaConsumption; +using Lumina.Application.Core.MediaConsumption.Queries.GetMostConsumed; +using Lumina.Contracts.Requests.MediaConsumption; +using Lumina.Contracts.Responses.Common; +using Lumina.Contracts.Responses.MediaConsumption; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Common.Routes.Library.Statistics; +using Lumina.Presentation.Api.Core.Endpoints.Common; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Library.Statistics.GetMostConsumed; + +/// +/// API endpoint for the /users/{userId}/consumption-history/most-consumed route. +/// +public class GetUserMostConsumedEndpoint : BaseEndpoint +{ + private readonly IQueryHandler>> _getMostConsumedQueryHandler; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for handling get most consumed queries. + public GetUserMostConsumedEndpoint(IQueryHandler>> getMostConsumedQueryHandler) + { + _getMostConsumedQueryHandler = getMostConsumedQueryHandler; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(FastEndpoints.Http.GET); + Routes(ApiRoutes.LibraryStatistics.GET_USER_MOST_CONSUMED); + Version(1); + DontCatchExceptions(); + } + + /// + /// Gets the most consumed media items of a user. + /// + /// The request containing the optional filters and the page bounds. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(GetMostConsumedRequest request, CancellationToken cancellationToken) + { + // The consumption history belongs to the target user, and only that user or an Admin may read it, 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.Append("Vary", "Authorization"); + // Take the target user from the route. The access policy in the query decides whether the caller is the target user or an admin, and a + // regular user targeting another user receives the same not authorized result as a route that names no accessible user. + string? targetUserId = HttpContext.Request.RouteValues["userId"]?.ToString(); + Result> result = await _getMostConsumedQueryHandler.HandleAsync(request.ToQuery(targetUserId), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Ok(success), Problem); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetMostConsumed/GetUserMostConsumedEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetMostConsumed/GetUserMostConsumedEndpointSummary.cs new file mode 100644 index 00000000..efca6d28 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetMostConsumed/GetUserMostConsumedEndpointSummary.cs @@ -0,0 +1,162 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Contracts.Requests.MediaConsumption; +using Lumina.Contracts.Responses.Common; +using Lumina.Contracts.Responses.MediaConsumption; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Library.Statistics.GetMostConsumed; + +/// +/// Class used for providing a textual description for the API endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class GetUserMostConsumedEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public GetUserMostConsumedEndpointSummary() + { + Summary = "Gets the most consumed media items of a user."; + Description = "Gets one page of the media items a user consumed the most, across every kind of media or restricted to one kind, one library, and a date range. A user can read only their own history, while an Admin can select any user with the userId route parameter; a regular user targeting another user receives the same not authorized result as a route that names no accessible user. The items are ordered by the number of sessions that count towards statistics, then by the consumed duration, then by the last consumption date, and finally by the media item Id so the order is stable. Music and book sessions appear in the same list, and an item consumed many times appears once. An item whose sessions all fall below the counting threshold of its kind still appears in this list with a countedSessionCount of zero, but it is ordered after every item that has at least one counted session, so it normally appears on a later page. Each item carries the display details of the media item it references: the title, the collection, the creator and the cover art. An item 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 delete it from the history."; + + ExampleRequest = new GetMostConsumedRequest( + LibraryId: null, + MediaKind: nameof(MediaKind.MusicTrack), + CurrentPage: 1, + PerPage: 50, + FromUtc: "2026-10-01T00:00:00Z", + ToUtc: "2026-10-31T23:59:59Z" + ); + + Params["userId"] = "The Id of the user whose history is retrieved. An Admin can name any user; a regular user can only name themselves."; + RequestParam(request => request.LibraryId, "The Id of the media library to restrict the history to. Optional."); + RequestParam(request => request.MediaKind, "The name of the kind of media to restrict the history to. Optional. Only the member names of the media kind enumeration are accepted."); + RequestParam(request => request.CurrentPage, "The one based page of media items to return. Optional."); + RequestParam(request => request.PerPage, "The number of media items per page. Optional."); + RequestParam(request => request.FromUtc, "The inclusive start of the date range. Optional."); + RequestParam(request => request.ToUtc, "The inclusive end of the date range. Optional."); + + ResponseParam>(response => response.Data, "The most consumed media items of the requested page, ordered by counted sessions, consumed duration, and last consumption date."); + ResponseParam>(response => response.CurrentPage, "The current page number."); + ResponseParam>(response => response.PerPage, "The number of media items retrieved per page."); + ResponseParam>(response => response.Count, "The total number of distinct media items that match the filters."); + ResponseParam>(response => response.NumberOfPages, "The total number of pages."); + ResponseParam(response => response.MediaKind, "The kind of the consumed media item."); + ResponseParam(response => response.MediaItemId, "The Id of the consumed media item."); + ResponseParam(response => response.LibraryId, "The Id of the media library that contains the media item."); + ResponseParam(response => response.IsAvailable, "Whether the media item still exists and its library is accessible to the current user."); + ResponseParam(response => response.Title, "The title of the media item, or an empty string when the item is not available."); + ResponseParam(response => response.CollectionTitle, "The title of the collection that contains the media item, or an empty string when there is none."); + ResponseParam(response => response.CreatorName, "The name of the creator of the media item, or an empty string when there is none."); + ResponseParam(response => response.CoverPath, "The path of the cover art of the media item, if available."); + ResponseParam(response => response.LastConsumedOnUtc, "The date and time when the media item was last consumed."); + ResponseParam(response => response.CountedSessionCount, "The number of consumption sessions of the media item that count towards statistics."); + ResponseParam(response => response.CompletedSessionCount, "The number of consumption sessions of the media item that completed."); + ResponseParam(response => response.ConsumedDurationInSeconds, "The active duration consumed in the media item, over all of its sessions, in seconds."); + + Response(200, "The most consumed media items of the user are returned.", "application/json", + example: new PaginatedResponse + { + Data = + [ + new ConsumedItemResponse( + MediaKind: MediaKind.MusicTrack, + MediaItemId: Guid.Parse("9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f"), + LibraryId: Guid.Parse("3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a"), + IsAvailable: true, + Title: "The Show Must Go On", + CollectionTitle: "Innuendo", + CreatorName: "Queen", + CoverPath: "/artwork/albums/e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f/cover.jpg", + LastConsumedOnUtc: new DateTime(2026, 10, 24, 12, 12, 0, DateTimeKind.Utc), + CountedSessionCount: 4, + CompletedSessionCount: 3, + ConsumedDurationInSeconds: 1424.5 + ), + new ConsumedItemResponse( + MediaKind: MediaKind.Book, + MediaItemId: Guid.Parse("7a6b5c4d-3e2f-4a1b-8c9d-0e1f2a3b4c5d"), + LibraryId: Guid.Parse("6c7d8e9f-0a1b-4c2d-9e3f-4a5b6c7d8e9f"), + IsAvailable: true, + Title: "The Fellowship of the Ring", + CollectionTitle: string.Empty, + CreatorName: "J. R. R. Tolkien", + CoverPath: "/artwork/books/7a6b5c4d-3e2f-4a1b-8c9d-0e1f2a3b4c5d/cover.jpg", + LastConsumedOnUtc: new DateTime(2026, 10, 23, 20, 40, 0, DateTimeKind.Utc), + CountedSessionCount: 2, + CompletedSessionCount: 1, + ConsumedDurationInSeconds: 7320 + ) + ], + CurrentPage = 1, + PerPage = 50, + Count = 2, + NumberOfPages = 1 + } + ); + + Response(401, "Authentication required.", "application/problem+json", + example: new[] + { + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "Authentication failed", + instance = "/api/v1/users/{userId}/consumption-history/most-consumed" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token has expired", + instance = "/api/v1/users/{userId}/consumption-history/most-consumed" + } + } + ); + + Response(403, "The request failed because the authenticated request does not carry the identity of a user, or because the current user is neither the target user nor an Admin.", "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/{userId}/consumption-history/most-consumed", + 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/{userId}/consumption-history/most-consumed", + errors = new Dictionary + { + { + "General.Validation", new[] + { + "TargetUserIdIsInvalid", + "LibraryIdCannotBeEmpty", + "UnsupportedMediaKind", + "ConsumptionDateRangeIsInvalid" + } + } + }, + traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00" + } + ); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetRecentlyConsumed/GetRecentlyConsumedEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetRecentlyConsumed/GetRecentlyConsumedEndpoint.cs new file mode 100644 index 00000000..763e19df --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetRecentlyConsumed/GetRecentlyConsumedEndpoint.cs @@ -0,0 +1,62 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.Mapping.MediaConsumption; +using Lumina.Application.Core.MediaConsumption.Queries.GetRecentlyConsumed; +using Lumina.Contracts.Requests.MediaConsumption; +using Lumina.Contracts.Responses.Common; +using Lumina.Contracts.Responses.MediaConsumption; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Common.Routes.Library.Statistics; +using Lumina.Presentation.Api.Core.Endpoints.Common; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Library.Statistics.GetRecentlyConsumed; + +/// +/// API endpoint for the /users/me/consumption-history/recently-consumed route. +/// +/// +/// Uses "me" because it is always for the currently authenticated user. +/// +public class GetRecentlyConsumedEndpoint : BaseEndpoint +{ + private readonly IQueryHandler>> _getRecentlyConsumedQueryHandler; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for handling get recently consumed queries. + public GetRecentlyConsumedEndpoint(IQueryHandler>> getRecentlyConsumedQueryHandler) + { + _getRecentlyConsumedQueryHandler = getRecentlyConsumedQueryHandler; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(FastEndpoints.Http.GET); + Routes(ApiRoutes.LibraryStatistics.GET_RECENTLY_CONSUMED); + Version(1); + DontCatchExceptions(); + } + + /// + /// Gets the recently consumed media items of the current user. + /// + /// The request containing the optional filters and the page bounds. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(GetRecentlyConsumedRequest request, CancellationToken cancellationToken) + { + // The consumption history belongs to the authenticated user, so no intermediary may store any response of this route, including its problem + // responses, and every response varies by the bearer token that authorized it. + HttpContext.Response.Headers["Cache-Control"] = "private, no-store"; + HttpContext.Response.Headers.Append("Vary", "Authorization"); + Result> result = await _getRecentlyConsumedQueryHandler.HandleAsync(request.ToQuery(targetUserId: null), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Ok(success), Problem); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetRecentlyConsumed/GetRecentlyConsumedEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetRecentlyConsumed/GetRecentlyConsumedEndpointSummary.cs new file mode 100644 index 00000000..f73719c7 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetRecentlyConsumed/GetRecentlyConsumedEndpointSummary.cs @@ -0,0 +1,160 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Contracts.Requests.MediaConsumption; +using Lumina.Contracts.Responses.Common; +using Lumina.Contracts.Responses.MediaConsumption; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Library.Statistics.GetRecentlyConsumed; + +/// +/// Class used for providing a textual description for the API endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class GetRecentlyConsumedEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public GetRecentlyConsumedEndpointSummary() + { + Summary = "Gets the recently consumed media items of the current user."; + Description = "Gets one page of the media items the current user consumed, from the most recently consumed, across every kind of media or restricted to one kind, one library, and a date range. Music and book sessions appear in the same list. An item whose sessions fall below the counting threshold of its kind is still listed, because the list shows the sessions that were really recorded; countedSessionCount reports only the sessions that count towards the statistics. Each item carries the display details of the media item it references: the title, the collection, the creator and the cover art. An item 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 delete it from the history. The history of another user is never returned by this route."; + + ExampleRequest = new GetRecentlyConsumedRequest( + LibraryId: null, + MediaKind: nameof(MediaKind.MusicTrack), + CurrentPage: 1, + PerPage: 50, + FromUtc: "2026-10-01T00:00:00Z", + ToUtc: "2026-10-31T23:59:59Z" + ); + + RequestParam(request => request.LibraryId, "The Id of the media library to restrict the history to. Optional."); + RequestParam(request => request.MediaKind, "The name of the kind of media to restrict the history to. Optional. Only the member names of the media kind enumeration are accepted."); + RequestParam(request => request.CurrentPage, "The one based page of media items to return. Optional."); + RequestParam(request => request.PerPage, "The number of media items per page. Optional."); + RequestParam(request => request.FromUtc, "The inclusive start of the date range. Optional."); + RequestParam(request => request.ToUtc, "The inclusive end of the date range. Optional."); + + ResponseParam>(response => response.Data, "The recently consumed media items of the requested page, from the most recently consumed."); + ResponseParam>(response => response.CurrentPage, "The current page number."); + ResponseParam>(response => response.PerPage, "The number of media items retrieved per page."); + ResponseParam>(response => response.Count, "The total number of distinct media items that match the filters."); + ResponseParam>(response => response.NumberOfPages, "The total number of pages."); + ResponseParam(response => response.MediaKind, "The kind of the consumed media item."); + ResponseParam(response => response.MediaItemId, "The Id of the consumed media item."); + ResponseParam(response => response.LibraryId, "The Id of the media library that contains the media item."); + ResponseParam(response => response.IsAvailable, "Whether the media item still exists and its library is accessible to the current user."); + ResponseParam(response => response.Title, "The title of the media item, or an empty string when the item is not available."); + ResponseParam(response => response.CollectionTitle, "The title of the collection that contains the media item, or an empty string when there is none."); + ResponseParam(response => response.CreatorName, "The name of the creator of the media item, or an empty string when there is none."); + ResponseParam(response => response.CoverPath, "The path of the cover art of the media item, if available."); + ResponseParam(response => response.LastConsumedOnUtc, "The date and time when the media item was last consumed."); + ResponseParam(response => response.CountedSessionCount, "The number of consumption sessions of the media item that count towards statistics."); + ResponseParam(response => response.CompletedSessionCount, "The number of consumption sessions of the media item that completed."); + ResponseParam(response => response.ConsumedDurationInSeconds, "The active duration consumed in the media item, over all of its sessions, in seconds."); + + Response(200, "The recently consumed media items of the current user are returned.", "application/json", + example: new PaginatedResponse + { + Data = + [ + new ConsumedItemResponse( + MediaKind: MediaKind.MusicTrack, + MediaItemId: Guid.Parse("9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f"), + LibraryId: Guid.Parse("3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a"), + IsAvailable: true, + Title: "The Show Must Go On", + CollectionTitle: "Innuendo", + CreatorName: "Queen", + CoverPath: "/artwork/albums/e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f/cover.jpg", + LastConsumedOnUtc: new DateTime(2026, 10, 24, 12, 12, 0, DateTimeKind.Utc), + CountedSessionCount: 4, + CompletedSessionCount: 3, + ConsumedDurationInSeconds: 1424.5 + ), + new ConsumedItemResponse( + MediaKind: MediaKind.Book, + MediaItemId: Guid.Parse("7a6b5c4d-3e2f-4a1b-8c9d-0e1f2a3b4c5d"), + LibraryId: Guid.Parse("6c7d8e9f-0a1b-4c2d-9e3f-4a5b6c7d8e9f"), + IsAvailable: true, + Title: "The Fellowship of the Ring", + CollectionTitle: string.Empty, + CreatorName: "J. R. R. Tolkien", + CoverPath: "/artwork/books/7a6b5c4d-3e2f-4a1b-8c9d-0e1f2a3b4c5d/cover.jpg", + LastConsumedOnUtc: new DateTime(2026, 10, 23, 20, 40, 0, DateTimeKind.Utc), + CountedSessionCount: 2, + CompletedSessionCount: 1, + ConsumedDurationInSeconds: 7320 + ) + ], + CurrentPage = 1, + PerPage = 50, + Count = 2, + NumberOfPages = 1 + } + ); + + Response(401, "Authentication required.", "application/problem+json", + example: new[] + { + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "Authentication failed", + instance = "/api/v1/users/me/consumption-history/recently-consumed" + }, + 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/consumption-history/recently-consumed" + } + } + ); + + 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/consumption-history/recently-consumed", + 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/consumption-history/recently-consumed", + errors = new Dictionary + { + { + "General.Validation", new[] + { + "LibraryIdCannotBeEmpty", + "UnsupportedMediaKind", + "ConsumptionDateRangeIsInvalid" + } + } + }, + traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00" + } + ); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetRecentlyConsumed/GetUserRecentlyConsumedEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetRecentlyConsumed/GetUserRecentlyConsumedEndpoint.cs new file mode 100644 index 00000000..5a880db5 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetRecentlyConsumed/GetUserRecentlyConsumedEndpoint.cs @@ -0,0 +1,62 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.Mapping.MediaConsumption; +using Lumina.Application.Core.MediaConsumption.Queries.GetRecentlyConsumed; +using Lumina.Contracts.Requests.MediaConsumption; +using Lumina.Contracts.Responses.Common; +using Lumina.Contracts.Responses.MediaConsumption; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Common.Routes.Library.Statistics; +using Lumina.Presentation.Api.Core.Endpoints.Common; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Library.Statistics.GetRecentlyConsumed; + +/// +/// API endpoint for the /users/{userId}/consumption-history/recently-consumed route. +/// +public class GetUserRecentlyConsumedEndpoint : BaseEndpoint +{ + private readonly IQueryHandler>> _getRecentlyConsumedQueryHandler; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for handling get recently consumed queries. + public GetUserRecentlyConsumedEndpoint(IQueryHandler>> getRecentlyConsumedQueryHandler) + { + _getRecentlyConsumedQueryHandler = getRecentlyConsumedQueryHandler; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(FastEndpoints.Http.GET); + Routes(ApiRoutes.LibraryStatistics.GET_USER_RECENTLY_CONSUMED); + Version(1); + DontCatchExceptions(); + } + + /// + /// Gets the recently consumed media items of a user. + /// + /// The request containing the optional filters and the page bounds. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(GetRecentlyConsumedRequest request, CancellationToken cancellationToken) + { + // The consumption history belongs to the target user, and only that user or an Admin may read it, 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.Append("Vary", "Authorization"); + // Take the target user from the route. The access policy in the query decides whether the caller is the target user or an admin, and a + // regular user targeting another user receives the same not authorized result as a route that names no accessible user. + string? targetUserId = HttpContext.Request.RouteValues["userId"]?.ToString(); + Result> result = await _getRecentlyConsumedQueryHandler.HandleAsync(request.ToQuery(targetUserId), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Ok(success), Problem); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetRecentlyConsumed/GetUserRecentlyConsumedEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetRecentlyConsumed/GetUserRecentlyConsumedEndpointSummary.cs new file mode 100644 index 00000000..2ebbcc2b --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetRecentlyConsumed/GetUserRecentlyConsumedEndpointSummary.cs @@ -0,0 +1,162 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Contracts.Requests.MediaConsumption; +using Lumina.Contracts.Responses.Common; +using Lumina.Contracts.Responses.MediaConsumption; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Library.Statistics.GetRecentlyConsumed; + +/// +/// Class used for providing a textual description for the API endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class GetUserRecentlyConsumedEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public GetUserRecentlyConsumedEndpointSummary() + { + Summary = "Gets the recently consumed media items of a user."; + Description = "Gets one page of the media items a user consumed, from the most recently consumed, across every kind of media or restricted to one kind, one library, and a date range. A user can read only their own history, while an Admin can select any user with the userId route parameter; a regular user targeting another user receives the same not authorized result as a route that names no accessible user. Music and book sessions appear in the same list. An item whose sessions fall below the counting threshold of its kind is still listed, because the list shows the sessions that were really recorded; countedSessionCount reports only the sessions that count towards the statistics. Each item carries the display details of the media item it references: the title, the collection, the creator and the cover art. An item 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 delete it from the history."; + + ExampleRequest = new GetRecentlyConsumedRequest( + LibraryId: null, + MediaKind: nameof(MediaKind.MusicTrack), + CurrentPage: 1, + PerPage: 50, + FromUtc: "2026-10-01T00:00:00Z", + ToUtc: "2026-10-31T23:59:59Z" + ); + + Params["userId"] = "The Id of the user whose history is retrieved. An Admin can name any user; a regular user can only name themselves."; + RequestParam(request => request.LibraryId, "The Id of the media library to restrict the history to. Optional."); + RequestParam(request => request.MediaKind, "The name of the kind of media to restrict the history to. Optional. Only the member names of the media kind enumeration are accepted."); + RequestParam(request => request.CurrentPage, "The one based page of media items to return. Optional."); + RequestParam(request => request.PerPage, "The number of media items per page. Optional."); + RequestParam(request => request.FromUtc, "The inclusive start of the date range. Optional."); + RequestParam(request => request.ToUtc, "The inclusive end of the date range. Optional."); + + ResponseParam>(response => response.Data, "The recently consumed media items of the requested page, from the most recently consumed."); + ResponseParam>(response => response.CurrentPage, "The current page number."); + ResponseParam>(response => response.PerPage, "The number of media items retrieved per page."); + ResponseParam>(response => response.Count, "The total number of distinct media items that match the filters."); + ResponseParam>(response => response.NumberOfPages, "The total number of pages."); + ResponseParam(response => response.MediaKind, "The kind of the consumed media item."); + ResponseParam(response => response.MediaItemId, "The Id of the consumed media item."); + ResponseParam(response => response.LibraryId, "The Id of the media library that contains the media item."); + ResponseParam(response => response.IsAvailable, "Whether the media item still exists and its library is accessible to the current user."); + ResponseParam(response => response.Title, "The title of the media item, or an empty string when the item is not available."); + ResponseParam(response => response.CollectionTitle, "The title of the collection that contains the media item, or an empty string when there is none."); + ResponseParam(response => response.CreatorName, "The name of the creator of the media item, or an empty string when there is none."); + ResponseParam(response => response.CoverPath, "The path of the cover art of the media item, if available."); + ResponseParam(response => response.LastConsumedOnUtc, "The date and time when the media item was last consumed."); + ResponseParam(response => response.CountedSessionCount, "The number of consumption sessions of the media item that count towards statistics."); + ResponseParam(response => response.CompletedSessionCount, "The number of consumption sessions of the media item that completed."); + ResponseParam(response => response.ConsumedDurationInSeconds, "The active duration consumed in the media item, over all of its sessions, in seconds."); + + Response(200, "The recently consumed media items of the user are returned.", "application/json", + example: new PaginatedResponse + { + Data = + [ + new ConsumedItemResponse( + MediaKind: MediaKind.MusicTrack, + MediaItemId: Guid.Parse("9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f"), + LibraryId: Guid.Parse("3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a"), + IsAvailable: true, + Title: "The Show Must Go On", + CollectionTitle: "Innuendo", + CreatorName: "Queen", + CoverPath: "/artwork/albums/e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f/cover.jpg", + LastConsumedOnUtc: new DateTime(2026, 10, 24, 12, 12, 0, DateTimeKind.Utc), + CountedSessionCount: 4, + CompletedSessionCount: 3, + ConsumedDurationInSeconds: 1424.5 + ), + new ConsumedItemResponse( + MediaKind: MediaKind.Book, + MediaItemId: Guid.Parse("7a6b5c4d-3e2f-4a1b-8c9d-0e1f2a3b4c5d"), + LibraryId: Guid.Parse("6c7d8e9f-0a1b-4c2d-9e3f-4a5b6c7d8e9f"), + IsAvailable: true, + Title: "The Fellowship of the Ring", + CollectionTitle: string.Empty, + CreatorName: "J. R. R. Tolkien", + CoverPath: "/artwork/books/7a6b5c4d-3e2f-4a1b-8c9d-0e1f2a3b4c5d/cover.jpg", + LastConsumedOnUtc: new DateTime(2026, 10, 23, 20, 40, 0, DateTimeKind.Utc), + CountedSessionCount: 2, + CompletedSessionCount: 1, + ConsumedDurationInSeconds: 7320 + ) + ], + CurrentPage = 1, + PerPage = 50, + Count = 2, + NumberOfPages = 1 + } + ); + + Response(401, "Authentication required.", "application/problem+json", + example: new[] + { + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "Authentication failed", + instance = "/api/v1/users/{userId}/consumption-history/recently-consumed" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token has expired", + instance = "/api/v1/users/{userId}/consumption-history/recently-consumed" + } + } + ); + + Response(403, "The request failed because the authenticated request does not carry the identity of a user, or because the current user is neither the target user nor an Admin.", "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/{userId}/consumption-history/recently-consumed", + 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/{userId}/consumption-history/recently-consumed", + errors = new Dictionary + { + { + "General.Validation", new[] + { + "TargetUserIdIsInvalid", + "LibraryIdCannotBeEmpty", + "UnsupportedMediaKind", + "ConsumptionDateRangeIsInvalid" + } + } + }, + traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00" + } + ); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetTagConsumption/GetTagConsumptionEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetTagConsumption/GetTagConsumptionEndpoint.cs new file mode 100644 index 00000000..aa5caa92 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetTagConsumption/GetTagConsumptionEndpoint.cs @@ -0,0 +1,62 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.Mapping.MediaConsumption; +using Lumina.Application.Core.MediaConsumption.Queries.GetTagConsumption; +using Lumina.Contracts.Requests.MediaConsumption; +using Lumina.Contracts.Responses.MediaConsumption; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Common.Routes.Library.Statistics; +using Lumina.Presentation.Api.Core.Endpoints.Common; +using Microsoft.AspNetCore.Http; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Library.Statistics.GetTagConsumption; + +/// +/// API endpoint for the /users/me/consumption-statistics/tags route. +/// +/// +/// Uses "me" because it is always for the currently authenticated user. +/// +public class GetTagConsumptionEndpoint : BaseEndpoint +{ + private readonly IQueryHandler>> _getTagConsumptionQueryHandler; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for handling get tag consumption queries. + public GetTagConsumptionEndpoint(IQueryHandler>> getTagConsumptionQueryHandler) + { + _getTagConsumptionQueryHandler = getTagConsumptionQueryHandler; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(FastEndpoints.Http.GET); + Routes(ApiRoutes.LibraryStatistics.GET_TAG_CONSUMPTION); + Version(1); + DontCatchExceptions(); + } + + /// + /// Gets the consumption statistics of the tags of the current user. + /// + /// The request containing the optional filters and the date range. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(GetTagConsumptionRequest request, CancellationToken cancellationToken) + { + // The consumption statistics 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.Append("Vary", "Authorization"); + Result> result = await _getTagConsumptionQueryHandler.HandleAsync(request.ToQuery(targetUserId: null), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Ok(success), Problem); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetTagConsumption/GetTagConsumptionEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetTagConsumption/GetTagConsumptionEndpointSummary.cs new file mode 100644 index 00000000..af3a686c --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetTagConsumption/GetTagConsumptionEndpointSummary.cs @@ -0,0 +1,120 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Contracts.Requests.MediaConsumption; +using Lumina.Contracts.Responses.MediaConsumption; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Library.Statistics.GetTagConsumption; + +/// +/// Class used for providing a textual description for the API endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class GetTagConsumptionEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public GetTagConsumptionEndpointSummary() + { + Summary = "Gets the consumption statistics of the tags of the current user."; + Description = "Gets the tags carried by the media items the current user consumed, grouped by lowercase name across every media kind, or restricted to one kind, one library, and a date range. Only an item with at least one session that counts towards statistics contributes, and each item contributes its tags once regardless of how many sessions it had, so a multi-tag item adds one to each of its tags, not one per session. The names are always lowercase and culture invariant, so a tag that is shared by a book and a track appears in one bucket. Tags of an item whose media item was deleted, or whose media library the user can no longer access, are not included, because their tags cannot be resolved, while their sessions still count in the summary. The statistics of another user are never returned by this route."; + + ExampleRequest = new GetTagConsumptionRequest( + LibraryId: null, + MediaKind: null, + FromUtc: "2026-10-01T00:00:00Z", + ToUtc: "2026-10-31T23:59:59Z" + ); + + RequestParam(request => request.LibraryId, "The Id of the media library to restrict the statistics to. Optional."); + RequestParam(request => request.MediaKind, "The name of the kind of media to restrict the statistics to. Optional. Only the member names of the media kind enumeration are accepted."); + RequestParam(request => request.FromUtc, "The inclusive start of the date range. Optional."); + RequestParam(request => request.ToUtc, "The inclusive end of the date range. Optional."); + + ResponseParam(response => response.Name, "The lowercase name of the tag."); + ResponseParam(response => response.ConsumedItemCount, "The number of distinct media items that carry the tag and were consumed."); + ResponseParam(response => response.ConsumedDurationInSeconds, "The active duration consumed in the media items that carry the tag, in seconds."); + + Response>(statusCode: 200, description: "The consumption statistics of the tags of the current user are returned.", contentType: "application/json", + example: + [ + new TagConsumptionResponse( + Name: "favourite", + ConsumedItemCount: 3, + ConsumedDurationInSeconds: 5400 + ), + new TagConsumptionResponse( + Name: "book-club", + ConsumedItemCount: 2, + ConsumedDurationInSeconds: 7320 + ), + new TagConsumptionResponse( + Name: "comfort-read", + ConsumedItemCount: 1, + ConsumedDurationInSeconds: 1424.5 + ) + ] + ); + + 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/consumption-statistics/tags" + }, + 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/consumption-statistics/tags" + } + } + ); + + 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/consumption-statistics/tags", + 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/consumption-statistics/tags", + errors = new Dictionary + { + { + "General.Validation", new[] + { + "LibraryIdCannotBeEmpty", + "UnsupportedMediaKind", + "ConsumptionDateRangeIsInvalid" + } + } + }, + traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00" + } + ); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetTagConsumption/GetUserTagConsumptionEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetTagConsumption/GetUserTagConsumptionEndpoint.cs new file mode 100644 index 00000000..0a2d9b4a --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetTagConsumption/GetUserTagConsumptionEndpoint.cs @@ -0,0 +1,62 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.Mapping.MediaConsumption; +using Lumina.Application.Core.MediaConsumption.Queries.GetTagConsumption; +using Lumina.Contracts.Requests.MediaConsumption; +using Lumina.Contracts.Responses.MediaConsumption; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Common.Routes.Library.Statistics; +using Lumina.Presentation.Api.Core.Endpoints.Common; +using Microsoft.AspNetCore.Http; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Library.Statistics.GetTagConsumption; + +/// +/// API endpoint for the /users/{userId}/consumption-statistics/tags route. +/// +public class GetUserTagConsumptionEndpoint : BaseEndpoint +{ + private readonly IQueryHandler>> _getTagConsumptionQueryHandler; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for handling get tag consumption queries. + public GetUserTagConsumptionEndpoint(IQueryHandler>> getTagConsumptionQueryHandler) + { + _getTagConsumptionQueryHandler = getTagConsumptionQueryHandler; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(FastEndpoints.Http.GET); + Routes(ApiRoutes.LibraryStatistics.GET_USER_TAG_CONSUMPTION); + Version(1); + DontCatchExceptions(); + } + + /// + /// Gets the consumption statistics of the tags of a user. + /// + /// The request containing the optional filters and the date range. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(GetTagConsumptionRequest request, CancellationToken cancellationToken) + { + // The consumption statistics belong to the target user, and only that user or an Admin may read them, 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.Append("Vary", "Authorization"); + // Take the target user from the route. The access policy in the query decides whether the caller is the target user or an admin, and a + // regular user targeting another user receives the same not authorized result as a route that names no accessible user. + string? targetUserId = HttpContext.Request.RouteValues["userId"]?.ToString(); + Result> result = await _getTagConsumptionQueryHandler.HandleAsync(request.ToQuery(targetUserId), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Ok(success), Problem); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetTagConsumption/GetUserTagConsumptionEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetTagConsumption/GetUserTagConsumptionEndpointSummary.cs new file mode 100644 index 00000000..f7871137 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetTagConsumption/GetUserTagConsumptionEndpointSummary.cs @@ -0,0 +1,122 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Contracts.Requests.MediaConsumption; +using Lumina.Contracts.Responses.MediaConsumption; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Library.Statistics.GetTagConsumption; + +/// +/// Class used for providing a textual description for the API endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class GetUserTagConsumptionEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public GetUserTagConsumptionEndpointSummary() + { + Summary = "Gets the consumption statistics of the tags of a user."; + Description = "Gets the tags carried by the media items a user consumed, grouped by lowercase name across every media kind, or restricted to one kind, one library, and a date range. A user can read only their own statistics, while an Admin can select any user with the userId route parameter; a regular user targeting another user receives the same not authorized result as a route that names no accessible user. Only an item with at least one session that counts towards statistics contributes, and each item contributes its tags once regardless of how many sessions it had, so a multi-tag item adds one to each of its tags, not one per session. The names are always lowercase and culture invariant, so a tag that is shared by a book and a track appears in one bucket. Tags of an item whose media item was deleted, or whose media library the user can no longer access, are not included, because their tags cannot be resolved, while their sessions still count in the summary."; + + ExampleRequest = new GetTagConsumptionRequest( + LibraryId: null, + MediaKind: null, + FromUtc: "2026-10-01T00:00:00Z", + ToUtc: "2026-10-31T23:59:59Z" + ); + + Params["userId"] = "The Id of the user whose statistics are retrieved. An Admin can name any user; a regular user can only name themselves."; + RequestParam(request => request.LibraryId, "The Id of the media library to restrict the statistics to. Optional."); + RequestParam(request => request.MediaKind, "The name of the kind of media to restrict the statistics to. Optional. Only the member names of the media kind enumeration are accepted."); + RequestParam(request => request.FromUtc, "The inclusive start of the date range. Optional."); + RequestParam(request => request.ToUtc, "The inclusive end of the date range. Optional."); + + ResponseParam(response => response.Name, "The lowercase name of the tag."); + ResponseParam(response => response.ConsumedItemCount, "The number of distinct media items that carry the tag and were consumed."); + ResponseParam(response => response.ConsumedDurationInSeconds, "The active duration consumed in the media items that carry the tag, in seconds."); + + Response>(statusCode: 200, description: "The consumption statistics of the tags of the user are returned.", contentType: "application/json", + example: + [ + new TagConsumptionResponse( + Name: "favourite", + ConsumedItemCount: 3, + ConsumedDurationInSeconds: 5400 + ), + new TagConsumptionResponse( + Name: "book-club", + ConsumedItemCount: 2, + ConsumedDurationInSeconds: 7320 + ), + new TagConsumptionResponse( + Name: "comfort-read", + ConsumedItemCount: 1, + ConsumedDurationInSeconds: 1424.5 + ) + ] + ); + + 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/{userId}/consumption-statistics/tags" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token has expired", + instance = "/api/v1/users/{userId}/consumption-statistics/tags" + } + } + ); + + Response(403, "The request failed because the authenticated request does not carry the identity of a user, or because the current user is neither the target user nor an Admin.", "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/{userId}/consumption-statistics/tags", + 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/{userId}/consumption-statistics/tags", + errors = new Dictionary + { + { + "General.Validation", new[] + { + "TargetUserIdIsInvalid", + "LibraryIdCannotBeEmpty", + "UnsupportedMediaKind", + "ConsumptionDateRangeIsInvalid" + } + } + }, + traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00" + } + ); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/MediaConsumption/CompleteConsumption/CompleteConsumptionEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/MediaConsumption/CompleteConsumption/CompleteConsumptionEndpoint.cs new file mode 100644 index 00000000..ff08a003 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/MediaConsumption/CompleteConsumption/CompleteConsumptionEndpoint.cs @@ -0,0 +1,63 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.Mapping.MediaConsumption; +using Lumina.Application.Core.MediaConsumption.Commands.CompleteConsumption; +using Lumina.Contracts.Requests.MediaConsumption; +using Lumina.Contracts.Responses.MediaConsumption; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Common.Routes.MediaConsumption; +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.MediaConsumption.CompleteConsumption; + +/// +/// API endpoint for the /users/me/consumption-records/{recordId}/complete route. +/// +/// +/// Uses "me" because it is always for the currently authenticated user. +/// +public class CompleteConsumptionEndpoint : BaseEndpoint +{ + private readonly ICommandHandler> _completeConsumptionCommandHandler; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for handling complete consumption commands. + public CompleteConsumptionEndpoint(ICommandHandler> completeConsumptionCommandHandler) + { + _completeConsumptionCommandHandler = completeConsumptionCommandHandler; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(FastEndpoints.Http.POST); + Routes(ApiRoutes.MediaConsumption.COMPLETE_CONSUMPTION); + Version(1); + DontCatchExceptions(); + } + + /// + /// Reports that a consumption session of the current user completed. + /// + /// The request containing the final position, the progress fraction, and the consumed duration. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(CompleteConsumptionRequest request, CancellationToken cancellationToken) + { + // The consumption record belongs to the authenticated user, so no intermediary may store any response of this route, including its problem + // responses, and every response varies by the bearer token that authorized it. + HttpContext.Response.Headers["Cache-Control"] = "private, no-store"; + HttpContext.Response.Headers.Append("Vary", "Authorization"); + // Take the unique identifier from the route, so that it cannot be replaced by a value posted in the body. + string? recordId = HttpContext.Request.RouteValues["recordId"]?.ToString(); + Result result = await _completeConsumptionCommandHandler.HandleAsync(request.ToCommand(recordId), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Ok(success), Problem); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/MediaConsumption/CompleteConsumption/CompleteConsumptionEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/MediaConsumption/CompleteConsumption/CompleteConsumptionEndpointSummary.cs new file mode 100644 index 00000000..d9074f4c --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/MediaConsumption/CompleteConsumption/CompleteConsumptionEndpointSummary.cs @@ -0,0 +1,194 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Contracts.Requests.MediaConsumption; +using Lumina.Contracts.Responses.MediaConsumption; +using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.MediaConsumption.CompleteConsumption; + +/// +/// Class used for providing a textual description for the API endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class CompleteConsumptionEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public CompleteConsumptionEndpointSummary() + { + Summary = "Completes a consumption session of the current user."; + Description = "Completes an in-progress consumption session of the current user, storing its final position, progress fraction, and active consumed duration. Completion is explicit, so it is recorded even when the media was not played to its final second. Completing a session deletes the resume point of the current user for the same media item. A music track reports its final position as a TimeOffset with TimeOffsetSeconds, while a book reports it as a Location with an opaque locator. A record of another user is reported with the same not found error as a missing record."; + + ExampleRequest = new CompleteConsumptionRequest( + Position: new MediaPositionRequest("TimeOffset", 300, null), + ProgressFraction: 1, + ConsumedDurationInSeconds: 300, + ConsecutivePagesRead: 0 + ); + RequestExamples.Add(new RequestExample(new CompleteConsumptionRequest( + Position: new MediaPositionRequest("Location", null, "epubcfi(/6/8[chapter-4]!/4/2/2)"), + ProgressFraction: 1, + ConsumedDurationInSeconds: 900, + ConsecutivePagesRead: 6 + ))); + Params["recordId"] = "The Id of the consumption record."; + + RequestParam(request => request.Position, "The final position reported for the media item, if the client knows it. It carries the position Kind, and either TimeOffsetSeconds or Location. Optional."); + RequestParam(request => request.ProgressFraction, "The final fraction of the media item that the client reached, between 0 and 1. Required."); + RequestParam(request => request.ConsumedDurationInSeconds, "The active duration consumed by the session, in seconds. Required."); + RequestParam(request => request.ConsecutivePagesRead, "The number of consecutive pages read in the session, used by page based media such as books. It must be omitted or zero for other kinds; a positive value is rejected with a forbidden error. When omitted, the count stored by the last progress report is kept. Optional."); + + ResponseParam(record => record.Id, "The Id of the consumption record."); + ResponseParam(record => record.LibraryId, "The Id of the media library that contains the consumed media item."); + ResponseParam(record => record.MediaItemId, "The Id of the consumed media item."); + ResponseParam(record => record.MediaKind, "The kind of media that was consumed."); + ResponseParam(record => record.Status, "The state of the consumption session."); + ResponseParam(record => record.StartedOnUtc, "The date and time when the session started."); + ResponseParam(record => record.LastActivityOnUtc, "The date and time when the session last received activity."); + ResponseParam(record => record.EndedOnUtc, "The date and time when the session completed."); + ResponseParam(record => record.ConsumedDurationInSeconds, "The active duration consumed by the session, in seconds."); + ResponseParam(record => record.LastPosition, "The final known position for the media item, if any. It carries the position Kind, and either TimeOffsetSeconds or Location."); + ResponseParam(record => record.LastProgressFraction, "The final reported progress fraction of the media item."); + ResponseParam(record => record.ConsecutivePagesRead, "The number of consecutive pages read in the session."); + + Response(statusCode: 200, description: "The consumption session is completed, its resume point is deleted, and the updated record is returned.", contentType: "application/json", + example: new ConsumptionRecordResponse( + Id: Guid.Parse("2c1b0a9f-8e7d-4c6b-5a4f-3e2d1c0b9a8f"), + LibraryId: Guid.Parse("3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a"), + MediaItemId: Guid.Parse("9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f"), + MediaKind: MediaKind.MusicTrack, + Status: ConsumptionStatus.Completed, + StartedOnUtc: new DateTime(2026, 10, 24, 12, 0, 0, DateTimeKind.Utc), + LastActivityOnUtc: new DateTime(2026, 10, 24, 12, 5, 0, DateTimeKind.Utc), + EndedOnUtc: new DateTime(2026, 10, 24, 12, 5, 0, DateTimeKind.Utc), + ConsumedDurationInSeconds: 300, + LastPosition: new MediaPositionResponse(MediaPositionKind.TimeOffset, 300, null), + LastProgressFraction: 1, + ConsecutivePagesRead: 0 + ) + ); + + 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/consumption-records/2c1b0a9f-8e7d-4c6b-5a4f-3e2d1c0b9a8f/complete" + }, + 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/consumption-records/2c1b0a9f-8e7d-4c6b-5a4f-3e2d1c0b9a8f/complete" + } + } + ); + + Response(403, "The request failed because the authenticated request does not carry the identity of a user, because the reported consumed duration is lower than the duration already stored for the session, or because a positive consecutive page count was reported for a kind of media that is not page based.", "application/problem+json", + example: new[] + { + new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.4", + title = "General.Unauthorized", + status = 403, + detail = "NotAuthorized", + instance = "/api/v1/users/me/consumption-records/2c1b0a9f-8e7d-4c6b-5a4f-3e2d1c0b9a8f/complete", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + }, + new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.4", + title = "General.Forbidden", + status = 403, + detail = "ConsumedDurationCannotDecrease", + instance = "/api/v1/users/me/consumption-records/2c1b0a9f-8e7d-4c6b-5a4f-3e2d1c0b9a8f/complete", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + }, + new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.4", + title = "General.Forbidden", + status = 403, + detail = "ConsecutivePagesReadIsOnlySupportedForPageBasedMedia", + instance = "/api/v1/users/me/consumption-records/2c1b0a9f-8e7d-4c6b-5a4f-3e2d1c0b9a8f/complete", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + } + } + ); + + Response(404, "The request failed because the consumption record does not exist, or it does not belong to the current user.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.5", + title = "General.NotFound", + status = 404, + detail = "ConsumptionRecordNotFound", + instance = "/api/v1/users/me/consumption-records/2c1b0a9f-8e7d-4c6b-5a4f-3e2d1c0b9a8f/complete", + traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00" + } + ); + + Response(409, "The request failed because the session is already terminal, or because another request changed it after this request read it.", "application/problem+json", + example: new[] + { + new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.10", + title = "General.Conflict", + status = 409, + detail = "ConsumptionIsAlreadyTerminal", + instance = "/api/v1/users/me/consumption-records/2c1b0a9f-8e7d-4c6b-5a4f-3e2d1c0b9a8f/complete", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + }, + new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.10", + title = "General.Conflict", + status = 409, + detail = "ConcurrencyConflict", + instance = "/api/v1/users/me/consumption-records/2c1b0a9f-8e7d-4c6b-5a4f-3e2d1c0b9a8f/complete", + 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/consumption-records/2c1b0a9f-8e7d-4c6b-5a4f-3e2d1c0b9a8f/complete", + errors = new Dictionary + { + { + "General.Validation", new[] + { + "ConsumptionRecordIdCannotBeEmpty", + "InvalidMediaPosition", + "InvalidProgressFraction", + "ConsumedDurationMustBeNonNegative", + "ConsumedDurationIsOutOfRange", + "ConsecutivePagesReadMustBeNonNegative" + } + } + }, + traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00" + } + ); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/MediaConsumption/GetConsumptionRecord/GetConsumptionRecordEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/MediaConsumption/GetConsumptionRecord/GetConsumptionRecordEndpoint.cs new file mode 100644 index 00000000..727ba9a5 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/MediaConsumption/GetConsumptionRecord/GetConsumptionRecordEndpoint.cs @@ -0,0 +1,61 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Core.MediaConsumption.Queries.GetConsumptionRecord; +using Lumina.Contracts.Responses.MediaConsumption; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Common.Routes.MediaConsumption; +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.MediaConsumption.GetConsumptionRecord; + +/// +/// API endpoint for the /users/me/consumption-records/{recordId} route. +/// +/// +/// Uses "me" because it is always for the currently authenticated user. +/// +public class GetConsumptionRecordEndpoint : BaseEndpoint +{ + private readonly IQueryHandler> _getConsumptionRecordQueryHandler; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for handling get consumption record queries. + public GetConsumptionRecordEndpoint(IQueryHandler> getConsumptionRecordQueryHandler) + { + _getConsumptionRecordQueryHandler = getConsumptionRecordQueryHandler; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(FastEndpoints.Http.GET); + Routes(ApiRoutes.MediaConsumption.GET_CONSUMPTION_RECORD); + Version(1); + DontCatchExceptions(); + } + + /// + /// Gets a consumption record of the current user. + /// + /// The request object. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(FastEndpoints.EmptyRequest request, CancellationToken cancellationToken) + { + // The consumption record belongs to the authenticated user, so no intermediary may store any response of this route, including its problem + // responses, and every response varies by the bearer token that authorized it. + HttpContext.Response.Headers["Cache-Control"] = "private, no-store"; + HttpContext.Response.Headers.Append("Vary", "Authorization"); + // Take the unique identifier from the route. + string? recordId = HttpContext.Request.RouteValues["recordId"]?.ToString(); + Result result = await _getConsumptionRecordQueryHandler.HandleAsync(new GetConsumptionRecordQuery(recordId), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Ok(success), Problem); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/MediaConsumption/GetConsumptionRecord/GetConsumptionRecordEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/MediaConsumption/GetConsumptionRecord/GetConsumptionRecordEndpointSummary.cs new file mode 100644 index 00000000..580da88b --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/MediaConsumption/GetConsumptionRecord/GetConsumptionRecordEndpointSummary.cs @@ -0,0 +1,126 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Contracts.Responses.MediaConsumption; +using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.MediaConsumption.GetConsumptionRecord; + +/// +/// Class used for providing a textual description for the API endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class GetConsumptionRecordEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public GetConsumptionRecordEndpointSummary() + { + Summary = "Retrieves a consumption record of the current user."; + Description = "Retrieves the consumption record identified by the route, when it belongs to the current user. The record carries the kind of media, the last reported position, the progress fraction, the consumed duration, the consecutive pages read for page based media, and whether the session is in progress, completed or stopped. It never carries a queue, a current index, a repeat or shuffle state, or a playback session. A record of another user is reported with the same not found error as a missing record. The example is a book record, whose position is an opaque location; a music track record uses a time offset instead."; + + Params["recordId"] = "The Id of the consumption record."; + + ResponseParam(record => record.Id, "The Id of the consumption record."); + ResponseParam(record => record.LibraryId, "The Id of the media library that contains the consumed media item."); + ResponseParam(record => record.MediaItemId, "The Id of the consumed media item."); + ResponseParam(record => record.MediaKind, "The kind of media that was consumed."); + ResponseParam(record => record.Status, "The state of the consumption session."); + ResponseParam(record => record.StartedOnUtc, "The date and time when the session started."); + ResponseParam(record => record.LastActivityOnUtc, "The date and time when the session last received activity."); + ResponseParam(record => record.EndedOnUtc, "The date and time when the session completed or stopped, if it has ended."); + ResponseParam(record => record.ConsumedDurationInSeconds, "The active duration consumed by the session, in seconds."); + ResponseParam(record => record.LastPosition, "The last known position for the media item, if any. It carries the position Kind, and either TimeOffsetSeconds or Location."); + ResponseParam(record => record.LastProgressFraction, "The latest reported progress fraction of the media item."); + ResponseParam(record => record.ConsecutivePagesRead, "The number of consecutive pages read in the session."); + + Response(statusCode: 200, description: "The consumption record is returned.", contentType: "application/json", + example: new ConsumptionRecordResponse( + Id: Guid.Parse("2c1b0a9f-8e7d-4c6b-5a4f-3e2d1c0b9a8f"), + LibraryId: Guid.Parse("3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a"), + MediaItemId: Guid.Parse("7a6b5c4d-3e2f-4a1b-8c9d-0e1f2a3b4c5d"), + MediaKind: MediaKind.Book, + Status: ConsumptionStatus.Stopped, + StartedOnUtc: new DateTime(2026, 10, 24, 12, 0, 0, DateTimeKind.Utc), + LastActivityOnUtc: new DateTime(2026, 10, 24, 12, 12, 0, DateTimeKind.Utc), + EndedOnUtc: new DateTime(2026, 10, 24, 12, 12, 0, DateTimeKind.Utc), + ConsumedDurationInSeconds: 720, + LastPosition: new MediaPositionResponse(MediaPositionKind.Location, null, "epubcfi(/6/4[chapter-3]!/4/2/2)"), + LastProgressFraction: 0.42, + ConsecutivePagesRead: 6 + ) + ); + + 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/consumption-records/2c1b0a9f-8e7d-4c6b-5a4f-3e2d1c0b9a8f" + }, + 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/consumption-records/2c1b0a9f-8e7d-4c6b-5a4f-3e2d1c0b9a8f" + } + } + ); + + 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/consumption-records/2c1b0a9f-8e7d-4c6b-5a4f-3e2d1c0b9a8f", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + } + ); + + Response(404, "The request failed because the consumption record does not exist, or it does not belong to the current user.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.5", + title = "General.NotFound", + status = 404, + detail = "ConsumptionRecordNotFound", + instance = "/api/v1/users/me/consumption-records/2c1b0a9f-8e7d-4c6b-5a4f-3e2d1c0b9a8f", + traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00" + } + ); + + Response(422, "The request did not pass validation checks.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc4918#section-11.2", + title = "General.Validation", + status = 422, + detail = "OneOrMoreValidationErrorsOccurred", + instance = "/api/v1/users/me/consumption-records/2c1b0a9f-8e7d-4c6b-5a4f-3e2d1c0b9a8f", + errors = new Dictionary + { + { + "General.Validation", new[] + { + "ConsumptionRecordIdCannotBeEmpty" + } + } + }, + traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00" + } + ); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/MediaConsumption/GetResumePoint/GetResumePointEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/MediaConsumption/GetResumePoint/GetResumePointEndpoint.cs new file mode 100644 index 00000000..dc91f473 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/MediaConsumption/GetResumePoint/GetResumePointEndpoint.cs @@ -0,0 +1,62 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Core.MediaConsumption.Queries.GetResumePoint; +using Lumina.Contracts.Responses.MediaConsumption; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Common.Routes.MediaConsumption; +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.MediaConsumption.GetResumePoint; + +/// +/// API endpoint for the /users/me/media-resume-points/{mediaKind}/{mediaItemId} route. +/// +/// +/// Uses "me" because it is always for the currently authenticated user. +/// +public class GetResumePointEndpoint : BaseEndpoint +{ + private readonly IQueryHandler> _getResumePointQueryHandler; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for handling get resume point queries. + public GetResumePointEndpoint(IQueryHandler> getResumePointQueryHandler) + { + _getResumePointQueryHandler = getResumePointQueryHandler; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(FastEndpoints.Http.GET); + Routes(ApiRoutes.MediaConsumption.GET_RESUME_POINT); + Version(1); + DontCatchExceptions(); + } + + /// + /// Gets the resume point of the current user for a media item. + /// + /// The request object. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(FastEndpoints.EmptyRequest request, CancellationToken cancellationToken) + { + // The resume point belongs to the authenticated user, so no intermediary may store any response of this route, including its problem + // responses, and every response varies by the bearer token that authorized it. + HttpContext.Response.Headers["Cache-Control"] = "private, no-store"; + HttpContext.Response.Headers.Append("Vary", "Authorization"); + // Take the unique identifiers from the route. + string? mediaKind = HttpContext.Request.RouteValues["mediaKind"]?.ToString(); + string? mediaItemId = HttpContext.Request.RouteValues["mediaItemId"]?.ToString(); + Result result = await _getResumePointQueryHandler.HandleAsync(new GetResumePointQuery(mediaKind, mediaItemId), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Ok(success), Problem); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/MediaConsumption/GetResumePoint/GetResumePointEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/MediaConsumption/GetResumePoint/GetResumePointEndpointSummary.cs new file mode 100644 index 00000000..46f008ab --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/MediaConsumption/GetResumePoint/GetResumePointEndpointSummary.cs @@ -0,0 +1,151 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Contracts.Responses.MediaConsumption; +using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.MediaConsumption.GetResumePoint; + +/// +/// Class used for providing a textual description for the API endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class GetResumePointEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public GetResumePointEndpointSummary() + { + Summary = "Retrieves the resume point of the current user for a media item."; + Description = "Retrieves the point at which the current user can resume the media item named by the route. A book example is /users/me/media-resume-points/Book/{bookId}, and a music track example is /users/me/media-resume-points/MusicTrack/{trackId}. A music track resume point carries a TimeOffset position, while a book resume point carries a Location with an opaque locator. Only the supported MusicTrack and Book kinds can resume. A planned kind whose catalogue does not exist yet is rejected with UnsupportedMediaKind, while a photo has no position representation and is rejected with MediaKindCannotResume. A resume point of another user is reported with the same not found error as a missing resume point. When the media item no longer exists, or no longer belongs to the recorded library, the orphan resume point is deleted and the item is reported as not found."; + + Params["mediaKind"] = "The kind of media to resume. One of MusicTrack or Book. A Photo cannot resume. Only the member names are accepted; numeric values are rejected."; + Params["mediaItemId"] = "The Id of the media item to resume."; + + ResponseParam(resumePoint => resumePoint.Id, "The Id of the resume point."); + ResponseParam(resumePoint => resumePoint.LibraryId, "The Id of the media library that contains the media item."); + ResponseParam(resumePoint => resumePoint.MediaItemId, "The Id of the media item to resume."); + ResponseParam(resumePoint => resumePoint.MediaKind, "The kind of media that is resumed."); + ResponseParam(resumePoint => resumePoint.LastPosition, "The position at which the media item can be resumed. It carries the position Kind, and either TimeOffsetSeconds or Location."); + ResponseParam(resumePoint => resumePoint.LastProgressFraction, "The progress fraction at which the media item can be resumed."); + ResponseParam(resumePoint => resumePoint.LastConsumedOnUtc, "The date and time when the media item was last consumed."); + + Response(statusCode: 200, description: "The resume point is returned.", contentType: "application/json", + example: new ResumePointResponse( + Id: Guid.Parse("4d5e6f70-8192-4a3b-9c4d-5e6f708192a3"), + LibraryId: Guid.Parse("3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a"), + MediaItemId: Guid.Parse("7a6b5c4d-3e2f-4a1b-8c9d-0e1f2a3b4c5d"), + MediaKind: MediaKind.Book, + LastPosition: new MediaPositionResponse(MediaPositionKind.Location, null, "epubcfi(/6/4[chapter-3]!/4/2/2)"), + LastProgressFraction: 0.42, + LastConsumedOnUtc: new DateTime(2026, 10, 24, 12, 12, 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/media-resume-points/Book/7a6b5c4d-3e2f-4a1b-8c9d-0e1f2a3b4c5d" + }, + 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/media-resume-points/Book/7a6b5c4d-3e2f-4a1b-8c9d-0e1f2a3b4c5d" + } + } + ); + + Response(403, "The request failed because the authenticated request does not carry the identity of a user, or because the kind of media cannot be resumed.", "application/problem+json", + example: new[] + { + new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.4", + title = "General.Unauthorized", + status = 403, + detail = "NotAuthorized", + instance = "/api/v1/users/me/media-resume-points/Photo/7a6b5c4d-3e2f-4a1b-8c9d-0e1f2a3b4c5d", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + }, + new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.4", + title = "General.Forbidden", + status = 403, + detail = "MediaKindCannotResume", + instance = "/api/v1/users/me/media-resume-points/Photo/7a6b5c4d-3e2f-4a1b-8c9d-0e1f2a3b4c5d", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + } + } + ); + + Response(404, "The request failed because the resume point does not exist, because the media item does not exist, or because the media item no longer belongs to the recorded library.", "application/problem+json", + example: new[] + { + new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.5", + title = "General.NotFound", + status = 404, + detail = "MediaResumePointNotFound", + instance = "/api/v1/users/me/media-resume-points/Book/7a6b5c4d-3e2f-4a1b-8c9d-0e1f2a3b4c5d", + traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00" + }, + new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.5", + title = "General.NotFound", + status = 404, + detail = "TrackNotFound", + instance = "/api/v1/users/me/media-resume-points/MusicTrack/9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f", + traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-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/media-resume-points/Book/7a6b5c4d-3e2f-4a1b-8c9d-0e1f2a3b4c5d", + traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00" + } + } + ); + + Response(422, "The request did not pass validation checks.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc4918#section-11.2", + title = "General.Validation", + status = 422, + detail = "OneOrMoreValidationErrorsOccurred", + instance = "/api/v1/users/me/media-resume-points/Book/7a6b5c4d-3e2f-4a1b-8c9d-0e1f2a3b4c5d", + errors = new Dictionary + { + { + "General.Validation", new[] + { + "MediaItemIdCannotBeEmpty", + "UnsupportedMediaKind" + } + } + }, + traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00" + } + ); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/MediaConsumption/ReportConsumptionProgress/ReportConsumptionProgressEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/MediaConsumption/ReportConsumptionProgress/ReportConsumptionProgressEndpoint.cs new file mode 100644 index 00000000..e02aff7b --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/MediaConsumption/ReportConsumptionProgress/ReportConsumptionProgressEndpoint.cs @@ -0,0 +1,63 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.Mapping.MediaConsumption; +using Lumina.Application.Core.MediaConsumption.Commands.ReportConsumptionProgress; +using Lumina.Contracts.Requests.MediaConsumption; +using Lumina.Contracts.Responses.MediaConsumption; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Common.Routes.MediaConsumption; +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.MediaConsumption.ReportConsumptionProgress; + +/// +/// API endpoint for the /users/me/consumption-records/{recordId}/progress route. +/// +/// +/// Uses "me" because it is always for the currently authenticated user. +/// +public class ReportConsumptionProgressEndpoint : BaseEndpoint +{ + private readonly ICommandHandler> _reportConsumptionProgressCommandHandler; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for handling report consumption progress commands. + public ReportConsumptionProgressEndpoint(ICommandHandler> reportConsumptionProgressCommandHandler) + { + _reportConsumptionProgressCommandHandler = reportConsumptionProgressCommandHandler; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(FastEndpoints.Http.PUT); + Routes(ApiRoutes.MediaConsumption.REPORT_CONSUMPTION_PROGRESS); + Version(1); + DontCatchExceptions(); + } + + /// + /// Reports the progress of a consumption session of the current user. + /// + /// The request containing the position, the progress fraction, and the consumed duration. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(ReportConsumptionProgressRequest request, CancellationToken cancellationToken) + { + // The consumption record belongs to the authenticated user, so no intermediary may store any response of this route, including its problem + // responses, and every response varies by the bearer token that authorized it. + HttpContext.Response.Headers["Cache-Control"] = "private, no-store"; + HttpContext.Response.Headers.Append("Vary", "Authorization"); + // Take the unique identifier from the route, so that it cannot be replaced by a value posted in the body. + string? recordId = HttpContext.Request.RouteValues["recordId"]?.ToString(); + Result result = await _reportConsumptionProgressCommandHandler.HandleAsync(request.ToCommand(recordId), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Ok(success), Problem); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/MediaConsumption/ReportConsumptionProgress/ReportConsumptionProgressEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/MediaConsumption/ReportConsumptionProgress/ReportConsumptionProgressEndpointSummary.cs new file mode 100644 index 00000000..e37bdc26 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/MediaConsumption/ReportConsumptionProgress/ReportConsumptionProgressEndpointSummary.cs @@ -0,0 +1,194 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Contracts.Requests.MediaConsumption; +using Lumina.Contracts.Responses.MediaConsumption; +using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.MediaConsumption.ReportConsumptionProgress; + +/// +/// Class used for providing a textual description for the API endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class ReportConsumptionProgressEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public ReportConsumptionProgressEndpointSummary() + { + Summary = "Reports the progress of a consumption session of the current user."; + Description = "Reports the last position, the progress fraction, and the active consumed duration of an in-progress consumption session of the current user. A music track reports its position as a TimeOffset with TimeOffsetSeconds, while a book reports it as a Location with an opaque locator and the number of consecutive pages read. The position and the progress fraction are the latest reported values and may move backwards. The consumed duration is the only monotonic measurement: it can never decrease within the session. A record of another user is reported with the same not found error as a missing record."; + + ExampleRequest = new ReportConsumptionProgressRequest( + Position: new MediaPositionRequest("TimeOffset", 92.5, null), + ProgressFraction: 0.31, + ConsumedDurationInSeconds: 92.5, + ConsecutivePagesRead: 0 + ); + RequestExamples.Add(new RequestExample(new ReportConsumptionProgressRequest( + Position: new MediaPositionRequest("Location", null, "epubcfi(/6/4[chapter-3]!/4/2/2)"), + ProgressFraction: 0.42, + ConsumedDurationInSeconds: 240, + ConsecutivePagesRead: 2 + ))); + Params["recordId"] = "The Id of the consumption record."; + + RequestParam(request => request.Position, "The last position reported for the media item, if the client knows it. It carries the position Kind, and either TimeOffsetSeconds or Location. Optional."); + RequestParam(request => request.ProgressFraction, "The fraction of the media item that the client reached, between 0 and 1. Required."); + RequestParam(request => request.ConsumedDurationInSeconds, "The active duration consumed by the session, in seconds. Required."); + RequestParam(request => request.ConsecutivePagesRead, "The number of consecutive pages read in the current session, used by page based media such as books. It must be zero for other kinds; a positive value is rejected with a forbidden error. Optional, defaults to 0."); + + ResponseParam(record => record.Id, "The Id of the consumption record."); + ResponseParam(record => record.LibraryId, "The Id of the media library that contains the consumed media item."); + ResponseParam(record => record.MediaItemId, "The Id of the consumed media item."); + ResponseParam(record => record.MediaKind, "The kind of media that was consumed."); + ResponseParam(record => record.Status, "The state of the consumption session."); + ResponseParam(record => record.StartedOnUtc, "The date and time when the session started."); + ResponseParam(record => record.LastActivityOnUtc, "The date and time when the session last received activity."); + ResponseParam(record => record.EndedOnUtc, "The date and time when the session completed or stopped, if it has ended."); + ResponseParam(record => record.ConsumedDurationInSeconds, "The active duration consumed by the session, in seconds."); + ResponseParam(record => record.LastPosition, "The last known position for the media item, if any. It carries the position Kind, and either TimeOffsetSeconds or Location."); + ResponseParam(record => record.LastProgressFraction, "The latest reported progress fraction of the media item."); + ResponseParam(record => record.ConsecutivePagesRead, "The number of consecutive pages read in the session."); + + Response(statusCode: 200, description: "The progress of the consumption session is reported and the updated record is returned.", contentType: "application/json", + example: new ConsumptionRecordResponse( + Id: Guid.Parse("2c1b0a9f-8e7d-4c6b-5a4f-3e2d1c0b9a8f"), + LibraryId: Guid.Parse("3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a"), + MediaItemId: Guid.Parse("9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f"), + MediaKind: MediaKind.MusicTrack, + Status: ConsumptionStatus.InProgress, + StartedOnUtc: new DateTime(2026, 10, 24, 12, 0, 0, DateTimeKind.Utc), + LastActivityOnUtc: new DateTime(2026, 10, 24, 12, 1, 32, 500, DateTimeKind.Utc), + EndedOnUtc: null, + ConsumedDurationInSeconds: 92.5, + LastPosition: new MediaPositionResponse(MediaPositionKind.TimeOffset, 92.5, null), + LastProgressFraction: 0.31, + ConsecutivePagesRead: 0 + ) + ); + + 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/consumption-records/2c1b0a9f-8e7d-4c6b-5a4f-3e2d1c0b9a8f/progress" + }, + 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/consumption-records/2c1b0a9f-8e7d-4c6b-5a4f-3e2d1c0b9a8f/progress" + } + } + ); + + Response(403, "The request failed because the authenticated request does not carry the identity of a user, because the reported consumed duration is lower than the duration already stored for the session, or because a session of a non-page-based kind reported consecutive pages.", "application/problem+json", + example: new[] + { + new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.4", + title = "General.Unauthorized", + status = 403, + detail = "NotAuthorized", + instance = "/api/v1/users/me/consumption-records/2c1b0a9f-8e7d-4c6b-5a4f-3e2d1c0b9a8f/progress", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + }, + new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.4", + title = "General.Forbidden", + status = 403, + detail = "ConsumedDurationCannotDecrease", + instance = "/api/v1/users/me/consumption-records/2c1b0a9f-8e7d-4c6b-5a4f-3e2d1c0b9a8f/progress", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + }, + new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.4", + title = "General.Forbidden", + status = 403, + detail = "ConsecutivePagesReadIsOnlySupportedForPageBasedMedia", + instance = "/api/v1/users/me/consumption-records/2c1b0a9f-8e7d-4c6b-5a4f-3e2d1c0b9a8f/progress", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + } + } + ); + + Response(404, "The request failed because the consumption record does not exist, or it does not belong to the current user.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.5", + title = "General.NotFound", + status = 404, + detail = "ConsumptionRecordNotFound", + instance = "/api/v1/users/me/consumption-records/2c1b0a9f-8e7d-4c6b-5a4f-3e2d1c0b9a8f/progress", + traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00" + } + ); + + Response(409, "The request failed because the session is not in progress anymore, or because another report changed it after this request read it.", "application/problem+json", + example: new[] + { + new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.10", + title = "General.Conflict", + status = 409, + detail = "ConsumptionIsNotInProgress", + instance = "/api/v1/users/me/consumption-records/2c1b0a9f-8e7d-4c6b-5a4f-3e2d1c0b9a8f/progress", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + }, + new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.10", + title = "General.Conflict", + status = 409, + detail = "ConcurrencyConflict", + instance = "/api/v1/users/me/consumption-records/2c1b0a9f-8e7d-4c6b-5a4f-3e2d1c0b9a8f/progress", + 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/consumption-records/2c1b0a9f-8e7d-4c6b-5a4f-3e2d1c0b9a8f/progress", + errors = new Dictionary + { + { + "General.Validation", new[] + { + "ConsumptionRecordIdCannotBeEmpty", + "InvalidMediaPosition", + "InvalidProgressFraction", + "ConsumedDurationMustBeNonNegative", + "ConsumedDurationIsOutOfRange", + "ConsecutivePagesReadMustBeNonNegative" + } + } + }, + traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00" + } + ); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/MediaConsumption/StartConsumption/StartConsumptionEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/MediaConsumption/StartConsumption/StartConsumptionEndpoint.cs new file mode 100644 index 00000000..f6b882ae --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/MediaConsumption/StartConsumption/StartConsumptionEndpoint.cs @@ -0,0 +1,60 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Core.MediaConsumption.Commands.StartConsumption; +using Lumina.Contracts.Responses.MediaConsumption; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Common.Routes.MediaConsumption; +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.MediaConsumption.StartConsumption; + +/// +/// API endpoint for the /libraries/{libraryId}/media-items/{mediaKind}/{mediaItemId}/consumption-records route. +/// +public class StartConsumptionEndpoint : BaseEndpoint +{ + private readonly ICommandHandler> _startConsumptionCommandHandler; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for handling start consumption commands. + public StartConsumptionEndpoint(ICommandHandler> startConsumptionCommandHandler) + { + _startConsumptionCommandHandler = startConsumptionCommandHandler; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(FastEndpoints.Http.POST); + Routes(ApiRoutes.MediaConsumption.START_CONSUMPTION); + Version(1); + DontCatchExceptions(); + } + + /// + /// Starts a media consumption session of the current user. + /// + /// The request object. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(FastEndpoints.EmptyRequest request, CancellationToken cancellationToken) + { + // The consumption record belongs to the authenticated user, so no intermediary may store any response of this route, including its problem + // responses, and every response varies by the bearer token that authorized it. + HttpContext.Response.Headers["Cache-Control"] = "private, no-store"; + HttpContext.Response.Headers.Append("Vary", "Authorization"); + // Take the unique identifiers from the route, so that they cannot be replaced by values posted in a body. + string? libraryId = HttpContext.Request.RouteValues["libraryId"]?.ToString(); + string? mediaKind = HttpContext.Request.RouteValues["mediaKind"]?.ToString(); + string? mediaItemId = HttpContext.Request.RouteValues["mediaItemId"]?.ToString(); + Result result = await _startConsumptionCommandHandler.HandleAsync(new StartConsumptionCommand(libraryId, mediaKind, mediaItemId), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Ok(success), Problem); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/MediaConsumption/StartConsumption/StartConsumptionEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/MediaConsumption/StartConsumption/StartConsumptionEndpointSummary.cs new file mode 100644 index 00000000..2b634da5 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/MediaConsumption/StartConsumption/StartConsumptionEndpointSummary.cs @@ -0,0 +1,163 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Contracts.Responses.MediaConsumption; +using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.MediaConsumption.StartConsumption; + +/// +/// Class used for providing a textual description for the API endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class StartConsumptionEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public StartConsumptionEndpointSummary() + { + Summary = "Starts a media consumption session of the current user."; + Description = "Starts a consumption record for the media item named by the route, in the library named by the route. The supported kinds are MusicTrack and Book. A music track example is /libraries/{libraryId}/media-items/MusicTrack/{trackId}/consumption-records, and a book example is /libraries/{libraryId}/media-items/Book/{bookId}/consumption-records. When the library tracks progress and the kind can resume, the new record starts from the stored resume point; the consumed duration always starts at zero. A missing media item and a media item that belongs to another library are reported with the same not found error, so the route cannot be used to probe another library. The record belongs to the current user, and it never stores a queue, a current index, a repeat or shuffle state, or a playback session."; + + Params["libraryId"] = "The Id of the media library that contains the media item."; + Params["mediaKind"] = "The kind of media that is consumed. One of MusicTrack or Book. Only the member names are accepted; numeric values are rejected."; + Params["mediaItemId"] = "The Id of the consumed media item."; + + ResponseParam(record => record.Id, "The Id of the consumption record."); + ResponseParam(record => record.LibraryId, "The Id of the media library that contains the consumed media item."); + ResponseParam(record => record.MediaItemId, "The Id of the consumed media item."); + ResponseParam(record => record.MediaKind, "The kind of media that was consumed."); + ResponseParam(record => record.Status, "The state of the consumption session."); + ResponseParam(record => record.StartedOnUtc, "The date and time when the session started."); + ResponseParam(record => record.LastActivityOnUtc, "The date and time when the session last received activity."); + ResponseParam(record => record.EndedOnUtc, "The date and time when the session completed or stopped, if it has ended."); + ResponseParam(record => record.ConsumedDurationInSeconds, "The active duration consumed by the session, in seconds."); + ResponseParam(record => record.LastPosition, "The last known position for the media item, if any. It carries the position Kind, and either TimeOffsetSeconds or Location."); + ResponseParam(record => record.LastProgressFraction, "The latest reported progress fraction of the media item."); + ResponseParam(record => record.ConsecutivePagesRead, "The number of consecutive pages read in the session."); + + Response(statusCode: 200, description: "The consumption record is started and returned.", contentType: "application/json", + example: new ConsumptionRecordResponse( + Id: Guid.Parse("2c1b0a9f-8e7d-4c6b-5a4f-3e2d1c0b9a8f"), + LibraryId: Guid.Parse("3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a"), + MediaItemId: Guid.Parse("9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f"), + MediaKind: MediaKind.MusicTrack, + Status: ConsumptionStatus.InProgress, + StartedOnUtc: new DateTime(2026, 10, 24, 12, 0, 0, DateTimeKind.Utc), + LastActivityOnUtc: new DateTime(2026, 10, 24, 12, 0, 0, DateTimeKind.Utc), + EndedOnUtc: null, + ConsumedDurationInSeconds: 0, + LastPosition: null, + LastProgressFraction: 0, + ConsecutivePagesRead: 0 + ) + ); + + Response(401, "Authentication required.", "application/problem+json", + example: new[] + { + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "Authentication failed", + instance = "/api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/media-items/MusicTrack/9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f/consumption-records" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token has expired", + instance = "/api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/media-items/MusicTrack/9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f/consumption-records" + } + } + ); + + Response(403, "The request failed because the authenticated request does not carry the identity of a user, or because the current user cannot access the library.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.4", + title = "General.Unauthorized", + status = 403, + detail = "NotAuthorized", + instance = "/api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/media-items/MusicTrack/9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f/consumption-records", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + } + ); + + Response(404, "The request failed because the library does not exist, or because the media item does not exist, or does not belong to the library named by the route.", "application/problem+json", + example: new[] + { + new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.5", + title = "General.NotFound", + status = 404, + detail = "LibraryNotFound", + instance = "/api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/media-items/MusicTrack/9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f/consumption-records", + traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00" + }, + new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.5", + title = "General.NotFound", + status = 404, + detail = "TrackNotFound", + instance = "/api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/media-items/MusicTrack/9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f/consumption-records", + traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00" + }, + new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.5", + title = "General.NotFound", + status = 404, + detail = "BookNotFound", + instance = "/api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/media-items/Book/7a6b5c4d-3e2f-4a1b-8c9d-0e1f2a3b4c5d/consumption-records", + traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00" + } + } + ); + + Response(409, "The request failed because the consumption record could not be stored, because the database is busy or locked. Repeating the request is safe.", "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/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/media-items/MusicTrack/9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f/consumption-records", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + } + ); + + Response(422, "The request did not pass validation checks.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc4918#section-11.2", + title = "General.Validation", + status = 422, + detail = "OneOrMoreValidationErrorsOccurred", + instance = "/api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/media-items/MusicTrack/9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f/consumption-records", + errors = new Dictionary + { + { + "General.Validation", new[] + { + "LibraryIdCannotBeEmpty", + "MediaItemIdCannotBeEmpty", + "UnsupportedMediaKind" + } + } + }, + traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00" + } + ); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/MediaConsumption/StopConsumption/StopConsumptionEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/MediaConsumption/StopConsumption/StopConsumptionEndpoint.cs new file mode 100644 index 00000000..45f7cc63 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/MediaConsumption/StopConsumption/StopConsumptionEndpoint.cs @@ -0,0 +1,63 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.Mapping.MediaConsumption; +using Lumina.Application.Core.MediaConsumption.Commands.StopConsumption; +using Lumina.Contracts.Requests.MediaConsumption; +using Lumina.Contracts.Responses.MediaConsumption; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Common.Routes.MediaConsumption; +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.MediaConsumption.StopConsumption; + +/// +/// API endpoint for the /users/me/consumption-records/{recordId}/stop route. +/// +/// +/// Uses "me" because it is always for the currently authenticated user. +/// +public class StopConsumptionEndpoint : BaseEndpoint +{ + private readonly ICommandHandler> _stopConsumptionCommandHandler; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for handling stop consumption commands. + public StopConsumptionEndpoint(ICommandHandler> stopConsumptionCommandHandler) + { + _stopConsumptionCommandHandler = stopConsumptionCommandHandler; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(FastEndpoints.Http.POST); + Routes(ApiRoutes.MediaConsumption.STOP_CONSUMPTION); + Version(1); + DontCatchExceptions(); + } + + /// + /// Reports that a consumption session of the current user stopped before it completed. + /// + /// The request containing the final position, the progress fraction, and the consumed duration. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(StopConsumptionRequest request, CancellationToken cancellationToken) + { + // The consumption record belongs to the authenticated user, so no intermediary may store any response of this route, including its problem + // responses, and every response varies by the bearer token that authorized it. + HttpContext.Response.Headers["Cache-Control"] = "private, no-store"; + HttpContext.Response.Headers.Append("Vary", "Authorization"); + // Take the unique identifier from the route, so that it cannot be replaced by a value posted in the body. + string? recordId = HttpContext.Request.RouteValues["recordId"]?.ToString(); + Result result = await _stopConsumptionCommandHandler.HandleAsync(request.ToCommand(recordId), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Ok(success), Problem); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/MediaConsumption/StopConsumption/StopConsumptionEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/MediaConsumption/StopConsumption/StopConsumptionEndpointSummary.cs new file mode 100644 index 00000000..7d3078cf --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/MediaConsumption/StopConsumption/StopConsumptionEndpointSummary.cs @@ -0,0 +1,194 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Contracts.Requests.MediaConsumption; +using Lumina.Contracts.Responses.MediaConsumption; +using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.MediaConsumption.StopConsumption; + +/// +/// Class used for providing a textual description for the API endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class StopConsumptionEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public StopConsumptionEndpointSummary() + { + Summary = "Stops a consumption session of the current user."; + Description = "Stops an in-progress consumption session of the current user, storing its final position, progress fraction, and active consumed duration. When the library tracks progress and the final progress reaches the library completion threshold, the session is recorded as completed instead of stopped and its resume point is deleted. Otherwise the session is recorded as stopped, and when the library tracks progress, the kind can resume, and a final position is known, its resume point is saved for the next time. A music track reports its final position as a TimeOffset with TimeOffsetSeconds, while a book reports it as a Location with an opaque locator. A record of another user is reported with the same not found error as a missing record."; + + ExampleRequest = new StopConsumptionRequest( + Position: new MediaPositionRequest("TimeOffset", 60, null), + ProgressFraction: 0.6, + ConsumedDurationInSeconds: 60, + ConsecutivePagesRead: 0 + ); + RequestExamples.Add(new RequestExample(new StopConsumptionRequest( + Position: new MediaPositionRequest("Location", null, "epubcfi(/6/6[chapter-2]!/4/2/2)"), + ProgressFraction: 0.18, + ConsumedDurationInSeconds: 300, + ConsecutivePagesRead: 6 + ))); + Params["recordId"] = "The Id of the consumption record."; + + RequestParam(request => request.Position, "The final position reported for the media item, if the client knows it. It carries the position Kind, and either TimeOffsetSeconds or Location. Optional."); + RequestParam(request => request.ProgressFraction, "The final fraction of the media item that the client reached, between 0 and 1. Required."); + RequestParam(request => request.ConsumedDurationInSeconds, "The active duration consumed by the session, in seconds. Required."); + RequestParam(request => request.ConsecutivePagesRead, "The number of consecutive pages read in the session, used by page based media such as books. It must be omitted or zero for other kinds; a positive value is rejected with a forbidden error. When omitted, the count stored by the last progress report is kept. Optional."); + + ResponseParam(record => record.Id, "The Id of the consumption record."); + ResponseParam(record => record.LibraryId, "The Id of the media library that contains the consumed media item."); + ResponseParam(record => record.MediaItemId, "The Id of the consumed media item."); + ResponseParam(record => record.MediaKind, "The kind of media that was consumed."); + ResponseParam(record => record.Status, "The state of the consumption session."); + ResponseParam(record => record.StartedOnUtc, "The date and time when the session started."); + ResponseParam(record => record.LastActivityOnUtc, "The date and time when the session last received activity."); + ResponseParam(record => record.EndedOnUtc, "The date and time when the session completed or stopped."); + ResponseParam(record => record.ConsumedDurationInSeconds, "The active duration consumed by the session, in seconds."); + ResponseParam(record => record.LastPosition, "The final known position for the media item, if any. It carries the position Kind, and either TimeOffsetSeconds or Location."); + ResponseParam(record => record.LastProgressFraction, "The final reported progress fraction of the media item."); + ResponseParam(record => record.ConsecutivePagesRead, "The number of consecutive pages read in the session."); + + Response(statusCode: 200, description: "The consumption session is stopped, or completed when it reached the library threshold, and the updated record is returned.", contentType: "application/json", + example: new ConsumptionRecordResponse( + Id: Guid.Parse("2c1b0a9f-8e7d-4c6b-5a4f-3e2d1c0b9a8f"), + LibraryId: Guid.Parse("3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a"), + MediaItemId: Guid.Parse("9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f"), + MediaKind: MediaKind.MusicTrack, + Status: ConsumptionStatus.Stopped, + StartedOnUtc: new DateTime(2026, 10, 24, 12, 0, 0, DateTimeKind.Utc), + LastActivityOnUtc: new DateTime(2026, 10, 24, 12, 1, 0, DateTimeKind.Utc), + EndedOnUtc: new DateTime(2026, 10, 24, 12, 1, 0, DateTimeKind.Utc), + ConsumedDurationInSeconds: 60, + LastPosition: new MediaPositionResponse(MediaPositionKind.TimeOffset, 60, null), + LastProgressFraction: 0.6, + ConsecutivePagesRead: 0 + ) + ); + + 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/consumption-records/2c1b0a9f-8e7d-4c6b-5a4f-3e2d1c0b9a8f/stop" + }, + 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/consumption-records/2c1b0a9f-8e7d-4c6b-5a4f-3e2d1c0b9a8f/stop" + } + } + ); + + Response(403, "The request failed because the authenticated request does not carry the identity of a user, because the reported consumed duration is lower than the duration already stored for the session, or because a positive consecutive page count was reported for a kind of media that is not page based.", "application/problem+json", + example: new[] + { + new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.4", + title = "General.Unauthorized", + status = 403, + detail = "NotAuthorized", + instance = "/api/v1/users/me/consumption-records/2c1b0a9f-8e7d-4c6b-5a4f-3e2d1c0b9a8f/stop", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + }, + new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.4", + title = "General.Forbidden", + status = 403, + detail = "ConsumedDurationCannotDecrease", + instance = "/api/v1/users/me/consumption-records/2c1b0a9f-8e7d-4c6b-5a4f-3e2d1c0b9a8f/stop", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + }, + new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.4", + title = "General.Forbidden", + status = 403, + detail = "ConsecutivePagesReadIsOnlySupportedForPageBasedMedia", + instance = "/api/v1/users/me/consumption-records/2c1b0a9f-8e7d-4c6b-5a4f-3e2d1c0b9a8f/stop", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + } + } + ); + + Response(404, "The request failed because the consumption record does not exist, or it does not belong to the current user.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.5", + title = "General.NotFound", + status = 404, + detail = "ConsumptionRecordNotFound", + instance = "/api/v1/users/me/consumption-records/2c1b0a9f-8e7d-4c6b-5a4f-3e2d1c0b9a8f/stop", + traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00" + } + ); + + Response(409, "The request failed because the session is already terminal, or because another request changed it after this request read it.", "application/problem+json", + example: new[] + { + new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.10", + title = "General.Conflict", + status = 409, + detail = "ConsumptionIsAlreadyTerminal", + instance = "/api/v1/users/me/consumption-records/2c1b0a9f-8e7d-4c6b-5a4f-3e2d1c0b9a8f/stop", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + }, + new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.10", + title = "General.Conflict", + status = 409, + detail = "ConcurrencyConflict", + instance = "/api/v1/users/me/consumption-records/2c1b0a9f-8e7d-4c6b-5a4f-3e2d1c0b9a8f/stop", + 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/consumption-records/2c1b0a9f-8e7d-4c6b-5a4f-3e2d1c0b9a8f/stop", + errors = new Dictionary + { + { + "General.Validation", new[] + { + "ConsumptionRecordIdCannotBeEmpty", + "InvalidMediaPosition", + "InvalidProgressFraction", + "ConsumedDurationMustBeNonNegative", + "ConsumedDurationIsOutOfRange", + "ConsecutivePagesReadMustBeNonNegative" + } + } + }, + traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00" + } + ); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Playlists/AddPlaylistEntries/AddPlaylistEntriesEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Playlists/AddPlaylistEntries/AddPlaylistEntriesEndpoint.cs new file mode 100644 index 00000000..356403e6 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Playlists/AddPlaylistEntries/AddPlaylistEntriesEndpoint.cs @@ -0,0 +1,63 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.Mapping.Playlists; +using Lumina.Application.Core.Playlists.Commands.AddPlaylistEntries; +using Lumina.Contracts.Requests.Playlists; +using Lumina.Contracts.Responses.Playlists; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Common.Routes.Playlists; +using Lumina.Presentation.Api.Core.Endpoints.Common; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Playlists.AddPlaylistEntries; + +/// +/// API endpoint for the /users/me/playlists/{playlistId}/entries-batch route. +/// +/// +/// Uses "me" because it is always for the currently authenticated user. +/// +public class AddPlaylistEntriesEndpoint : BaseEndpoint +{ + private readonly ICommandHandler> _addPlaylistEntriesCommandHandler; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for handling add playlist entries commands. + public AddPlaylistEntriesEndpoint(ICommandHandler> addPlaylistEntriesCommandHandler) + { + _addPlaylistEntriesCommandHandler = addPlaylistEntriesCommandHandler; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(FastEndpoints.Http.POST); + Routes(ApiRoutes.Playlists.ADD_PLAYLIST_ENTRIES); + Version(1); + DontCatchExceptions(); + } + + /// + /// Adds several tracks to the end of the ordered entries of a playlist of the current user, in order. + /// + /// The request containing the tracks to add. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(AddPlaylistEntriesRequest request, CancellationToken cancellationToken) + { + // The playlists belong to the authenticated user, so no intermediary may store any response of this route, including its problem + // responses, and every response varies by the bearer token that authorized it. + HttpContext.Response.Headers["Cache-Control"] = "private, no-store"; + HttpContext.Response.Headers["Vary"] = "Authorization"; + // The playlist is identified by the route value, not by any id posted in the body. + string? playlistId = HttpContext.Request.RouteValues["playlistId"]?.ToString(); + Result result = await _addPlaylistEntriesCommandHandler.HandleAsync(request.ToCommand(playlistId), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Ok(success), Problem); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Playlists/AddPlaylistEntries/AddPlaylistEntriesEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Playlists/AddPlaylistEntries/AddPlaylistEntriesEndpointSummary.cs new file mode 100644 index 00000000..28dfa0dc --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Playlists/AddPlaylistEntries/AddPlaylistEntriesEndpointSummary.cs @@ -0,0 +1,159 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Contracts.Requests.Playlists; +using Lumina.Contracts.Responses.Playlists; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Playlists.AddPlaylistEntries; + +/// +/// Class used for providing a textual description for the API endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class AddPlaylistEntriesEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public AddPlaylistEntriesEndpointSummary() + { + Summary = "Adds several tracks to a playlist of the current user."; + Description = "Adds several tracks to the end of the ordered entries of the playlist identified by its Id, when the playlist belongs to the currently authenticated user, in the order the request lists them. Every track must exist, and the media library of every track must be reachable by the current user; a missing track and an unreachable library are both reported as not found, so the response never reveals whether a track exists in another user's library. The playlist must accept music tracks, which is the only media kind exposed until video libraries are catalogued. The same track may appear more than once. The request is applied as a whole: when any track is missing or not reachable, no entry is added. The tracks are inserted in bounded batches, so a long queue is accepted."; + + ExampleRequest = new AddPlaylistEntriesRequest( + TrackIds: + [ + Guid.Parse("9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f"), + Guid.Parse("8e1f2a3b-4c5d-4e6f-8a9b-0c1d2e3f4a5b") + ] + ); + RequestParam(request => request.TrackIds, "The Ids of the tracks to add, in the order they must take. Required."); + + ResponseParam(response => response.PlaylistId, "The Id of the playlist the entries were added to."); + ResponseParam(response => response.AddedCount, "The number of entries that were appended, including repeated tracks."); + ResponseParam(response => response.UpdatedOnUtc, "The date and time when the playlist was last updated, if applicable."); + + Response(200, "The number of added entries is returned with the playlist activity time.", + example: new PlaylistEntriesAddedResponse( + PlaylistId: Guid.Parse("1f2e3d4c-5b6a-4978-8a9b-0c1d2e3f4a5b"), + AddedCount: 12, + UpdatedOnUtc: new DateTime(2026, 10, 20, 12, 0, 0, DateTimeKind.Utc) + ) + ); + + Response(401, "Authentication required.", "application/problem+json", + example: new[] + { + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "Authentication failed", + instance = "/api/v1/users/me/playlists/1f2e3d4c-5b6a-4978-8a9b-0c1d2e3f4a5b/entries-batch" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token has expired", + instance = "/api/v1/users/me/playlists/1f2e3d4c-5b6a-4978-8a9b-0c1d2e3f4a5b/entries-batch" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token is invalid", + instance = "/api/v1/users/me/playlists/1f2e3d4c-5b6a-4978-8a9b-0c1d2e3f4a5b/entries-batch" + } + } + ); + + Response(403, "The request failed because the playlist does not accept music tracks.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.4", + title = "General.Forbidden", + status = 403, + detail = "PlaylistDoesNotAcceptMediaItems", + instance = "/api/v1/users/me/playlists/1f2e3d4c-5b6a-4978-8a9b-0c1d2e3f4a5b/entries-batch", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + } + ); + + Response(404, "The request failed because the playlist does not exist, does not belong to the current user, or a track does not exist or is not reachable.", "application/problem+json", + example: new[] + { + new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.5", + title = "General.NotFound", + status = 404, + detail = "PlaylistNotFound", + instance = "/api/v1/users/me/playlists/1f2e3d4c-5b6a-4978-8a9b-0c1d2e3f4a5b/entries-batch", + traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00" + }, + new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.5", + title = "General.NotFound", + status = 404, + detail = "TrackNotFound", + instance = "/api/v1/users/me/playlists/1f2e3d4c-5b6a-4978-8a9b-0c1d2e3f4a5b/entries-batch", + traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00" + } + } + ); + + Response(409, "The request failed because the entries could not be stored, because of a conflicting row or because the database is busy.", "application/problem+json", + example: new[] + { + new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.10", + title = "General.Conflict", + status = 409, + detail = "UniqueConstraintViolation", + instance = "/api/v1/users/me/playlists/1f2e3d4c-5b6a-4978-8a9b-0c1d2e3f4a5b/entries-batch", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + }, + new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.10", + title = "General.Conflict", + status = 409, + detail = "ConcurrencyConflict", + instance = "/api/v1/users/me/playlists/1f2e3d4c-5b6a-4978-8a9b-0c1d2e3f4a5b/entries-batch", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + } + } + ); + + Response(422, "The request did not pass validation checks.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc4918#section-11.2", + title = "General.Validation", + status = 422, + detail = "OneOrMoreValidationErrorsOccurred", + instance = "/api/v1/users/me/playlists/1f2e3d4c-5b6a-4978-8a9b-0c1d2e3f4a5b/entries-batch", + errors = new Dictionary + { + { + "General.Validation", new[] + { + "PlaylistIdCannotBeEmpty", + "TrackIdCannotBeEmpty" + } + } + }, + traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00" + } + ); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Playlists/AddPlaylistEntry/AddPlaylistEntryEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Playlists/AddPlaylistEntry/AddPlaylistEntryEndpoint.cs new file mode 100644 index 00000000..8c7a5143 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Playlists/AddPlaylistEntry/AddPlaylistEntryEndpoint.cs @@ -0,0 +1,63 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.Mapping.Playlists; +using Lumina.Application.Core.Playlists.Commands.AddPlaylistEntry; +using Lumina.Contracts.Requests.Playlists; +using Lumina.Contracts.Responses.Playlists; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Common.Routes.Playlists; +using Lumina.Presentation.Api.Core.Endpoints.Common; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Playlists.AddPlaylistEntry; + +/// +/// API endpoint for the /users/me/playlists/{playlistId}/entries route. +/// +/// +/// Uses "me" because it is always for the currently authenticated user. +/// +public class AddPlaylistEntryEndpoint : BaseEndpoint +{ + private readonly ICommandHandler> _addPlaylistEntryCommandHandler; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for handling add playlist entry commands. + public AddPlaylistEntryEndpoint(ICommandHandler> addPlaylistEntryCommandHandler) + { + _addPlaylistEntryCommandHandler = addPlaylistEntryCommandHandler; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(FastEndpoints.Http.POST); + Routes(ApiRoutes.Playlists.ADD_PLAYLIST_ENTRY); + Version(1); + DontCatchExceptions(); + } + + /// + /// Adds a track to the end of the ordered entries of a playlist of the current user. + /// + /// The request containing the track to add. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(AddPlaylistEntryRequest request, CancellationToken cancellationToken) + { + // The playlists belong to the authenticated user, so no intermediary may store any response of this route, including its problem + // responses, and every response varies by the bearer token that authorized it. + HttpContext.Response.Headers["Cache-Control"] = "private, no-store"; + HttpContext.Response.Headers["Vary"] = "Authorization"; + // The playlist is identified by the route value, not by any id posted in the body. + string? playlistId = HttpContext.Request.RouteValues["playlistId"]?.ToString(); + Result result = await _addPlaylistEntryCommandHandler.HandleAsync(request.ToCommand(playlistId), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Ok(success), Problem); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Playlists/AddPlaylistEntry/AddPlaylistEntryEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Playlists/AddPlaylistEntry/AddPlaylistEntryEndpointSummary.cs new file mode 100644 index 00000000..39915404 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Playlists/AddPlaylistEntry/AddPlaylistEntryEndpointSummary.cs @@ -0,0 +1,181 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Contracts.Requests.Playlists; +using Lumina.Contracts.Responses.Playlists; +using Lumina.Domain.SharedKernel.Common.Enums.Playlists; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Playlists.AddPlaylistEntry; + +/// +/// Class used for providing a textual description for the API endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class AddPlaylistEntryEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public AddPlaylistEntryEndpointSummary() + { + Summary = "Adds a track to a playlist of the current user."; + Description = "Adds a track to the end of the ordered entries of the playlist identified by its Id, when the playlist belongs to the currently authenticated user. The track must exist, and its media library must be reachable by the current user; a missing track and an unreachable library are both reported as not found, so the response never reveals whether a track exists in another user's library. The playlist must accept music tracks, which is the only media kind exposed until video libraries are catalogued. The same track may appear in a playlist more than once."; + + ExampleRequest = new AddPlaylistEntryRequest( + TrackId: Guid.Parse("9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f") + ); + RequestParam(request => request.TrackId, "The Id of the track to add. Required."); + + ResponseParam(response => response.PlaylistId, "The Id of the playlist the entry was added to."); + ResponseParam(response => response.Entry, "The added entry."); + ResponseParam(response => response.Entry.Id, "The Id of the added entry."); + ResponseParam(response => response.Entry.MediaItemId, "The Id of the media item the entry references."); + ResponseParam(response => response.Entry.MediaItemType, "The kind of media item the entry references."); + ResponseParam(response => response.Entry.Position, "The zero based position of the entry in the playlist."); + ResponseParam(response => response.Entry.LibraryId, "The Id of the media library that contains the media item."); + ResponseParam(response => response.Entry.CollectionId, "The Id of the collection that contains the media item."); + ResponseParam(response => response.Entry.CreatorId, "The Id of the creator of the media item."); + ResponseParam(response => response.Entry.MediaItemTitle, "The title of the media item."); + ResponseParam(response => response.Entry.CollectionTitle, "The title of the collection that contains the media item."); + ResponseParam(response => response.Entry.CreatorName, "The name of the creator of the media item."); + ResponseParam(response => response.Entry.DurationInSeconds, "The duration of the media item in seconds."); + ResponseParam(response => response.Entry.CoverPath, "The path of the cover art of the collection, if available."); + ResponseParam(response => response.UpdatedOnUtc, "The date and time when the playlist was last updated."); + + Response(200, "The added entry is returned with the playlist activity time.", + example: new PlaylistEntryAddedResponse( + PlaylistId: Guid.Parse("1f2e3d4c-5b6a-4978-8a9b-0c1d2e3f4a5b"), + Entry: new PlaylistEntryResponse( + Id: Guid.Parse("2a3b4c5d-6e7f-4a8b-9c0d-1e2f3a4b5c6d"), + MediaItemId: Guid.Parse("9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f"), + MediaItemType: PlaylistMediaItemType.MusicTrack, + Position: 11, + LibraryId: Guid.Parse("3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a"), + CollectionId: Guid.Parse("e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f"), + CreatorId: Guid.Parse("d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a"), + MediaItemTitle: "The Show Must Go On", + CollectionTitle: "Innuendo", + CreatorName: "Queen", + DurationInSeconds: 262, + CoverPath: "/artwork/albums/e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f/cover.jpg" + ), + UpdatedOnUtc: new DateTime(2026, 10, 20, 12, 0, 0, DateTimeKind.Utc) + ) + ); + + Response(401, "Authentication required.", "application/problem+json", + example: new[] + { + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "Authentication failed", + instance = "/api/v1/users/me/playlists/1f2e3d4c-5b6a-4978-8a9b-0c1d2e3f4a5b/entries" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token has expired", + instance = "/api/v1/users/me/playlists/1f2e3d4c-5b6a-4978-8a9b-0c1d2e3f4a5b/entries" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token is invalid", + instance = "/api/v1/users/me/playlists/1f2e3d4c-5b6a-4978-8a9b-0c1d2e3f4a5b/entries" + } + } + ); + + Response(403, "The request failed because the playlist does not accept music tracks.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.4", + title = "General.Forbidden", + status = 403, + detail = "PlaylistDoesNotAcceptMediaItems", + instance = "/api/v1/users/me/playlists/1f2e3d4c-5b6a-4978-8a9b-0c1d2e3f4a5b/entries", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + } + ); + + Response(404, "The request failed because the playlist does not exist, does not belong to the current user, or the track does not exist or is not reachable.", "application/problem+json", + example: new[] + { + new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.5", + title = "General.NotFound", + status = 404, + detail = "PlaylistNotFound", + instance = "/api/v1/users/me/playlists/1f2e3d4c-5b6a-4978-8a9b-0c1d2e3f4a5b/entries", + traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00" + }, + new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.5", + title = "General.NotFound", + status = 404, + detail = "TrackNotFound", + instance = "/api/v1/users/me/playlists/1f2e3d4c-5b6a-4978-8a9b-0c1d2e3f4a5b/entries", + traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00" + } + } + ); + + Response(409, "The request failed because the entry could not be stored, because of a conflicting row or because the database is busy.", "application/problem+json", + example: new[] + { + new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.10", + title = "General.Conflict", + status = 409, + detail = "UniqueConstraintViolation", + instance = "/api/v1/users/me/playlists/1f2e3d4c-5b6a-4978-8a9b-0c1d2e3f4a5b/entries", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + }, + new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.10", + title = "General.Conflict", + status = 409, + detail = "ConcurrencyConflict", + instance = "/api/v1/users/me/playlists/1f2e3d4c-5b6a-4978-8a9b-0c1d2e3f4a5b/entries", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + } + } + ); + + Response(422, "The request did not pass validation checks.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc4918#section-11.2", + title = "General.Validation", + status = 422, + detail = "OneOrMoreValidationErrorsOccurred", + instance = "/api/v1/users/me/playlists/1f2e3d4c-5b6a-4978-8a9b-0c1d2e3f4a5b/entries", + errors = new Dictionary + { + { + "General.Validation", new[] + { + "PlaylistIdCannotBeEmpty", + "TrackIdCannotBeEmpty" + } + } + }, + traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00" + } + ); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Playlists/AddPlaylistScopeEntries/AddPlaylistScopeEntriesEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Playlists/AddPlaylistScopeEntries/AddPlaylistScopeEntriesEndpoint.cs new file mode 100644 index 00000000..b6022976 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Playlists/AddPlaylistScopeEntries/AddPlaylistScopeEntriesEndpoint.cs @@ -0,0 +1,63 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.Mapping.Playlists; +using Lumina.Application.Core.Playlists.Commands.AddPlaylistScopeEntries; +using Lumina.Contracts.Requests.Playlists; +using Lumina.Contracts.Responses.Playlists; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Common.Routes.Playlists; +using Lumina.Presentation.Api.Core.Endpoints.Common; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Playlists.AddPlaylistScopeEntries; + +/// +/// API endpoint for the /users/me/playlists/{playlistId}/entries-scope route. +/// +/// +/// Uses "me" because it is always for the currently authenticated user. +/// +public class AddPlaylistScopeEntriesEndpoint : BaseEndpoint +{ + private readonly ICommandHandler> _addPlaylistScopeEntriesCommandHandler; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for handling add playlist scope entries commands. + public AddPlaylistScopeEntriesEndpoint(ICommandHandler> addPlaylistScopeEntriesCommandHandler) + { + _addPlaylistScopeEntriesCommandHandler = addPlaylistScopeEntriesCommandHandler; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(FastEndpoints.Http.POST); + Routes(ApiRoutes.Playlists.ADD_PLAYLIST_SCOPE_ENTRIES); + Version(1); + DontCatchExceptions(); + } + + /// + /// Adds every track of a music library, an artist or an album to a playlist of the current user. + /// + /// The request containing the scope whose tracks are appended. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(AddPlaylistScopeEntriesRequest request, CancellationToken cancellationToken) + { + // The playlists belong to the authenticated user, so no intermediary may store any response of this route, including its problem + // responses, and every response varies by the bearer token that authorized it. + HttpContext.Response.Headers["Cache-Control"] = "private, no-store"; + HttpContext.Response.Headers["Vary"] = "Authorization"; + // The playlist is identified by the route value, not by any id posted in the body. + string? playlistId = HttpContext.Request.RouteValues["playlistId"]?.ToString(); + Result result = await _addPlaylistScopeEntriesCommandHandler.HandleAsync(request.ToCommand(playlistId), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Ok(success), Problem); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Playlists/AddPlaylistScopeEntries/AddPlaylistScopeEntriesEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Playlists/AddPlaylistScopeEntries/AddPlaylistScopeEntriesEndpointSummary.cs new file mode 100644 index 00000000..2e5ef145 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Playlists/AddPlaylistScopeEntries/AddPlaylistScopeEntriesEndpointSummary.cs @@ -0,0 +1,149 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Contracts.Requests.Playlists; +using Lumina.Contracts.Responses.Playlists; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Playlists.AddPlaylistScopeEntries; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class AddPlaylistScopeEntriesEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public AddPlaylistScopeEntriesEndpointSummary() + { + Summary = "Adds every track of a library, artist or album to a playlist of the current user."; + Description = "Appends every track of the music library identified by libraryId, optionally limited to an artist or an album, to the end of the ordered entries of the playlist identified by its Id. The server resolves the scope in catalogue order with one set-based statement, so a whole library is appended without materializing its track Ids, sorting them in memory or sending them to the data access layer. The playlist must belong to the currently authenticated user, and the library must be reachable by the current user. An empty scope appends nothing and reports a zero count without an activity time. The same track may appear in a playlist more than once."; + + ExampleRequest = new AddPlaylistScopeEntriesRequest( + LibraryId: Guid.Parse("3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a"), + ArtistId: Guid.Parse("d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a"), + AlbumId: Guid.Parse("e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f") + ); + RequestParam(request => request.LibraryId, "The Id of the music library the scope belongs to. Required."); + RequestParam(request => request.ArtistId, "The Id of the artist the scope is limited to. Optional."); + RequestParam(request => request.AlbumId, "The Id of the album the scope is limited to. Optional."); + + ResponseParam(response => response.PlaylistId, "The Id of the playlist the entries were added to."); + ResponseParam(response => response.AddedCount, "The number of entries that were appended, including repeated tracks."); + ResponseParam(response => response.UpdatedOnUtc, "The date and time when the playlist was last updated, if applicable."); + + Response(200, "The scope was appended to the playlist.", + example: new PlaylistEntriesAddedResponse( + PlaylistId: Guid.Parse("1f2e3d4c-5b6a-4978-8a9b-0c1d2e3f4a5b"), + AddedCount: 120, + UpdatedOnUtc: new DateTime(2026, 10, 20, 12, 0, 0, DateTimeKind.Utc) + ) + ); + + Response(401, "Authentication required.", "application/problem+json", + example: new[] + { + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "Authentication failed", + instance = "/api/v1/users/me/playlists/1f2e3d4c-5b6a-4978-8a9b-0c1d2e3f4a5b/entries-scope" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token has expired", + instance = "/api/v1/users/me/playlists/1f2e3d4c-5b6a-4978-8a9b-0c1d2e3f4a5b/entries-scope" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token is invalid", + instance = "/api/v1/users/me/playlists/1f2e3d4c-5b6a-4978-8a9b-0c1d2e3f4a5b/entries-scope" + } + } + ); + + Response(403, "The request failed because the library is not accessible to the current user.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.4", + title = "General.Unauthorized", + status = 403, + detail = "NotAuthorized", + instance = "/api/v1/users/me/playlists/1f2e3d4c-5b6a-4978-8a9b-0c1d2e3f4a5b/entries-scope", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + } + ); + + Response(404, "The request failed because the playlist does not exist, or it does not belong to the current user.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.5", + title = "General.NotFound", + status = 404, + detail = "PlaylistNotFound", + instance = "/api/v1/users/me/playlists/1f2e3d4c-5b6a-4978-8a9b-0c1d2e3f4a5b/entries-scope", + traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00" + } + ); + + Response(409, "The request failed because the entries could not be stored, because of a conflicting row or because the database is busy.", "application/problem+json", + example: new[] + { + new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.10", + title = "General.Conflict", + status = 409, + detail = "UniqueConstraintViolation", + instance = "/api/v1/users/me/playlists/1f2e3d4c-5b6a-4978-8a9b-0c1d2e3f4a5b/entries-scope", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + }, + new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.10", + title = "General.Conflict", + status = 409, + detail = "ConcurrencyConflict", + instance = "/api/v1/users/me/playlists/1f2e3d4c-5b6a-4978-8a9b-0c1d2e3f4a5b/entries-scope", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + } + } + ); + + Response(422, "The request did not pass validation checks.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc4918#section-11.2", + title = "General.Validation", + status = 422, + detail = "OneOrMoreValidationErrorsOccurred", + instance = "/api/v1/users/me/playlists/1f2e3d4c-5b6a-4978-8a9b-0c1d2e3f4a5b/entries-scope", + errors = new Dictionary + { + { + "General.Validation", new[] + { + "PlaylistIdCannotBeEmpty", + "LibraryIdCannotBeEmpty", + "ArtistIdCannotBeEmpty", + "AlbumIdCannotBeEmpty" + } + } + }, + traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00" + } + ); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Playlists/CreatePlaylist/CreatePlaylistEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Playlists/CreatePlaylist/CreatePlaylistEndpoint.cs new file mode 100644 index 00000000..c75e5684 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Playlists/CreatePlaylist/CreatePlaylistEndpoint.cs @@ -0,0 +1,61 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.Mapping.Playlists; +using Lumina.Application.Core.Playlists.Commands.CreatePlaylist; +using Lumina.Contracts.Requests.Playlists; +using Lumina.Contracts.Responses.Playlists; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Common.Routes.Playlists; +using Lumina.Presentation.Api.Core.Endpoints.Common; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Playlists.CreatePlaylist; + +/// +/// API endpoint for the /users/me/playlists route. +/// +/// +/// Uses "me" because it is always for the currently authenticated user. +/// +public class CreatePlaylistEndpoint : BaseEndpoint +{ + private readonly ICommandHandler> _createPlaylistCommandHandler; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for handling create playlist commands. + public CreatePlaylistEndpoint(ICommandHandler> createPlaylistCommandHandler) + { + _createPlaylistCommandHandler = createPlaylistCommandHandler; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(FastEndpoints.Http.POST); + Routes(ApiRoutes.Playlists.CREATE_PLAYLIST); + Version(1); + DontCatchExceptions(); + } + + /// + /// Creates a playlist of the current user. + /// + /// The request containing the details of the playlist to create. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(CreatePlaylistRequest request, CancellationToken cancellationToken) + { + // The playlists belong to the authenticated user, so no intermediary may store any response of this route, including its problem + // responses, and every response varies by the bearer token that authorized it. + HttpContext.Response.Headers["Cache-Control"] = "private, no-store"; + HttpContext.Response.Headers["Vary"] = "Authorization"; + Result result = await _createPlaylistCommandHandler.HandleAsync(request.ToCommand(), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Ok(success), Problem); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Playlists/CreatePlaylist/CreatePlaylistEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Playlists/CreatePlaylist/CreatePlaylistEndpointSummary.cs new file mode 100644 index 00000000..0c5643f1 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Playlists/CreatePlaylist/CreatePlaylistEndpointSummary.cs @@ -0,0 +1,142 @@ +#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; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Playlists.CreatePlaylist; + +/// +/// Class used for providing a textual description for the API endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class CreatePlaylistEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public CreatePlaylistEndpointSummary() + { + Summary = "Creates a playlist of the current user."; + Description = "Creates a playlist that belongs to the currently authenticated user. The name is required, while the description is optional. The type decides which media items the playlist accepts. Only the music type is exposed, because video libraries are not catalogued yet; the entry model and the storage already carry a generic media item kind, so exposing video playlists later does not require a schema change. The new playlist starts empty."; + + ExampleRequest = new CreatePlaylistRequest( + Name: "Evening listening", + Description: "Quiet tracks for the end of the day.", + Type: PlaylistType.Music + ); + RequestParam(request => request.Name, "The name of the playlist. Required, maximum 255 characters."); + RequestParam(request => request.Description, "The description of the playlist. Optional, maximum 2000 characters."); + RequestParam(request => request.Type, "The kind of media the playlist holds. Required. Only Music is currently supported."); + + ResponseParam(response => response.Id, "The Id of the playlist."); + ResponseParam(response => response.Name, "The name of the playlist."); + ResponseParam(response => response.Description, "The description of the playlist, if applicable."); + ResponseParam(response => response.Type, "The kind of media the playlist holds."); + ResponseParam(response => response.Entries, "The page of ordered entries of the playlist, with its pagination metadata."); + ResponseParam(response => response.CreatedOnUtc, "The date and time when the playlist was created."); + ResponseParam(response => response.UpdatedOnUtc, "The date and time when the playlist was last updated, if applicable."); + + Response(200, "The playlist was created and is returned.", + example: new PlaylistResponse( + Id: Guid.Parse("1f2e3d4c-5b6a-4978-8a9b-0c1d2e3f4a5b"), + Name: "Evening listening", + Description: "Quiet tracks for the end of the day.", + Type: PlaylistType.Music, + Entries: new PaginatedResponse + { + Data = [], + CurrentPage = 1, + PerPage = 200, + Count = 0, + NumberOfPages = 0 + }, + CreatedOnUtc: new DateTime(2026, 10, 21, 12, 0, 0, DateTimeKind.Utc), + UpdatedOnUtc: null + ) + ); + + Response(401, "Authentication required.", "application/problem+json", + example: new[] + { + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "Authentication failed", + instance = "/api/v1/users/me/playlists" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token has expired", + instance = "/api/v1/users/me/playlists" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token is invalid", + instance = "/api/v1/users/me/playlists" + } + } + ); + + Response(409, "The request failed because the playlist could not be stored, because of a conflicting row or because the database is busy.", "application/problem+json", + example: new[] + { + new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.10", + title = "General.Conflict", + status = 409, + detail = "UniqueConstraintViolation", + instance = "/api/v1/users/me/playlists", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + }, + new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.10", + title = "General.Conflict", + status = 409, + detail = "ConcurrencyConflict", + instance = "/api/v1/users/me/playlists", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + } + } + ); + + Response(422, "The request did not pass validation checks.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc4918#section-11.2", + title = "General.Validation", + status = 422, + detail = "OneOrMoreValidationErrorsOccurred", + instance = "/api/v1/users/me/playlists", + errors = new Dictionary + { + { + "General.Validation", new[] + { + "PlaylistNameCannotBeEmpty", + "PlaylistNameMustBeMaximum255CharactersLong", + "PlaylistDescriptionMustBeMaximum2000CharactersLong", + "PlaylistTypeIsInvalid" + } + } + }, + traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00" + } + ); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Playlists/DeletePlaylist/DeletePlaylistEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Playlists/DeletePlaylist/DeletePlaylistEndpoint.cs new file mode 100644 index 00000000..0911fd18 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Playlists/DeletePlaylist/DeletePlaylistEndpoint.cs @@ -0,0 +1,60 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Core.Playlists.Commands.DeletePlaylist; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Common.Routes.Playlists; +using Lumina.Presentation.Api.Core.Endpoints.Common; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Playlists.DeletePlaylist; + +/// +/// API endpoint for the /users/me/playlists/{playlistId} route. +/// +/// +/// Uses "me" because it is always for the currently authenticated user. +/// +public class DeletePlaylistEndpoint : BaseEndpoint +{ + private readonly ICommandHandler> _deletePlaylistCommandHandler; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for handling delete playlist commands. + public DeletePlaylistEndpoint(ICommandHandler> deletePlaylistCommandHandler) + { + _deletePlaylistCommandHandler = deletePlaylistCommandHandler; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(FastEndpoints.Http.DELETE); + Routes(ApiRoutes.Playlists.DELETE_PLAYLIST); + Version(1); + DontCatchExceptions(); + } + + /// + /// Deletes a playlist of the current user. + /// + /// The request object. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(FastEndpoints.EmptyRequest request, CancellationToken cancellationToken) + { + // The playlists belong to the authenticated user, so no intermediary may store any response of this route, including its problem + // responses, and every response varies by the bearer token that authorized it. + HttpContext.Response.Headers["Cache-Control"] = "private, no-store"; + HttpContext.Response.Headers["Vary"] = "Authorization"; + // Take the unique identifier from the route. + string? playlistId = HttpContext.Request.RouteValues["playlistId"]?.ToString(); + Result result = await _deletePlaylistCommandHandler.HandleAsync(new DeletePlaylistCommand(playlistId), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Ok(success), Problem); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Playlists/DeletePlaylist/DeletePlaylistEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Playlists/DeletePlaylist/DeletePlaylistEndpointSummary.cs new file mode 100644 index 00000000..39c4a706 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Playlists/DeletePlaylist/DeletePlaylistEndpointSummary.cs @@ -0,0 +1,95 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Playlists.DeletePlaylist; + +/// +/// Class used for providing a textual description for the API endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class DeletePlaylistEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public DeletePlaylistEndpointSummary() + { + Summary = "Deletes a playlist of the current user."; + Description = "Deletes the playlist identified by its Id when it belongs to the currently authenticated user, together with its ordered entries. The tracks it referenced are not deleted, because a playlist only references them by Id."; + + Response(200, "The playlist was successfully deleted."); + + Response(401, "Authentication required.", "application/problem+json", + example: new[] + { + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "Authentication failed", + instance = "/api/v1/users/me/playlists/1f2e3d4c-5b6a-4978-8a9b-0c1d2e3f4a5b" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token has expired", + instance = "/api/v1/users/me/playlists/1f2e3d4c-5b6a-4978-8a9b-0c1d2e3f4a5b" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token is invalid", + instance = "/api/v1/users/me/playlists/1f2e3d4c-5b6a-4978-8a9b-0c1d2e3f4a5b" + } + } + ); + + Response(404, "The request failed because the playlist does not exist, or it does not belong to the current user.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.5", + title = "General.NotFound", + status = 404, + detail = "PlaylistNotFound", + instance = "/api/v1/users/me/playlists/1f2e3d4c-5b6a-4978-8a9b-0c1d2e3f4a5b", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + } + ); + + Response(409, "The request failed because another request changed the playlist after it was read.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.10", + title = "General.Conflict", + status = 409, + detail = "ConcurrencyConflict", + instance = "/api/v1/users/me/playlists/1f2e3d4c-5b6a-4978-8a9b-0c1d2e3f4a5b", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + } + ); + + Response(422, "The request did not pass validation checks.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc4918#section-11.2", + title = "General.Validation", + status = 422, + detail = "OneOrMoreValidationErrorsOccurred", + instance = "/api/v1/users/me/playlists/1f2e3d4c-5b6a-4978-8a9b-0c1d2e3f4a5b", + errors = new Dictionary + { + { "General.Validation", new[] { "PlaylistIdCannotBeEmpty" } } + }, + traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00" + } + ); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Playlists/GetPlaylist/GetPlaylistEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Playlists/GetPlaylist/GetPlaylistEndpoint.cs new file mode 100644 index 00000000..78a354fd --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Playlists/GetPlaylist/GetPlaylistEndpoint.cs @@ -0,0 +1,63 @@ +#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; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Common.Routes.Playlists; +using Lumina.Presentation.Api.Core.Endpoints.Common; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Playlists.GetPlaylist; + +/// +/// API endpoint for the /users/me/playlists/{playlistId} route. +/// +/// +/// Uses "me" because it is always for the currently authenticated user. +/// +public class GetPlaylistEndpoint : BaseEndpoint +{ + private readonly IQueryHandler> _getPlaylistQueryHandler; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for handling get playlist queries. + public GetPlaylistEndpoint(IQueryHandler> getPlaylistQueryHandler) + { + _getPlaylistQueryHandler = getPlaylistQueryHandler; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(FastEndpoints.Http.GET); + Routes(ApiRoutes.Playlists.GET_PLAYLIST); + Version(1); + DontCatchExceptions(); + } + + /// + /// Gets a page of the entries of a playlist of the current user. + /// + /// The request object. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(GetPlaylistRequest request, CancellationToken cancellationToken) + { + // The playlist belongs to the authenticated user, so no intermediary may store any response of this route, including its problem + // responses, and every response varies by the bearer token that authorized it. + HttpContext.Response.Headers["Cache-Control"] = "private, no-store"; + HttpContext.Response.Headers["Vary"] = "Authorization"; + // Take the unique identifier from the route. + string? playlistId = HttpContext.Request.RouteValues["playlistId"]?.ToString(); + Result result = await _getPlaylistQueryHandler.HandleAsync(request.ToQuery(playlistId), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Ok(success), Problem); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Playlists/GetPlaylist/GetPlaylistEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Playlists/GetPlaylist/GetPlaylistEndpointSummary.cs new file mode 100644 index 00000000..b832ccb9 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Playlists/GetPlaylist/GetPlaylistEndpointSummary.cs @@ -0,0 +1,141 @@ +#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; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Playlists.GetPlaylist; + +/// +/// Class used for providing a textual description for the API endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class GetPlaylistEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public GetPlaylistEndpointSummary() + { + Summary = "Gets a playlist of the current user."; + Description = "Gets the playlist identified by its Id when it belongs to the currently authenticated user, together with a 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( + CurrentPage: 1, + PerPage: 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(response => response.Id, "The Id of the playlist."); + ResponseParam(response => response.Name, "The name of the playlist."); + ResponseParam(response => response.Description, "The description of the playlist, if applicable."); + ResponseParam(response => response.Type, "The kind of media the playlist holds."); + ResponseParam(response => response.Entries, "The page of ordered entries of the playlist, with its pagination metadata."); + ResponseParam(response => response.CreatedOnUtc, "The date and time when the playlist was created."); + ResponseParam(response => response.UpdatedOnUtc, "The date and time when the playlist was last updated, if applicable."); + + Response(200, "The playlist and its ordered entries are returned.", + example: new PlaylistResponse( + Id: Guid.Parse("1f2e3d4c-5b6a-4978-8a9b-0c1d2e3f4a5b"), + Name: "Evening listening", + Description: "Quiet tracks for the end of the day.", + Type: PlaylistType.Music, + Entries: new PaginatedResponse + { + 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) + ) + ); + + Response(401, "Authentication required.", "application/problem+json", + example: new[] + { + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "Authentication failed", + instance = "/api/v1/users/me/playlists/1f2e3d4c-5b6a-4978-8a9b-0c1d2e3f4a5b" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token has expired", + instance = "/api/v1/users/me/playlists/1f2e3d4c-5b6a-4978-8a9b-0c1d2e3f4a5b" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token is invalid", + instance = "/api/v1/users/me/playlists/1f2e3d4c-5b6a-4978-8a9b-0c1d2e3f4a5b" + } + } + ); + + Response(404, "The request failed because the playlist does not exist, or it does not belong to the current user.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.5", + title = "General.NotFound", + status = 404, + detail = "PlaylistNotFound", + instance = "/api/v1/users/me/playlists/1f2e3d4c-5b6a-4978-8a9b-0c1d2e3f4a5b", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + } + ); + + Response(422, "The request did not pass validation checks.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc4918#section-11.2", + title = "General.Validation", + status = 422, + detail = "OneOrMoreValidationErrorsOccurred", + instance = "/api/v1/users/me/playlists/1f2e3d4c-5b6a-4978-8a9b-0c1d2e3f4a5b", + errors = new Dictionary + { + { + "General.Validation", new[] + { + "PlaylistIdCannotBeEmpty" + } + } + }, + traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00" + } + ); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Playlists/GetPlaylists/GetPlaylistsEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Playlists/GetPlaylists/GetPlaylistsEndpoint.cs new file mode 100644 index 00000000..1fe5f1ab --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Playlists/GetPlaylists/GetPlaylistsEndpoint.cs @@ -0,0 +1,59 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Core.Playlists.Queries.GetPlaylists; +using Lumina.Contracts.Responses.Playlists; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Common.Routes.Playlists; +using Lumina.Presentation.Api.Core.Endpoints.Common; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Playlists.GetPlaylists; + +/// +/// API endpoint for the /users/me/playlists route. +/// +/// +/// Uses "me" because it is always for the currently authenticated user. +/// +public class GetPlaylistsEndpoint : BaseEndpoint +{ + private readonly IQueryHandler> _getPlaylistsQueryHandler; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for handling get playlists queries. + public GetPlaylistsEndpoint(IQueryHandler> getPlaylistsQueryHandler) + { + _getPlaylistsQueryHandler = getPlaylistsQueryHandler; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(FastEndpoints.Http.GET); + Routes(ApiRoutes.Playlists.GET_PLAYLISTS); + Version(1); + DontCatchExceptions(); + } + + /// + /// Gets the playlists of the current user. + /// + /// The request object. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(FastEndpoints.EmptyRequest request, CancellationToken cancellationToken) + { + // The playlists belong to the authenticated user, so no intermediary may store any response of this route, including its problem + // responses, and every response varies by the bearer token that authorized it. + HttpContext.Response.Headers["Cache-Control"] = "private, no-store"; + HttpContext.Response.Headers["Vary"] = "Authorization"; + Result result = await _getPlaylistsQueryHandler.HandleAsync(new GetPlaylistsQuery(), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Ok(success), Problem); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Playlists/GetPlaylists/GetPlaylistsEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Playlists/GetPlaylists/GetPlaylistsEndpointSummary.cs new file mode 100644 index 00000000..baf48137 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Playlists/GetPlaylists/GetPlaylistsEndpointSummary.cs @@ -0,0 +1,78 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Contracts.Responses.Playlists; +using Lumina.Domain.SharedKernel.Common.Enums.Playlists; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Playlists.GetPlaylists; + +/// +/// Class used for providing a textual description for the API endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class GetPlaylistsEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public GetPlaylistsEndpointSummary() + { + Summary = "Gets the playlists of the current user."; + Description = "Gets the playlists that belong to the currently authenticated user, ordered by their most recent activity. Each playlist is returned without its entries, together with the number of entries it holds. A playlist of another user is never returned."; + + ResponseParam(response => response.Id, "The Id of the playlist."); + ResponseParam(response => response.Name, "The name of the playlist."); + ResponseParam(response => response.Description, "The description of the playlist, if applicable."); + ResponseParam(response => response.Type, "The kind of media the playlist holds."); + ResponseParam(response => response.EntryCount, "The number of entries of the playlist."); + ResponseParam(response => response.CreatedOnUtc, "The date and time when the playlist was created."); + ResponseParam(response => response.UpdatedOnUtc, "The date and time when the playlist was last updated, if applicable."); + + Response(200, "The playlists of the current user are returned.", + example: new[] + { + new PlaylistSummaryResponse( + Id: Guid.Parse("1f2e3d4c-5b6a-4978-8a9b-0c1d2e3f4a5b"), + Name: "Evening listening", + Description: "Quiet tracks for the end of the day.", + Type: PlaylistType.Music, + EntryCount: 12, + CreatedOnUtc: new DateTime(2026, 10, 19, 18, 0, 0, DateTimeKind.Utc), + UpdatedOnUtc: new DateTime(2026, 10, 19, 19, 30, 0, DateTimeKind.Utc) + ) + } + ); + + Response(401, "Authentication required.", "application/problem+json", + example: new[] + { + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "Authentication failed", + instance = "/api/v1/users/me/playlists" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token has expired", + instance = "/api/v1/users/me/playlists" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token is invalid", + instance = "/api/v1/users/me/playlists" + } + } + ); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Playlists/MovePlaylistEntry/MovePlaylistEntryEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Playlists/MovePlaylistEntry/MovePlaylistEntryEndpoint.cs new file mode 100644 index 00000000..6086d177 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Playlists/MovePlaylistEntry/MovePlaylistEntryEndpoint.cs @@ -0,0 +1,64 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.Mapping.Playlists; +using Lumina.Application.Core.Playlists.Commands.MovePlaylistEntry; +using Lumina.Contracts.Requests.Playlists; +using Lumina.Contracts.Responses.Playlists; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Common.Routes.Playlists; +using Lumina.Presentation.Api.Core.Endpoints.Common; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Playlists.MovePlaylistEntry; + +/// +/// API endpoint for the /users/me/playlists/{playlistId}/entries/{playlistEntryId}/move route. +/// +/// +/// Uses "me" because it is always for the currently authenticated user. +/// +public class MovePlaylistEntryEndpoint : BaseEndpoint +{ + private readonly ICommandHandler> _movePlaylistEntryCommandHandler; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for handling move playlist entry commands. + public MovePlaylistEntryEndpoint(ICommandHandler> movePlaylistEntryCommandHandler) + { + _movePlaylistEntryCommandHandler = movePlaylistEntryCommandHandler; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(FastEndpoints.Http.PUT); + Routes(ApiRoutes.Playlists.MOVE_PLAYLIST_ENTRY); + Version(1); + DontCatchExceptions(); + } + + /// + /// Moves one entry of a playlist of the current user to a new position. + /// + /// The request containing the new position of the entry. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(MovePlaylistEntryRequest request, CancellationToken cancellationToken) + { + // The playlists belong to the authenticated user, so no intermediary may store any response of this route, including its problem + // responses, and every response varies by the bearer token that authorized it. + HttpContext.Response.Headers["Cache-Control"] = "private, no-store"; + HttpContext.Response.Headers["Vary"] = "Authorization"; + // The playlist and the entry are identified by the route values, not by any id posted in the body. + string? playlistId = HttpContext.Request.RouteValues["playlistId"]?.ToString(); + string? playlistEntryId = HttpContext.Request.RouteValues["playlistEntryId"]?.ToString(); + Result result = await _movePlaylistEntryCommandHandler.HandleAsync(request.ToCommand(playlistId, playlistEntryId), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Ok(success), Problem); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Playlists/MovePlaylistEntry/MovePlaylistEntryEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Playlists/MovePlaylistEntry/MovePlaylistEntryEndpointSummary.cs new file mode 100644 index 00000000..ad434da2 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Playlists/MovePlaylistEntry/MovePlaylistEntryEndpointSummary.cs @@ -0,0 +1,146 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Contracts.Requests.Playlists; +using Lumina.Contracts.Responses.Playlists; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Playlists.MovePlaylistEntry; + +/// +/// Class used for providing a textual description for the API endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class MovePlaylistEntryEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public MovePlaylistEntryEndpointSummary() + { + Summary = "Moves one entry of a playlist of the current user."; + Description = "Moves the entry identified by its Id to the target zero based position in the ordered entries of the playlist identified by its Id, when the playlist belongs to the currently authenticated user. The request carries only the target position, so the move changes one sparse order key instead of rewriting the following entries. The moved entry and its new position are returned."; + + ExampleRequest = new MovePlaylistEntryRequest( + TargetPosition: 3 + ); + RequestParam(request => request.TargetPosition, "The new zero based position of the entry. Required, zero or greater."); + + ResponseParam(response => response.PlaylistId, "The Id of the playlist whose entry was moved."); + ResponseParam(response => response.EntryId, "The Id of the moved entry."); + ResponseParam(response => response.Position, "The new zero based position of the entry."); + ResponseParam(response => response.UpdatedOnUtc, "The date and time when the playlist was last updated."); + + Response(200, "The moved entry and its new position are returned.", + example: new PlaylistEntryMovedResponse( + PlaylistId: Guid.Parse("1f2e3d4c-5b6a-4978-8a9b-0c1d2e3f4a5b"), + EntryId: Guid.Parse("2a3b4c5d-6e7f-4a8b-9c0d-1e2f3a4b5c6d"), + Position: 3, + UpdatedOnUtc: new DateTime(2026, 10, 20, 12, 0, 0, DateTimeKind.Utc) + ) + ); + + Response(401, "Authentication required.", "application/problem+json", + example: new[] + { + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "Authentication failed", + instance = "/api/v1/users/me/playlists/1f2e3d4c-5b6a-4978-8a9b-0c1d2e3f4a5b/entries/2a3b4c5d-6e7f-4a8b-9c0d-1e2f3a4b5c6d/move" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token has expired", + instance = "/api/v1/users/me/playlists/1f2e3d4c-5b6a-4978-8a9b-0c1d2e3f4a5b/entries/2a3b4c5d-6e7f-4a8b-9c0d-1e2f3a4b5c6d/move" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token is invalid", + instance = "/api/v1/users/me/playlists/1f2e3d4c-5b6a-4978-8a9b-0c1d2e3f4a5b/entries/2a3b4c5d-6e7f-4a8b-9c0d-1e2f3a4b5c6d/move" + } + } + ); + + Response(404, "The request failed because the playlist or the entry does not exist, or the playlist does not belong to the current user.", "application/problem+json", + example: new[] + { + new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.5", + title = "General.NotFound", + status = 404, + detail = "PlaylistNotFound", + instance = "/api/v1/users/me/playlists/1f2e3d4c-5b6a-4978-8a9b-0c1d2e3f4a5b/entries/2a3b4c5d-6e7f-4a8b-9c0d-1e2f3a4b5c6d/move", + traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00" + }, + new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.5", + title = "General.NotFound", + status = 404, + detail = "PlaylistEntryNotFound", + instance = "/api/v1/users/me/playlists/1f2e3d4c-5b6a-4978-8a9b-0c1d2e3f4a5b/entries/2a3b4c5d-6e7f-4a8b-9c0d-1e2f3a4b5c6d/move", + traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00" + } + } + ); + + Response(409, "The request failed because another request changed the playlist after it was read, or because the new position could not be stored.", "application/problem+json", + example: new[] + { + new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.10", + title = "General.Conflict", + status = 409, + detail = "ConcurrencyConflict", + instance = "/api/v1/users/me/playlists/1f2e3d4c-5b6a-4978-8a9b-0c1d2e3f4a5b/entries/2a3b4c5d-6e7f-4a8b-9c0d-1e2f3a4b5c6d/move", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + }, + new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.10", + title = "General.Conflict", + status = 409, + detail = "UniqueConstraintViolation", + instance = "/api/v1/users/me/playlists/1f2e3d4c-5b6a-4978-8a9b-0c1d2e3f4a5b/entries/2a3b4c5d-6e7f-4a8b-9c0d-1e2f3a4b5c6d/move", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + } + } + ); + + Response(422, "The request did not pass validation checks.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc4918#section-11.2", + title = "General.Validation", + status = 422, + detail = "OneOrMoreValidationErrorsOccurred", + instance = "/api/v1/users/me/playlists/1f2e3d4c-5b6a-4978-8a9b-0c1d2e3f4a5b/entries/2a3b4c5d-6e7f-4a8b-9c0d-1e2f3a4b5c6d/move", + errors = new Dictionary + { + { + "General.Validation", new[] + { + "PlaylistIdCannotBeEmpty", + "PlaylistEntryIdCannotBeEmpty", + "PlaylistMoveTargetPositionIsInvalid" + } + } + }, + traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00" + } + ); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Playlists/RemovePlaylistEntry/RemovePlaylistEntryEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Playlists/RemovePlaylistEntry/RemovePlaylistEntryEndpoint.cs new file mode 100644 index 00000000..b8e200b6 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Playlists/RemovePlaylistEntry/RemovePlaylistEntryEndpoint.cs @@ -0,0 +1,62 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Core.Playlists.Commands.RemovePlaylistEntry; +using Lumina.Contracts.Responses.Playlists; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Common.Routes.Playlists; +using Lumina.Presentation.Api.Core.Endpoints.Common; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Playlists.RemovePlaylistEntry; + +/// +/// API endpoint for the /users/me/playlists/{playlistId}/entries/{playlistEntryId} route. +/// +/// +/// Uses "me" because it is always for the currently authenticated user. +/// +public class RemovePlaylistEntryEndpoint : BaseEndpoint +{ + private readonly ICommandHandler> _removePlaylistEntryCommandHandler; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for handling remove playlist entry commands. + public RemovePlaylistEntryEndpoint(ICommandHandler> removePlaylistEntryCommandHandler) + { + _removePlaylistEntryCommandHandler = removePlaylistEntryCommandHandler; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(FastEndpoints.Http.DELETE); + Routes(ApiRoutes.Playlists.REMOVE_PLAYLIST_ENTRY); + Version(1); + DontCatchExceptions(); + } + + /// + /// Removes an entry from a playlist of the current user. + /// + /// The request object. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(FastEndpoints.EmptyRequest request, CancellationToken cancellationToken) + { + // The playlists belong to the authenticated user, so no intermediary may store any response of this route, including its problem + // responses, and every response varies by the bearer token that authorized it. + HttpContext.Response.Headers["Cache-Control"] = "private, no-store"; + HttpContext.Response.Headers["Vary"] = "Authorization"; + // Take the unique identifiers from the route. + string? playlistId = HttpContext.Request.RouteValues["playlistId"]?.ToString(); + string? playlistEntryId = HttpContext.Request.RouteValues["playlistEntryId"]?.ToString(); + Result result = await _removePlaylistEntryCommandHandler.HandleAsync(new RemovePlaylistEntryCommand(playlistId, playlistEntryId), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Ok(success), Problem); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Playlists/RemovePlaylistEntry/RemovePlaylistEntryEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Playlists/RemovePlaylistEntry/RemovePlaylistEntryEndpointSummary.cs new file mode 100644 index 00000000..f66ea768 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Playlists/RemovePlaylistEntry/RemovePlaylistEntryEndpointSummary.cs @@ -0,0 +1,127 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Contracts.Responses.Playlists; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Playlists.RemovePlaylistEntry; + +/// +/// Class used for providing a textual description for the API endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class RemovePlaylistEntryEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public RemovePlaylistEntryEndpointSummary() + { + Summary = "Removes an entry from a playlist of the current user."; + Description = "Removes the entry identified by its Id from the playlist identified by its Id, when the playlist belongs to the currently authenticated user. The entries use sparse order keys, so only the removed row is written and no remaining entry needs to be repositioned. The referenced track is not deleted."; + + ResponseParam(response => response.PlaylistId, "The Id of the playlist the entry was removed from."); + ResponseParam(response => response.RemovedEntryId, "The Id of the removed entry."); + ResponseParam(response => response.RepositionedCount, "Always zero, because sparse order keys need no remaining entries to be repositioned."); + ResponseParam(response => response.UpdatedOnUtc, "The date and time when the playlist was last updated."); + + Response(200, "The removed entry and the number of repositioned entries are returned.", + example: new PlaylistEntryRemovedResponse( + PlaylistId: Guid.Parse("1f2e3d4c-5b6a-4978-8a9b-0c1d2e3f4a5b"), + RemovedEntryId: Guid.Parse("2a3b4c5d-6e7f-4a8b-9c0d-1e2f3a4b5c6d"), + RepositionedCount: 0, + UpdatedOnUtc: new DateTime(2026, 10, 20, 12, 0, 0, DateTimeKind.Utc) + ) + ); + + Response(401, "Authentication required.", "application/problem+json", + example: new[] + { + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "Authentication failed", + instance = "/api/v1/users/me/playlists/1f2e3d4c-5b6a-4978-8a9b-0c1d2e3f4a5b/entries/2a3b4c5d-6e7f-4a8b-9c0d-1e2f3a4b5c6d" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token has expired", + instance = "/api/v1/users/me/playlists/1f2e3d4c-5b6a-4978-8a9b-0c1d2e3f4a5b/entries/2a3b4c5d-6e7f-4a8b-9c0d-1e2f3a4b5c6d" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token is invalid", + instance = "/api/v1/users/me/playlists/1f2e3d4c-5b6a-4978-8a9b-0c1d2e3f4a5b/entries/2a3b4c5d-6e7f-4a8b-9c0d-1e2f3a4b5c6d" + } + } + ); + + Response(404, "The request failed because the playlist or the entry does not exist, or the playlist does not belong to the current user.", "application/problem+json", + example: new[] + { + new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.5", + title = "General.NotFound", + status = 404, + detail = "PlaylistNotFound", + instance = "/api/v1/users/me/playlists/1f2e3d4c-5b6a-4978-8a9b-0c1d2e3f4a5b/entries/2a3b4c5d-6e7f-4a8b-9c0d-1e2f3a4b5c6d", + traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00" + }, + new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.5", + title = "General.NotFound", + status = 404, + detail = "PlaylistEntryNotFound", + instance = "/api/v1/users/me/playlists/1f2e3d4c-5b6a-4978-8a9b-0c1d2e3f4a5b/entries/2a3b4c5d-6e7f-4a8b-9c0d-1e2f3a4b5c6d", + traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00" + } + } + ); + + Response(409, "The request failed because another request changed the playlist after it was read.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.10", + title = "General.Conflict", + status = 409, + detail = "ConcurrencyConflict", + instance = "/api/v1/users/me/playlists/1f2e3d4c-5b6a-4978-8a9b-0c1d2e3f4a5b/entries/2a3b4c5d-6e7f-4a8b-9c0d-1e2f3a4b5c6d", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + } + ); + + Response(422, "The request did not pass validation checks.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc4918#section-11.2", + title = "General.Validation", + status = 422, + detail = "OneOrMoreValidationErrorsOccurred", + instance = "/api/v1/users/me/playlists/1f2e3d4c-5b6a-4978-8a9b-0c1d2e3f4a5b/entries/2a3b4c5d-6e7f-4a8b-9c0d-1e2f3a4b5c6d", + errors = new Dictionary + { + { + "General.Validation", new[] + { + "PlaylistIdCannotBeEmpty", + "PlaylistEntryIdCannotBeEmpty" + } + } + }, + traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00" + } + ); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Playlists/UpdatePlaylist/UpdatePlaylistEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Playlists/UpdatePlaylist/UpdatePlaylistEndpoint.cs new file mode 100644 index 00000000..5978e2ec --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Playlists/UpdatePlaylist/UpdatePlaylistEndpoint.cs @@ -0,0 +1,64 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.Mapping.Playlists; +using Lumina.Application.Core.Playlists.Commands.UpdatePlaylist; +using Lumina.Contracts.Requests.Playlists; +using Lumina.Contracts.Responses.Playlists; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Common.Routes.Playlists; +using Lumina.Presentation.Api.Core.Endpoints.Common; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Playlists.UpdatePlaylist; + +/// +/// API endpoint for the /users/me/playlists/{playlistId} route. +/// +/// +/// Uses "me" because it is always for the currently authenticated user. +/// +public class UpdatePlaylistEndpoint : BaseEndpoint +{ + private readonly ICommandHandler> _updatePlaylistCommandHandler; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for handling update playlist commands. + public UpdatePlaylistEndpoint(ICommandHandler> updatePlaylistCommandHandler) + { + _updatePlaylistCommandHandler = updatePlaylistCommandHandler; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(FastEndpoints.Http.PUT); + Routes(ApiRoutes.Playlists.UPDATE_PLAYLIST); + Version(1); + DontCatchExceptions(); + } + + /// + /// Updates the details of a playlist of the current user. + /// + /// The request containing the new details of the playlist. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(UpdatePlaylistRequest request, CancellationToken cancellationToken) + { + // The playlists belong to the authenticated user, so no intermediary may store any response of this route, including its problem + // responses, and every response varies by the bearer token that authorized it. + HttpContext.Response.Headers["Cache-Control"] = "private, no-store"; + HttpContext.Response.Headers["Vary"] = "Authorization"; + // The playlist is identified by the route value, not by any id posted in the body, so that a mismatched id can never redirect the + // update to another playlist. + string? playlistId = HttpContext.Request.RouteValues["playlistId"]?.ToString(); + Result result = await _updatePlaylistCommandHandler.HandleAsync(request.ToCommand(playlistId), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Ok(success), Problem); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Playlists/UpdatePlaylist/UpdatePlaylistEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Playlists/UpdatePlaylist/UpdatePlaylistEndpointSummary.cs new file mode 100644 index 00000000..c0215763 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Playlists/UpdatePlaylist/UpdatePlaylistEndpointSummary.cs @@ -0,0 +1,128 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Contracts.Requests.Playlists; +using Lumina.Contracts.Responses.Playlists; +using Lumina.Domain.SharedKernel.Common.Enums.Playlists; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Playlists.UpdatePlaylist; + +/// +/// Class used for providing a textual description for the API endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class UpdatePlaylistEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public UpdatePlaylistEndpointSummary() + { + Summary = "Updates the details of a playlist of the current user."; + Description = "Updates the name and the description of the playlist identified by its Id when it belongs to the currently authenticated user, leaving its ordered entries untouched. The playlist is identified by the route value, not by any id posted in the body."; + + ExampleRequest = new UpdatePlaylistRequest( + Name: "Evening listening", + Description: "Quiet tracks for the end of the day." + ); + RequestParam(request => request.Name, "The name of the playlist. Required, maximum 255 characters."); + RequestParam(request => request.Description, "The description of the playlist. Optional, maximum 2000 characters."); + + ResponseParam(response => response.Id, "The Id of the playlist."); + ResponseParam(response => response.Name, "The name of the playlist."); + ResponseParam(response => response.Description, "The description of the playlist, if applicable."); + ResponseParam(response => response.Type, "The kind of media the playlist holds."); + ResponseParam(response => response.UpdatedOnUtc, "The date and time when the playlist was last updated, if applicable."); + + Response(200, "The updated playlist scalars are returned.", + example: new PlaylistDetailsResponse( + Id: Guid.Parse("1f2e3d4c-5b6a-4978-8a9b-0c1d2e3f4a5b"), + Name: "Evening listening", + Description: "Quiet tracks for the end of the day.", + Type: PlaylistType.Music, + UpdatedOnUtc: new DateTime(2026, 10, 20, 12, 0, 0, DateTimeKind.Utc) + ) + ); + + Response(401, "Authentication required.", "application/problem+json", + example: new[] + { + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "Authentication failed", + instance = "/api/v1/users/me/playlists/1f2e3d4c-5b6a-4978-8a9b-0c1d2e3f4a5b" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token has expired", + instance = "/api/v1/users/me/playlists/1f2e3d4c-5b6a-4978-8a9b-0c1d2e3f4a5b" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token is invalid", + instance = "/api/v1/users/me/playlists/1f2e3d4c-5b6a-4978-8a9b-0c1d2e3f4a5b" + } + } + ); + + Response(404, "The request failed because the playlist does not exist, or it does not belong to the current user.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.5", + title = "General.NotFound", + status = 404, + detail = "PlaylistNotFound", + instance = "/api/v1/users/me/playlists/1f2e3d4c-5b6a-4978-8a9b-0c1d2e3f4a5b", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + } + ); + + Response(409, "The request failed because another request changed the playlist after it was read.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.10", + title = "General.Conflict", + status = 409, + detail = "ConcurrencyConflict", + instance = "/api/v1/users/me/playlists/1f2e3d4c-5b6a-4978-8a9b-0c1d2e3f4a5b", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + } + ); + + Response(422, "The request did not pass validation checks.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc4918#section-11.2", + title = "General.Validation", + status = 422, + detail = "OneOrMoreValidationErrorsOccurred", + instance = "/api/v1/users/me/playlists/1f2e3d4c-5b6a-4978-8a9b-0c1d2e3f4a5b", + errors = new Dictionary + { + { + "General.Validation", new[] + { + "PlaylistIdCannotBeEmpty", + "PlaylistNameCannotBeEmpty", + "PlaylistNameMustBeMaximum255CharactersLong", + "PlaylistDescriptionMustBeMaximum2000CharactersLong" + } + } + }, + traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00" + } + ); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authentication/Login/LoginEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authentication/Login/LoginEndpoint.cs index d3bd7ea2..e6f568d1 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authentication/Login/LoginEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authentication/Login/LoginEndpoint.cs @@ -6,6 +6,7 @@ using Lumina.Application.Core.UsersManagement.Authentication.Queries.LoginUser; using Lumina.Contracts.Requests.Authentication; using Lumina.Contracts.Responses.Authentication; using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Common.DependencyInjection; using Lumina.Presentation.Api.Common.Routes.UsersManagement; using Lumina.Presentation.Api.Core.Endpoints.Common; using Microsoft.AspNetCore.Builder; @@ -42,7 +43,7 @@ public class LoginEndpoint : BaseEndpoint Version(1); AllowAnonymous(); DontCatchExceptions(); - Options(x => x.RequireRateLimiting("authenticationPolicy")); + Options(x => x.RequireRateLimiting(PresentationApiLayerServices.AUTHENTICATION_RATE_LIMIT_POLICY)); } /// diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authentication/RecoverPassword/RecoverPasswordEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authentication/RecoverPassword/RecoverPasswordEndpoint.cs index 2077b918..f83a6b69 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authentication/RecoverPassword/RecoverPasswordEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authentication/RecoverPassword/RecoverPasswordEndpoint.cs @@ -5,6 +5,7 @@ using Lumina.Application.Core.UsersManagement.Authentication.Commands.RecoverPas using Lumina.Contracts.Requests.Authentication; using Lumina.Contracts.Responses.Authentication; using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Common.DependencyInjection; using Lumina.Presentation.Api.Common.Routes.UsersManagement; using Lumina.Presentation.Api.Core.Endpoints.Common; using Microsoft.AspNetCore.Builder; @@ -41,7 +42,7 @@ public class RecoverPasswordEndpoint : BaseEndpoint x.RequireRateLimiting("authenticationPolicy")); + Options(x => x.RequireRateLimiting(PresentationApiLayerServices.AUTHENTICATION_RATE_LIMIT_POLICY)); } /// diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authentication/Register/RegisterEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authentication/Register/RegisterEndpoint.cs index 0af9ce38..d74178f9 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authentication/Register/RegisterEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authentication/Register/RegisterEndpoint.cs @@ -5,6 +5,7 @@ using Lumina.Application.Core.UsersManagement.Authentication.Commands.RegisterUs using Lumina.Contracts.Requests.Authentication; using Lumina.Contracts.Responses.Authentication; using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Common.DependencyInjection; using Lumina.Presentation.Api.Common.Routes.UsersManagement; using Lumina.Presentation.Api.Core.Endpoints.Common; using Microsoft.AspNetCore.Builder; @@ -41,7 +42,7 @@ public class RegisterEndpoint : BaseEndpoint Version(1); AllowAnonymous(); DontCatchExceptions(); - Options(x => x.RequireRateLimiting("authenticationPolicy")); + Options(x => x.RequireRateLimiting(PresentationApiLayerServices.AUTHENTICATION_RATE_LIMIT_POLICY)); } /// diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authorization/GetAuthorization/GetAuthorizationEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authorization/GetAuthorization/GetAuthorizationEndpointSummary.cs index 062e5e36..b07ca65b 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authorization/GetAuthorization/GetAuthorizationEndpointSummary.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authorization/GetAuthorization/GetAuthorizationEndpointSummary.cs @@ -1,5 +1,6 @@ #region ========================================================================= USING ===================================================================================== using FastEndpoints; +using Lumina.Application.Common.Infrastructure.Authorization; using Lumina.Contracts.Requests.Authorization; using Lumina.Contracts.Responses.Authorization; using Lumina.Domain.SharedKernel.Common.Enums.Authorization; @@ -33,7 +34,7 @@ public class GetAuthorizationEndpointSummary : Summary() { AuthorizationPermission.CanRegisterUsers, AuthorizationPermission.CanDeleteUsers } )); diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authorization/GetUserRole/GetUserRoleEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authorization/GetUserRole/GetUserRoleEndpointSummary.cs index 9761783b..49a54a90 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authorization/GetUserRole/GetUserRoleEndpointSummary.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authorization/GetUserRole/GetUserRoleEndpointSummary.cs @@ -1,5 +1,6 @@ #region ========================================================================= USING ===================================================================================== using FastEndpoints; +using Lumina.Application.Common.Infrastructure.Authorization; using Lumina.Contracts.Requests.Authorization; using Lumina.Contracts.Responses.Authorization; using Lumina.Domain.SharedKernel.Common.Enums.Authorization; @@ -33,7 +34,7 @@ public class GetUserRoleEndpointSummary : Summary +/// API endpoint for the /users/me/settings/playback-state route. +/// +/// +/// Uses "me" because it is always for the currently authenticated user. +/// +public class GetPlaybackStateEndpoint : BaseEndpoint +{ + private readonly IQueryHandler> _getPlaybackStateQueryHandler; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for handling get playback state queries. + public GetPlaybackStateEndpoint(IQueryHandler> getPlaybackStateQueryHandler) + { + _getPlaybackStateQueryHandler = getPlaybackStateQueryHandler; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(Http.GET); + Routes(ApiRoutes.Users.GET_PLAYBACK_STATE); + Version(1); + DontCatchExceptions(); + } + + /// + /// Gets the playback state the player reported for the current user automatically. + /// + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(EmptyRequest request, CancellationToken cancellationToken) + { + Result result = await _getPlaybackStateQueryHandler.HandleAsync(new GetPlaybackStateQuery(), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Ok(success), Problem); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Settings/GetPlaybackState/GetPlaybackStateEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Settings/GetPlaybackState/GetPlaybackStateEndpointSummary.cs new file mode 100644 index 00000000..1ee71e41 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Settings/GetPlaybackState/GetPlaybackStateEndpointSummary.cs @@ -0,0 +1,59 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Contracts.Responses.UsersManagement.Settings; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.UsersManagement.Settings.GetPlaybackState; + +/// +/// Class used for providing a textual description for the API endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class GetPlaybackStateEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public GetPlaybackStateEndpointSummary() + { + Summary = "Retrieves the playback state the player reported for the current user."; + Description = "Retrieves the last volume and mute state the player reported for the current user. When no settings are stored for the user yet, the default values are returned."; + + Response(200, "The playback state of the current user is returned.", + example: new PlaybackStateResponse( + Volume: 1.0, + IsMuted: false + )); + + 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/settings/playback-state" + }, + 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/settings/playback-state" + }, + 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/settings/playback-state" + } + } + ); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Settings/GetUserSettings/GetUserSettingsEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Settings/GetUserSettings/GetUserSettingsEndpointSummary.cs index 708a3959..f5f65cb5 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Settings/GetUserSettings/GetUserSettingsEndpointSummary.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Settings/GetUserSettings/GetUserSettingsEndpointSummary.cs @@ -1,6 +1,7 @@ #region ========================================================================= USING ===================================================================================== using FastEndpoints; using Lumina.Contracts.Responses.UsersManagement.Settings; +using Lumina.Domain.SharedKernel.Common.Enums.Playback; using System; using System.Diagnostics.CodeAnalysis; #endregion @@ -21,6 +22,30 @@ public class GetUserSettingsEndpointSummary : Summary(r => r.UserId, "The unique identifier of the user that owns these settings."); + ResponseParam(r => r.IsPaginationEnabled, "Whether pagination is enabled for the user, or not."); + ResponseParam(r => r.ItemsPerPage, "The number of library items displayed per page when pagination is enabled."); + ResponseParam(r => r.ShouldIgnoreThePrefixForAlphaPicker, "Whether the \"The\" prefix of library item titles is ignored by the alpha picker, or not."); + ResponseParam(r => r.IsThemeCachingEnabled, "Whether the theme data served to this user is cached, or not."); + ResponseParam(r => r.ShouldAggregateMetadataWhenMissing, "Whether the metadata of the media library items is aggregated from multiple providers, when fields are missing, or not."); + ResponseParam(r => r.ShouldAggregateArtworkWhenMissing, "Whether the artwork of the media library items is aggregated from multiple providers, when it is missing, or not."); + ResponseParam(r => r.ShouldRenderPdfAsImages, "Whether PDF books are rendered as page images for the user, or not."); + ResponseParam(r => r.ShouldPreserveBookStyles, "Whether the styles of the book content are preserved when it is rendered for the user, or not."); + ResponseParam(r => r.ShouldKeepDownloadingWhilePaused, "Whether the player keeps downloading a track while playback is paused, or not."); + ResponseParam(r => r.ShouldAutoplay, "Whether the player continues playback at the end of an album or artist, or not."); + ResponseParam(r => r.IsGaplessPlaybackEnabled, "Whether the player transitions between consecutive tracks without a gap, or not."); + ResponseParam(r => r.ReplayGainMode, "The way ReplayGain normalization is applied to the tracks the user plays."); + ResponseParam(r => r.StreamingQuality, "The quality cap applied to the audio the server normalizes for the user."); + ResponseParam(r => r.VuMeterOrientation, "The direction in which each channel of the VU meter of the audio player grows."); + ResponseParam(r => r.VuMeterSegmentCount, "The number of segments each channel of the VU meter is divided into."); + ResponseParam(r => r.VuMeterSegmentGap, "The gap, in pixels, between the segments and the channels of the VU meter."); + ResponseParam(r => r.VuMeterMediumThreshold, "The level, between 0 and 1, above which a segment of the VU meter is drawn with its medium state."); + ResponseParam(r => r.VuMeterHighThreshold, "The level, between 0 and 1, above which a segment of the VU meter is drawn with its high state."); + ResponseParam(r => r.VuMeterShowPeak, "Whether the VU meter holds the peak level of each channel after it falls, or not."); + ResponseParam(r => r.VuMeterPeakHoldDurationInMilliseconds, "The time, in milliseconds, a peak of the VU meter is held before it starts falling."); + ResponseParam(r => r.VuMeterReleasePerSecond, "The number of level units the display of the VU meter falls per second when the input level drops."); + ResponseParam(r => r.VuMeterPeakReleasePerSecond, "The number of level units the peak of the VU meter falls per second after its hold time elapsed."); + Response(200, "The settings of the current user are returned.", example: new UserSettingsResponse( UserId: Guid.NewGuid(), @@ -31,7 +56,21 @@ public class GetUserSettingsEndpointSummary : Summary +/// API endpoint for the /users/me/settings/playback-state route. +/// +/// +/// Uses "me" because it is always for the currently authenticated user. +/// +public class UpdatePlaybackStateEndpoint : BaseEndpoint +{ + private readonly ICommandHandler> _updatePlaybackStateCommandHandler; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for handling update playback state commands. + public UpdatePlaybackStateEndpoint(ICommandHandler> updatePlaybackStateCommandHandler) + { + _updatePlaybackStateCommandHandler = updatePlaybackStateCommandHandler; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(FastEndpoints.Http.PUT); + Routes(ApiRoutes.Users.UPDATE_PLAYBACK_STATE); + Version(1); + DontCatchExceptions(); + } + + /// + /// Updates the playback state the player reported for the current user automatically. + /// + /// The request containing the latest playback state of the current user. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(UpdatePlaybackStateRequest request, CancellationToken cancellationToken) + { + Result result = await _updatePlaybackStateCommandHandler.HandleAsync(request.ToCommand(), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Ok(success), Problem); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Settings/UpdatePlaybackState/UpdatePlaybackStateEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Settings/UpdatePlaybackState/UpdatePlaybackStateEndpointSummary.cs new file mode 100644 index 00000000..03a9c9fa --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Settings/UpdatePlaybackState/UpdatePlaybackStateEndpointSummary.cs @@ -0,0 +1,87 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Contracts.Requests.UsersManagement.Settings; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.UsersManagement.Settings.UpdatePlaybackState; + +/// +/// Class used for providing a textual description for the API endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class UpdatePlaybackStateEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public UpdatePlaybackStateEndpointSummary() + { + Summary = "Updates the playback state the player reported for the current user."; + Description = "Updates the last volume and mute state the player reported for the current user. This is written automatically by the player and is not part of the settings the user edits. When no settings are stored for the user yet, they are created with the provided playback state."; + + ExampleRequest = new UpdatePlaybackStateRequest( + Volume: 0.75, + IsMuted: false + ); + + RequestParam(r => r.Volume, "The last volume the player reported, as a value between 0 and 1. Required."); + RequestParam(r => r.IsMuted, "The last mute state the player reported. Required."); + + Response(200, "The playback state of the current user was successfully updated."); + + 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/settings/playback-state" + }, + 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/settings/playback-state" + }, + 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/settings/playback-state" + } + } + ); + + 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/settings/playback-state", + errors = new Dictionary + { + { + "General.Validation", new[] + { + "VolumeCannotBeNull", + "VolumeMustBeBetweenZeroAndOne", + "IsMutedCannotBeNull" + } + } + }, + traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00" + } + ); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Settings/UpdateUserSettings/UpdateUserSettingsEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Settings/UpdateUserSettings/UpdateUserSettingsEndpointSummary.cs index 7e78c199..6261e404 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Settings/UpdateUserSettings/UpdateUserSettingsEndpointSummary.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Settings/UpdateUserSettings/UpdateUserSettingsEndpointSummary.cs @@ -1,6 +1,7 @@ #region ========================================================================= USING ===================================================================================== using FastEndpoints; using Lumina.Contracts.Requests.UsersManagement.Settings; +using Lumina.Domain.SharedKernel.Common.Enums.Playback; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; #endregion @@ -29,7 +30,21 @@ public class UpdateUserSettingsEndpointSummary : Summary r.IsPaginationEnabled, "Whether pagination is enabled for the user, or not. Required."); @@ -40,6 +55,20 @@ public class UpdateUserSettingsEndpointSummary : Summary r.ShouldAggregateArtworkWhenMissing, "Whether the artwork of the media library items is aggregated from multiple providers, when it is missing, or not. Required."); RequestParam(r => r.ShouldRenderPdfAsImages, "Whether PDF books are rendered as page images for the user, or not. Required."); RequestParam(r => r.ShouldPreserveBookStyles, "Whether the styles of the book content are preserved when it is rendered for the user, or not. Required."); + RequestParam(r => r.ShouldKeepDownloadingWhilePaused, "Whether the player keeps downloading a track while playback is paused, or not. Required."); + RequestParam(r => r.ShouldAutoplay, "Whether the player continues playback at the end of an album or artist, or not. Required."); + RequestParam(r => r.IsGaplessPlaybackEnabled, "Whether the player transitions between consecutive tracks without a gap, or not. Required."); + RequestParam(r => r.ReplayGainMode, "The way ReplayGain normalization is applied to the tracks the user plays. Required."); + RequestParam(r => r.StreamingQuality, "The quality cap applied to the audio the server normalizes for the user. Required."); + RequestParam(r => r.VuMeterOrientation, "The direction in which each channel of the VU meter of the audio player grows. Required."); + RequestParam(r => r.VuMeterSegmentCount, "The number of segments each channel of the VU meter is divided into. Required."); + RequestParam(r => r.VuMeterSegmentGap, "The gap, in pixels, between the segments and the channels of the VU meter. Required."); + RequestParam(r => r.VuMeterMediumThreshold, "The level, between 0 and 1, above which a segment of the VU meter is drawn with its medium state. Required."); + RequestParam(r => r.VuMeterHighThreshold, "The level, between 0 and 1, above which a segment of the VU meter is drawn with its high state. Required."); + RequestParam(r => r.VuMeterShowPeak, "Whether the VU meter holds the peak level of each channel after it falls, or not. Required."); + RequestParam(r => r.VuMeterPeakHoldDurationInMilliseconds, "The time, in milliseconds, a peak of the VU meter is held before it starts falling. Required."); + RequestParam(r => r.VuMeterReleasePerSecond, "The number of level units the display of the VU meter falls per second when the input level drops. Required."); + RequestParam(r => r.VuMeterPeakReleasePerSecond, "The number of level units the peak of the VU meter falls per second after its hold time elapsed. Required."); Response(200, "The settings of the current user were successfully updated."); @@ -73,6 +102,18 @@ public class UpdateUserSettingsEndpointSummary : Summary(); - await context.Database.MigrateAsync(); + // Migrations can need a temporary store for an update or a table rebuild. The process can run in an environment whose + // temporary directory is missing or read-only, so the migration connection keeps the temporary store in memory instead + // of failing with SQLite error 14 while it tries to create a temporary file. + await context.Database.OpenConnectionAsync(); + try + { + await context.Database.ExecuteSqlRawAsync("PRAGMA temp_store = MEMORY;"); + await context.Database.MigrateAsync(); + } + finally + { + await context.Database.CloseConnectionAsync(); + } // Enable the Write-Ahead Logging journal mode and a busy timeout, so that the Entity Framework connection and the dedicated connections // used by the bulk data access operations of Dapper can access the database concurrently, without database locking errors. diff --git a/src/Lumina.Presentation.Web/Common/Api/ApiStreamResult.cs b/src/Lumina.Presentation.Web/Common/Api/ApiStreamResult.cs new file mode 100644 index 00000000..a68ff3cc --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Api/ApiStreamResult.cs @@ -0,0 +1,154 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using System.Linq; +using System.Net; +using System.Net.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Common.Api; + +/// +/// Represents the streamed response of a remote API request. It exposes the status code, the range related headers and the +/// content stream of the response, so that a caller can forward the response to a client without ever buffering its content. +/// +public sealed class ApiStreamResult : IAsyncDisposable +{ + /// + /// The response header that carries the number of segments of a normalized audio production. It must match the name the API sends. + /// + public const string SEGMENT_COUNT_HEADER_NAME = "X-Lumina-Segment-Count"; + + /// + /// The response header that carries the exact start of a segment on the track timeline, in seconds. It must match the name the API sends. + /// + public const string SEGMENT_START_SECONDS_HEADER_NAME = "X-Segment-Start-Seconds"; + + /// + /// The response header that carries the produced duration of the normalized track, in seconds. It must match the name the API sends. + /// + public const string TRACK_DURATION_SECONDS_HEADER_NAME = "X-Lumina-Track-Duration-Seconds"; + + private readonly HttpResponseMessage _response; + + /// + /// Gets the status code of the response. + /// + public HttpStatusCode StatusCode { get; } + + /// + /// Gets the content stream of the response. + /// + public Stream Content { get; } + + /// + /// Gets the media type of the content of the response, or when the response declares none. + /// + public string? ContentType { get; } + + /// + /// Gets the length of the content of the response, or when the response declares none. + /// + public long? ContentLength { get; } + + /// + /// Gets the range of the content of the response, when the response is a partial content response. + /// + public string? ContentRange { get; } + + /// + /// Gets the ranges the remote API accepts, when the response declares them. + /// + public string? AcceptRanges { get; } + + /// + /// Gets the entity tag of the content of the response, when the response declares one. + /// + public string? ETag { get; } + + /// + /// Gets the date and time the content of the response was last modified, when the response declares it. + /// + public DateTimeOffset? LastModified { get; } + + /// + /// Gets the caching instructions of the response, when the response declares them. + /// + public string? CacheControl { get; } + + /// + /// Gets the number of segments the normalized audio production holds, when the response is a segment of one and declares it. + /// + public int? SegmentCount { get; } + + /// + /// Gets the exact start of the segment on the track timeline, in seconds, as declared by the API, or when the response + /// declares none. + /// + public string? SegmentStartSeconds { get; } + + /// + /// Gets the produced duration of the normalized track, in seconds, as declared by the API, or when the response declares none. + /// + public int? TrackDurationSeconds { get; } + + /// + /// Initializes a new instance of the class. + /// + /// The response returned by the remote API. + /// The content stream of the response. + private ApiStreamResult(HttpResponseMessage response, Stream content) + { + _response = response; + Content = content; + StatusCode = response.StatusCode; + ContentType = response.Content.Headers.ContentType?.ToString(); + ContentLength = response.Content.Headers.ContentLength; + ContentRange = response.Content.Headers.ContentRange?.ToString(); + AcceptRanges = response.Headers.AcceptRanges.Count > 0 ? string.Join(", ", response.Headers.AcceptRanges) : null; + ETag = response.Headers.ETag?.ToString(); + LastModified = response.Content.Headers.LastModified; + CacheControl = response.Headers.CacheControl?.ToString(); + // The count is optional, because the same result also represents a track stream, which has no segments. A malformed or negative + // value is treated as absent instead of being passed to a caller that would use it to decide where the audio ends. + SegmentCount = response.Headers.TryGetValues(SEGMENT_COUNT_HEADER_NAME, out IEnumerable? segmentCountValues) + && int.TryParse(segmentCountValues.FirstOrDefault(), NumberStyles.None, CultureInfo.InvariantCulture, out int parsedSegmentCount) + && parsedSegmentCount >= 0 + ? parsedSegmentCount + : null; + // The start is forwarded as the API wrote it, so the web hop never reinterprets a decimal with the culture of this application. + SegmentStartSeconds = response.Headers.TryGetValues(SEGMENT_START_SECONDS_HEADER_NAME, out IEnumerable? segmentStartValues) + ? segmentStartValues.FirstOrDefault() + : null; + TrackDurationSeconds = response.Headers.TryGetValues(TRACK_DURATION_SECONDS_HEADER_NAME, out IEnumerable? trackDurationValues) + && int.TryParse(trackDurationValues.FirstOrDefault(), NumberStyles.None, CultureInfo.InvariantCulture, out int parsedTrackDuration) + && parsedTrackDuration > 0 + ? parsedTrackDuration + : null; + } + + /// + /// Creates a from a response, without buffering the content of the response. + /// + /// The response returned by the remote API. + /// Cancellation token that can be used to stop the execution. + /// The streamed response. + public static async Task CreateAsync(HttpResponseMessage response, CancellationToken cancellationToken) + { + Stream content = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false); + return new ApiStreamResult(response, content); + } + + /// + /// Disposes the content stream and the response it belongs to. + /// + public async ValueTask DisposeAsync() + { + await Content.DisposeAsync().ConfigureAwait(false); + _response.Dispose(); + } +} diff --git a/src/Lumina.Presentation.Web/Common/Api/IStreamingApiHttpClient.cs b/src/Lumina.Presentation.Web/Common/Api/IStreamingApiHttpClient.cs new file mode 100644 index 00000000..756ccf15 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Api/IStreamingApiHttpClient.cs @@ -0,0 +1,23 @@ +#region ========================================================================= USING ===================================================================================== +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Common.Api; + +/// +/// Interface for typed clients that stream responses from the remote API without buffering their content. +/// +public interface IStreamingApiHttpClient +{ + /// + /// Sends a GET request to the specified as an asynchronous operation and returns the response as a stream, without ever buffering its content in memory. + /// + /// The API endpoint where the request is being sent. + /// The range and conditional headers of the incoming request to forward, so that the API, + /// which is the only party that knows the entity tag and the modification time of the resource, validates them itself. + /// Cancellation token that can be used to stop the execution. + /// The streamed response of the API request, which the caller must dispose once it has finished copying it. + Task GetStreamAsync(string endpoint, IReadOnlyDictionary requestHeaders, CancellationToken cancellationToken = default); +} diff --git a/src/Lumina.Presentation.Web/Common/Api/StreamingApiHttpClient.cs b/src/Lumina.Presentation.Web/Common/Api/StreamingApiHttpClient.cs new file mode 100644 index 00000000..0b8b3227 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Api/StreamingApiHttpClient.cs @@ -0,0 +1,125 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.Common; +using Lumina.Presentation.Web.Common.DTO.Configuration; +using Lumina.Presentation.Web.Common.Exceptions; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.Options; +using System; +using System.Collections.Generic; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Common.Api; + +/// +/// Typed client for streaming API access. Unlike , it never buffers a response in memory and is +/// intentionally free of any retry or circuit breaker policy, because a stream is meant to be handed to the client as a whole. +/// +public class StreamingApiHttpClient : IStreamingApiHttpClient +{ + private static readonly JsonSerializerOptions s_jsonOptions = new() + { + PropertyNameCaseInsensitive = true, + DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull, + Converters = { new JsonStringEnumConverter() } + }; + + private readonly HttpClient _httpClient; + private readonly HttpContext? _httpContext; + + /// + /// Initializes a new instance of the class. + /// + /// Injected HttpClient for interacting with the API. + /// Injected service for providing the current HTTP context. + /// Injected server configuration application settings. + public StreamingApiHttpClient(HttpClient httpClient, IHttpContextAccessor httpContextAccessor, IOptionsSnapshot serverConfigurationOptions) + { + _httpClient = httpClient; + _httpContext = httpContextAccessor.HttpContext; + // Read the API server configuration values from the configuration, and assign them to the injected client. + ServerConfigurationDto serverConfiguration = serverConfigurationOptions.Value; + httpClient.BaseAddress = new Uri($"{serverConfiguration.BaseAddress}:{serverConfiguration.Port}/api/v{serverConfiguration.ApiVersion}/"); + // A streamed response stays open for as long as the client keeps reading it, so the timeout is generously large, but it is bounded: + // an upstream that accepts the request and never answers must not hold a connection and a stream permit open forever. No track, and + // no movie, is longer than this. + httpClient.Timeout = TimeSpan.FromHours(12); + } + + /// + /// Sends a GET request to the specified as an asynchronous operation and returns the response + /// as a stream, without ever buffering its content in memory. + /// + /// The API endpoint where the request is being sent. + /// The range and conditional headers of the incoming request to forward, so that the API, which is the only party that knows the entity tag and the modification time of the resource, validates them itself. + /// Cancellation token that can be used to stop the execution. + /// The streamed response of the API request, which the caller must dispose once it has finished copying it. + /// Thrown if the response is not successful, with the if available. + public async Task GetStreamAsync(string endpoint, IReadOnlyDictionary requestHeaders, CancellationToken cancellationToken = default) + { + using (HttpRequestMessage request = new(HttpMethod.Get, endpoint)) + { + AuthenticationHeaderValue? authenticationHeader = GetAuthenticationHeader(); + if (authenticationHeader is not null) + request.Headers.Authorization = authenticationHeader; + // The range and the conditional headers are forwarded as they are, so that the API, and never this client, decides what a partial response contains. + foreach (KeyValuePair header in requestHeaders) + request.Headers.TryAddWithoutValidation(header.Key, header.Value); + + // Only the headers of the response are awaited, so that its content is streamed to the client instead of being copied into memory first. + HttpResponseMessage response = await _httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); + // A not modified response and a range not satisfiable response are valid outcomes of a conditional or ranged request, and their + // headers (the entity tag, the last modified date, the content range) are the whole answer, so they are passed through instead of + // being turned into an error, which would drop the very headers the caller needs to revalidate or recover. + if (!response.IsSuccessStatusCode && response.StatusCode != HttpStatusCode.NotModified && response.StatusCode != HttpStatusCode.RequestedRangeNotSatisfiable) + { + HttpStatusCode statusCode = response.StatusCode; + string content; + try + { + content = await response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + } + finally + { + // The response is turned into an exception, so it is disposed even when reading its error body fails, otherwise its connection would leak. + response.Dispose(); + } + ProblemDetailsDto? problemDetails = null; + try + { + problemDetails = JsonSerializer.Deserialize(content, s_jsonOptions); + } + catch { /* If we can't deserialize to ProblemDetails, we'll just use the status code. */ } + throw new ApiException(problemDetails, statusCode, request.RequestUri?.AbsolutePath); + } + try + { + return await ApiStreamResult.CreateAsync(response, cancellationToken).ConfigureAwait(false); + } + catch + { + // The response was already received, so it must be disposed if its content stream could not be obtained, otherwise its connection would leak. + response.Dispose(); + throw; + } + } + } + + /// + /// Retrieves the authentication header for the current user, if available. + /// + /// + /// An with a Bearer token if the user's token is found, otherwise. + /// + private AuthenticationHeaderValue? GetAuthenticationHeader() + { + string? token = _httpContext?.User?.FindFirst("Token")?.Value; + return !string.IsNullOrEmpty(token) ? new AuthenticationHeaderValue("Bearer", token) : null; + } +} diff --git a/src/Lumina.Presentation.Web/Common/DTO/AudioLibrary/MusicLibrary/MusicAlbumDto.cs b/src/Lumina.Presentation.Web/Common/DTO/AudioLibrary/MusicLibrary/MusicAlbumDto.cs index 00e59bb0..19b856ae 100644 --- a/src/Lumina.Presentation.Web/Common/DTO/AudioLibrary/MusicLibrary/MusicAlbumDto.cs +++ b/src/Lumina.Presentation.Web/Common/DTO/AudioLibrary/MusicLibrary/MusicAlbumDto.cs @@ -26,6 +26,11 @@ public class MusicAlbumDto /// public Guid ArtistId { get; set; } + /// + /// Gets or sets the name of the artist the album belongs to. + /// + public string ArtistName { get; set; } = string.Empty; + /// /// Gets or sets the Id of the media library this album belongs to. /// diff --git a/src/Lumina.Presentation.Web/Common/DTO/AudioLibrary/MusicLibrary/MusicShuffleTrackDto.cs b/src/Lumina.Presentation.Web/Common/DTO/AudioLibrary/MusicLibrary/MusicShuffleTrackDto.cs new file mode 100644 index 00000000..022de5cc --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/DTO/AudioLibrary/MusicLibrary/MusicShuffleTrackDto.cs @@ -0,0 +1,48 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary; + +/// +/// Data transfer object for a track returned by a randomized shuffle query. +/// +[DebuggerDisplay("Title: {Title}")] +public class MusicShuffleTrackDto +{ + /// + /// Gets or sets the Id of the track. + /// + public Guid TrackId { get; set; } + + /// + /// Gets or sets the title of the track. + /// + public string Title { get; set; } = string.Empty; + + /// + /// Gets or sets the duration of the track in seconds. + /// + public int DurationInSeconds { get; set; } + + /// + /// Gets or sets the Id of the album the track belongs to. + /// + public Guid AlbumId { get; set; } + + /// + /// Gets or sets the title of the album the track belongs to. + /// + public string AlbumTitle { get; set; } = string.Empty; + + /// + /// Gets or sets the Id of the artist the album belongs to. + /// + public Guid ArtistId { get; set; } + + /// + /// Gets or sets the path of the cover of the album, if available. + /// + public string? CoverPath { get; set; } +} diff --git a/src/Lumina.Presentation.Web/Common/DTO/AudioLibrary/MusicLibrary/PaginatedMusicAlbumLiteDto.cs b/src/Lumina.Presentation.Web/Common/DTO/AudioLibrary/MusicLibrary/PaginatedMusicAlbumLiteDto.cs deleted file mode 100644 index 19cfaa36..00000000 --- a/src/Lumina.Presentation.Web/Common/DTO/AudioLibrary/MusicLibrary/PaginatedMusicAlbumLiteDto.cs +++ /dev/null @@ -1,38 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using System.Collections.Generic; -using System.Diagnostics; -#endregion - -namespace Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary; - -/// -/// Data transfer object for a paginated collection of lightweight album elements, together with pagination metadata. -/// -[DebuggerDisplay("CurrentPage: {CurrentPage}; Count: {Count}")] -public class PaginatedMusicAlbumLiteDto -{ - /// - /// Gets or sets the collection of lightweight album elements associated with this instance. - /// - public IReadOnlyList Data { get; set; } = []; - - /// - /// Gets or sets the current page number in a paginated collection. - /// - public int CurrentPage { get; set; } - - /// - /// Gets or sets the number of items to include per page in paginated results. - /// - public int PerPage { get; set; } - - /// - /// Gets or sets the total number of elements available in the paginated result set. - /// - public int Count { get; set; } - - /// - /// Gets or sets the total number of pages based on elements available in the result set and per page. - /// - public int NumberOfPages { get; set; } -} diff --git a/src/Lumina.Presentation.Web/Common/DTO/AudioLibrary/MusicLibrary/PaginatedMusicArtistLiteDto.cs b/src/Lumina.Presentation.Web/Common/DTO/AudioLibrary/MusicLibrary/PaginatedMusicArtistLiteDto.cs deleted file mode 100644 index 780e6638..00000000 --- a/src/Lumina.Presentation.Web/Common/DTO/AudioLibrary/MusicLibrary/PaginatedMusicArtistLiteDto.cs +++ /dev/null @@ -1,38 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using System.Collections.Generic; -using System.Diagnostics; -#endregion - -namespace Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary; - -/// -/// Data transfer object for a paginated collection of lightweight music artist elements, together with pagination metadata. -/// -[DebuggerDisplay("CurrentPage: {CurrentPage}; Count: {Count}")] -public class PaginatedMusicArtistLiteDto -{ - /// - /// Gets or sets the collection of lightweight music artist elements associated with this instance. - /// - public IReadOnlyList Data { get; set; } = []; - - /// - /// Gets or sets the current page number in a paginated collection. - /// - public int CurrentPage { get; set; } - - /// - /// Gets or sets the number of items to include per page in paginated results. - /// - public int PerPage { get; set; } - - /// - /// Gets or sets the total number of elements available in the paginated result set. - /// - public int Count { get; set; } - - /// - /// Gets or sets the total number of pages based on elements available in the result set and per page. - /// - public int NumberOfPages { get; set; } -} diff --git a/src/Lumina.Presentation.Web/Common/DTO/AudioLibrary/MusicLibrary/PaginatedMusicTrackLiteDto.cs b/src/Lumina.Presentation.Web/Common/DTO/AudioLibrary/MusicLibrary/PaginatedMusicTrackLiteDto.cs deleted file mode 100644 index 6c112daa..00000000 --- a/src/Lumina.Presentation.Web/Common/DTO/AudioLibrary/MusicLibrary/PaginatedMusicTrackLiteDto.cs +++ /dev/null @@ -1,38 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using System.Collections.Generic; -using System.Diagnostics; -#endregion - -namespace Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary; - -/// -/// Data transfer object for a paginated collection of lightweight track elements, together with pagination metadata. -/// -[DebuggerDisplay("CurrentPage: {CurrentPage}; Count: {Count}")] -public class PaginatedMusicTrackLiteDto -{ - /// - /// Gets or sets the collection of lightweight track elements associated with this instance. - /// - public IReadOnlyList Data { get; set; } = []; - - /// - /// Gets or sets the current page number in a paginated collection. - /// - public int CurrentPage { get; set; } - - /// - /// Gets or sets the number of items to include per page in paginated results. - /// - public int PerPage { get; set; } - - /// - /// Gets or sets the total number of elements available in the paginated result set. - /// - public int Count { get; set; } - - /// - /// Gets or sets the total number of pages based on elements available in the result set and per page. - /// - public int NumberOfPages { get; set; } -} diff --git a/src/Lumina.Presentation.Web/Common/DTO/AudioLibrary/MusicLibrary/PlaybackManifestDto.cs b/src/Lumina.Presentation.Web/Common/DTO/AudioLibrary/MusicLibrary/PlaybackManifestDto.cs new file mode 100644 index 00000000..0fa128aa --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/DTO/AudioLibrary/MusicLibrary/PlaybackManifestDto.cs @@ -0,0 +1,118 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Enums.AudioLibrary; +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary; + +/// +/// Data transfer object for the playback manifest of a track, describing the format of its stored audio, the delivery the server decided on for the requesting player, and the path of its stream. +/// +[DebuggerDisplay("TrackId: {TrackId} IsDirectPlay: {IsDirectPlay}")] +public class PlaybackManifestDto +{ + /// + /// Gets or sets the Id of the track the manifest describes. + /// + public Guid TrackId { get; set; } + + /// + /// Gets or sets the duration of the audio of the track, in seconds. + /// + public int DurationInSeconds { get; set; } + + /// + /// Gets or sets the container of the audio file of the track, as stored by the probe. + /// + public string? SourceContainer { get; set; } + + /// + /// Gets or sets the codec of the audio of the track, as stored by the probe. + /// + public string? SourceCodec { get; set; } + + /// + /// Gets or sets the sample rate of the audio of the track, in Hz. + /// + public int SampleRate { get; set; } + + /// + /// Gets or sets the number of audio channels of the track. + /// + public int Channels { get; set; } + + /// + /// Gets or sets the bit depth of the audio of the track. + /// + public int? BitDepth { get; set; } + + /// + /// Gets or sets the ReplayGain track gain of the track, in decibels. + /// + public decimal? ReplayGainTrackGain { get; set; } + + /// + /// Gets or sets the ReplayGain track peak of the track. + /// + public decimal? ReplayGainTrackPeak { get; set; } + + /// + /// Gets or sets the ReplayGain album gain of the track, in decibels. + /// + public decimal? ReplayGainAlbumGain { get; set; } + + /// + /// Gets or sets the ReplayGain album peak of the track. + /// + public decimal? ReplayGainAlbumPeak { get; set; } + + /// + /// Gets or sets whether the player can play the stored audio as it is, without the server changing its container or its codec. + /// + public bool IsDirectPlay { get; set; } + + /// + /// Gets or sets the container of the audio the server delivers, when the delivery is not a direct play. + /// + public string? DeliveryContainer { get; set; } + + /// + /// Gets or sets the codec of the audio the server delivers, when the delivery is not a direct play. + /// + public string? DeliveryCodec { get; set; } + + /// + /// Gets or sets the shape the delivered audio is addressed and seeked by, when the delivery is not a direct play. + /// + public PlaybackDeliveryShape? DeliveryShape { get; set; } + + /// + /// Gets or sets the duration of each segment of the delivered audio, in seconds, when the delivery is addressed as time addressed segments. + /// + public int? SegmentDurationSeconds { get; set; } + + /// + /// Gets or sets whether the delivered audio can be seeked by the player. + /// + public bool IsSeekable { get; set; } + + /// + /// Gets or sets the path of the track stream. The API returns it relative to itself; this web application replaces it with + /// the URL of its own streaming proxy, so that the browser never reaches the API server directly. + /// + public string StreamPath { get; set; } = string.Empty; + + /// + /// Gets or sets the opaque handle of the normalized delivery. The API returns it so the segment route can address exactly the delivery + /// the manifest declared. It is for a direct play. + /// + public string? DeliveryId { get; set; } + + /// + /// Gets or sets the path template of the segment route of the normalized delivery. The API returns it relative to itself with a + /// {deliveryId} and a {segmentIndex} placeholder; this web application replaces it with the URL of its own segment proxy, so + /// that the browser never reaches the API server directly. It is for a direct play. + /// + public string? SegmentStreamPathTemplate { get; set; } +} diff --git a/src/Lumina.Presentation.Web/Common/DTO/Common/PaginatedDto.cs b/src/Lumina.Presentation.Web/Common/DTO/Common/PaginatedDto.cs new file mode 100644 index 00000000..7973410c --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/DTO/Common/PaginatedDto.cs @@ -0,0 +1,24 @@ +#region ========================================================================= USING ===================================================================================== +using System.Collections.Generic; +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.DTO.Common; + +/// +/// Data transfer object for a page of elements together with its pagination metadata. +/// +/// The type of the elements of the page. +/// The elements of the requested page. +/// The one based number of the returned page. +/// The number of elements requested per page. +/// The total number of elements that match the filter, even when only a page of them is returned. +/// The total number of pages that match the filter. +[DebuggerDisplay("CurrentPage: {CurrentPage}; PerPage: {PerPage}; Count: {Count}")] +public sealed record PaginatedDto( + List Data, + int CurrentPage, + int PerPage, + int Count, + int NumberOfPages +); diff --git a/src/Lumina.Presentation.Web/Common/DTO/Favorites/FavoriteDto.cs b/src/Lumina.Presentation.Web/Common/DTO/Favorites/FavoriteDto.cs new file mode 100644 index 00000000..9030ed24 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/DTO/Favorites/FavoriteDto.cs @@ -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; + +/// +/// Data transfer object for a favorite of the current user. +/// +/// The Id of the favorite. +/// The kind of the favorited media item. +/// The Id of the favorited media item. +/// The date and time when the media item was favorited. +[DebuggerDisplay("Id: {Id}; MediaKind: {MediaKind}; MediaItemId: {MediaItemId}")] +public sealed record FavoriteDto( + Guid Id, + FavoriteMediaKind MediaKind, + Guid MediaItemId, + DateTime FavoritedOnUtc +); diff --git a/src/Lumina.Presentation.Web/Common/DTO/Favorites/FavoriteItemDto.cs b/src/Lumina.Presentation.Web/Common/DTO/Favorites/FavoriteItemDto.cs new file mode 100644 index 00000000..337abd18 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/DTO/Favorites/FavoriteItemDto.cs @@ -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; + +/// +/// Data transfer object for a favorite of the current user together with the display details of the media item it references. +/// +/// The kind of the favorited media item. +/// The Id of the favorited media item. +/// Whether the media item still exists and can be accessed by the user. When , every display field is empty. +/// The Id of the media library that contains the media item, or an empty Guid when the item is not available. +/// The title of the media item, or an empty string when the item is not available. +/// The Id of the collection that contains the media item, or an empty Guid when there is none. +/// The title of the collection that contains the media item, or an empty string when there is none. +/// The Id of the creator of the media item, or an empty Guid when there is none. +/// The name of the creator of the media item, or an empty string when there is none. +/// The path of the cover art of the media item, if available. +[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 +); diff --git a/src/Lumina.Presentation.Web/Common/DTO/Favorites/FavoriteStatusDto.cs b/src/Lumina.Presentation.Web/Common/DTO/Favorites/FavoriteStatusDto.cs new file mode 100644 index 00000000..faf78733 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/DTO/Favorites/FavoriteStatusDto.cs @@ -0,0 +1,16 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Collections.Generic; +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.DTO.Favorites; + +/// +/// Data transfer object that tells which of the checked media items are favorites of the current user. +/// +/// The Ids, among the checked ones, of the media items that are favorites of the current user. +[DebuggerDisplay("Favorited: {FavoritedMediaItemIds.Count}")] +public sealed record FavoriteStatusDto( + List FavoritedMediaItemIds +); diff --git a/src/Lumina.Presentation.Web/Common/DTO/Libraries/LibraryDto.cs b/src/Lumina.Presentation.Web/Common/DTO/Libraries/LibraryDto.cs index 69d1d494..dedea595 100644 --- a/src/Lumina.Presentation.Web/Common/DTO/Libraries/LibraryDto.cs +++ b/src/Lumina.Presentation.Web/Common/DTO/Libraries/LibraryDto.cs @@ -68,6 +68,17 @@ public class LibraryDto /// public bool ShouldSkipUnchangedDirectoriesDuringScan { get; set; } = false; + /// + /// Gets or sets whether the consumption progress of the media library items is tracked, or not. When absent, the default of the library type is used on create, and the stored value is kept on update. + /// + public bool? ShouldTrackConsumptionProgress { get; set; } + + /// + /// Gets or sets the percentage of a media library item that must be consumed for its session to be considered completed. When absent, the default of the library type is used on create, + /// and the stored value is kept on update. + /// + public int? CompletionThresholdPercentage { get; set; } + /// /// Gets or sets the ordered parts of the template describing the structure of the media library on disk. /// diff --git a/src/Lumina.Presentation.Web/Common/DTO/Libraries/PaginatedBookLiteDto.cs b/src/Lumina.Presentation.Web/Common/DTO/Libraries/PaginatedBookLiteDto.cs deleted file mode 100644 index 763276e0..00000000 --- a/src/Lumina.Presentation.Web/Common/DTO/Libraries/PaginatedBookLiteDto.cs +++ /dev/null @@ -1,38 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using System.Collections.Generic; -using System.Diagnostics; -#endregion - -namespace Lumina.Presentation.Web.Common.DTO.Libraries; - -/// -/// Data transfer object for a paginated collection of lightweight book elements, together with pagination metadata. -/// -[DebuggerDisplay("CurrentPage: {CurrentPage}; Count: {Count}")] -public class PaginatedBookLiteDto -{ - /// - /// Gets or sets the collection of lightweight book elements associated with this instance. - /// - public IReadOnlyList Data { get; set; } = []; - - /// - /// Gets or sets the current page number in a paginated collection. - /// - public int CurrentPage { get; set; } - - /// - /// Gets or sets the number of items to include per page in paginated results. - /// - public int PerPage { get; set; } - - /// - /// Gets or sets the total number of elements available in the paginated result set. - /// - public int Count { get; set; } - - /// - /// Gets or sets the total number of pages based on elements available in the result set and per page. - /// - public int NumberOfPages { get; set; } -} diff --git a/src/Lumina.Presentation.Web/Common/DTO/MediaConsumption/AllUsersConsumptionStatisticsDto.cs b/src/Lumina.Presentation.Web/Common/DTO/MediaConsumption/AllUsersConsumptionStatisticsDto.cs new file mode 100644 index 00000000..1712e52d --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/DTO/MediaConsumption/AllUsersConsumptionStatisticsDto.cs @@ -0,0 +1,17 @@ +#region ========================================================================= USING ===================================================================================== +using System.Collections.Generic; +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.DTO.MediaConsumption; + +/// +/// Data transfer object for the consumption statistics of every user, together with their combined totals. +/// +/// The combined consumption statistics of every user. +/// The consumption statistics of each user. +[DebuggerDisplay("UserCount: {Users.Count}; CountedSessionCount: {Total.CountedSessionCount}")] +public sealed record AllUsersConsumptionStatisticsDto( + ConsumptionTotalsDto Total, + IReadOnlyList Users +); diff --git a/src/Lumina.Presentation.Web/Common/DTO/MediaConsumption/ConsumedItemDto.cs b/src/Lumina.Presentation.Web/Common/DTO/MediaConsumption/ConsumedItemDto.cs new file mode 100644 index 00000000..041de9f4 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/DTO/MediaConsumption/ConsumedItemDto.cs @@ -0,0 +1,38 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Enums.MediaConsumption; +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.DTO.MediaConsumption; + +/// +/// Data transfer object for a media item of the consumption history, together with its aggregated consumption counts and display details. +/// +/// The kind of the consumed media item. +/// The Id of the consumed media item. +/// The Id of the media library that contains the media item. +/// Whether the media item still exists and can be accessed by the user. When , the title, collection title, creator name, and cover path are blank, while the identity and aggregation fields remain. +/// The title of the media item, or an empty string when the item is not available. +/// The title of the collection that contains the media item, or an empty string when there is none. +/// The name of the creator of the media item, or an empty string when there is none. +/// The path of the cover art of the media item, if available. +/// The date and time when the media item was last consumed. +/// The number of consumption sessions of the media item that count towards statistics. +/// The number of consumption sessions of the media item that completed. +/// The active duration consumed in the media item, over all of its sessions, in seconds. +[DebuggerDisplay("MediaKind: {MediaKind}; MediaItemId: {MediaItemId}; CountedSessionCount: {CountedSessionCount}")] +public sealed record ConsumedItemDto( + MediaKind MediaKind, + Guid MediaItemId, + Guid LibraryId, + bool IsAvailable, + string Title, + string CollectionTitle, + string CreatorName, + string? CoverPath, + DateTime LastConsumedOnUtc, + int CountedSessionCount, + int CompletedSessionCount, + double ConsumedDurationInSeconds +); diff --git a/src/Lumina.Presentation.Web/Common/DTO/MediaConsumption/ConsumptionRecordDto.cs b/src/Lumina.Presentation.Web/Common/DTO/MediaConsumption/ConsumptionRecordDto.cs new file mode 100644 index 00000000..6d2ee69a --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/DTO/MediaConsumption/ConsumptionRecordDto.cs @@ -0,0 +1,38 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Enums.MediaConsumption; +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.DTO.MediaConsumption; + +/// +/// Data transfer object for a media consumption session of the current user. +/// +/// The Id of the consumption record. +/// The Id of the media library that contains the consumed media item. +/// The Id of the consumed media item. +/// The kind of media that was consumed. +/// The state of the consumption session. +/// The date and time when the session started. +/// The date and time when the session last received activity. +/// The date and time when the session completed or stopped, if it has ended. +/// The active duration consumed by the session, in seconds. +/// The last known position for the media item, if any. +/// The latest reported progress fraction of the media item. +/// The number of consecutive pages read in the session. +[DebuggerDisplay("Id: {Id}; MediaKind: {MediaKind}; Status: {Status}")] +public sealed record ConsumptionRecordDto( + Guid Id, + Guid LibraryId, + Guid MediaItemId, + MediaKind MediaKind, + ConsumptionStatus Status, + DateTime StartedOnUtc, + DateTime LastActivityOnUtc, + DateTime? EndedOnUtc, + double ConsumedDurationInSeconds, + MediaPositionDto? LastPosition, + double LastProgressFraction, + int ConsecutivePagesRead +); diff --git a/src/Lumina.Presentation.Web/Common/DTO/MediaConsumption/ConsumptionSummaryDto.cs b/src/Lumina.Presentation.Web/Common/DTO/MediaConsumption/ConsumptionSummaryDto.cs new file mode 100644 index 00000000..624c709a --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/DTO/MediaConsumption/ConsumptionSummaryDto.cs @@ -0,0 +1,28 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Collections.Generic; +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.DTO.MediaConsumption; + +/// +/// Data transfer object for the consumption statistics of a user. +/// +/// The Id of the user the statistics belong to. +/// The total duration consumed over every recorded session, in seconds. +/// The number of recorded sessions that count towards statistics. +/// The number of recorded sessions that completed. +/// The number of recorded sessions that stopped before they completed and count towards statistics. +/// The fraction of the counted sessions that completed, between 0 and 1, or 0 when there is no counted session. +/// The consumption statistics broken down by media kind. +[DebuggerDisplay("UserId: {UserId}; CountedSessionCount: {CountedSessionCount}")] +public sealed record ConsumptionSummaryDto( + Guid UserId, + double TotalConsumedDurationInSeconds, + int CountedSessionCount, + int CompletedSessionCount, + int StoppedSessionCount, + double CompletionRate, + IReadOnlyList MediaKindSummaries +); diff --git a/src/Lumina.Presentation.Web/Common/DTO/MediaConsumption/ConsumptionTotalsDto.cs b/src/Lumina.Presentation.Web/Common/DTO/MediaConsumption/ConsumptionTotalsDto.cs new file mode 100644 index 00000000..3ab6abcb --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/DTO/MediaConsumption/ConsumptionTotalsDto.cs @@ -0,0 +1,25 @@ +#region ========================================================================= USING ===================================================================================== +using System.Collections.Generic; +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.DTO.MediaConsumption; + +/// +/// Data transfer object for the combined consumption statistics of every user. +/// +/// The total duration consumed over every recorded session of every user, in seconds. +/// The number of recorded sessions of every user that count towards statistics. +/// The number of recorded sessions of every user that completed. +/// The number of recorded sessions of every user that stopped before they completed and count towards statistics. +/// The fraction of the counted sessions of every user that completed, between 0 and 1, or 0 when there is no counted session. +/// The combined consumption statistics broken down by media kind. +[DebuggerDisplay("CountedSessionCount: {CountedSessionCount}; CompletedSessionCount: {CompletedSessionCount}")] +public sealed record ConsumptionTotalsDto( + double TotalConsumedDurationInSeconds, + int CountedSessionCount, + int CompletedSessionCount, + int StoppedSessionCount, + double CompletionRate, + IReadOnlyList MediaKindSummaries +); diff --git a/src/Lumina.Presentation.Web/Common/DTO/MediaConsumption/GenreConsumptionDto.cs b/src/Lumina.Presentation.Web/Common/DTO/MediaConsumption/GenreConsumptionDto.cs new file mode 100644 index 00000000..48b116e4 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/DTO/MediaConsumption/GenreConsumptionDto.cs @@ -0,0 +1,18 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.DTO.MediaConsumption; + +/// +/// Data transfer object for the consumption statistics of a genre, grouped across media kinds. +/// +/// The lowercase name of the genre. +/// The number of distinct media items that carry the genre and were consumed. +/// The active duration consumed in the media items that carry the genre, in seconds. +[DebuggerDisplay("Name: {Name}; ConsumedItemCount: {ConsumedItemCount}")] +public sealed record GenreConsumptionDto( + string Name, + int ConsumedItemCount, + double ConsumedDurationInSeconds +); diff --git a/src/Lumina.Presentation.Web/Common/DTO/MediaConsumption/MediaKindConsumptionSummaryDto.cs b/src/Lumina.Presentation.Web/Common/DTO/MediaConsumption/MediaKindConsumptionSummaryDto.cs new file mode 100644 index 00000000..bdb52f31 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/DTO/MediaConsumption/MediaKindConsumptionSummaryDto.cs @@ -0,0 +1,25 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Enums.MediaConsumption; +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.DTO.MediaConsumption; + +/// +/// Data transfer object for the consumption statistics of one kind of media. +/// +/// The kind of media the statistics belong to. +/// The total duration consumed over every recorded session of the media kind, in seconds. +/// The number of recorded sessions of the media kind that count towards statistics. +/// The number of recorded sessions of the media kind that completed. +/// The number of recorded sessions of the media kind that stopped before they completed and count towards statistics. +/// The fraction of the counted sessions of the media kind that completed, between 0 and 1. +[DebuggerDisplay("MediaKind: {MediaKind}; CountedSessionCount: {CountedSessionCount}")] +public sealed record MediaKindConsumptionSummaryDto( + MediaKind MediaKind, + double TotalConsumedDurationInSeconds, + int CountedSessionCount, + int CompletedSessionCount, + int StoppedSessionCount, + double CompletionRate +); diff --git a/src/Lumina.Presentation.Web/Common/DTO/MediaConsumption/MediaPositionDto.cs b/src/Lumina.Presentation.Web/Common/DTO/MediaConsumption/MediaPositionDto.cs new file mode 100644 index 00000000..dea11a9f --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/DTO/MediaConsumption/MediaPositionDto.cs @@ -0,0 +1,19 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Enums.MediaConsumption; +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.DTO.MediaConsumption; + +/// +/// Data transfer object for a position reached in a media item during a consumption session. +/// +/// The kind of representation used by the position. +/// The position within the media item, in seconds, when the position is a time offset. +/// The opaque locator within the media item, when the position is not a time offset. +[DebuggerDisplay("Kind: {Kind}; TimeOffsetSeconds: {TimeOffsetSeconds}")] +public sealed record MediaPositionDto( + MediaPositionKind Kind, + double? TimeOffsetSeconds, + string? Location +); diff --git a/src/Lumina.Presentation.Web/Common/DTO/MediaConsumption/ResumePointDto.cs b/src/Lumina.Presentation.Web/Common/DTO/MediaConsumption/ResumePointDto.cs new file mode 100644 index 00000000..6725366a --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/DTO/MediaConsumption/ResumePointDto.cs @@ -0,0 +1,28 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Enums.MediaConsumption; +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.DTO.MediaConsumption; + +/// +/// Data transfer object for the point at which a user can resume consuming a media item. +/// +/// The Id of the resume point. +/// The Id of the media library that contains the media item. +/// The Id of the media item to resume. +/// The kind of media that is resumed. +/// The position at which the media item can be resumed. +/// The progress fraction at which the media item can be resumed. +/// The date and time when the media item was last consumed. +[DebuggerDisplay("Id: {Id}; MediaKind: {MediaKind}; MediaItemId: {MediaItemId}")] +public sealed record ResumePointDto( + Guid Id, + Guid LibraryId, + Guid MediaItemId, + MediaKind MediaKind, + MediaPositionDto LastPosition, + double LastProgressFraction, + DateTime LastConsumedOnUtc +); diff --git a/src/Lumina.Presentation.Web/Common/DTO/MediaConsumption/StatisticsPageDto.cs b/src/Lumina.Presentation.Web/Common/DTO/MediaConsumption/StatisticsPageDto.cs new file mode 100644 index 00000000..60ca939b --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/DTO/MediaConsumption/StatisticsPageDto.cs @@ -0,0 +1,43 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.DTO.MediaConsumption; + +/// +/// Data transfer object for the data and the proxy routes of the statistics page. +/// +/// The localized title of the page. +/// Whether the current user is an administrator and can select another user or all users. +/// The Id of the current user, or when it cannot be determined. +/// The culture of the page. +/// The route that returns the statistics of the selected user. +/// The route that returns the statistics of every user. +/// The route that returns the recently consumed media items of the selected user. +/// The route that returns the most consumed media items of the selected user. +/// The route that returns the tag consumption of the selected user. +/// The route that returns the genre consumption of the selected user. +/// The route that returns the libraries available for the library filter. +/// The route that returns the users available for the administrator user selector, or an empty string for a regular user. +/// The route that deletes every consumption record of a media item. +/// The route that deletes the consumption history of the selected user. +/// The route that deletes the resume points of the selected user. +[DebuggerDisplay("IsAdmin: {IsAdmin}; CurrentUserId: {CurrentUserId}")] +public sealed record StatisticsPageDto( + string Title, + bool IsAdmin, + Guid? CurrentUserId, + string Culture, + string GetStatisticsUrl, + string GetAllUsersStatisticsUrl, + string GetRecentlyConsumedUrl, + string GetMostConsumedUrl, + string GetTagConsumptionUrl, + string GetGenreConsumptionUrl, + string GetLibrariesUrl, + string GetUsersUrl, + string DeleteConsumptionItemHistoryUrl, + string ClearConsumptionHistoryUrl, + string ClearResumePointsUrl +); diff --git a/src/Lumina.Presentation.Web/Common/DTO/MediaConsumption/TagConsumptionDto.cs b/src/Lumina.Presentation.Web/Common/DTO/MediaConsumption/TagConsumptionDto.cs new file mode 100644 index 00000000..9d377976 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/DTO/MediaConsumption/TagConsumptionDto.cs @@ -0,0 +1,18 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.DTO.MediaConsumption; + +/// +/// Data transfer object for the consumption statistics of a tag, grouped across media kinds. +/// +/// The lowercase name of the tag. +/// The number of distinct media items that carry the tag and were consumed. +/// The active duration consumed in the media items that carry the tag, in seconds. +[DebuggerDisplay("Name: {Name}; ConsumedItemCount: {ConsumedItemCount}")] +public sealed record TagConsumptionDto( + string Name, + int ConsumedItemCount, + double ConsumedDurationInSeconds +); diff --git a/src/Lumina.Presentation.Web/Common/DTO/Playlists/PlaylistDetailsDto.cs b/src/Lumina.Presentation.Web/Common/DTO/Playlists/PlaylistDetailsDto.cs new file mode 100644 index 00000000..fa47d0da --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/DTO/Playlists/PlaylistDetailsDto.cs @@ -0,0 +1,24 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Enums.Playlists; +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.DTO.Playlists; + +/// +/// Data transfer object for the editable scalars of a playlist after a details update. +/// +/// The Id of the playlist. +/// The name of the playlist. +/// The description of the playlist, if applicable. +/// The kind of media the playlist holds. +/// The date and time when the playlist was last updated, if applicable. +[DebuggerDisplay("Id: {Id}; Name: {Name}")] +public sealed record PlaylistDetailsDto( + Guid Id, + string Name, + string? Description, + PlaylistType Type, + DateTime? UpdatedOnUtc +); diff --git a/src/Lumina.Presentation.Web/Common/DTO/Playlists/PlaylistDto.cs b/src/Lumina.Presentation.Web/Common/DTO/Playlists/PlaylistDto.cs new file mode 100644 index 00000000..8ce52ef0 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/DTO/Playlists/PlaylistDto.cs @@ -0,0 +1,29 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.Common; +using Lumina.Presentation.Web.Common.Enums.Playlists; +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.DTO.Playlists; + +/// +/// Data transfer object for a playlist together with a page of its ordered entries. +/// +/// The Id of the playlist. +/// The name of the playlist. +/// The description of the playlist, if applicable. +/// The kind of media the playlist holds. +/// The page of ordered entries of the playlist, together with its pagination metadata. +/// The date and time when the playlist was created. +/// The date and time when the playlist was last updated, if applicable. +[DebuggerDisplay("Id: {Id}; Name: {Name}; Entries: {Entries.Count}")] +public sealed record PlaylistDto( + Guid Id, + string Name, + string? Description, + PlaylistType Type, + PaginatedDto Entries, + DateTime CreatedOnUtc, + DateTime? UpdatedOnUtc +); diff --git a/src/Lumina.Presentation.Web/Common/DTO/Playlists/PlaylistEntriesAddedDto.cs b/src/Lumina.Presentation.Web/Common/DTO/Playlists/PlaylistEntriesAddedDto.cs new file mode 100644 index 00000000..af9ccb81 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/DTO/Playlists/PlaylistEntriesAddedDto.cs @@ -0,0 +1,19 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.DTO.Playlists; + +/// +/// Data transfer object for the result of appending several tracks to a playlist. +/// +/// The Id of the playlist the entries were added to. +/// The number of entries that were appended, including repeated tracks. +/// The date and time when the playlist was last updated, if applicable. +[DebuggerDisplay("PlaylistId: {PlaylistId}; AddedCount: {AddedCount}")] +public sealed record PlaylistEntriesAddedDto( + Guid PlaylistId, + int AddedCount, + DateTime? UpdatedOnUtc +); diff --git a/src/Lumina.Presentation.Web/Common/DTO/Playlists/PlaylistEntryAddedDto.cs b/src/Lumina.Presentation.Web/Common/DTO/Playlists/PlaylistEntryAddedDto.cs new file mode 100644 index 00000000..b5c5a123 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/DTO/Playlists/PlaylistEntryAddedDto.cs @@ -0,0 +1,19 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.DTO.Playlists; + +/// +/// Data transfer object for an entry appended to a playlist. +/// +/// The Id of the playlist the entry was added to. +/// The added entry. +/// The date and time when the playlist was last updated, if applicable. +[DebuggerDisplay("PlaylistId: {PlaylistId}; Entry: {Entry.Id}")] +public sealed record PlaylistEntryAddedDto( + Guid PlaylistId, + PlaylistEntryDto Entry, + DateTime? UpdatedOnUtc +); diff --git a/src/Lumina.Presentation.Web/Common/DTO/Playlists/PlaylistEntryDto.cs b/src/Lumina.Presentation.Web/Common/DTO/Playlists/PlaylistEntryDto.cs new file mode 100644 index 00000000..4265d2ff --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/DTO/Playlists/PlaylistEntryDto.cs @@ -0,0 +1,38 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Enums.Playlists; +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.DTO.Playlists; + +/// +/// Data transfer object for an ordered playlist entry together with the display details of the media item it references. +/// +/// The Id of the entry. +/// The Id of the media item referenced by the entry. +/// The kind of media item referenced by the entry. +/// The zero based position of the entry in the playlist. +/// The Id of the media library that contains the media item, or an empty Guid when the item no longer exists. +/// The Id of the collection that contains the media item, or an empty Guid when the item no longer exists. +/// The Id of the creator of the media item, or an empty Guid when the item no longer exists. +/// The title of the media item, or an empty string when the item no longer exists. +/// The title of the collection that contains the media item, or an empty string when the item no longer exists. +/// The name of the creator of the media item, or an empty string when the item no longer exists. +/// The duration of the media item in seconds, or zero when the item no longer exists. +/// The path of the cover art of the collection, if available. +[DebuggerDisplay("Id: {Id}; MediaItemId: {MediaItemId}; Position: {Position}")] +public sealed record PlaylistEntryDto( + Guid Id, + Guid MediaItemId, + PlaylistMediaItemType MediaItemType, + int Position, + Guid LibraryId, + Guid CollectionId, + Guid CreatorId, + string MediaItemTitle, + string CollectionTitle, + string CreatorName, + int DurationInSeconds, + string? CoverPath +); diff --git a/src/Lumina.Presentation.Web/Common/DTO/Playlists/PlaylistEntryMovedDto.cs b/src/Lumina.Presentation.Web/Common/DTO/Playlists/PlaylistEntryMovedDto.cs new file mode 100644 index 00000000..4d0da515 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/DTO/Playlists/PlaylistEntryMovedDto.cs @@ -0,0 +1,21 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.DTO.Playlists; + +/// +/// Data transfer object for the result of moving one entry of a playlist to a new position. +/// +/// The Id of the playlist whose entry was moved. +/// The Id of the moved entry. +/// The new zero based position of the entry. +/// The date and time when the playlist was last updated, if applicable. +[DebuggerDisplay("PlaylistId: {PlaylistId}; EntryId: {EntryId}; Position: {Position}")] +public sealed record PlaylistEntryMovedDto( + Guid PlaylistId, + Guid EntryId, + int Position, + DateTime? UpdatedOnUtc +); diff --git a/src/Lumina.Presentation.Web/Common/DTO/Playlists/PlaylistSummaryDto.cs b/src/Lumina.Presentation.Web/Common/DTO/Playlists/PlaylistSummaryDto.cs new file mode 100644 index 00000000..46af5da3 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/DTO/Playlists/PlaylistSummaryDto.cs @@ -0,0 +1,28 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Enums.Playlists; +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.DTO.Playlists; + +/// +/// Data transfer object for a playlist in a list, without its entries. +/// +/// The Id of the playlist. +/// The name of the playlist. +/// The description of the playlist, if applicable. +/// The kind of media the playlist holds. +/// The number of entries of the playlist. +/// The date and time when the playlist was created. +/// The date and time when the playlist was last updated, if applicable. +[DebuggerDisplay("Id: {Id}; Name: {Name}; EntryCount: {EntryCount}")] +public sealed record PlaylistSummaryDto( + Guid Id, + string Name, + string? Description, + PlaylistType Type, + int EntryCount, + DateTime CreatedOnUtc, + DateTime? UpdatedOnUtc +); diff --git a/src/Lumina.Presentation.Web/Common/DTO/Themes/ThemeAudioPlayerDto.cs b/src/Lumina.Presentation.Web/Common/DTO/Themes/ThemeAudioPlayerDto.cs new file mode 100644 index 00000000..923565b8 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/DTO/Themes/ThemeAudioPlayerDto.cs @@ -0,0 +1,23 @@ +#region ========================================================================= USING ===================================================================================== +using System.Collections.Generic; +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.DTO.Themes; + +/// +/// Data transfer object for the model available to the themed audio player template. +/// +/// The absolute base URL of the Web application, used to reference application scripts from the theme template. +/// The base URL of the theme assets, used by the theme template to reference its own assets. +/// The raw template source of a queue item, rendered client side for each track of the play context. +/// The raw template source of a playlist item, rendered client side for each entry of a saved playlist. +/// The localized strings of the audio player, keyed by resource name. +[DebuggerDisplay("AssetBase: {AssetBase}")] +public sealed record ThemeAudioPlayerDto( + string AppBase, + string AssetBase, + string QueueItemTemplate, + string PlaylistItemTemplate, + IReadOnlyDictionary Strings +); diff --git a/src/Lumina.Presentation.Web/Common/DTO/UsersManagement/PlaybackStateDto.cs b/src/Lumina.Presentation.Web/Common/DTO/UsersManagement/PlaybackStateDto.cs new file mode 100644 index 00000000..a28ccb0d --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/DTO/UsersManagement/PlaybackStateDto.cs @@ -0,0 +1,22 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.DTO.UsersManagement; + +/// +/// Data transfer object for the playback state a user last reported to the player. The player writes these values automatically, and they are not part of the settings the user edits. +/// +[DebuggerDisplay("Volume: {Volume}; IsMuted: {IsMuted}")] +public class PlaybackStateDto +{ + /// + /// Gets or sets the last volume the player reported, as a value between 0 and 1. + /// + public double? Volume { get; set; } + + /// + /// Gets or sets the last mute state the player reported. + /// + public bool? IsMuted { get; set; } +} diff --git a/src/Lumina.Presentation.Web/Common/DTO/UsersManagement/UserSettingsDto.cs b/src/Lumina.Presentation.Web/Common/DTO/UsersManagement/UserSettingsDto.cs index 4290cf87..fd9e7aea 100644 --- a/src/Lumina.Presentation.Web/Common/DTO/UsersManagement/UserSettingsDto.cs +++ b/src/Lumina.Presentation.Web/Common/DTO/UsersManagement/UserSettingsDto.cs @@ -1,4 +1,5 @@ #region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Enums.AudioLibrary; using System; using System.Diagnostics; #endregion @@ -58,4 +59,74 @@ public class UserSettingsDto /// external servers, which those servers could observe; stripping them removes that possibility, at the cost of the look of the book. /// public bool ShouldPreserveBookStyles { get; set; } + + /// + /// Gets or sets whether the player keeps downloading a track while playback is paused, or not, up to the entire file. + /// + public bool? ShouldKeepDownloadingWhilePaused { get; set; } + + /// + /// Gets or sets whether the player continues playback at the end of an album or artist, or not. + /// + public bool? ShouldAutoplay { get; set; } + + /// + /// Gets or sets whether the player transitions between consecutive tracks without a gap, or not. + /// + public bool? IsGaplessPlaybackEnabled { get; set; } + + /// + /// Gets or sets the way ReplayGain normalization is applied to the tracks the user plays. + /// + public ReplayGainMode? ReplayGainMode { get; set; } + + /// + /// Gets or sets the quality cap applied to the audio the server normalizes for the user. + /// + public PlaybackStreamingQuality? StreamingQuality { get; set; } + + /// + /// Gets or sets the direction in which each channel of the VU meter of the audio player grows. + /// + public VuMeterOrientation? VuMeterOrientation { get; set; } = Enums.AudioLibrary.VuMeterOrientation.Vertical; + + /// + /// Gets or sets the number of segments each channel of the VU meter is divided into. + /// + public int? VuMeterSegmentCount { get; set; } = 12; + + /// + /// Gets or sets the gap, in pixels, between the segments and the channels of the VU meter. + /// + public int? VuMeterSegmentGap { get; set; } = 1; + + /// + /// Gets or sets the level, between 0 and 1, above which a segment of the VU meter is drawn with its medium state. + /// + public double? VuMeterMediumThreshold { get; set; } = 0.6; + + /// + /// Gets or sets the level, between 0 and 1, above which a segment of the VU meter is drawn with its high state. + /// + public double? VuMeterHighThreshold { get; set; } = 0.8; + + /// + /// Gets or sets whether the VU meter holds the peak level of each channel after it falls, or not. + /// + public bool? VuMeterShowPeak { get; set; } = true; + + /// + /// Gets or sets the time, in milliseconds, a peak of the VU meter is held before it starts falling. + /// + public int? VuMeterPeakHoldDurationInMilliseconds { get; set; } = 650; + + /// + /// Gets or sets the number of level units the display of the VU meter falls per second when the input level drops. + /// + public double? VuMeterReleasePerSecond { get; set; } = 3.0; + + /// + /// Gets or sets the number of level units the peak of the VU meter falls per second after its hold time elapsed. + /// + public double? VuMeterPeakReleasePerSecond { get; set; } = 0.65; } diff --git a/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebLayerServices.cs b/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebLayerServices.cs index ddd8275a..1f78ce97 100644 --- a/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebLayerServices.cs +++ b/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebLayerServices.cs @@ -20,6 +20,7 @@ using Microsoft.AspNetCore.Localization; using Microsoft.AspNetCore.Localization.Routing; using Microsoft.AspNetCore.Mvc.Localization; using Microsoft.AspNetCore.Mvc.Razor; +using Microsoft.AspNetCore.RateLimiting; using Microsoft.Extensions.DependencyInjection; using Polly; using Polly.CircuitBreaker; @@ -31,7 +32,9 @@ using System.Globalization; using System.Linq; using System.Net; using System.Net.Http; +using System.Security.Claims; using System.Text.Json.Serialization; +using System.Threading.RateLimiting; using System.Threading.Tasks; #endregion @@ -43,6 +46,11 @@ namespace Lumina.Presentation.Web.Common.DependencyInjection; [ExcludeFromCodeCoverage] public static class PresentationWebLayerServices { + /// + /// The name of the rate limiting policy that bounds the number of concurrent track streams held by a single user. + /// + public const string TRACK_STREAM_RATE_LIMIT_POLICY = "trackStreamPolicy"; + /// /// Registers the services of the Presentation Web layer into the Dependency Injection container. /// @@ -288,6 +296,26 @@ public static class PresentationWebLayerServices AsyncPolicyWrap policy = Policy.WrapAsync(retryPolicy, circuitBreakerPolicy); + // Bound the number of long lived streams a single user can hold open at once, mirroring the concurrency limit the API server applies to + // its own stream route. Without it, an authenticated user could make this application open an unbounded number of parallel streams, each + // pinning a connection towards the API for the whole duration of a track, turning this application into an exhaustion amplifier. + services.AddRateLimiter(rateLimiterOptions => + { + rateLimiterOptions.RejectionStatusCode = StatusCodes.Status429TooManyRequests; + rateLimiterOptions.AddPolicy(TRACK_STREAM_RATE_LIMIT_POLICY, httpContext => + { + // The limit is partitioned per authenticated user, and it is a concurrency limit, not a per IP attempt window, so it is deliberately separate from any login throttling. + string userId = httpContext.User.FindFirst(ClaimTypes.NameIdentifier)?.Value ?? "anonymous"; + return RateLimitPartition.GetConcurrencyLimiter( + partitionKey: $"trackStream_{userId}", + factory: _ => new ConcurrencyLimiterOptions + { + PermitLimit = 4, // Allow 4 concurrent audio streams per user, matching the API server. + QueueLimit = 0 // Don't queue requests, a request beyond the limit is rejected instead of waiting. + }); + }); + }); + // Register the HTTP typed client used for the API interaction. services.AddHttpClient() .AddHttpMessageHandler() @@ -295,6 +323,18 @@ public static class PresentationWebLayerServices .AddPolicyHandler(retryPolicy) .AddPolicyHandler(circuitBreakerPolicy); + // Register the HTTP typed client used for streaming responses from the API. It deliberately has no retry and no circuit breaker policy, + // because a stream cannot be transparently retried once its content has started reaching the client. It configures a bounded, generous + // timeout itself, because a stream stays open for as long as the client keeps reading it, yet a stalled one must never be held forever. + services.AddHttpClient() + // Cap the connections a stream can pin towards the API, as a backstop on top of the per user concurrency limit of the stream route. + .ConfigurePrimaryHttpMessageHandler(() => new SocketsHttpHandler + { + // A blackholed connection attempt must fail on its own, well before the request timeout, instead of holding a stream permit. + ConnectTimeout = TimeSpan.FromSeconds(30), + MaxConnectionsPerServer = 64 + }); + services.AddScoped(); services.AddScoped(); services.AddScoped(); @@ -311,6 +351,8 @@ public static class PresentationWebLayerServices services.AddScoped(); services.AddScoped(); services.AddScoped(); + services.AddScoped(); + services.AddScoped(); services.AddScoped(); services.AddScoped(); diff --git a/src/Lumina.Presentation.Web/Common/Enums/AudioLibrary/PlaybackDeliveryShape.cs b/src/Lumina.Presentation.Web/Common/Enums/AudioLibrary/PlaybackDeliveryShape.cs new file mode 100644 index 00000000..d1c6a97a --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Enums/AudioLibrary/PlaybackDeliveryShape.cs @@ -0,0 +1,23 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.Enums.AudioLibrary; + +/// +/// Enumeration for the shapes in which delivered audio is addressed and seeked. +/// +[DebuggerDisplay("{ToString()}")] +public enum PlaybackDeliveryShape +{ + /// + /// The delivered media is the original file itself, addressed and seeked by byte range. + /// + ByteRangeSeekable, + + /// + /// The delivered media is a sequence of fixed duration segments, addressed and seeked by time, so that finding a time never + /// requires mapping a byte range to it. + /// + TimeAddressedSegments, +} diff --git a/src/Lumina.Presentation.Web/Common/Enums/AudioLibrary/PlaybackStreamingQuality.cs b/src/Lumina.Presentation.Web/Common/Enums/AudioLibrary/PlaybackStreamingQuality.cs new file mode 100644 index 00000000..345f01fa --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Enums/AudioLibrary/PlaybackStreamingQuality.cs @@ -0,0 +1,36 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.Enums.AudioLibrary; + +/// +/// Enumeration for the quality cap applied to the audio the server normalizes (remuxes or transcodes) for a user. +/// +/// +/// The caps apply only to audio the server re-encodes into a lossy codec. A track that is played directly is delivered as it was stored, a remux only +/// repackages the stored codec without re-encoding it, and a lossless transcode is not reduced, so none of those deliveries is capped. +/// +[DebuggerDisplay("{ToString()}")] +public enum PlaybackStreamingQuality +{ + /// + /// The server chooses the quality, with a default cap of 192 kbps for a lossy re-encode. + /// + Auto, + + /// + /// A lossy normalized audio stream is capped at 96 kbps. + /// + Low, + + /// + /// A lossy normalized audio stream is capped at 160 kbps. + /// + Medium, + + /// + /// A lossy normalized audio stream is capped at 320 kbps. + /// + High, +} diff --git a/src/Lumina.Presentation.Web/Common/Enums/AudioLibrary/ReplayGainMode.cs b/src/Lumina.Presentation.Web/Common/Enums/AudioLibrary/ReplayGainMode.cs new file mode 100644 index 00000000..ebcd97ec --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Enums/AudioLibrary/ReplayGainMode.cs @@ -0,0 +1,28 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.Enums.AudioLibrary; + +/// +/// Enumeration for the ways ReplayGain normalization is applied to the tracks a user plays. +/// +[DebuggerDisplay("{ToString()}")] +public enum ReplayGainMode +{ + /// + /// ReplayGain is not applied. Tracks play at the loudness at which they were stored. + /// + Off, + + /// + /// Each track is normalized using its own ReplayGain track gain, so tracks from different albums play at a similar loudness. + /// + Track, + + /// + /// Each track is normalized using the ReplayGain album gain of the album it belongs to, so an album keeps its relative loudness + /// while albums play at a similar loudness to each other. + /// + Album, +} diff --git a/src/Lumina.Presentation.Web/Common/Enums/AudioLibrary/VuMeterOrientation.cs b/src/Lumina.Presentation.Web/Common/Enums/AudioLibrary/VuMeterOrientation.cs new file mode 100644 index 00000000..118a8c91 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Enums/AudioLibrary/VuMeterOrientation.cs @@ -0,0 +1,22 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.Enums.AudioLibrary; + +/// +/// Enumeration for the direction in which each channel of the VU meter of the audio player grows. +/// +[DebuggerDisplay("{ToString()}")] +public enum VuMeterOrientation +{ + /// + /// The channels of the meter are columns and their levels grow from bottom to top. + /// + Vertical, + + /// + /// The channels of the meter are rows and their levels grow from left to right. + /// + Horizontal, +} diff --git a/src/Lumina.Presentation.Web/Common/Enums/Favorites/FavoriteMediaKind.cs b/src/Lumina.Presentation.Web/Common/Enums/Favorites/FavoriteMediaKind.cs new file mode 100644 index 00000000..7c82ee2b --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Enums/Favorites/FavoriteMediaKind.cs @@ -0,0 +1,47 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.Enums.Favorites; + +/// +/// Enumeration for the kinds of media item that can be marked as a favorite. +/// +[DebuggerDisplay("{ToString()}")] +public enum FavoriteMediaKind +{ + /// + /// No media kind. Used as the default value; it is not a kind that can be marked as a favorite. + /// + None = 0, + + /// + /// A favorite that references an artist of a music library. + /// + MusicArtist, + + /// + /// A favorite that references an album of a music library. + /// + MusicAlbum, + + /// + /// A favorite that references a track of a music library. + /// + MusicTrack, + + /// + /// A favorite that references a book of a book library. + /// + Book, + + /// + /// A favorite that references a video file. Planned: video libraries are not catalogued yet, so this kind cannot be favorited. + /// + Video, + + /// + /// A favorite that references a photo. Planned: photo libraries are not catalogued yet, so this kind cannot be favorited. + /// + Photo, +} diff --git a/src/Lumina.Presentation.Web/Common/Enums/MediaConsumption/ConsumptionStatus.cs b/src/Lumina.Presentation.Web/Common/Enums/MediaConsumption/ConsumptionStatus.cs new file mode 100644 index 00000000..0746cd61 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Enums/MediaConsumption/ConsumptionStatus.cs @@ -0,0 +1,22 @@ +namespace Lumina.Presentation.Web.Common.Enums.MediaConsumption; + +/// +/// Enumeration for the states of a media consumption session. +/// +public enum ConsumptionStatus +{ + /// + /// The consumption session started and has not ended yet. + /// + InProgress, + + /// + /// The consumption session reached its explicit completion or the completion threshold of its library. + /// + Completed, + + /// + /// The consumption session ended before it completed. + /// + Stopped +} diff --git a/src/Lumina.Presentation.Web/Common/Enums/MediaConsumption/MediaKind.cs b/src/Lumina.Presentation.Web/Common/Enums/MediaConsumption/MediaKind.cs new file mode 100644 index 00000000..6a1c7401 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Enums/MediaConsumption/MediaKind.cs @@ -0,0 +1,52 @@ +namespace Lumina.Presentation.Web.Common.Enums.MediaConsumption; + +/// +/// Enumeration for the kinds of media items of the consumption history and statistics. +/// +public enum MediaKind +{ + /// + /// No media kind. Used as the default value; it is not a valid kind for a media item. + /// + None = 0, + + /// + /// A track of a music library. + /// + MusicTrack, + + /// + /// An episode of a podcast. + /// + PodcastEpisode, + + /// + /// An audiobook. + /// + Audiobook, + + /// + /// A movie. + /// + Movie, + + /// + /// An episode of a TV show. + /// + TvEpisode, + + /// + /// A book of a written content library. + /// + Book, + + /// + /// A photo. + /// + Photo, + + /// + /// A video file. + /// + Video +} diff --git a/src/Lumina.Presentation.Web/Common/Enums/MediaConsumption/MediaPositionKind.cs b/src/Lumina.Presentation.Web/Common/Enums/MediaConsumption/MediaPositionKind.cs new file mode 100644 index 00000000..24eb2ca1 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Enums/MediaConsumption/MediaPositionKind.cs @@ -0,0 +1,17 @@ +namespace Lumina.Presentation.Web.Common.Enums.MediaConsumption; + +/// +/// Enumeration for the kinds of position that a media consumption session can report. +/// +public enum MediaPositionKind +{ + /// + /// The position is a time offset within the media item. + /// + TimeOffset, + + /// + /// The position is an opaque locator within the media item, such as a reading location of a book. + /// + Location +} diff --git a/src/Lumina.Presentation.Web/Common/Enums/Playlists/PlaylistMediaItemType.cs b/src/Lumina.Presentation.Web/Common/Enums/Playlists/PlaylistMediaItemType.cs new file mode 100644 index 00000000..71f7dd80 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Enums/Playlists/PlaylistMediaItemType.cs @@ -0,0 +1,22 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.Enums.Playlists; + +/// +/// Enumeration for the kinds of media item an ordered playlist entry can reference. +/// +[DebuggerDisplay("{ToString()}")] +public enum PlaylistMediaItemType +{ + /// + /// An entry that references a music track. + /// + MusicTrack, + + /// + /// An entry that references a video file. + /// + VideoFile, +} diff --git a/src/Lumina.Presentation.Web/Common/Enums/Playlists/PlaylistType.cs b/src/Lumina.Presentation.Web/Common/Enums/Playlists/PlaylistType.cs new file mode 100644 index 00000000..978c044b --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Enums/Playlists/PlaylistType.cs @@ -0,0 +1,17 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.Enums.Playlists; + +/// +/// Enumeration for the kinds of media a playlist can hold. +/// +[DebuggerDisplay("{ToString()}")] +public enum PlaylistType +{ + /// + /// A playlist whose ordered entries reference music tracks. + /// + Music, +} diff --git a/src/Lumina.Presentation.Web/Common/HealthChecks/ApiReachabilityHealthCheck.cs b/src/Lumina.Presentation.Web/Common/HealthChecks/ApiReachabilityHealthCheck.cs index 496e1493..a9d8ca7a 100644 --- a/src/Lumina.Presentation.Web/Common/HealthChecks/ApiReachabilityHealthCheck.cs +++ b/src/Lumina.Presentation.Web/Common/HealthChecks/ApiReachabilityHealthCheck.cs @@ -33,7 +33,7 @@ public class ApiReachabilityHealthCheck : IHealthCheck /// Checks whether the remote API is reachable by probing its readiness endpoint. /// /// The health check context. - /// Token to monitor for cancellation requests. + /// Cancellation token that can be used to stop the execution. /// A task that represents the asynchronous operation, containing the health check result. public virtual async Task CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken) { diff --git a/src/Lumina.Presentation.Web/Common/Http/ApiStreamProxy.cs b/src/Lumina.Presentation.Web/Common/Http/ApiStreamProxy.cs new file mode 100644 index 00000000..6e6ca03f --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Http/ApiStreamProxy.cs @@ -0,0 +1,75 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Api; +using Microsoft.AspNetCore.Http; +using System.Net.Http.Headers; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Common.Http; + +/// +/// Writes a streamed API response to the browser, so the direct track stream and the normalized segment proxy share the same status, header, caching and body forwarding rules and cannot drift apart. +/// +public static class ApiStreamProxy +{ + /// + /// Copies the streamed API response to the response sent to the browser, without buffering its content. + /// + /// The response sent to the browser. + /// The streamed response of the API. + /// Cancellation token that can be used to stop the copy when the client disconnects. + /// A that represents the asynchronous copy operation. + public static async Task WriteAsync(HttpResponse response, ApiStreamResult streamResult, CancellationToken cancellationToken) + { + response.StatusCode = (int)streamResult.StatusCode; + if (!string.IsNullOrEmpty(streamResult.ContentType)) + response.ContentType = streamResult.ContentType; + if (streamResult.ContentLength.HasValue) + response.ContentLength = streamResult.ContentLength.Value; + SetHeader(response, "Content-Range", streamResult.ContentRange); + SetHeader(response, "Accept-Ranges", streamResult.AcceptRanges); + SetHeader(response, "ETag", streamResult.ETag); + SetHeader(response, "Last-Modified", streamResult.LastModified?.ToString("R")); + if (streamResult.SegmentCount.HasValue) + SetHeader(response, ApiStreamResult.SEGMENT_COUNT_HEADER_NAME, streamResult.SegmentCount.Value.ToString()); + SetHeader(response, ApiStreamResult.SEGMENT_START_SECONDS_HEADER_NAME, streamResult.SegmentStartSeconds); + if (streamResult.TrackDurationSeconds.HasValue) + SetHeader(response, ApiStreamResult.TRACK_DURATION_SECONDS_HEADER_NAME, streamResult.TrackDurationSeconds.Value.ToString()); + // The response is private to the cookie that authenticates this hop, and it never becomes publicly cacheable, whatever the API declared. + response.Headers["Cache-Control"] = BuildCacheControl(streamResult.CacheControl); + response.Headers["Vary"] = "Cookie"; + await streamResult.Content.CopyToAsync(response.Body, cancellationToken).ConfigureAwait(false); + } + + /// + /// Sets a response header to the given value, unless the value is missing. + /// + /// The response to set the header on. + /// The name of the header. + /// The value of the header, or when the API did not send it. + private static void SetHeader(HttpResponse response, string name, string? value) + { + if (!string.IsNullOrEmpty(value)) + response.Headers[name] = value; + } + + /// + /// Builds the caching instructions of the browser response from the instructions of the API. + /// + /// + /// A streamed media response is specific to the authenticated user, so it must never be stored by a shared cache. Every other instruction of + /// the API, like a maximum age for the private cache of the browser or a no-store, is kept, so the web hop never silently ignores a caching + /// decision the API made for the resource. + /// + /// The caching instructions of the API response, or when it declared none. + /// The caching instructions of the response sent to the browser. + private static string BuildCacheControl(string? apiCacheControl) + { + if (!CacheControlHeaderValue.TryParse(apiCacheControl, out CacheControlHeaderValue? cacheControl)) + cacheControl = new CacheControlHeaderValue(); + cacheControl.Public = false; + cacheControl.Private = true; + return cacheControl.ToString(); + } +} diff --git a/src/Lumina.Presentation.Web/Common/Http/HttpContextItemKeys.cs b/src/Lumina.Presentation.Web/Common/Http/HttpContextItemKeys.cs index 440e00f6..76feaf10 100644 --- a/src/Lumina.Presentation.Web/Common/Http/HttpContextItemKeys.cs +++ b/src/Lumina.Presentation.Web/Common/Http/HttpContextItemKeys.cs @@ -8,4 +8,9 @@ public static class HttpContextItemKeys public const string ERRORS = "errors"; public const string PENDING_SUPER_ADMIN_SETUP = "PendingSuperAdminSetup"; public const string LAST_DISPLAYED_VIEW = "LastViewUrl"; + + /// + /// The Cache-Control value chosen by the endpoint, restored when the response starts. + /// + public const string CACHE_CONTROL = "CacheControl"; } diff --git a/src/Lumina.Presentation.Web/Common/Middlewares/CacheControlHeaderMiddleware.cs b/src/Lumina.Presentation.Web/Common/Middlewares/CacheControlHeaderMiddleware.cs new file mode 100644 index 00000000..5e6b366f --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Middlewares/CacheControlHeaderMiddleware.cs @@ -0,0 +1,45 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Http; +using Microsoft.AspNetCore.Http; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Common.Middlewares; + +/// +/// Middleware that restores the Cache-Control header chosen by an endpoint after any middleware that overwrites it. +/// +/// +/// The session middleware sets Cache-Control: no-cache,no-store, Pragma: no-cache and Expires: -1 when it establishes +/// a new session, and it registers that write before the endpoint runs. Response-start callbacks run in reverse registration order, so a +/// callback registered here, before the session middleware, runs after the session middleware and can restore the endpoint's value. +/// +public class CacheControlHeaderMiddleware +{ + private readonly RequestDelegate _next; + + /// + /// Initializes a new instance of the class. + /// + /// The next middleware in the request pipeline. + public CacheControlHeaderMiddleware(RequestDelegate next) + { + _next = next; + } + + /// + /// Restores the endpoint's Cache-Control value when the response starts, after the response-start callbacks registered later, such as the session middleware's, have run. + /// + /// The for the current request. + /// A task representing the asynchronous operation. + public async Task InvokeAsync(HttpContext context) + { + context.Response.OnStarting(() => + { + if (context.Items.TryGetValue(HttpContextItemKeys.CACHE_CONTROL, out object? value) && value is string cacheControl && !string.IsNullOrEmpty(cacheControl)) + context.Response.Headers.CacheControl = cacheControl; + return Task.CompletedTask; + }); + await _next(context); + } +} diff --git a/src/Lumina.Presentation.Web/Common/Middlewares/ExceptionHandlingMiddleware.cs b/src/Lumina.Presentation.Web/Common/Middlewares/ExceptionHandlingMiddleware.cs index 5be0b61e..5dff1bc5 100644 --- a/src/Lumina.Presentation.Web/Common/Middlewares/ExceptionHandlingMiddleware.cs +++ b/src/Lumina.Presentation.Web/Common/Middlewares/ExceptionHandlingMiddleware.cs @@ -10,6 +10,7 @@ using System.Linq; using System.Net; using System.Text; using System.Text.Json; +using System.Threading; using System.Threading.Tasks; #endregion @@ -47,6 +48,11 @@ public class ExceptionHandlingMiddleware { await _next(context); } + catch (OperationCanceledException) when (context.RequestAborted.IsCancellationRequested) + { + // The client went away while its request or response was being processed, so there is nobody left to answer. + context.Abort(); + } catch (ApiException apiException) // threat API exceptions differently - they contain Problem Details properties { await HandleApiExceptionAsync(context, apiException); @@ -54,6 +60,13 @@ public class ExceptionHandlingMiddleware catch (Exception ex) // other cases - { _logger.LogError(ex, "Unexpected exception occurred: {Message}", ex.Message); + // Once the response has started, its status and headers are already on the wire, so they can no longer be replaced: the connection + // is aborted instead, so that the client sees a failed transfer rather than a success response it cannot trust. + if (context.Response.HasStarted) + { + context.Abort(); + return; + } // return a JSON result with the error details await WriteJsonResponseAsync(context, new { @@ -77,34 +90,23 @@ public class ExceptionHandlingMiddleware apiException.ProblemDetails?.Detail, apiException.ProblemDetails?.Extensions); + // Once the response has started, its status and headers are already on the wire, so they can no longer be replaced: the connection + // is aborted instead, so that the client sees a failed transfer rather than a redirect it could not follow or a body it would misread. + if (context.Response.HasStarted) + { + context.Abort(); + return; + } + // handle unauthorized errors by prompting the user to re-login if (apiException.HttpStatusCode == HttpStatusCode.Unauthorized) // HTTP 401 Unauthorized actually means lack of valid authentication credentials (not logged in) await HandleUnauthorizedAsync(context); else if (apiException.HttpStatusCode == HttpStatusCode.NotFound) // await HandleNotFoundAsync(context, apiException); else if (apiException.HttpStatusCode == HttpStatusCode.Forbidden) - { - if (IsApiRequest(context)) - { - string errorMessage = BuildErrorMessage(apiException); - await WriteJsonResponseAsync(context, new - { - success = false, - errorMessage - }); - } - else - await context.ForbidAsync(); - } + await HandleForbiddenAsync(context, apiException); else - { - string errorMessage = BuildErrorMessage(apiException); - await WriteJsonResponseAsync(context, new - { - success = false, - errorMessage - }); - } + await HandleGenericApiErrorAsync(context, apiException); } /// @@ -120,7 +122,7 @@ public class ExceptionHandlingMiddleware return; } - if (IsApiRequest(context)) + if (IsJsonRequest(context)) { context.Response.StatusCode = (int)HttpStatusCode.NotFound; await WriteJsonResponseAsync(context, new @@ -129,7 +131,7 @@ public class ExceptionHandlingMiddleware errorMessage = "NotFound" }); } - else + else if (IsNavigationRequest(context)) { context.Response.StatusCode = (int)HttpStatusCode.NotFound; @@ -138,6 +140,48 @@ public class ExceptionHandlingMiddleware _logger.LogInformation("Redirecting user to NotFound url"); context.Response.Redirect(notFoundUrl); // force an entire refresh of the current location, so that header and footer are re-rendered too } + else + await WriteStatusOnlyResponseAsync(context, (int)HttpStatusCode.NotFound).ConfigureAwait(false); + } + + /// + /// Handles forbidden exceptions. + /// + private async Task HandleForbiddenAsync(HttpContext context, ApiException apiException) + { + if (IsJsonRequest(context)) + { + string errorMessage = BuildErrorMessage(apiException); + await WriteJsonResponseAsync(context, new + { + success = false, + errorMessage + }); + } + else if (IsNavigationRequest(context)) + await context.ForbidAsync(); + else + await WriteStatusOnlyResponseAsync(context, (int)HttpStatusCode.Forbidden).ConfigureAwait(false); + } + + /// + /// Handles the API exceptions that are neither authentication, authorization, nor not found failures. + /// + private async Task HandleGenericApiErrorAsync(HttpContext context, ApiException apiException) + { + // JSON callers and page navigations get the localized error message; any other caller, like an audio request, is answered with + // a bare status code, because a JSON body is not a representation such a caller can consume. + if (IsJsonRequest(context) || IsNavigationRequest(context)) + { + string errorMessage = BuildErrorMessage(apiException); + await WriteJsonResponseAsync(context, new + { + success = false, + errorMessage + }); + } + else + await WriteStatusOnlyResponseAsync(context, (int)apiException.HttpStatusCode).ConfigureAwait(false); } /// @@ -149,7 +193,7 @@ public class ExceptionHandlingMiddleware await context.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme).ConfigureAwait(false); context.Response.Cookies.Delete("Token"); - if (IsApiRequest(context)) + if (IsJsonRequest(context)) { context.Response.StatusCode = (int)HttpStatusCode.Unauthorized; await WriteJsonResponseAsync(context, new @@ -158,7 +202,7 @@ public class ExceptionHandlingMiddleware errorMessage = "Unauthorized" }); } - else + else if (IsNavigationRequest(context)) { string culture = context.Request.RouteValues["culture"]?.ToString()?.ToLower() ?? "en-us"; string returnUrl = $"{context.Request.Path}{context.Request.QueryString}"; @@ -166,6 +210,8 @@ public class ExceptionHandlingMiddleware _logger.LogInformation("Redirecting unauthorized user to {Url}", loginUrl); context.Response.Redirect(loginUrl); // force an entire refresh of the current location, so that header and footer are re-rendered too } + else + await WriteStatusOnlyResponseAsync(context, (int)HttpStatusCode.Unauthorized).ConfigureAwait(false); } /// @@ -203,11 +249,38 @@ public class ExceptionHandlingMiddleware } /// - /// Checks if the current request is an API request. + /// Checks if the current request is a programmatic request that expects a JSON response. /// - private static bool IsApiRequest(HttpContext context) + /// + /// Every request is classified into exactly one of three kinds: a JSON request, which this method detects, a browser navigation, which + /// detects, and a raw request, which is neither of the two and is answered with a bare status code. + /// + /// The for the current request. + /// when the request expects JSON, otherwise. + private static bool IsJsonRequest(HttpContext context) { - return context.Request.Headers.Accept.Any(x => x?.Contains("application/json") == true) || context.Request.Headers.XRequestedWith == "XMLHttpRequest"; + return context.Request.Headers.Accept.Any(accept => accept?.Contains("application/json", StringComparison.OrdinalIgnoreCase) == true) + || context.Request.Headers.XRequestedWith == "XMLHttpRequest"; + } + + /// + /// Checks if the current request is a browser navigation, which is the only kind of request that can follow a redirect. + /// + /// + /// A request that explicitly asks for something other than HTML, like an audio or a media request, is answered with a bare status + /// code: treating it as a page would redirect it to an HTML login or not-found page, which its caller cannot consume. A request that + /// states no preference at all keeps the historical page behavior, so that callers that send no Accept header are not silently + /// changed, but a request that carries no Accept yet asks for a byte range is treated as a raw request, because a headerless + /// range request comes from a media client or a probe, not from a browser. + /// + /// The for the current request. + /// when the request is a navigation, otherwise. + private static bool IsNavigationRequest(HttpContext context) + { + return (context.Request.Headers.Accept.Count == 0 && context.Request.Headers.Range.Count == 0) + || context.Request.Headers.Accept.Any(accept => accept?.Contains("text/html", StringComparison.OrdinalIgnoreCase) == true) + || string.Equals(context.Request.Headers["Sec-Fetch-Mode"].ToString(), "navigate", StringComparison.OrdinalIgnoreCase) + || string.Equals(context.Request.Headers["Sec-Fetch-Dest"].ToString(), "document", StringComparison.OrdinalIgnoreCase); } /// @@ -219,6 +292,34 @@ public class ExceptionHandlingMiddleware await context.Response.WriteAsJsonAsync(response); } + /// + /// Writes the response of a raw request, which is a status code and no body. + /// + /// + /// This is the third branch of the request classification, the one that answers a request that is neither a JSON request, which + /// detects, nor a browser navigation, which detects. + /// + /// The for the current request. + /// The status code to answer with. + private async Task WriteStatusOnlyResponseAsync(HttpContext context, int statusCode) + { + context.Response.StatusCode = statusCode; + context.Response.ContentLength = 0; + try + { + // Starting the response commits the status code and the headers, so that no outer middleware replaces this decision with a page, + // and so that a caller that asked for content never receives HTML instead. A token that is never cancelled is used on purpose, + // because a request whose token is already cancelled would otherwise throw here, inside the exception handler, and escape it. + await context.Response.StartAsync(CancellationToken.None).ConfigureAwait(false); + } + catch (Exception startException) + { + // There is nobody left to answer, so the connection is aborted, and the failure is only recorded for diagnostics. + _logger.LogDebug(startException, "Could not commit the status only response, the client has likely disconnected."); + context.Abort(); + } + } + /// /// Determines whether the API exception originated from the authorization check of the currently logged in user. /// diff --git a/src/Lumina.Presentation.Web/Common/Playback/PlaybackDeliveryId.cs b/src/Lumina.Presentation.Web/Common/Playback/PlaybackDeliveryId.cs new file mode 100644 index 00000000..6a897aa6 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Playback/PlaybackDeliveryId.cs @@ -0,0 +1,31 @@ +namespace Lumina.Presentation.Web.Common.Playback; + +/// +/// Defines the format of the opaque delivery handle of a playback manifest. +/// +/// +/// The web application is a separate project that keeps its own contracts, so it repeats the API's rule rather than sharing a type: a handle is +/// exactly 32 lowercase hexadecimal characters, the N format of a GUID. A value that does not match it is rejected, never normalized. +/// +public static class PlaybackDeliveryId +{ + /// + /// The number of characters of a delivery handle. + /// + public const int CHARACTER_COUNT = 32; + + /// + /// Checks whether a value has the format of a delivery handle. + /// + /// The value to check. + /// when the value is exactly 32 lowercase hexadecimal characters, otherwise . + public static bool IsValid(string? value) + { + if (value is null || value.Length != CHARACTER_COUNT) + return false; + foreach (char character in value) + if (!((character >= '0' && character <= '9') || (character >= 'a' && character <= 'f'))) + return false; + return true; + } +} diff --git a/src/Lumina.Presentation.Web/Common/Requests/Favorites/AddFavoriteRequest.cs b/src/Lumina.Presentation.Web/Common/Requests/Favorites/AddFavoriteRequest.cs new file mode 100644 index 00000000..23183831 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Requests/Favorites/AddFavoriteRequest.cs @@ -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; + +/// +/// Represents a request for marking a media item as a favorite of the current user. +/// +/// The kind of the media item to favorite. Required. +/// The Id of the media item to favorite. Required. +[DebuggerDisplay("MediaKind: {MediaKind}; MediaItemId: {MediaItemId}")] +public record AddFavoriteRequest( + FavoriteMediaKind? MediaKind, + Guid? MediaItemId +); diff --git a/src/Lumina.Presentation.Web/Common/Requests/Favorites/GetFavoriteStatusRequest.cs b/src/Lumina.Presentation.Web/Common/Requests/Favorites/GetFavoriteStatusRequest.cs new file mode 100644 index 00000000..a01b9111 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Requests/Favorites/GetFavoriteStatusRequest.cs @@ -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; + +/// +/// Represents a request for finding out which media items of one kind are favorites of the current user. +/// +/// The kind of the media items to check. Required. +/// The Ids of the media items to check, from 1 to 100. Required. +[DebuggerDisplay("MediaKind: {MediaKind}")] +public record GetFavoriteStatusRequest( + FavoriteMediaKind? MediaKind, + List? MediaItemIds +); diff --git a/src/Lumina.Presentation.Web/Common/Requests/Favorites/GetFavoritesRequest.cs b/src/Lumina.Presentation.Web/Common/Requests/Favorites/GetFavoritesRequest.cs new file mode 100644 index 00000000..baef0067 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Requests/Favorites/GetFavoritesRequest.cs @@ -0,0 +1,19 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Enums.Favorites; +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.Requests.Favorites; + +/// +/// Represents a request for getting a page of the favorites of the current user. +/// +/// The kind of media item to restrict the favorites to. Optional; every kind is returned when omitted. +/// The one based page of favorites to return. Optional; defaults to 1. +/// The number of favorites per page. Optional; defaults to 200. +[DebuggerDisplay("MediaKind: {MediaKind}; CurrentPage: {CurrentPage}; PerPage: {PerPage}")] +public record GetFavoritesRequest( + FavoriteMediaKind? MediaKind, + int? CurrentPage, + int? PerPage +); diff --git a/src/Lumina.Presentation.Web/Common/Requests/Library/AudioLibrary/MusicLibrary/Tracks/GetPlaybackManifestRequest.cs b/src/Lumina.Presentation.Web/Common/Requests/Library/AudioLibrary/MusicLibrary/Tracks/GetPlaybackManifestRequest.cs new file mode 100644 index 00000000..4ed17207 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Requests/Library/AudioLibrary/MusicLibrary/Tracks/GetPlaybackManifestRequest.cs @@ -0,0 +1,23 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.Requests.Library.AudioLibrary.MusicLibrary.Tracks; + +/// +/// Represents a request to get the playback manifest of a track. +/// +/// The unique identifier of the artist the album belongs to, taken from the route. Required. +/// The unique identifier of the album the track belongs to, taken from the route. Required. +/// The unique identifier of the track whose manifest is requested, taken from the route. Required. +/// The Id of the media library the track belongs to. Required. +/// The comma separated list of the container and codec pairs the player advertises it can play directly. Optional. +[DebuggerDisplay("TrackId: {TrackId}")] +public record GetPlaybackManifestRequest( + string ArtistId, + string AlbumId, + string TrackId, + Guid LibraryId, + string? Capabilities +); diff --git a/src/Lumina.Presentation.Web/Common/Requests/Library/AudioLibrary/MusicLibrary/Tracks/ShuffleTracksRequest.cs b/src/Lumina.Presentation.Web/Common/Requests/Library/AudioLibrary/MusicLibrary/Tracks/ShuffleTracksRequest.cs new file mode 100644 index 00000000..08df127f --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Requests/Library/AudioLibrary/MusicLibrary/Tracks/ShuffleTracksRequest.cs @@ -0,0 +1,24 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Collections.Generic; +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.Requests.Library.AudioLibrary.MusicLibrary.Tracks; + +/// +/// Represents a request to draw a random selection of tracks from a media library, an artist or an album. +/// +/// The unique identifier of the media library the tracks are sampled from. Required. +/// The maximum number of tracks to return. Required. +/// The unique identifier of the artist whose tracks are sampled. Optional. +/// The unique identifier of the album whose tracks are sampled. Optional. +/// The tracks that must not be returned, usually the ones already in the queue. Optional. +[DebuggerDisplay("LibraryId: {LibraryId} Count: {Count}")] +public record ShuffleTracksRequest( + Guid LibraryId, + int Count, + Guid? ArtistId, + Guid? AlbumId, + List? ExcludedTrackIds +); diff --git a/src/Lumina.Presentation.Web/Common/Requests/Library/AudioLibrary/MusicLibrary/Tracks/StreamMusicTrackRequest.cs b/src/Lumina.Presentation.Web/Common/Requests/Library/AudioLibrary/MusicLibrary/Tracks/StreamMusicTrackRequest.cs new file mode 100644 index 00000000..8a0dfbbd --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Requests/Library/AudioLibrary/MusicLibrary/Tracks/StreamMusicTrackRequest.cs @@ -0,0 +1,21 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.Requests.Library.AudioLibrary.MusicLibrary.Tracks; + +/// +/// Represents a request to stream the audio file of a track. +/// +/// The unique identifier of the artist the album belongs to, taken from the route. Required. +/// The unique identifier of the album the track belongs to, taken from the route. Required. +/// The unique identifier of the track to stream, taken from the route. Required. +/// The Id of the media library the track belongs to. Required. +[DebuggerDisplay("TrackId: {TrackId}")] +public record StreamMusicTrackRequest( + string ArtistId, + string AlbumId, + string TrackId, + Guid LibraryId +); diff --git a/src/Lumina.Presentation.Web/Common/Requests/Library/AudioLibrary/MusicLibrary/Tracks/StreamMusicTrackSegmentRequest.cs b/src/Lumina.Presentation.Web/Common/Requests/Library/AudioLibrary/MusicLibrary/Tracks/StreamMusicTrackSegmentRequest.cs new file mode 100644 index 00000000..b87294e8 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Requests/Library/AudioLibrary/MusicLibrary/Tracks/StreamMusicTrackSegmentRequest.cs @@ -0,0 +1,25 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.Requests.Library.AudioLibrary.MusicLibrary.Tracks; + +/// +/// Represents a request to stream one segment of the normalized audio of a track. +/// +/// The unique identifier of the artist the album belongs to, taken from the route. Required. +/// The unique identifier of the album the track belongs to, taken from the route. Required. +/// The unique identifier of the track to stream, taken from the route. Required. +/// The opaque handle of the normalized delivery, taken from the route. Required. +/// The zero based index of the segment of the normalized audio, taken from the route. Required. +/// The Id of the media library the track belongs to. Required. +[DebuggerDisplay("TrackId: {TrackId} DeliveryId: {DeliveryId} SegmentIndex: {SegmentIndex}")] +public record StreamMusicTrackSegmentRequest( + string ArtistId, + string AlbumId, + string TrackId, + string DeliveryId, + int SegmentIndex, + Guid LibraryId +); diff --git a/src/Lumina.Presentation.Web/Common/Requests/Library/AudioLibrary/MusicLibrary/Tracks/UpdateMusicTrackRequest.cs b/src/Lumina.Presentation.Web/Common/Requests/Library/AudioLibrary/MusicLibrary/Tracks/UpdateMusicTrackRequest.cs index aa98dfed..048fe6b9 100644 --- a/src/Lumina.Presentation.Web/Common/Requests/Library/AudioLibrary/MusicLibrary/Tracks/UpdateMusicTrackRequest.cs +++ b/src/Lumina.Presentation.Web/Common/Requests/Library/AudioLibrary/MusicLibrary/Tracks/UpdateMusicTrackRequest.cs @@ -14,7 +14,6 @@ namespace Lumina.Presentation.Web.Common.Requests.Library.AudioLibrary.MusicLibr /// /// Represents a request to update an existing track of an album of a music artist. /// -/// The file system path of the track. Required. /// The audio metadata of the track. Required. /// The number of the track on its disc. Required. /// The number of the disc the track belongs to. Optional. @@ -30,7 +29,6 @@ namespace Lumina.Presentation.Web.Common.Requests.Library.AudioLibrary.MusicLibr /// The list of ratings for this track. Required. [DebuggerDisplay("Title: {Metadata?.Title}")] public record UpdateMusicTrackRequest( - string? Path, MusicTrackMetadataDto? Metadata, int? TrackNumber, int? DiscNumber, diff --git a/src/Lumina.Presentation.Web/Common/Requests/Library/Statistics/ClearConsumptionHistoryRequest.cs b/src/Lumina.Presentation.Web/Common/Requests/Library/Statistics/ClearConsumptionHistoryRequest.cs new file mode 100644 index 00000000..3cfc8a43 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Requests/Library/Statistics/ClearConsumptionHistoryRequest.cs @@ -0,0 +1,14 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.Requests.Library.Statistics; + +/// +/// Represents a request to delete the consumption history of a user. +/// +/// The Id of the user whose history is deleted. Optional; when omitted, the current user is used. +[DebuggerDisplay("UserId: {UserId}")] +public sealed record ClearConsumptionHistoryRequest( + string? UserId +); diff --git a/src/Lumina.Presentation.Web/Common/Requests/Library/Statistics/ClearResumePointsRequest.cs b/src/Lumina.Presentation.Web/Common/Requests/Library/Statistics/ClearResumePointsRequest.cs new file mode 100644 index 00000000..2eb58a34 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Requests/Library/Statistics/ClearResumePointsRequest.cs @@ -0,0 +1,16 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.Requests.Library.Statistics; + +/// +/// Represents a request to delete the resume points of a user. +/// +/// The Id of the user whose resume points are deleted. Optional; when omitted, the current user is used. +/// The Id of the media library to restrict the deletion to. Optional. +[DebuggerDisplay("UserId: {UserId}; LibraryId: {LibraryId}")] +public sealed record ClearResumePointsRequest( + string? UserId, + string? LibraryId +); diff --git a/src/Lumina.Presentation.Web/Common/Requests/Library/Statistics/DeleteConsumptionItemHistoryRequest.cs b/src/Lumina.Presentation.Web/Common/Requests/Library/Statistics/DeleteConsumptionItemHistoryRequest.cs new file mode 100644 index 00000000..30c20d47 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Requests/Library/Statistics/DeleteConsumptionItemHistoryRequest.cs @@ -0,0 +1,22 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Enums.MediaConsumption; +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.Requests.Library.Statistics; + +/// +/// Represents a request to delete every consumption record of a media item. +/// +/// The Id of the user whose history is deleted. Optional; when omitted, the current user is used. +/// The kind of the consumed media item. +/// The Id of the consumed media item. +/// The Id of the media library that contains the media item. +[DebuggerDisplay("UserId: {UserId}; MediaKind: {MediaKind}; MediaItemId: {MediaItemId}")] +public sealed record DeleteConsumptionItemHistoryRequest( + string? UserId, + MediaKind MediaKind, + Guid MediaItemId, + Guid LibraryId +); diff --git a/src/Lumina.Presentation.Web/Common/Requests/Library/Statistics/GetAllUsersConsumptionStatisticsRequest.cs b/src/Lumina.Presentation.Web/Common/Requests/Library/Statistics/GetAllUsersConsumptionStatisticsRequest.cs new file mode 100644 index 00000000..b4355740 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Requests/Library/Statistics/GetAllUsersConsumptionStatisticsRequest.cs @@ -0,0 +1,22 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Enums.MediaConsumption; +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.Requests.Library.Statistics; + +/// +/// Represents a request for getting the consumption statistics of every user. +/// +/// The Id of the media library to restrict the statistics to. Optional. +/// The kind of media to restrict the statistics to. Optional. +/// The inclusive start of the date range. Optional. +/// The inclusive end of the date range. Optional. +[DebuggerDisplay("MediaKind: {MediaKind}; FromUtc: {FromUtc}; ToUtc: {ToUtc}")] +public sealed record GetAllUsersConsumptionStatisticsRequest( + string? LibraryId, + MediaKind? MediaKind, + DateTime? FromUtc, + DateTime? ToUtc +); diff --git a/src/Lumina.Presentation.Web/Common/Requests/Library/Statistics/GetConsumptionStatisticsRequest.cs b/src/Lumina.Presentation.Web/Common/Requests/Library/Statistics/GetConsumptionStatisticsRequest.cs new file mode 100644 index 00000000..f87208b3 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Requests/Library/Statistics/GetConsumptionStatisticsRequest.cs @@ -0,0 +1,24 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Enums.MediaConsumption; +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.Requests.Library.Statistics; + +/// +/// Represents a request for getting the consumption statistics of a user. +/// +/// The Id of the user whose statistics are retrieved. Optional; when omitted, the current user is used. +/// The Id of the media library to restrict the statistics to. Optional. +/// The kind of media to restrict the statistics to. Optional. +/// The inclusive start of the date range. Optional. +/// The inclusive end of the date range. Optional. +[DebuggerDisplay("UserId: {UserId}; MediaKind: {MediaKind}")] +public sealed record GetConsumptionStatisticsRequest( + string? UserId, + string? LibraryId, + MediaKind? MediaKind, + DateTime? FromUtc, + DateTime? ToUtc +); diff --git a/src/Lumina.Presentation.Web/Common/Requests/Library/Statistics/GetGenreConsumptionRequest.cs b/src/Lumina.Presentation.Web/Common/Requests/Library/Statistics/GetGenreConsumptionRequest.cs new file mode 100644 index 00000000..53a9ef80 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Requests/Library/Statistics/GetGenreConsumptionRequest.cs @@ -0,0 +1,24 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Enums.MediaConsumption; +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.Requests.Library.Statistics; + +/// +/// Represents a request for getting the consumption statistics of the genres of a user. +/// +/// The Id of the user whose statistics are retrieved. Optional; when omitted, the current user is used. +/// The Id of the media library to restrict the statistics to. Optional. +/// The kind of media to restrict the statistics to. Optional. +/// The inclusive start of the date range. Optional. +/// The inclusive end of the date range. Optional. +[DebuggerDisplay("UserId: {UserId}; MediaKind: {MediaKind}; FromUtc: {FromUtc}")] +public sealed record GetGenreConsumptionRequest( + string? UserId, + string? LibraryId, + MediaKind? MediaKind, + DateTime? FromUtc, + DateTime? ToUtc +); diff --git a/src/Lumina.Presentation.Web/Common/Requests/Library/Statistics/GetMostConsumedRequest.cs b/src/Lumina.Presentation.Web/Common/Requests/Library/Statistics/GetMostConsumedRequest.cs new file mode 100644 index 00000000..d9cd7cd3 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Requests/Library/Statistics/GetMostConsumedRequest.cs @@ -0,0 +1,28 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Enums.MediaConsumption; +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.Requests.Library.Statistics; + +/// +/// Represents a request for getting a window of the most consumed media items of a user. +/// +/// The Id of the user whose history is retrieved. Optional; when omitted, the current user is used. +/// The Id of the media library to restrict the history to. Optional. +/// The kind of media to restrict the history to. Optional. +/// The inclusive start of the date range. Optional. +/// The inclusive end of the date range. Optional. +/// The one based page of media items to return. Optional. +/// The number of media items per page. Optional. +[DebuggerDisplay("UserId: {UserId}; MediaKind: {MediaKind}; CurrentPage: {CurrentPage}")] +public sealed record GetMostConsumedRequest( + string? UserId, + string? LibraryId, + MediaKind? MediaKind, + DateTime? FromUtc, + DateTime? ToUtc, + int? CurrentPage, + int? PerPage +); diff --git a/src/Lumina.Presentation.Web/Common/Requests/Library/Statistics/GetRecentlyConsumedRequest.cs b/src/Lumina.Presentation.Web/Common/Requests/Library/Statistics/GetRecentlyConsumedRequest.cs new file mode 100644 index 00000000..9463c355 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Requests/Library/Statistics/GetRecentlyConsumedRequest.cs @@ -0,0 +1,28 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Enums.MediaConsumption; +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.Requests.Library.Statistics; + +/// +/// Represents a request for getting a window of the recently consumed media items of a user. +/// +/// The Id of the user whose history is retrieved. Optional; when omitted, the current user is used. +/// The Id of the media library to restrict the history to. Optional. +/// The kind of media to restrict the history to. Optional. +/// The inclusive start of the date range. Optional. +/// The inclusive end of the date range. Optional. +/// The one based page of media items to return. Optional. +/// The number of media items per page. Optional. +[DebuggerDisplay("UserId: {UserId}; MediaKind: {MediaKind}; CurrentPage: {CurrentPage}")] +public sealed record GetRecentlyConsumedRequest( + string? UserId, + string? LibraryId, + MediaKind? MediaKind, + DateTime? FromUtc, + DateTime? ToUtc, + int? CurrentPage, + int? PerPage +); diff --git a/src/Lumina.Presentation.Web/Common/Requests/Library/Statistics/GetTagConsumptionRequest.cs b/src/Lumina.Presentation.Web/Common/Requests/Library/Statistics/GetTagConsumptionRequest.cs new file mode 100644 index 00000000..744acaaf --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Requests/Library/Statistics/GetTagConsumptionRequest.cs @@ -0,0 +1,24 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Enums.MediaConsumption; +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.Requests.Library.Statistics; + +/// +/// Represents a request for getting the consumption statistics of the tags of a user. +/// +/// The Id of the user whose statistics are retrieved. Optional; when omitted, the current user is used. +/// The Id of the media library to restrict the statistics to. Optional. +/// The kind of media to restrict the statistics to. Optional. +/// The inclusive start of the date range. Optional. +/// The inclusive end of the date range. Optional. +[DebuggerDisplay("UserId: {UserId}; MediaKind: {MediaKind}; FromUtc: {FromUtc}")] +public sealed record GetTagConsumptionRequest( + string? UserId, + string? LibraryId, + MediaKind? MediaKind, + DateTime? FromUtc, + DateTime? ToUtc +); diff --git a/src/Lumina.Presentation.Web/Common/Requests/MediaConsumption/CompleteConsumptionRequest.cs b/src/Lumina.Presentation.Web/Common/Requests/MediaConsumption/CompleteConsumptionRequest.cs new file mode 100644 index 00000000..0cb170cd --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Requests/MediaConsumption/CompleteConsumptionRequest.cs @@ -0,0 +1,21 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.Requests.MediaConsumption; + +/// +/// Represents a request to report that a media consumption session completed. +/// +/// The final position reported for the media item, if the client knows it. Optional. +/// The fraction of the media item that the client reached, between 0 and 1. Required. +/// The active duration consumed by the session, in seconds. Required. +/// The number of consecutive pages read in the session, used by page based media such as books. +/// It must be omitted or zero for other kinds; a positive value is rejected with a forbidden error. When omitted, the count stored by the last progress report is kept. Optional. +[DebuggerDisplay("ProgressFraction: {ProgressFraction}; ConsumedDurationInSeconds: {ConsumedDurationInSeconds}; ConsecutivePagesRead: {ConsecutivePagesRead}")] +public sealed record CompleteConsumptionRequest( + MediaPositionRequest? Position, + double? ProgressFraction, + double? ConsumedDurationInSeconds, + int? ConsecutivePagesRead = null +); diff --git a/src/Lumina.Presentation.Web/Common/Requests/MediaConsumption/MediaPositionRequest.cs b/src/Lumina.Presentation.Web/Common/Requests/MediaConsumption/MediaPositionRequest.cs new file mode 100644 index 00000000..a39c064c --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Requests/MediaConsumption/MediaPositionRequest.cs @@ -0,0 +1,18 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.Requests.MediaConsumption; + +/// +/// Represents a request to report a position in a media consumption session. +/// +/// The kind of the position. Required. +/// The position within the media item, in seconds, when the position is a time offset. Optional. +/// The opaque locator within the media item, when the position is not a time offset. Optional. +[DebuggerDisplay("Kind: {Kind}; TimeOffsetSeconds: {TimeOffsetSeconds}")] +public sealed record MediaPositionRequest( + string? Kind, + double? TimeOffsetSeconds, + string? Location +); diff --git a/src/Lumina.Presentation.Web/Common/Requests/MediaConsumption/ReportConsumptionProgressRequest.cs b/src/Lumina.Presentation.Web/Common/Requests/MediaConsumption/ReportConsumptionProgressRequest.cs new file mode 100644 index 00000000..b77ab1a6 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Requests/MediaConsumption/ReportConsumptionProgressRequest.cs @@ -0,0 +1,21 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.Requests.MediaConsumption; + +/// +/// Represents a request to report the progress of a media consumption session. +/// +/// The last position reported for the media item, if the client knows it. Optional. +/// The fraction of the media item that the client reached, between 0 and 1. Required. +/// The active duration consumed by the session, in seconds. Required. +/// The number of consecutive pages read in the current session, used by page based media such as books. +/// It must be zero for other kinds; a positive value is rejected with a forbidden error. Defaults to 0. Optional. +[DebuggerDisplay("ProgressFraction: {ProgressFraction}; ConsumedDurationInSeconds: {ConsumedDurationInSeconds}; ConsecutivePagesRead: {ConsecutivePagesRead}")] +public sealed record ReportConsumptionProgressRequest( + MediaPositionRequest? Position, + double? ProgressFraction, + double? ConsumedDurationInSeconds, + int ConsecutivePagesRead = 0 +); diff --git a/src/Lumina.Presentation.Web/Common/Requests/MediaConsumption/StopConsumptionRequest.cs b/src/Lumina.Presentation.Web/Common/Requests/MediaConsumption/StopConsumptionRequest.cs new file mode 100644 index 00000000..12ffcc78 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Requests/MediaConsumption/StopConsumptionRequest.cs @@ -0,0 +1,21 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.Requests.MediaConsumption; + +/// +/// Represents a request to report that a media consumption session stopped. +/// +/// The final position reported for the media item, if the client knows it. Optional. +/// The fraction of the media item that the client reached, between 0 and 1. Required. +/// The active duration consumed by the session, in seconds. Required. +/// The number of consecutive pages read in the session, used by page based media such as books. +/// It must be omitted or zero for other kinds; a positive value is rejected with a forbidden error. When omitted, the count stored by the last progress report is kept. Optional. +[DebuggerDisplay("ProgressFraction: {ProgressFraction}; ConsumedDurationInSeconds: {ConsumedDurationInSeconds}; ConsecutivePagesRead: {ConsecutivePagesRead}")] +public sealed record StopConsumptionRequest( + MediaPositionRequest? Position, + double? ProgressFraction, + double? ConsumedDurationInSeconds, + int? ConsecutivePagesRead = null +); diff --git a/src/Lumina.Presentation.Web/Common/Requests/Playlists/AddPlaylistEntriesRequest.cs b/src/Lumina.Presentation.Web/Common/Requests/Playlists/AddPlaylistEntriesRequest.cs new file mode 100644 index 00000000..dd5a7729 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Requests/Playlists/AddPlaylistEntriesRequest.cs @@ -0,0 +1,16 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Collections.Generic; +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.Requests.Playlists; + +/// +/// Represents a request for adding several tracks to a playlist of the current user, in order. +/// +/// The Ids of the tracks to add, in the order they must take. Required. +[DebuggerDisplay("TrackCount: {TrackIds.Count}")] +public record AddPlaylistEntriesRequest( + List? TrackIds +); diff --git a/src/Lumina.Presentation.Web/Common/Requests/Playlists/AddPlaylistEntryRequest.cs b/src/Lumina.Presentation.Web/Common/Requests/Playlists/AddPlaylistEntryRequest.cs new file mode 100644 index 00000000..098c6ae1 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Requests/Playlists/AddPlaylistEntryRequest.cs @@ -0,0 +1,15 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.Requests.Playlists; + +/// +/// Represents a request for adding a track to a playlist of the current user. +/// +/// The Id of the track to add. Required. +[DebuggerDisplay("TrackId: {TrackId}")] +public record AddPlaylistEntryRequest( + Guid? TrackId +); diff --git a/src/Lumina.Presentation.Web/Common/Requests/Playlists/AddPlaylistScopeEntriesRequest.cs b/src/Lumina.Presentation.Web/Common/Requests/Playlists/AddPlaylistScopeEntriesRequest.cs new file mode 100644 index 00000000..96dcdde1 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Requests/Playlists/AddPlaylistScopeEntriesRequest.cs @@ -0,0 +1,19 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.Requests.Playlists; + +/// +/// Represents a request to add every track of a music library, an artist or an album to a playlist, resolved on the server. +/// +/// The Id of the music library the scope belongs to. Required. +/// The Id of the artist the scope is limited to. Optional. +/// The Id of the album the scope is limited to. Optional. +[DebuggerDisplay("LibraryId: {LibraryId}; ArtistId: {ArtistId}; AlbumId: {AlbumId}")] +public record AddPlaylistScopeEntriesRequest( + Guid LibraryId, + Guid? ArtistId, + Guid? AlbumId +); diff --git a/src/Lumina.Presentation.Web/Common/Requests/Playlists/CreatePlaylistRequest.cs b/src/Lumina.Presentation.Web/Common/Requests/Playlists/CreatePlaylistRequest.cs new file mode 100644 index 00000000..878159a4 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Requests/Playlists/CreatePlaylistRequest.cs @@ -0,0 +1,19 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Enums.Playlists; +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.Requests.Playlists; + +/// +/// Represents a request for creating a playlist of the current user. +/// +/// The name of the playlist. Required. +/// The description of the playlist. Optional. +/// The kind of media the playlist holds. Required. +[DebuggerDisplay("Name: {Name}")] +public record CreatePlaylistRequest( + string? Name, + string? Description, + PlaylistType? Type +); diff --git a/src/Lumina.Presentation.Web/Common/Requests/Playlists/GetPlaylistRequest.cs b/src/Lumina.Presentation.Web/Common/Requests/Playlists/GetPlaylistRequest.cs new file mode 100644 index 00000000..2ca534d2 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Requests/Playlists/GetPlaylistRequest.cs @@ -0,0 +1,16 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.Requests.Playlists; + +/// +/// Represents a request for getting a page of the entries of a playlist of the current user. +/// +/// The one based page of entries to return. Optional; defaults to 1. +/// The number of entries per page. Optional; defaults to 200. +[DebuggerDisplay("CurrentPage: {CurrentPage}; PerPage: {PerPage}")] +public record GetPlaylistRequest( + int? CurrentPage, + int? PerPage +); diff --git a/src/Lumina.Presentation.Web/Common/Requests/Playlists/MovePlaylistEntryRequest.cs b/src/Lumina.Presentation.Web/Common/Requests/Playlists/MovePlaylistEntryRequest.cs new file mode 100644 index 00000000..7115dcd3 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Requests/Playlists/MovePlaylistEntryRequest.cs @@ -0,0 +1,14 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.Requests.Playlists; + +/// +/// Represents a request for moving one entry of a playlist of the current user to a new position. +/// +/// The new zero based position of the entry. Required. +[DebuggerDisplay("TargetPosition: {TargetPosition}")] +public record MovePlaylistEntryRequest( + int? TargetPosition +); diff --git a/src/Lumina.Presentation.Web/Common/Requests/Playlists/UpdatePlaylistRequest.cs b/src/Lumina.Presentation.Web/Common/Requests/Playlists/UpdatePlaylistRequest.cs new file mode 100644 index 00000000..b1524751 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Requests/Playlists/UpdatePlaylistRequest.cs @@ -0,0 +1,16 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.Requests.Playlists; + +/// +/// Represents a request for updating the details of a playlist of the current user. +/// +/// The name of the playlist. Required. +/// The description of the playlist. Optional. +[DebuggerDisplay("Name: {Name}")] +public record UpdatePlaylistRequest( + string? Name, + string? Description +); diff --git a/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.Favorites.cs b/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.Favorites.cs new file mode 100644 index 00000000..5631c035 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.Favorites.cs @@ -0,0 +1,18 @@ +namespace Lumina.Presentation.Web.Common.Routes; + +/// +/// Class for the collection of remote API routes called by this Web application. +/// +public static partial class ApiRoutes +{ + /// + /// Routes for the favorites endpoints of the remote API. + /// + 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"; + } +} diff --git a/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.LibraryStatistics.cs b/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.LibraryStatistics.cs new file mode 100644 index 00000000..ea682d5f --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.LibraryStatistics.cs @@ -0,0 +1,31 @@ +namespace Lumina.Presentation.Web.Common.Routes; + +/// +/// Class for the collection of remote API routes called by this Web application. +/// +public static partial class ApiRoutes +{ + /// + /// Routes for the consumption history, consumption statistics, and resume points of the remote API. + /// + public static class LibraryStatistics + { + public const string GET_RECENTLY_CONSUMED = "users/me/consumption-history/recently-consumed"; + public const string GET_MOST_CONSUMED = "users/me/consumption-history/most-consumed"; + public const string GET_CONSUMPTION_STATISTICS = "users/me/consumption-statistics"; + public const string GET_TAG_CONSUMPTION = "users/me/consumption-statistics/tags"; + public const string GET_GENRE_CONSUMPTION = "users/me/consumption-statistics/genres"; + public const string GET_USER_RECENTLY_CONSUMED = "users/{userId}/consumption-history/recently-consumed"; + public const string GET_USER_MOST_CONSUMED = "users/{userId}/consumption-history/most-consumed"; + public const string GET_USER_CONSUMPTION_STATISTICS = "users/{userId}/consumption-statistics"; + public const string GET_USER_TAG_CONSUMPTION = "users/{userId}/consumption-statistics/tags"; + public const string GET_USER_GENRE_CONSUMPTION = "users/{userId}/consumption-statistics/genres"; + public const string GET_ALL_USERS_CONSUMPTION_STATISTICS = "users/consumption-statistics"; + public const string DELETE_CONSUMPTION_ITEM_HISTORY = "users/me/consumption-history/media-items/{mediaKind}/{mediaItemId}/{libraryId}"; + public const string DELETE_USER_CONSUMPTION_ITEM_HISTORY = "users/{userId}/consumption-history/media-items/{mediaKind}/{mediaItemId}/{libraryId}"; + public const string CLEAR_CONSUMPTION_HISTORY = "users/me/consumption-history"; + public const string CLEAR_USER_CONSUMPTION_HISTORY = "users/{userId}/consumption-history"; + public const string CLEAR_RESUME_POINTS = "users/me/media-resume-points"; + public const string CLEAR_USER_RESUME_POINTS = "users/{userId}/media-resume-points"; + } +} diff --git a/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.MediaConsumption.cs b/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.MediaConsumption.cs new file mode 100644 index 00000000..e0282348 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.MediaConsumption.cs @@ -0,0 +1,19 @@ +namespace Lumina.Presentation.Web.Common.Routes; + +/// +/// Class for the collection of remote API routes called by this Web application. +/// +public static partial class ApiRoutes +{ + /// + /// Routes for the media consumption lifecycle and resume point endpoints of the remote API. + /// + public static class MediaConsumption + { + public const string START_CONSUMPTION = "libraries/{libraryId}/media-items/{mediaKind}/{mediaItemId}/consumption-records"; + public const string REPORT_CONSUMPTION_PROGRESS = "users/me/consumption-records/{recordId}/progress"; + public const string COMPLETE_CONSUMPTION = "users/me/consumption-records/{recordId}/complete"; + public const string STOP_CONSUMPTION = "users/me/consumption-records/{recordId}/stop"; + public const string GET_RESUME_POINT = "users/me/media-resume-points/{mediaKind}/{mediaItemId}"; + } +} diff --git a/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.Music.cs b/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.Music.cs index e1778db2..59622a18 100644 --- a/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.Music.cs +++ b/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.Music.cs @@ -21,8 +21,12 @@ public static partial class ApiRoutes public const string UPDATE_ALBUM_COVER = "libraries/{libraryId}/artists/{artistId}/albums/{albumId}/cover"; public const string DELETE_ALBUM = "libraries/{libraryId}/artists/{artistId}/albums/{albumId}"; public const string GET_ALBUM_TRACKS_LITE = "libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/lite"; + public const string SHUFFLE_TRACKS = "libraries/{libraryId}/tracks/shuffle"; public const string GET_TRACK = "libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}"; public const string UPDATE_TRACK = "libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}"; public const string DELETE_TRACK = "libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}"; + public const string STREAM_TRACK = "libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}/stream"; + public const string STREAM_TRACK_SEGMENT = "libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}/stream/deliveries/{deliveryId}/segments/{segmentIndex}"; + public const string GET_PLAYBACK_MANIFEST = "libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}/playback-manifest"; } } diff --git a/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.Playlists.cs b/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.Playlists.cs new file mode 100644 index 00000000..e698d4ed --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.Playlists.cs @@ -0,0 +1,24 @@ +namespace Lumina.Presentation.Web.Common.Routes; + +/// +/// Class for the collection of remote API routes called by this Web application. +/// +public static partial class ApiRoutes +{ + /// + /// Routes for the playlists endpoints of the remote API. + /// + public static class Playlists + { + public const string GET_PLAYLISTS = "users/me/playlists"; + public const string CREATE_PLAYLIST = "users/me/playlists"; + public const string GET_PLAYLIST = "users/me/playlists/{playlistId}"; + public const string UPDATE_PLAYLIST = "users/me/playlists/{playlistId}"; + public const string DELETE_PLAYLIST = "users/me/playlists/{playlistId}"; + public const string ADD_PLAYLIST_ENTRY = "users/me/playlists/{playlistId}/entries"; + public const string ADD_PLAYLIST_ENTRIES = "users/me/playlists/{playlistId}/entries-batch"; + public const string ADD_PLAYLIST_SCOPE_ENTRIES = "users/me/playlists/{playlistId}/entries-scope"; + public const string REMOVE_PLAYLIST_ENTRY = "users/me/playlists/{playlistId}/entries/{playlistEntryId}"; + public const string MOVE_PLAYLIST_ENTRY = "users/me/playlists/{playlistId}/entries/{playlistEntryId}/move"; + } +} diff --git a/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.Users.cs b/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.Users.cs index 7ef9fa39..dbcfecf3 100644 --- a/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.Users.cs +++ b/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.Users.cs @@ -12,5 +12,7 @@ public static partial class ApiRoutes { public const string GET_USER_SETTINGS = "users/me/settings"; public const string UPDATE_USER_SETTINGS = "users/me/settings"; + public const string GET_PLAYBACK_STATE = "users/me/settings/playback-state"; + public const string UPDATE_PLAYBACK_STATE = "users/me/settings/playback-state"; } } diff --git a/src/Lumina.Presentation.Web/Common/Routes/WebRoutes.Favorites.cs b/src/Lumina.Presentation.Web/Common/Routes/WebRoutes.Favorites.cs new file mode 100644 index 00000000..f9b59e20 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Routes/WebRoutes.Favorites.cs @@ -0,0 +1,19 @@ +namespace Lumina.Presentation.Web.Common.Routes; + +/// +/// Class for the collection of routes defined in the Web application. +/// +public static partial class WebRoutes +{ + /// + /// Routes for the favorites pages. + /// + public static class Favorites + { + public const string INDEX = "{culture}/favorites"; + public const string GET_FAVORITES = "{culture}/favorites/api-get-favorites"; + public const string GET_FAVORITE_STATUS = "{culture}/favorites/api-get-favorite-status"; + public const string ADD_FAVORITE = "{culture}/favorites/api-add-favorite"; + public const string REMOVE_FAVORITE = "{culture}/favorites/{mediaKind}/{mediaItemId}/api-remove-favorite"; + } +} diff --git a/src/Lumina.Presentation.Web/Common/Routes/WebRoutes.LibraryStatistics.cs b/src/Lumina.Presentation.Web/Common/Routes/WebRoutes.LibraryStatistics.cs new file mode 100644 index 00000000..9135ff8e --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Routes/WebRoutes.LibraryStatistics.cs @@ -0,0 +1,26 @@ +namespace Lumina.Presentation.Web.Common.Routes; + +/// +/// Class for the collection of routes defined in the Web application. +/// +public static partial class WebRoutes +{ + /// + /// Routes for the library statistics pages. + /// + public static class LibraryStatistics + { + public const string INDEX = "{culture}/library/statistics"; + public const string GET_STATISTICS = "{culture}/library/statistics/api-get-statistics"; + public const string GET_ALL_USERS_STATISTICS = "{culture}/library/statistics/api-get-all-users-statistics"; + public const string GET_RECENTLY_CONSUMED = "{culture}/library/statistics/api-get-recently-consumed"; + public const string GET_MOST_CONSUMED = "{culture}/library/statistics/api-get-most-consumed"; + public const string GET_TAG_CONSUMPTION = "{culture}/library/statistics/api-get-tag-consumption"; + public const string GET_GENRE_CONSUMPTION = "{culture}/library/statistics/api-get-genre-consumption"; + public const string GET_LIBRARIES = "{culture}/library/statistics/api-get-libraries"; + public const string GET_USERS = "{culture}/library/statistics/api-get-users"; + public const string DELETE_CONSUMPTION_ITEM_HISTORY = "{culture}/library/statistics/api-delete-consumption-item-history"; + public const string CLEAR_CONSUMPTION_HISTORY = "{culture}/library/statistics/api-clear-consumption-history"; + public const string CLEAR_RESUME_POINTS = "{culture}/library/statistics/api-clear-resume-points"; + } +} diff --git a/src/Lumina.Presentation.Web/Common/Routes/WebRoutes.MediaConsumption.cs b/src/Lumina.Presentation.Web/Common/Routes/WebRoutes.MediaConsumption.cs new file mode 100644 index 00000000..d35e3935 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Routes/WebRoutes.MediaConsumption.cs @@ -0,0 +1,19 @@ +namespace Lumina.Presentation.Web.Common.Routes; + +/// +/// Class for the collection of routes defined in the Web application. +/// +public static partial class WebRoutes +{ + /// + /// Routes for the media consumption lifecycle actions and resume points the browser clients report to, proxied to the remote API. + /// + public static class MediaConsumption + { + public const string START_CONSUMPTION = "{culture}/media-consumption/api-start-consumption/{libraryId}/{mediaKind}/{mediaItemId}"; + public const string REPORT_CONSUMPTION_PROGRESS = "{culture}/media-consumption/api-report-consumption-progress/{recordId}"; + public const string COMPLETE_CONSUMPTION = "{culture}/media-consumption/api-complete-consumption/{recordId}"; + public const string STOP_CONSUMPTION = "{culture}/media-consumption/api-stop-consumption/{recordId}"; + public const string GET_RESUME_POINT = "{culture}/media-consumption/api-get-resume-point/{mediaKind}/{mediaItemId}"; + } +} diff --git a/src/Lumina.Presentation.Web/Common/Routes/WebRoutes.Music.cs b/src/Lumina.Presentation.Web/Common/Routes/WebRoutes.Music.cs index dd707299..1279314c 100644 --- a/src/Lumina.Presentation.Web/Common/Routes/WebRoutes.Music.cs +++ b/src/Lumina.Presentation.Web/Common/Routes/WebRoutes.Music.cs @@ -24,9 +24,13 @@ public static partial class WebRoutes public const string UPDATE_ALBUM_COVER = "{culture}/library/audio-library/music-library/artists/{artistId}/albums/{albumId}/api-update-cover"; public const string DELETE_ALBUM = "{culture}/library/audio-library/music-library/artists/{artistId}/albums/{albumId}/api-delete-album"; public const string GET_ALBUM_TRACKS = "{culture}/library/audio-library/music-library/artists/{artistId}/albums/{albumId}/tracks/api-get-tracks"; + public const string SHUFFLE_TRACKS = "{culture}/library/audio-library/music-library/tracks/api-shuffle-tracks"; public const string TRACK = "{culture}/library/audio-library/music-library/artists/{artistId}/albums/{albumId}/tracks/{trackId}"; public const string GET_TRACK = "{culture}/library/audio-library/music-library/artists/{artistId}/albums/{albumId}/tracks/{trackId}/api-get-track"; public const string SAVE_TRACK = "{culture}/library/audio-library/music-library/artists/{artistId}/albums/{albumId}/tracks/{trackId}/api-save-track"; public const string DELETE_TRACK = "{culture}/library/audio-library/music-library/artists/{artistId}/albums/{albumId}/tracks/{trackId}/api-delete-track"; + public const string STREAM_TRACK = "{culture}/library/audio-library/music-library/artists/{artistId}/albums/{albumId}/tracks/{trackId}/api-stream-track"; + public const string STREAM_TRACK_SEGMENT = "{culture}/library/audio-library/music-library/artists/{artistId}/albums/{albumId}/tracks/{trackId}/api-stream-track-segment/{deliveryId}/{segmentIndex}"; + public const string GET_PLAYBACK_MANIFEST = "{culture}/library/audio-library/music-library/artists/{artistId}/albums/{albumId}/tracks/{trackId}/api-get-playback-manifest"; } } diff --git a/src/Lumina.Presentation.Web/Common/Routes/WebRoutes.Playlists.cs b/src/Lumina.Presentation.Web/Common/Routes/WebRoutes.Playlists.cs new file mode 100644 index 00000000..390a4fc6 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Routes/WebRoutes.Playlists.cs @@ -0,0 +1,27 @@ +namespace Lumina.Presentation.Web.Common.Routes; + +/// +/// Class for the collection of routes defined in the Web application. +/// +public static partial class WebRoutes +{ + /// + /// Routes for the playlist pages. + /// + public static class Playlists + { + public const string INDEX = "{culture}/playlists"; + public const string GET_PLAYLISTS = "{culture}/playlists/api-get-playlists"; + public const string CREATE_PLAYLIST = "{culture}/playlists/api-create-playlist"; + public const string ADD = "{culture}/playlists/item"; + public const string ITEM = "{culture}/playlists/item/{playlistId}"; + public const string GET_PLAYLIST = "{culture}/playlists/item/{playlistId}/api-get-playlist"; + public const string UPDATE_PLAYLIST = "{culture}/playlists/item/{playlistId}/api-update-playlist"; + public const string DELETE_PLAYLIST = "{culture}/playlists/item/{playlistId}/api-delete-playlist"; + public const string ADD_PLAYLIST_ENTRY = "{culture}/playlists/item/{playlistId}/entries/api-add-entry"; + public const string ADD_PLAYLIST_ENTRIES = "{culture}/playlists/item/{playlistId}/api-add-entries"; + public const string ADD_PLAYLIST_SCOPE_ENTRIES = "{culture}/playlists/item/{playlistId}/api-add-scope-entries"; + public const string REMOVE_PLAYLIST_ENTRY = "{culture}/playlists/item/{playlistId}/entries/{playlistEntryId}/api-remove-entry"; + public const string MOVE_PLAYLIST_ENTRY = "{culture}/playlists/item/{playlistId}/entries/{playlistEntryId}/api-move-entry"; + } +} diff --git a/src/Lumina.Presentation.Web/Common/Routes/WebRoutes.Settings.cs b/src/Lumina.Presentation.Web/Common/Routes/WebRoutes.Settings.cs index 267383c8..3806b805 100644 --- a/src/Lumina.Presentation.Web/Common/Routes/WebRoutes.Settings.cs +++ b/src/Lumina.Presentation.Web/Common/Routes/WebRoutes.Settings.cs @@ -13,5 +13,7 @@ public static partial class WebRoutes public const string INDEX = "{culture}/tools/settings"; public const string GET_USER_SETTINGS = "{culture}/tools/settings/api-get-user-settings"; public const string UPDATE_USER_SETTINGS = "{culture}/tools/settings/api-update-user-settings"; + public const string GET_PLAYBACK_STATE = "{culture}/tools/settings/api-get-playback-state"; + public const string UPDATE_PLAYBACK_STATE = "{culture}/tools/settings/api-update-playback-state"; } } diff --git a/src/Lumina.Presentation.Web/Common/Services/IUrlService.cs b/src/Lumina.Presentation.Web/Common/Services/IUrlService.cs index 93663e4d..dda5ac04 100644 --- a/src/Lumina.Presentation.Web/Common/Services/IUrlService.cs +++ b/src/Lumina.Presentation.Web/Common/Services/IUrlService.cs @@ -1,7 +1,7 @@ namespace Lumina.Presentation.Web.Common.Services; /// -/// Interface for the service for generating absolute URLs from the application route templates, with URL localization. +/// Interface for the service for generating URLs from the application route templates, with URL localization. /// public interface IUrlService { @@ -12,4 +12,13 @@ public interface IUrlService /// Optional additional route values, like route parameters. /// An absolute URL to the specified route. string? GetAbsoluteUrl(string routeTemplate, object? additionalRouteValues = null); + + /// + /// Generates a root relative URL for the specified route template, including the path base and the culture, but not the scheme or the host. + /// A browser resolves it against the origin of the page, so it does not depend on how the server sees its own host behind a proxy. + /// + /// The route template of the target page or endpoint, taken from the constants. + /// Optional additional route values, like route parameters. + /// A root relative URL to the specified route. + string? GetRelativeUrl(string routeTemplate, object? additionalRouteValues = null); } diff --git a/src/Lumina.Presentation.Web/Common/Services/UrlService.cs b/src/Lumina.Presentation.Web/Common/Services/UrlService.cs index acc29775..2c6ac95a 100644 --- a/src/Lumina.Presentation.Web/Common/Services/UrlService.cs +++ b/src/Lumina.Presentation.Web/Common/Services/UrlService.cs @@ -38,7 +38,20 @@ public class UrlService : IUrlService /// Thrown when is not one of the route templates defined in the constants. public string? GetAbsoluteUrl(string routeTemplate, object? additionalRouteValues = null) { - // fail fast when the route template is not one of the ones defined in the WebRoutes constants, instead of silently generating a broken URL + string? path = GetRelativeUrl(routeTemplate, additionalRouteValues); + if (path is null) + return null; + HttpContext? httpContext = _httpContextAccessor.HttpContext; + if (httpContext is null) + return null; + // Build the absolute URL from the request's scheme, host and the already localized path base. + return $"{httpContext.Request.Scheme}://{httpContext.Request.Host}{path}"; + } + + /// + public string? GetRelativeUrl(string routeTemplate, object? additionalRouteValues = null) + { + // Fail fast when the route template is not one of the ones defined in the WebRoutes constants, instead of silently generating a broken URL. if (!s_knownRouteTemplates.Contains(routeTemplate)) throw new ArgumentException($"The route template '{routeTemplate}' is not defined in the WebRoutes constants.", nameof(routeTemplate)); @@ -50,11 +63,12 @@ public class UrlService : IUrlService if (additionalRouteValues is not null) foreach (PropertyInfo property in additionalRouteValues.GetType().GetProperties()) path = path.Replace($"{{{property.Name}}}", property.GetValue(additionalRouteValues)?.ToString(), StringComparison.OrdinalIgnoreCase); - // ensure the path starts with a slash, so that it is relative to the server root when concatenated with the host and the path base + // Ensure the path starts with a slash, so that it is relative to the server root when concatenated with the path base. if (!path.StartsWith('/')) path = "/" + path; - // build the absolute URL from the request's scheme, host and path base - return $"{httpContext.Request.Scheme}://{httpContext.Request.Host}{httpContext.Request.PathBase}{path}"; + // The scheme and host are deliberately omitted. A browser resolves this against its own origin, so the value stays + // correct behind a reverse proxy even when the request headers do not describe the origin the browser used. + return $"{httpContext.Request.PathBase}{path}"; } /// diff --git a/src/Lumina.Presentation.Web/Common/Utilities/CacheControlHeaderMiddlewareUtilities.cs b/src/Lumina.Presentation.Web/Common/Utilities/CacheControlHeaderMiddlewareUtilities.cs new file mode 100644 index 00000000..08c4ffd5 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Utilities/CacheControlHeaderMiddlewareUtilities.cs @@ -0,0 +1,25 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Middlewares; +using Microsoft.AspNetCore.Builder; +#endregion + +namespace Lumina.Presentation.Web.Common.Utilities; + +/// +/// Extension methods for adding the to the request pipeline. +/// +public static class CacheControlHeaderMiddlewareUtilities +{ + /// + /// Adds the to the application's request pipeline. + /// + /// + /// It must be registered before the session middleware, so that its response-start callback runs after the one of the session middleware. + /// + /// The used to configure the application's request pipeline. + /// The for further configuration. + public static IApplicationBuilder UseCacheControlHeader(this IApplicationBuilder builder) + { + return builder.UseMiddleware(); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Common/BaseEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Common/BaseEndpoint.cs index f00b760c..ae003d6b 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Common/BaseEndpoint.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Common/BaseEndpoint.cs @@ -31,6 +31,20 @@ public abstract class BaseEndpoint : Endpoint + /// Sets the Cache-Control header, and remembers the chosen value so that it can be restored after later components overwrite it. + /// + /// + /// The antiforgery token generation and the session middleware both force their own Cache-Control value, and they can run after the + /// endpoint has chosen one. The remembered value is restored when the response starts by the CacheControlHeaderMiddleware. + /// + /// The Cache-Control value chosen by the endpoint. + protected void SetCacheControl(string cacheControl) + { + HttpContext.Response.Headers.CacheControl = cacheControl; + HttpContext.Items[HttpContextItemKeys.CACHE_CONTROL] = cacheControl; + } + /// /// Renders a Razor view to the response. /// @@ -40,6 +54,13 @@ public abstract class BaseEndpoint : EndpointAn that renders the view. protected IResult View(string viewName, object? model = null, IReadOnlyDictionary? viewData = null) { + // A view endpoint that set the Cache-Control header directly, instead of through SetCacheControl, still has its value remembered. + if (!HttpContext.Items.ContainsKey(HttpContextItemKeys.CACHE_CONTROL)) + { + string cacheControl = HttpContext.Response.Headers.CacheControl.ToString(); + if (!string.IsNullOrEmpty(cacheControl)) + HttpContext.Items[HttpContextItemKeys.CACHE_CONTROL] = cacheControl; + } // Store the path of the displayed view in the session, so that the login redirect after the JWT token expires points to it; ignore the login endpoint, // because it is incorrect to be redirected to the login URL, with the login URL as the return URL. if (HttpContext.Request.Path != "/en-us/auth/login") diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Favorites/AddFavorite/AddFavoriteEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Favorites/AddFavorite/AddFavoriteEndpoint.cs new file mode 100644 index 00000000..e8c7e82e --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Favorites/AddFavorite/AddFavoriteEndpoint.cs @@ -0,0 +1,55 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.Favorites; +using Lumina.Presentation.Web.Common.Requests.Favorites; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Favorites.AddFavorite; + +/// +/// API endpoint for the /{culture}/favorites/api-add-favorite route. +/// +public class AddFavoriteEndpoint : BaseEndpoint +{ + private readonly IApiHttpClient _apiHttpClient; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for interactions with the API. + public AddFavoriteEndpoint(IApiHttpClient apiHttpClient) + { + _apiHttpClient = apiHttpClient; + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.POST); + Routes(WebRoutes.Favorites.ADD_FAVORITE); + DontAutoTag(); + Options(options => options.WithTags("Favorites")); + EnableAntiforgery(); + } + + /// + /// Marks a media item as a favorite of the current user. + /// + /// The request containing the kind and the Id of the media item to favorite. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(AddFavoriteRequest request, CancellationToken cancellationToken) + { + FavoriteDto favorite = await _apiHttpClient.PostAsync(ApiRoutes.Favorites.ADD_FAVORITE, request, cancellationToken).ConfigureAwait(false); + return JsonSuccess(favorite); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Favorites/AddFavorite/AddFavoriteEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Favorites/AddFavorite/AddFavoriteEndpointSummary.cs new file mode 100644 index 00000000..c4d7590b --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Favorites/AddFavorite/AddFavoriteEndpointSummary.cs @@ -0,0 +1,42 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.DTO.Common; +using Lumina.Presentation.Web.Common.DTO.Favorites; +using Lumina.Presentation.Web.Common.Enums.Favorites; +using Lumina.Presentation.Web.Common.Requests.Favorites; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Favorites.AddFavorite; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class AddFavoriteEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public AddFavoriteEndpointSummary() + { + Summary = "Marks a media item as a favorite of the current user."; + Description = "Proxies the request that marks a media item as a favorite to the API server. Adding an item that is already a favorite is not an error: the existing favorite is returned."; + + 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: MusicArtist, MusicAlbum, MusicTrack or Book. Required."); + RequestParam(request => request.MediaItemId, "The Id of the media item to favorite. Required."); + + Response(200, "The media item is a favorite and the favorite is returned.", + example: new SuccessResponse(true, new FavoriteDto( + Id: Guid.Parse("4b7a2c10-5d3e-4f68-9a1b-0c2d3e4f5a6b"), + MediaKind: FavoriteMediaKind.MusicTrack, + MediaItemId: Guid.Parse("9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f"), + FavoritedOnUtc: new DateTime(2026, 10, 21, 9, 30, 0, DateTimeKind.Utc))) + ); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Favorites/GetFavoriteStatus/GetFavoriteStatusEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Favorites/GetFavoriteStatus/GetFavoriteStatusEndpoint.cs new file mode 100644 index 00000000..9da4de1a --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Favorites/GetFavoriteStatus/GetFavoriteStatusEndpoint.cs @@ -0,0 +1,72 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.Favorites; +using Lumina.Presentation.Web.Common.Requests.Favorites; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Favorites.GetFavoriteStatus; + +/// +/// API endpoint for the /{culture}/favorites/api-get-favorite-status route. +/// +public class GetFavoriteStatusEndpoint : BaseEndpoint +{ + // The API accepts at most 100 Ids per check, so one more is forwarded to let its validator report an oversized list. + private const int MAXIMUM_FORWARDED_MEDIA_ITEM_COUNT = 101; + + private readonly IApiHttpClient _apiHttpClient; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for interactions with the API. + public GetFavoriteStatusEndpoint(IApiHttpClient apiHttpClient) + { + _apiHttpClient = apiHttpClient; + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.GET); + Routes(WebRoutes.Favorites.GET_FAVORITE_STATUS); + DontAutoTag(); + Options(options => options.WithTags("Favorites")); + } + + /// + /// Retrieves which of the given media items are favorites of the current user. + /// + /// The request containing the kind and the Ids of the media items to check. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(GetFavoriteStatusRequest request, CancellationToken cancellationToken) + { + // The favorites belong to the authenticated user, so no intermediary may store them, and the response varies by the sign in cookie. + HttpContext.Response.Headers["Cache-Control"] = "private, no-store"; + HttpContext.Response.Headers["Vary"] = "Cookie"; + // The query string is rebuilt from the typed request values instead of forwarding the raw one, so that crafted text can never alter the upstream URL. + // A missing kind or Id list is left out, so that the API reports the validation error itself. + List queryParameters = []; + if (request.MediaKind is not null) + queryParameters.Add($"mediaKind={Uri.EscapeDataString(request.MediaKind.Value.ToString())}"); + // The forwarded list is bounded, so the upstream URL stays bounded too. + foreach (Guid mediaItemId in (request.MediaItemIds ?? []).Take(MAXIMUM_FORWARDED_MEDIA_ITEM_COUNT)) + queryParameters.Add($"mediaItemIds={mediaItemId}"); + string url = queryParameters.Count == 0 ? ApiRoutes.Favorites.GET_FAVORITE_STATUS : $"{ApiRoutes.Favorites.GET_FAVORITE_STATUS}?{string.Join('&', queryParameters)}"; + FavoriteStatusDto status = await _apiHttpClient.GetAsync(url, cancellationToken).ConfigureAwait(false); + return JsonSuccess(status); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Favorites/GetFavoriteStatus/GetFavoriteStatusEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Favorites/GetFavoriteStatus/GetFavoriteStatusEndpointSummary.cs new file mode 100644 index 00000000..5e51c588 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Favorites/GetFavoriteStatus/GetFavoriteStatusEndpointSummary.cs @@ -0,0 +1,43 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.DTO.Common; +using Lumina.Presentation.Web.Common.DTO.Favorites; +using Lumina.Presentation.Web.Common.Enums.Favorites; +using Lumina.Presentation.Web.Common.Requests.Favorites; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Favorites.GetFavoriteStatus; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class GetFavoriteStatusEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public GetFavoriteStatusEndpointSummary() + { + Summary = "Gets which media items are favorites of the current user."; + Description = "Proxies the request that finds out which of the given media items of one kind are favorites of the current user to the API server. The mediaItemIds query parameter is repeated, once per Id."; + + ExampleRequest = new GetFavoriteStatusRequest( + MediaKind: FavoriteMediaKind.MusicTrack, + MediaItemIds: + [ + Guid.Parse("9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f"), + Guid.Parse("5a4b3c2d-1e0f-4a9b-8c7d-6e5f4a3b2c1d") + ] + ); + RequestParam(request => request.MediaKind, "The kind of the media items to check: MusicArtist, MusicAlbum, MusicTrack or Book. Required."); + RequestParam(request => request.MediaItemIds, "The Ids of the media items to check, from 1 to 100, sent as a repeated mediaItemIds query parameter. Required."); + + Response(200, "The Ids, among the checked ones, of the media items that are favorites of the current user are returned.", + example: new SuccessResponse(true, new FavoriteStatusDto( + FavoritedMediaItemIds: [Guid.Parse("9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f")])) + ); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Favorites/GetFavorites/GetFavoritesEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Favorites/GetFavorites/GetFavoritesEndpoint.cs new file mode 100644 index 00000000..db023ad4 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Favorites/GetFavorites/GetFavoritesEndpoint.cs @@ -0,0 +1,69 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.Common; +using Lumina.Presentation.Web.Common.DTO.Favorites; +using Lumina.Presentation.Web.Common.Requests.Favorites; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System; +using System.Globalization; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Favorites.GetFavorites; + +/// +/// API endpoint for the /{culture}/favorites/api-get-favorites route. +/// +public class GetFavoritesEndpoint : BaseEndpoint +{ + private const int DEFAULT_FAVORITE_PAGE_SIZE = 200; + + private readonly IApiHttpClient _apiHttpClient; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for interactions with the API. + public GetFavoritesEndpoint(IApiHttpClient apiHttpClient) + { + _apiHttpClient = apiHttpClient; + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.GET); + Routes(WebRoutes.Favorites.GET_FAVORITES); + DontAutoTag(); + Options(options => options.WithTags("Favorites")); + } + + /// + /// Retrieves a page of the favorites of the current user. + /// + /// The request object. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(GetFavoritesRequest request, CancellationToken cancellationToken) + { + // The favorites belong to the authenticated user, so no intermediary may store them, and the response varies by the sign in cookie. + HttpContext.Response.Headers["Cache-Control"] = "private, no-store"; + HttpContext.Response.Headers["Vary"] = "Cookie"; + // The query string is rebuilt from the typed request values instead of forwarding the raw one, so that crafted text can never alter the upstream URL. + // The page bounds are normalized by the API pagination data, exactly like every other paginated collection of the application. + int currentPage = request.CurrentPage ?? 1; + int perPage = request.PerPage ?? DEFAULT_FAVORITE_PAGE_SIZE; + string url = ApiRoutes.Favorites.GET_FAVORITES + $"?currentPage={currentPage.ToString(CultureInfo.InvariantCulture)}&perPage={perPage.ToString(CultureInfo.InvariantCulture)}"; + if (request.MediaKind is not null) + url += $"&mediaKind={Uri.EscapeDataString(request.MediaKind.Value.ToString())}"; + PaginatedDto favorites = await _apiHttpClient.GetAsync>(url, cancellationToken).ConfigureAwait(false); + return JsonSuccess(favorites); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Favorites/GetFavorites/GetFavoritesEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Favorites/GetFavorites/GetFavoritesEndpointSummary.cs new file mode 100644 index 00000000..8bc35307 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Favorites/GetFavorites/GetFavoritesEndpointSummary.cs @@ -0,0 +1,58 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.DTO.Common; +using Lumina.Presentation.Web.Common.DTO.Favorites; +using Lumina.Presentation.Web.Common.Enums.Favorites; +using Lumina.Presentation.Web.Common.Requests.Favorites; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Favorites.GetFavorites; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class GetFavoritesEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public GetFavoritesEndpointSummary() + { + Summary = "Gets the favorites of the current user."; + Description = "Proxies the request that gets a page of the favorites of the current user, from the most recently favorited, to the API server. The currentPage and perPage query parameters select the page, and count reports the total number of favorites that match the filter. Each favorite carries the display details of its media item."; + + ExampleRequest = new GetFavoritesRequest( + MediaKind: FavoriteMediaKind.MusicTrack, + CurrentPage: 1, + PerPage: 200 + ); + RequestParam(request => request.MediaKind, "The kind of media item to restrict the favorites to: MusicArtist, MusicAlbum, MusicTrack or Book. Optional; every kind is returned when omitted."); + RequestParam(request => request.CurrentPage, "The one based page of favorites to return. Optional; defaults to 1."); + RequestParam(request => request.PerPage, "The number of favorites per page. Optional; defaults to 200."); + + Response(200, "The requested page of the favorites of the current user is returned.", + example: new SuccessResponse>(true, new PaginatedDto( + Data: + [ + new FavoriteItemDto( + MediaKind: FavoriteMediaKind.MusicTrack, + MediaItemId: Guid.Parse("9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f"), + IsAvailable: true, + LibraryId: Guid.Parse("1a2b3c4d-5e6f-4a7b-8c9d-0e1f2a3b4c5d"), + Title: "Time", + CollectionId: Guid.Parse("7c6b5a49-3827-4165-9d0e-1f2a3b4c5d6e"), + CollectionTitle: "The Dark Side of the Moon", + CreatorId: Guid.Parse("2d3e4f5a-6b7c-4d8e-9f0a-1b2c3d4e5f6a"), + CreatorName: "Pink Floyd", + CoverPath: "covers/dark-side-of-the-moon.jpg") + ], + CurrentPage: 1, + PerPage: 200, + Count: 1, + NumberOfPages: 1)) + ); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Favorites/Index/FavoritesIndexViewEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Favorites/Index/FavoritesIndexViewEndpoint.cs new file mode 100644 index 00000000..3e046172 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Favorites/Index/FavoritesIndexViewEndpoint.cs @@ -0,0 +1,108 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.DTO.Themes; +using Lumina.Presentation.Web.Common.Primitives; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Common.Services; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Lumina.Presentation.Web.Core.Themes; +using Microsoft.AspNetCore.Antiforgery; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.Localization; +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Favorites.Index; + +/// +/// API endpoint for the /{culture}/favorites route. +/// +public class FavoritesIndexViewEndpoint : BaseEndpoint +{ + // The resource base name deliberately excludes the "Core.Resources" segment: the localization factory re-roots it with the configured ResourcesPath. + private const string VIEW_RESOURCE_BASE_NAME = "Lumina.Presentation.Web.Views.Favorites.Index"; + private const string VIEW_RESOURCE_LOCATION = "Lumina.Presentation.Web"; + // The page key mirrors the path of the Razor view under Core/Views, so that theme templates can override it at the page, section or default scope. + private const string VIEW_PAGE_KEY = "favorites/index"; + + private readonly IUrlService _urlService; + private readonly ThemePageRenderer _themePageRenderer; + private readonly IAntiforgery _antiforgery; + private readonly IStringLocalizer _localizer; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for generating URLs from action and controller names, with localization. + /// Injected service for rendering themed pages. + /// Injected service for anti-forgery token handling. + /// Injected factory used to create the localizer of the view resources. + public FavoritesIndexViewEndpoint(IUrlService urlService, ThemePageRenderer themePageRenderer, IAntiforgery antiforgery, IStringLocalizerFactory stringLocalizerFactory) + { + _urlService = urlService; + _themePageRenderer = themePageRenderer; + _antiforgery = antiforgery; + _localizer = stringLocalizerFactory.Create(VIEW_RESOURCE_BASE_NAME, VIEW_RESOURCE_LOCATION); + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.GET); + Routes(WebRoutes.Favorites.INDEX); + DontAutoTag(); + Options(options => options.WithTags("Favorites")); + } + + /// + /// Displays the favorites of the current user across media kinds, rendered by the active theme with a fallback to the Razor view. + /// + /// The request object. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(EmptyRequest request, CancellationToken cancellationToken) + { + // The page shows the favorites of the authenticated user, so no intermediary may store it, and the response varies by the sign in cookie. + SetCacheControl("private, no-store"); + HttpContext.Response.Headers["Vary"] = "Cookie"; + // The page removes favorites, which submit through the form anti-forgery token, so a fresh token is issued for it. + AntiforgeryTokenSet antiforgeryTokens = _antiforgery.GetAndStoreTokens(HttpContext); + string title = _localizer["Title"].Value; + + // The media item link templates carry the all-zero Guid placeholders of their route values, in route order, which the page replaces + // one at a time. The remove template keeps its named mediaKind and mediaItemId route placeholders instead, so those two values do not + // depend on the segment order. The detail pages of the media items expect the Id of their media library in the libraryId query + // parameter, which the page appends to the link from the favorite item. + ThemePageDto pageModel = new() + { + PageKey = VIEW_PAGE_KEY, + Title = title, + Description = string.Empty, + PageData = new Dictionary + { + ["getFavoritesUrl"] = _urlService.GetAbsoluteUrl(WebRoutes.Favorites.GET_FAVORITES) ?? string.Empty, + ["getFavoriteStatusUrl"] = _urlService.GetAbsoluteUrl(WebRoutes.Favorites.GET_FAVORITE_STATUS) ?? string.Empty, + ["addFavoriteUrl"] = _urlService.GetAbsoluteUrl(WebRoutes.Favorites.ADD_FAVORITE) ?? string.Empty, + ["removeFavoriteUrl"] = _urlService.GetAbsoluteUrl(WebRoutes.Favorites.REMOVE_FAVORITE) ?? string.Empty, + ["artistUrl"] = _urlService.GetAbsoluteUrl(WebRoutes.Music.ARTIST, new { artistId = default(Guid) }) ?? string.Empty, + ["albumUrl"] = _urlService.GetAbsoluteUrl(WebRoutes.Music.ALBUM, new { artistId = default(Guid), albumId = default(Guid) }) ?? string.Empty, + ["trackUrl"] = _urlService.GetAbsoluteUrl(WebRoutes.Music.TRACK, new { artistId = default(Guid), albumId = default(Guid), trackId = default(Guid) }) ?? string.Empty, + ["bookUrl"] = _urlService.GetAbsoluteUrl(WebRoutes.Books.EDIT_BOOK, new { bookId = default(Guid) }) ?? string.Empty, + ["antiforgeryToken"] = antiforgeryTokens.RequestToken, + ["strings"] = ThemePageDataFactory.CreateLocalizedStrings(_localizer) + } + }; + + Result sectionResult = await _themePageRenderer.RenderAsync(pageModel, requestedThemeId: null, cancellationToken).ConfigureAwait(false); + if (sectionResult.IsFailure) + return View("/Core/Views/Favorites/Index.cshtml", viewData: new Dictionary { ["Title"] = title }); + + return View("/Core/Views/Shared/_ThemedView.cshtml", new ThemeViewDto(sectionResult.Value.Content, sectionResult.Value.Script), new Dictionary { ["Title"] = title }); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Favorites/Index/FavoritesIndexViewEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Favorites/Index/FavoritesIndexViewEndpointSummary.cs new file mode 100644 index 00000000..171ea8d7 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Favorites/Index/FavoritesIndexViewEndpointSummary.cs @@ -0,0 +1,24 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Favorites.Index; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class FavoritesIndexViewEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public FavoritesIndexViewEndpointSummary() + { + Summary = "Renders the favorites page."; + Description = "Renders the page that lists the favorites of the current user across media kinds and removes them."; + + Response(200, "The favorites page is rendered."); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Favorites/RemoveFavorite/RemoveFavoriteEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Favorites/RemoveFavorite/RemoveFavoriteEndpoint.cs new file mode 100644 index 00000000..3d6b6fc0 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Favorites/RemoveFavorite/RemoveFavoriteEndpoint.cs @@ -0,0 +1,71 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.Enums.Favorites; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Favorites.RemoveFavorite; + +/// +/// API endpoint for the /{culture}/favorites/{mediaKind}/{mediaItemId}/api-remove-favorite route. +/// +public class RemoveFavoriteEndpoint : BaseEndpoint +{ + // A value that is not a name of FavoriteMediaKind, so the API rejects a crafted route value with its own validation error. + private const string INVALID_MEDIA_KIND_PLACEHOLDER = "Invalid"; + + private readonly IApiHttpClient _apiHttpClient; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for interactions with the API. + public RemoveFavoriteEndpoint(IApiHttpClient apiHttpClient) + { + _apiHttpClient = apiHttpClient; + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.DELETE); + Routes(WebRoutes.Favorites.REMOVE_FAVORITE); + DontAutoTag(); + Options(options => options.WithTags("Favorites")); + EnableAntiforgery(); + } + + /// + /// Removes a media item from the favorites of the current user. + /// + /// The request object. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(FastEndpoints.EmptyRequest request, CancellationToken cancellationToken) + { + // The route values are normalized before they are substituted into the upstream URL, so that a crafted value can never escape its URL segment. + // The media kind must be the name of a FavoriteMediaKind member, which also rejects numeric strings and comma separated flag lists, and the Id must be a Guid. + string routeMediaKind = HttpContext.Request.RouteValues["mediaKind"]?.ToString() ?? string.Empty; + string mediaKind = INVALID_MEDIA_KIND_PLACEHOLDER; + foreach (string mediaKindName in Enum.GetNames()) + if (mediaKindName != nameof(FavoriteMediaKind.None) && string.Equals(mediaKindName, routeMediaKind, StringComparison.OrdinalIgnoreCase)) + mediaKind = mediaKindName; + string routeMediaItemId = HttpContext.Request.RouteValues["mediaItemId"]?.ToString() ?? string.Empty; + string mediaItemId = Guid.TryParse(routeMediaItemId, out Guid parsedMediaItemId) ? parsedMediaItemId.ToString() : Guid.Empty.ToString(); + await _apiHttpClient.DeleteAsync( + ApiRoutes.Favorites.REMOVE_FAVORITE + .Replace("{mediaKind}", mediaKind) + .Replace("{mediaItemId}", mediaItemId), + cancellationToken).ConfigureAwait(false); + return JsonSuccess(); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Favorites/RemoveFavorite/RemoveFavoriteEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Favorites/RemoveFavorite/RemoveFavoriteEndpointSummary.cs new file mode 100644 index 00000000..c176a59b --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Favorites/RemoveFavorite/RemoveFavoriteEndpointSummary.cs @@ -0,0 +1,30 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.DTO.Common; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Favorites.RemoveFavorite; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class RemoveFavoriteEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public RemoveFavoriteEndpointSummary() + { + Summary = "Removes a media item from the favorites of the current user."; + Description = "Proxies the request that removes a favorite to the API server. The media item itself is not deleted. The favorite belongs to the current user, so this route cannot remove another user's favorite. Removing is idempotent: a media item that is not a favorite of the current user already has the desired state, so the request succeeds."; + + Params["mediaKind"] = "The kind of the favorited media item: MusicArtist, MusicAlbum, MusicTrack or Book."; + Params["mediaItemId"] = "The Id of the favorited media item."; + + Response(200, "The media item was removed from the favorites, or the item was already not a favorite.", + example: new SuccessResponse(true) + ); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/EditMusicAlbum/EditMusicAlbumViewEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/EditMusicAlbum/EditMusicAlbumViewEndpoint.cs index 0a491be2..d07f4259 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/EditMusicAlbum/EditMusicAlbumViewEndpoint.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/EditMusicAlbum/EditMusicAlbumViewEndpoint.cs @@ -14,6 +14,7 @@ using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Localization; using System; using System.Collections.Generic; +using System.Linq; using System.Text.Json; using System.Text.Json.Serialization; using System.Threading; @@ -88,6 +89,13 @@ public class EditMusicAlbumViewEndpoint : BaseEndpoint(ApiRoutes.Music.GET_ALBUM.Replace("{libraryId}", request.LibraryId.ToString()).Replace("{artistId}", request.ArtistId).Replace("{albumId}", request.AlbumId), cancellationToken).ConfigureAwait(false); string title = album.Metadata?.Title ?? string.Empty; + // The play album trigger presents the album, so it carries the same cover this page displays: the stored cover, or the first stored artwork when the album has no cover. + string albumCoverPath = album.CoverPath ?? string.Empty; + if (string.IsNullOrWhiteSpace(albumCoverPath)) + albumCoverPath = (album.Artwork ?? []).FirstOrDefault(artwork => !string.IsNullOrWhiteSpace(artwork.Path))?.Path ?? string.Empty; + // A release the API already reported as empty has nothing to play, so the themed play trigger starts disabled. The + // release list the page loads later only refines this state, and a failed request never changes it. + bool albumHasTracks = (album.Tracks?.Count ?? 0) > 0; // The themed view is a regular page that submits its own requests, so a fresh anti-forgery token must be issued for it. AntiforgeryTokenSet antiforgeryTokens = _antiforgery.GetAndStoreTokens(HttpContext); @@ -109,6 +117,9 @@ public class EditMusicAlbumViewEndpoint : BaseEndpointCancellation token that can be used to stop the execution. public override async Task ExecuteAsync(GetArtistAlbumsLiteRequest request, CancellationToken cancellationToken) { - PaginatedMusicAlbumLiteDto response = await _apiHttpClient.GetAsync(BuildItemsEndpoint(request), cancellationToken).ConfigureAwait(false); + PaginatedDto response = await _apiHttpClient.GetAsync>(BuildItemsEndpoint(request), cancellationToken).ConfigureAwait(false); return JsonSuccess(response); } diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/EditMusicArtist/EditMusicArtistViewEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/EditMusicArtist/EditMusicArtistViewEndpoint.cs index c025b99d..43af7563 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/EditMusicArtist/EditMusicArtistViewEndpoint.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/EditMusicArtist/EditMusicArtistViewEndpoint.cs @@ -87,6 +87,9 @@ public class EditMusicArtistViewEndpoint : BaseEndpoint(ApiRoutes.Music.GET_ARTIST.Replace("{libraryId}", request.LibraryId.ToString()).Replace("{artistId}", request.ArtistId), cancellationToken).ConfigureAwait(false); string title = artist.Metadata?.Name ?? string.Empty; + // An artist the API already reported without releases has nothing to play, so the themed play trigger starts disabled. + // The release list the page loads later only refines this state, and a failed request never changes it. + bool artistHasReleases = (artist.Albums?.Count ?? 0) > 0; // The themed view is a regular page that submits its own requests, so a fresh anti-forgery token must be issued for it. AntiforgeryTokenSet antiforgeryTokens = _antiforgery.GetAndStoreTokens(HttpContext); @@ -108,6 +111,9 @@ public class EditMusicArtistViewEndpoint : BaseEndpointCancellation token that can be used to stop the execution. public override async Task ExecuteAsync(GetMusicArtistsLiteRequest request, CancellationToken cancellationToken) { - PaginatedMusicArtistLiteDto response = await _apiHttpClient.GetAsync(BuildItemsEndpoint(request), cancellationToken).ConfigureAwait(false); + PaginatedDto response = await _apiHttpClient.GetAsync>(BuildItemsEndpoint(request), cancellationToken).ConfigureAwait(false); return JsonSuccess(response); } diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/EditMusicTrack/EditMusicTrackViewEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/EditMusicTrack/EditMusicTrackViewEndpoint.cs index 6695f583..319790ec 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/EditMusicTrack/EditMusicTrackViewEndpoint.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/EditMusicTrack/EditMusicTrackViewEndpoint.cs @@ -14,6 +14,7 @@ using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Localization; using System; using System.Collections.Generic; +using System.Linq; using System.Text.Json; using System.Text.Json.Serialization; using System.Threading; @@ -95,6 +96,12 @@ public class EditMusicTrackViewEndpoint : BaseEndpoint( ApiRoutes.Music.GET_ALBUM.Replace("{libraryId}", request.LibraryId.ToString()).Replace("{artistId}", normalizedArtistId).Replace("{albumId}", normalizedAlbumId), cancellationToken).ConfigureAwait(false); + // The track page and its play trigger show the same cover the album page shows: the stored cover, or the first stored + // artwork when the album has no cover. It is resolved once and used for both the themed page data and the fallback view. + string albumCoverPath = album.CoverPath ?? string.Empty; + if (string.IsNullOrWhiteSpace(albumCoverPath)) + albumCoverPath = (album.Artwork ?? []).FirstOrDefault(artwork => !string.IsNullOrWhiteSpace(artwork.Path))?.Path ?? string.Empty; + string albumTitle = album.Metadata?.Title ?? string.Empty; // The themed view is a regular page that submits its own requests, so a fresh anti-forgery token must be issued for it. AntiforgeryTokenSet antiforgeryTokens = _antiforgery.GetAndStoreTokens(HttpContext); @@ -114,7 +121,10 @@ public class EditMusicTrackViewEndpoint : BaseEndpoint viewData = new() { ["Title"] = title, - ["AlbumCoverPath"] = album.CoverPath ?? string.Empty + ["ArtistId"] = normalizedArtistId, + ["AlbumCoverPath"] = albumCoverPath, + ["AlbumTitle"] = albumTitle }; return View("/Core/Views/Library/AudioLibrary/MusicLibrary/Tracks/Item.cshtml", track, viewData); } diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetAlbumTracks/GetAlbumTracksEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetAlbumTracks/GetAlbumTracksEndpoint.cs index 8cdc19b4..1fede253 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetAlbumTracks/GetAlbumTracksEndpoint.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetAlbumTracks/GetAlbumTracksEndpoint.cs @@ -2,6 +2,7 @@ using FastEndpoints; using Lumina.Presentation.Web.Common.Api; using Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary; +using Lumina.Presentation.Web.Common.DTO.Common; using Lumina.Presentation.Web.Common.Requests.Library.AudioLibrary.MusicLibrary.Tracks; using Lumina.Presentation.Web.Common.Routes; using Lumina.Presentation.Web.Core.Endpoints.Common; @@ -50,7 +51,7 @@ public class GetAlbumTracksEndpoint : BaseEndpointCancellation token that can be used to stop the execution. public override async Task ExecuteAsync(GetAlbumTracksLiteRequest request, CancellationToken cancellationToken) { - PaginatedMusicTrackLiteDto response = await _apiHttpClient.GetAsync(BuildItemsEndpoint(request), cancellationToken).ConfigureAwait(false); + PaginatedDto response = await _apiHttpClient.GetAsync>(BuildItemsEndpoint(request), cancellationToken).ConfigureAwait(false); return JsonSuccess(response); } diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetPlaybackManifest/GetPlaybackManifestEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetPlaybackManifest/GetPlaybackManifestEndpoint.cs new file mode 100644 index 00000000..793a1a81 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetPlaybackManifest/GetPlaybackManifestEndpoint.cs @@ -0,0 +1,188 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary; +using Lumina.Presentation.Web.Common.DTO.Common; +using Lumina.Presentation.Web.Common.Exceptions; +using Lumina.Presentation.Web.Common.Playback; +using Lumina.Presentation.Web.Common.Requests.Library.AudioLibrary.MusicLibrary.Tracks; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Microsoft.AspNetCore.Http; +using System; +using System.Net; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.GetPlaybackManifest; + +/// +/// API endpoint for the /{culture}/library/audio-library/music-library/artists/{artistId}/albums/{albumId}/tracks/{trackId}/api-get-playback-manifest route. +/// +public class GetPlaybackManifestEndpoint : BaseEndpoint +{ + private readonly IApiHttpClient _apiHttpClient; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for interactions with the API. + public GetPlaybackManifestEndpoint(IApiHttpClient apiHttpClient) + { + _apiHttpClient = apiHttpClient; + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.GET); + Routes(WebRoutes.Music.GET_PLAYBACK_MANIFEST); + DontAutoTag(); + Options(options => options.WithTags("Music")); + } + + /// + /// Retrieves the playback manifest of the track identified by , with the stream path of this application. + /// + /// The request containing the Ids of the artist, album, track and media library to get the manifest of, and the capabilities of the player. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(GetPlaybackManifestRequest request, CancellationToken cancellationToken) + { + // The route values are normalized to Guids before they are substituted into the upstream URL, so that a crafted route value can never + // escape its URL segment, and an unparseable id is reported by the API as a missing id. + string normalizedArtistId = Guid.TryParse(request.ArtistId, out Guid parsedArtistId) ? parsedArtistId.ToString() : Guid.Empty.ToString(); + string normalizedAlbumId = Guid.TryParse(request.AlbumId, out Guid parsedAlbumId) ? parsedAlbumId.ToString() : Guid.Empty.ToString(); + string normalizedTrackId = Guid.TryParse(request.TrackId, out Guid parsedTrackId) ? parsedTrackId.ToString() : Guid.Empty.ToString(); + string endpoint = ApiRoutes.Music.GET_PLAYBACK_MANIFEST + .Replace("{libraryId}", request.LibraryId.ToString()) + .Replace("{artistId}", normalizedArtistId) + .Replace("{albumId}", normalizedAlbumId) + .Replace("{trackId}", normalizedTrackId); + // The capabilities the player advertises are optional and are forwarded only when the player sent them. + if (!string.IsNullOrWhiteSpace(request.Capabilities)) + endpoint = $"{endpoint}?capabilities={Uri.EscapeDataString(request.Capabilities)}"; + + PlaybackManifestDto? manifest = await _apiHttpClient.GetAsync(endpoint, cancellationToken).ConfigureAwait(false) ?? throw new ApiException(new ProblemDetailsDto + { + Title = "General.Failure", + Detail = "InternalServerError", + Status = StatusCodes.Status502BadGateway + }, HttpStatusCode.BadGateway, endpoint); + // The API only knows the relative paths of its own stream and segment endpoints, and the browser only reaches this application, so + // they are replaced with the paths of the streaming proxies of this application, which are the URLs the player actually consumes. + manifest.StreamPath = BuildBrowserStreamPath(request.LibraryId, normalizedArtistId, normalizedAlbumId, normalizedTrackId); + if (string.IsNullOrEmpty(manifest.SegmentStreamPathTemplate)) + { + manifest.DeliveryId = null; + manifest.SegmentStreamPathTemplate = null; + } + else + { + // The API decides how its delivery is addressed: the web app only rewrites the path it reported, and only requires the opaque + // handle the path needs. It never infers the addressing from the direct play flag. + if (!PlaybackDeliveryId.IsValid(manifest.DeliveryId)) + throw new ApiException(new ProblemDetailsDto + { + Title = "General.Failure", + Detail = "InternalServerError", + Status = StatusCodes.Status502BadGateway + }, HttpStatusCode.BadGateway, endpoint); + manifest.SegmentStreamPathTemplate = BuildBrowserSegmentStreamPath(request.LibraryId, normalizedArtistId, normalizedAlbumId, normalizedTrackId); + } + // The manifest is specific to the authenticated user and carries a stateful delivery handle, so the browser hop never stores it publicly and + // it varies by the cookie that authenticates this hop. + HttpContext.Response.Headers["Cache-Control"] = "private, no-store"; + HttpContext.Response.Headers["Vary"] = "Cookie"; + return JsonSuccess(manifest); + } + + /// + /// Builds the browser facing relative path of the streaming proxy of this application for the track identified by the given Ids. + /// + /// + /// The path is built from the route template of this application, and never from the host, the scheme, or the port of the incoming request. + /// The path base is derived from a forwarded header that a caller can spoof, so it is only used when it is a plain absolute path, and the + /// culture is confined to a single path segment, so that no part of the result can introduce an authority, which would make the browser + /// resolve the stream from another origin. + /// + /// The Id of the media library the track belongs to. + /// The normalized Id of the artist the album belongs to. + /// The normalized Id of the album the track belongs to. + /// The normalized Id of the track. + /// The root relative path the browser fetches the stream from, on its own origin. + private string BuildBrowserStreamPath(Guid libraryId, string artistId, string albumId, string trackId) + { + string culture = IsSafePathSegment(Culture) ? Culture : "en-US"; + string pathBase = IsSafePathBase(HttpContext.Request.PathBase.ToString()) ? HttpContext.Request.PathBase.ToString().TrimEnd('/') : string.Empty; + string streamPath = WebRoutes.Music.STREAM_TRACK + .Replace("{culture}", culture, StringComparison.OrdinalIgnoreCase) + .Replace("{artistId}", artistId, StringComparison.Ordinal) + .Replace("{albumId}", albumId, StringComparison.Ordinal) + .Replace("{trackId}", trackId, StringComparison.Ordinal); + return $"{pathBase}/{streamPath}?libraryId={libraryId}"; + } + + /// + /// Builds the browser facing relative path template of the segment streaming proxy of this application for the track identified by the given Ids. + /// + /// + /// The placeholders of the route template are replaced with the Ids the manifest was requested for, and the delivery handle and segment index + /// placeholders are kept for the player to expand. The player substitutes the handle the manifest reported, so the segment request addresses + /// exactly the delivery that manifest declared, and the path is built exactly like the track stream path, so it can only ever point at this origin. + /// + /// The Id of the media library the track belongs to. + /// The normalized Id of the artist the album belongs to. + /// The normalized Id of the album the track belongs to. + /// The normalized Id of the track. + /// The root relative path template the browser fetches a segment from, on its own origin. + private string BuildBrowserSegmentStreamPath(Guid libraryId, string artistId, string albumId, string trackId) + { + string culture = IsSafePathSegment(Culture) ? Culture : "en-US"; + string pathBase = IsSafePathBase(HttpContext.Request.PathBase.ToString()) ? HttpContext.Request.PathBase.ToString().TrimEnd('/') : string.Empty; + string segmentPath = WebRoutes.Music.STREAM_TRACK_SEGMENT + .Replace("{culture}", culture, StringComparison.OrdinalIgnoreCase) + .Replace("{artistId}", artistId, StringComparison.Ordinal) + .Replace("{albumId}", albumId, StringComparison.Ordinal) + .Replace("{trackId}", trackId, StringComparison.Ordinal); + return $"{pathBase}/{segmentPath}?libraryId={libraryId}"; + } + + /// + /// Checks whether a value can be used safely as a single segment of a path the browser resolves against its own origin. + /// + /// The value to check. + /// when the value cannot introduce a path separator, a query, a fragment, or a control character, otherwise. + private static bool IsSafePathSegment(string? value) + { + if (string.IsNullOrEmpty(value)) + return false; + foreach (char character in value) + if (character == '/' || character == '\\' || character == '?' || character == '#' || character == '%' || char.IsControl(character)) + return false; + return true; + } + + /// + /// Checks whether a value can be used safely as the path base of a path the browser resolves against its own origin. + /// + /// The path base to check. + /// when the value is a plain absolute path, otherwise. + private static bool IsSafePathBase(string pathBase) + { + if (string.IsNullOrEmpty(pathBase)) + return true; + // A path base that does not start with a single slash, or that contains a backslash or a control character, can be normalized by a + // browser into a protocol relative or absolute reference, which would point the stream fetch at another origin. A query or a fragment + // (or an escape that decodes into one) would truncate the built path instead. + if (!pathBase.StartsWith('/') || pathBase.StartsWith("//", StringComparison.Ordinal)) + return false; + foreach (char character in pathBase) + if (character == '\\' || character == '?' || character == '#' || character == '%' || char.IsControl(character)) + return false; + return !pathBase.Contains("//", StringComparison.Ordinal); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetPlaybackManifest/GetPlaybackManifestEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetPlaybackManifest/GetPlaybackManifestEndpointSummary.cs new file mode 100644 index 00000000..7cc4d6bf --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetPlaybackManifest/GetPlaybackManifestEndpointSummary.cs @@ -0,0 +1,31 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Requests.Library.AudioLibrary.MusicLibrary.Tracks; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.GetPlaybackManifest; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class GetPlaybackManifestEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public GetPlaybackManifestEndpointSummary() + { + Summary = "Retrieves the playback manifest of a music track."; + Description = "Retrieves the playback manifest of the music track identified by the route, with the stream path and the segment path template replaced by the URLs of the streaming proxies of this application. A normalized delivery also carries the opaque delivery handle the segment proxy forwards, so the segments are addressed by the delivery the manifest declared."; + + RequestParam(r => r.ArtistId, "The unique identifier of the artist the album belongs to. Required."); + RequestParam(r => r.AlbumId, "The unique identifier of the album the track belongs to. Required."); + RequestParam(r => r.TrackId, "The unique identifier of the track whose manifest is requested. Required."); + RequestParam(r => r.LibraryId, "The unique identifier of the media library the track belongs to. Required."); + RequestParam(r => r.Capabilities, "The comma separated list of the container and codec pairs the player advertises it can play directly. Optional."); + + Response(200, "The playback manifest of the track is retrieved."); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/ShuffleTracks/ShuffleTracksEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/ShuffleTracks/ShuffleTracksEndpoint.cs new file mode 100644 index 00000000..82301af5 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/ShuffleTracks/ShuffleTracksEndpoint.cs @@ -0,0 +1,67 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary; +using Lumina.Presentation.Web.Common.Requests.Library.AudioLibrary.MusicLibrary.Tracks; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Microsoft.AspNetCore.Http; +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.ShuffleTracks; + +/// +/// API endpoint for the /{culture}/library/audio-library/music-library/tracks/api-shuffle-tracks route. +/// +public class ShuffleTracksEndpoint : BaseEndpoint +{ + private readonly IApiHttpClient _apiHttpClient; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for interactions with the API. + public ShuffleTracksEndpoint(IApiHttpClient apiHttpClient) + { + _apiHttpClient = apiHttpClient; + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.POST); + Routes(WebRoutes.Music.SHUFFLE_TRACKS); + DontAutoTag(); + Options(options => options.WithTags("Music")); + } + + /// + /// Retrieves a random selection of tracks of the library identified in the request. + /// + /// The request containing the selection size, the optional scope and the tracks to exclude. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(ShuffleTracksRequest request, CancellationToken cancellationToken) + { + List response = await _apiHttpClient.PostAsync, ShuffleTracksRequest>( + BuildEndpoint(request.LibraryId), request, cancellationToken).ConfigureAwait(false); + return JsonSuccess(response); + } + + /// + /// Builds the API endpoint used to retrieve a random selection of tracks. + /// + /// The Id of the media library the tracks are sampled from. + /// The API endpoint to which the retrieval request is sent. + private static string BuildEndpoint(Guid libraryId) + { + // The strongly typed Id is formatted as a Guid, so the substituted route value can never escape its URL segment. + return ApiRoutes.Music.SHUFFLE_TRACKS.Replace("{libraryId}", libraryId.ToString()); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/ShuffleTracks/ShuffleTracksEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/ShuffleTracks/ShuffleTracksEndpointSummary.cs new file mode 100644 index 00000000..8887c215 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/ShuffleTracks/ShuffleTracksEndpointSummary.cs @@ -0,0 +1,36 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary; +using Lumina.Presentation.Web.Common.Requests.Library.AudioLibrary.MusicLibrary.Tracks; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.ShuffleTracks; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class ShuffleTracksEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public ShuffleTracksEndpointSummary() + { + Summary = "Draws a random selection of tracks from a media library, an artist or an album."; + Description = "Returns uniformly random tracks from the whole library, one artist, or one album, excluding the tracks the caller already queued. The tracks are selected by the API database, so a large library does not have to be enumerated by the browser."; + + Response(200, "The random selection of tracks is returned.", example: new[] { new MusicShuffleTrackDto + { + TrackId = Guid.NewGuid(), + Title = "Bohemian Rhapsody", + DurationInSeconds = 354, + AlbumId = Guid.NewGuid(), + AlbumTitle = "A Night at the Opera", + ArtistId = Guid.NewGuid(), + CoverPath = "/music/queen/a-night-at-the-opera/cover.jpg" + }}); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/StreamMusicTrack/StreamMusicTrackEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/StreamMusicTrack/StreamMusicTrackEndpoint.cs new file mode 100644 index 00000000..1848ec1a --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/StreamMusicTrack/StreamMusicTrackEndpoint.cs @@ -0,0 +1,109 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DependencyInjection; +using Lumina.Presentation.Web.Common.Exceptions; +using Lumina.Presentation.Web.Common.Http; +using Lumina.Presentation.Web.Common.Requests.Library.AudioLibrary.MusicLibrary.Tracks; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.Primitives; +using System; +using System.Collections.Generic; +using System.Net; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.StreamMusicTrack; + +/// +/// API endpoint for the /{culture}/library/audio-library/music-library/artists/{artistId}/albums/{albumId}/tracks/{trackId}/api-stream-track route. +/// +public class StreamMusicTrackEndpoint : BaseEndpoint +{ + private readonly IStreamingApiHttpClient _streamingApiHttpClient; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for streaming interactions with the API. + public StreamMusicTrackEndpoint(IStreamingApiHttpClient streamingApiHttpClient) + { + _streamingApiHttpClient = streamingApiHttpClient; + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.GET); + Routes(WebRoutes.Music.STREAM_TRACK); + DontAutoTag(); + // The stream is bounded per user with a concurrency limit, exactly like the stream route of the API server, so that a single user can + // never hold an unbounded number of long lived streams open at once and exhaust the connections towards the API. + Options(options => options + .WithTags("Music") + .RequireRateLimiting(PresentationWebLayerServices.TRACK_STREAM_RATE_LIMIT_POLICY)); + } + + /// + /// Streams the audio file of the track identified by through the API, without buffering it. + /// + /// The request containing the Ids of the artist, album, track and media library to stream. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(StreamMusicTrackRequest request, CancellationToken cancellationToken) + { + // The route values are normalized to Guids before they are substituted into the upstream URL, so that a crafted route value can never + // escape its URL segment, and an unparseable id is reported by the API as a missing id. + string normalizedArtistId = Guid.TryParse(request.ArtistId, out Guid parsedArtistId) ? parsedArtistId.ToString() : Guid.Empty.ToString(); + string normalizedAlbumId = Guid.TryParse(request.AlbumId, out Guid parsedAlbumId) ? parsedAlbumId.ToString() : Guid.Empty.ToString(); + string normalizedTrackId = Guid.TryParse(request.TrackId, out Guid parsedTrackId) ? parsedTrackId.ToString() : Guid.Empty.ToString(); + string endpoint = ApiRoutes.Music.STREAM_TRACK + .Replace("{libraryId}", request.LibraryId.ToString()) + .Replace("{artistId}", normalizedArtistId) + .Replace("{albumId}", normalizedAlbumId) + .Replace("{trackId}", normalizedTrackId); + // The range and the conditional headers that revalidate it are forwarded as they are, so that the API, which is the only party that + // knows the entity tag and the modification time of the file, answers a partial, a resumed, or an unchanged request by itself. + Dictionary forwardHeaders = []; + AddHeader(forwardHeaders, "Range", HttpContext.Request.Headers.Range); + AddHeader(forwardHeaders, "If-Range", HttpContext.Request.Headers.IfRange); + AddHeader(forwardHeaders, "If-None-Match", HttpContext.Request.Headers.IfNoneMatch); + AddHeader(forwardHeaders, "If-Modified-Since", HttpContext.Request.Headers.IfModifiedSince); + + // The API response is disposed once the copy ends, so that the underlying connection is released as soon as the client stops reading. + ApiStreamResult streamResult; + try + { + streamResult = await _streamingApiHttpClient.GetStreamAsync(endpoint, forwardHeaders, cancellationToken).ConfigureAwait(false); + } + catch (ApiException apiException) when (apiException.HttpStatusCode is HttpStatusCode.ServiceUnavailable or HttpStatusCode.TooManyRequests) + { + // A busy normalization pipeline or the stream concurrency limit is an expected, transient condition that the player retries. It is + // answered with a bare status instead of being logged as an unexpected API failure with a stack trace. + HttpContext.Response.StatusCode = (int)apiException.HttpStatusCode; + HttpContext.Response.ContentLength = 0; + return Results.Empty; + } + await using (streamResult) // The proxy owns the status, header, caching and body rules shared with the normalized segment proxy. + await ApiStreamProxy.WriteAsync(HttpContext.Response, streamResult, cancellationToken).ConfigureAwait(false); + return Results.Empty; + } + + /// + /// Adds a request header to the set of headers forwarded to the API, unless the incoming request did not carry it. + /// + /// The set of headers forwarded to the API. + /// The name of the header. + /// The value of the header in the incoming request, which is empty when the header was not sent. + private static void AddHeader(Dictionary headers, string name, StringValues value) + { + if (value.Count > 0 && !string.IsNullOrWhiteSpace(value.ToString())) + headers[name] = value.ToString(); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/StreamMusicTrack/StreamMusicTrackEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/StreamMusicTrack/StreamMusicTrackEndpointSummary.cs new file mode 100644 index 00000000..bcbcef3f --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/StreamMusicTrack/StreamMusicTrackEndpointSummary.cs @@ -0,0 +1,38 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Requests.Library.AudioLibrary.MusicLibrary.Tracks; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.StreamMusicTrack; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class StreamMusicTrackEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public StreamMusicTrackEndpointSummary() + { + Summary = "Streams the audio file of a music track."; + Description = "Streams the audio file of the music track identified by the route, forwarding the range and the conditional headers the browser sends, so that the player can start playback before the whole file is downloaded, resume a partial download, and revalidate a cached copy."; + + RequestParam(r => r.ArtistId, "The unique identifier of the artist the album belongs to. Required."); + RequestParam(r => r.AlbumId, "The unique identifier of the album the track belongs to. Required."); + RequestParam(r => r.TrackId, "The unique identifier of the track to stream. Required."); + RequestParam(r => r.LibraryId, "The unique identifier of the media library the track belongs to. Required."); + + Response(200, "The whole audio file of the track is streamed."); + Response(206, "The requested range of the audio file of the track is streamed, with its content range."); + Response(304, "The audio file of the track did not change since the copy the browser already holds, and its validators are returned."); + Response(416, "The requested range cannot be satisfied, and the total length of the audio file is returned in the content range."); + Response(401, "The user is not authenticated."); + Response(403, "The user is not allowed to stream the track of the media library."); + Response(404, "The track, the album, the artist, or the media library was not found, or is out of the scope of the route."); + Response(429, "The user is already holding the maximum number of concurrent track streams."); + Response(502, "The remote API did not return the audio file of the track."); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/StreamMusicTrackSegment/StreamMusicTrackSegmentEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/StreamMusicTrackSegment/StreamMusicTrackSegmentEndpoint.cs new file mode 100644 index 00000000..51b377ab --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/StreamMusicTrackSegment/StreamMusicTrackSegmentEndpoint.cs @@ -0,0 +1,99 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DependencyInjection; +using Lumina.Presentation.Web.Common.Exceptions; +using Lumina.Presentation.Web.Common.Http; +using Lumina.Presentation.Web.Common.Playback; +using Lumina.Presentation.Web.Common.Requests.Library.AudioLibrary.MusicLibrary.Tracks; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System; +using System.Collections.Generic; +using System.Net; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.StreamMusicTrackSegment; + +/// +/// API endpoint for the /{culture}/library/audio-library/music-library/artists/{artistId}/albums/{albumId}/tracks/{trackId}/api-stream-track-segment/{deliveryId}/{segmentIndex} route. +/// +public class StreamMusicTrackSegmentEndpoint : BaseEndpoint +{ + private readonly IStreamingApiHttpClient _streamingApiHttpClient; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for streaming interactions with the API. + public StreamMusicTrackSegmentEndpoint(IStreamingApiHttpClient streamingApiHttpClient) + { + _streamingApiHttpClient = streamingApiHttpClient; + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.GET); + Routes(WebRoutes.Music.STREAM_TRACK_SEGMENT); + DontAutoTag(); + // The segment stream is bounded per user with the same concurrency limit as the track stream, so a single user can never hold an + // unbounded number of long lived responses open at once and exhaust the connections towards the API. + Options(options => options + .WithTags("Music") + .RequireRateLimiting(PresentationWebLayerServices.TRACK_STREAM_RATE_LIMIT_POLICY)); + } + + /// + /// Streams one segment of the normalized audio of the track identified by through the API, without buffering it. + /// + /// The request containing the Ids of the artist, album, track and media library, the delivery handle, and the segment index. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(StreamMusicTrackSegmentRequest request, CancellationToken cancellationToken) + { + // The route values are normalized to Guids before they are substituted into the upstream URL, so that a crafted route value can never + // escape its URL segment, and an unparseable id is reported by the API as a missing id. + string normalizedArtistId = Guid.TryParse(request.ArtistId, out Guid parsedArtistId) ? parsedArtistId.ToString() : Guid.Empty.ToString(); + string normalizedAlbumId = Guid.TryParse(request.AlbumId, out Guid parsedAlbumId) ? parsedAlbumId.ToString() : Guid.Empty.ToString(); + string normalizedTrackId = Guid.TryParse(request.TrackId, out Guid parsedTrackId) ? parsedTrackId.ToString() : Guid.Empty.ToString(); + // The handle has exactly one accepted format, so it is never normalized into another value that would silently address a different delivery. + if (!PlaybackDeliveryId.IsValid(request.DeliveryId)) + { + HttpContext.Response.StatusCode = (int)HttpStatusCode.NotFound; + HttpContext.Response.ContentLength = 0; + return Results.Empty; + } + string endpoint = ApiRoutes.Music.STREAM_TRACK_SEGMENT + .Replace("{libraryId}", request.LibraryId.ToString()) + .Replace("{artistId}", normalizedArtistId) + .Replace("{albumId}", normalizedAlbumId) + .Replace("{trackId}", normalizedTrackId) + .Replace("{deliveryId}", request.DeliveryId) + .Replace("{segmentIndex}", request.SegmentIndex.ToString()); + + // The API response is disposed once the copy ends, so that the underlying connection is released as soon as the client stops reading. + ApiStreamResult streamResult; + try + { + streamResult = await _streamingApiHttpClient.GetStreamAsync(endpoint, new Dictionary(), cancellationToken).ConfigureAwait(false); + } + catch (ApiException apiException) when (apiException.HttpStatusCode is HttpStatusCode.ServiceUnavailable or HttpStatusCode.TooManyRequests) + { + // A busy normalization pipeline or the stream concurrency limit is an expected, transient condition that the player retries. It is + // answered with a bare status instead of being logged as an unexpected API failure with a stack trace. + HttpContext.Response.StatusCode = (int)apiException.HttpStatusCode; + HttpContext.Response.ContentLength = 0; + return Results.Empty; + } + await using (streamResult) // The proxy owns the status, header, caching and body rules shared with the direct track stream proxy. + await ApiStreamProxy.WriteAsync(HttpContext.Response, streamResult, cancellationToken).ConfigureAwait(false); + return Results.Empty; + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/StreamMusicTrackSegment/StreamMusicTrackSegmentEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/StreamMusicTrackSegment/StreamMusicTrackSegmentEndpointSummary.cs new file mode 100644 index 00000000..eb9bc92c --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/StreamMusicTrackSegment/StreamMusicTrackSegmentEndpointSummary.cs @@ -0,0 +1,39 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Requests.Library.AudioLibrary.MusicLibrary.Tracks; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.StreamMusicTrackSegment; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class StreamMusicTrackSegmentEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public StreamMusicTrackSegmentEndpointSummary() + { + Summary = "Streams one segment of the normalized audio of a music track."; + Description = "Streams one fixed duration segment of the normalized audio of the music track identified by the route, through the API. A track the player cannot play directly is delivered as time addressed segments, so the player seeks by segment index instead of by byte range. The delivery handle is the opaque value the playback manifest reported, and it binds the segment to exactly the delivery that manifest declared."; + + RequestParam(r => r.ArtistId, "The unique identifier of the artist the album belongs to. Required."); + RequestParam(r => r.AlbumId, "The unique identifier of the album the track belongs to. Required."); + RequestParam(r => r.TrackId, "The unique identifier of the track to stream. Required."); + RequestParam(r => r.DeliveryId, "The opaque handle of the normalized delivery, reported by the playback manifest. Required."); + RequestParam(r => r.SegmentIndex, "The zero based index of the segment of the normalized audio. Required."); + RequestParam(r => r.LibraryId, "The unique identifier of the media library the track belongs to. Required."); + + Response(200, "The requested segment of the normalized audio of the track is streamed."); + Response(401, "The user is not authenticated."); + Response(403, "The user is not allowed to stream the track of the media library."); + Response(404, "The track, the album, the artist, the media library, the delivery handle, or the requested segment was not found, or is out of the scope of the route."); + Response(409, "The delivery handle no longer describes the delivery, or the source file changed. The player requests the manifest again."); + Response(429, "The user is already holding the maximum number of concurrent track streams."); + Response(502, "The remote API did not return the segment of the normalized audio of the track."); + Response(503, "The normalization pipeline is temporarily busy. The player retries the request."); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/ClearConsumptionHistory/ClearConsumptionHistoryEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/ClearConsumptionHistory/ClearConsumptionHistoryEndpoint.cs new file mode 100644 index 00000000..5470368c --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/ClearConsumptionHistory/ClearConsumptionHistoryEndpoint.cs @@ -0,0 +1,61 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.Requests.Library.Statistics; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Library.Statistics.ClearConsumptionHistory; + +/// +/// API endpoint for the /{culture}/library/statistics/api-clear-consumption-history route. +/// +public class ClearConsumptionHistoryEndpoint : BaseEndpoint +{ + private readonly IApiHttpClient _apiHttpClient; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for interactions with the API. + public ClearConsumptionHistoryEndpoint(IApiHttpClient apiHttpClient) + { + _apiHttpClient = apiHttpClient; + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.DELETE); + Routes(WebRoutes.LibraryStatistics.CLEAR_CONSUMPTION_HISTORY); + DontAutoTag(); + Options(options => options.WithTags("Statistics")); + EnableAntiforgery(); + } + + /// + /// Deletes every consumption record of the selected user. + /// + /// The request containing the selected user. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(ClearConsumptionHistoryRequest request, CancellationToken cancellationToken) + { + // The history belongs to the selected user, so no intermediary may store any response of this route, and the response varies by the sign in cookie. + HttpContext.Response.Headers["Cache-Control"] = "private, no-store"; + HttpContext.Response.Headers["Vary"] = "Cookie"; + string path = string.IsNullOrWhiteSpace(request.UserId) + ? ApiRoutes.LibraryStatistics.CLEAR_CONSUMPTION_HISTORY + : ApiRoutes.LibraryStatistics.CLEAR_USER_CONSUMPTION_HISTORY.Replace("{userId}", Uri.EscapeDataString(request.UserId), StringComparison.Ordinal); + await _apiHttpClient.DeleteAsync(path, cancellationToken).ConfigureAwait(false); + return JsonSuccess(); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/ClearConsumptionHistory/ClearConsumptionHistoryEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/ClearConsumptionHistory/ClearConsumptionHistoryEndpointSummary.cs new file mode 100644 index 00000000..06a48a23 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/ClearConsumptionHistory/ClearConsumptionHistoryEndpointSummary.cs @@ -0,0 +1,32 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.DTO.Common; +using Lumina.Presentation.Web.Common.Requests.Library.Statistics; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Library.Statistics.ClearConsumptionHistory; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class ClearConsumptionHistoryEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public ClearConsumptionHistoryEndpointSummary() + { + Summary = "Deletes every consumption record of the selected user."; + Description = "Proxies the request that deletes every recorded consumption session of the selected user to the API server. When userId is omitted, the history of the current user is deleted; an administrator can name another user. Clearing an already empty history succeeds without changing anything. The resume points are not deleted. A failure is returned as a JSON object with success set to false and a localized errorMessage."; + + RequestParam(request => request.UserId, "The Id of the user whose history is deleted. Optional; when omitted, the current user is used."); + + ResponseParam(response => response.IsSuccess, "Whether the operation succeeded."); + + Response(200, "The consumption history was cleared, or a JSON error with success set to false.", + example: new SuccessResponse(true) + ); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/ClearResumePoints/ClearResumePointsEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/ClearResumePoints/ClearResumePointsEndpoint.cs new file mode 100644 index 00000000..dc523a6a --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/ClearResumePoints/ClearResumePointsEndpoint.cs @@ -0,0 +1,63 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.Requests.Library.Statistics; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Library.Statistics.ClearResumePoints; + +/// +/// API endpoint for the /{culture}/library/statistics/api-clear-resume-points route. +/// +public class ClearResumePointsEndpoint : BaseEndpoint +{ + private readonly IApiHttpClient _apiHttpClient; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for interactions with the API. + public ClearResumePointsEndpoint(IApiHttpClient apiHttpClient) + { + _apiHttpClient = apiHttpClient; + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.DELETE); + Routes(WebRoutes.LibraryStatistics.CLEAR_RESUME_POINTS); + DontAutoTag(); + Options(options => options.WithTags("Statistics")); + EnableAntiforgery(); + } + + /// + /// Deletes the resume points of the selected user. + /// + /// The request containing the selected user and the optional library filter. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(ClearResumePointsRequest request, CancellationToken cancellationToken) + { + // The resume points belong to the selected user, so no intermediary may store any response of this route, and the response varies by the sign in cookie. + HttpContext.Response.Headers["Cache-Control"] = "private, no-store"; + HttpContext.Response.Headers["Vary"] = "Cookie"; + string path = string.IsNullOrWhiteSpace(request.UserId) + ? ApiRoutes.LibraryStatistics.CLEAR_RESUME_POINTS + : ApiRoutes.LibraryStatistics.CLEAR_USER_RESUME_POINTS.Replace("{userId}", Uri.EscapeDataString(request.UserId), StringComparison.Ordinal); + if (!string.IsNullOrWhiteSpace(request.LibraryId)) + path += $"?libraryId={Uri.EscapeDataString(request.LibraryId)}"; + await _apiHttpClient.DeleteAsync(path, cancellationToken).ConfigureAwait(false); + return JsonSuccess(); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/ClearResumePoints/ClearResumePointsEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/ClearResumePoints/ClearResumePointsEndpointSummary.cs new file mode 100644 index 00000000..f628f584 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/ClearResumePoints/ClearResumePointsEndpointSummary.cs @@ -0,0 +1,33 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.DTO.Common; +using Lumina.Presentation.Web.Common.Requests.Library.Statistics; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Library.Statistics.ClearResumePoints; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class ClearResumePointsEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public ClearResumePointsEndpointSummary() + { + Summary = "Deletes the resume points of the selected user."; + Description = "Proxies the request that deletes the resume points of the selected user, optionally limited to one library, to the API server. When userId is omitted, the resume points of the current user are deleted; an administrator can name another user. The consumption history is not deleted. A failure is returned as a JSON object with success set to false and a localized errorMessage."; + + RequestParam(request => request.UserId, "The Id of the user whose resume points are deleted. Optional; when omitted, the current user is used."); + RequestParam(request => request.LibraryId, "The Id of the media library to restrict the deletion to. Optional."); + + ResponseParam(response => response.IsSuccess, "Whether the operation succeeded."); + + Response(200, "The resume points were removed, or a JSON error with success set to false.", + example: new SuccessResponse(true) + ); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/DeleteConsumptionItemHistory/DeleteConsumptionItemHistoryEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/DeleteConsumptionItemHistory/DeleteConsumptionItemHistoryEndpoint.cs new file mode 100644 index 00000000..9c6833f2 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/DeleteConsumptionItemHistory/DeleteConsumptionItemHistoryEndpoint.cs @@ -0,0 +1,65 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.Requests.Library.Statistics; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Library.Statistics.DeleteConsumptionItemHistory; + +/// +/// API endpoint for the /{culture}/library/statistics/api-delete-consumption-item-history route. +/// +public class DeleteConsumptionItemHistoryEndpoint : BaseEndpoint +{ + private readonly IApiHttpClient _apiHttpClient; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for interactions with the API. + public DeleteConsumptionItemHistoryEndpoint(IApiHttpClient apiHttpClient) + { + _apiHttpClient = apiHttpClient; + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.DELETE); + Routes(WebRoutes.LibraryStatistics.DELETE_CONSUMPTION_ITEM_HISTORY); + DontAutoTag(); + Options(options => options.WithTags("Statistics")); + EnableAntiforgery(); + } + + /// + /// Deletes every consumption record of a media item of the selected user. + /// + /// The request containing the selected user, the media item, and its library. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(DeleteConsumptionItemHistoryRequest request, CancellationToken cancellationToken) + { + // The records belong to the selected user, so no intermediary may store any response of this route, and the response varies by the sign in cookie. + HttpContext.Response.Headers["Cache-Control"] = "private, no-store"; + HttpContext.Response.Headers["Vary"] = "Cookie"; + string path = string.IsNullOrWhiteSpace(request.UserId) + ? ApiRoutes.LibraryStatistics.DELETE_CONSUMPTION_ITEM_HISTORY + : ApiRoutes.LibraryStatistics.DELETE_USER_CONSUMPTION_ITEM_HISTORY.Replace("{userId}", Uri.EscapeDataString(request.UserId), StringComparison.Ordinal); + path = path + .Replace("{mediaKind}", request.MediaKind.ToString(), StringComparison.Ordinal) + .Replace("{mediaItemId}", request.MediaItemId.ToString(), StringComparison.Ordinal) + .Replace("{libraryId}", request.LibraryId.ToString(), StringComparison.Ordinal); + await _apiHttpClient.DeleteAsync(path, cancellationToken).ConfigureAwait(false); + return JsonSuccess(); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/DeleteConsumptionItemHistory/DeleteConsumptionItemHistoryEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/DeleteConsumptionItemHistory/DeleteConsumptionItemHistoryEndpointSummary.cs new file mode 100644 index 00000000..87c5718d --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/DeleteConsumptionItemHistory/DeleteConsumptionItemHistoryEndpointSummary.cs @@ -0,0 +1,35 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.DTO.Common; +using Lumina.Presentation.Web.Common.Requests.Library.Statistics; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Library.Statistics.DeleteConsumptionItemHistory; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class DeleteConsumptionItemHistoryEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public DeleteConsumptionItemHistoryEndpointSummary() + { + Summary = "Deletes every consumption record of a media item of the selected user."; + Description = "Proxies the request that deletes every recorded consumption session of one media item of the selected user, in the library named by the request, to the API server. The deletion covers every session of the item, independent of any date range. When userId is omitted, the history of the current user is deleted; an administrator can name another user. Deleting an item that has no recorded session succeeds without changing anything. The resume point of the media item is not deleted. A failure is returned as a JSON object with success set to false and a localized errorMessage."; + + RequestParam(request => request.UserId, "The Id of the user whose history is deleted. Optional; when omitted, the current user is used."); + RequestParam(request => request.MediaKind, "The kind of the consumed media item."); + RequestParam(request => request.MediaItemId, "The Id of the consumed media item."); + RequestParam(request => request.LibraryId, "The Id of the media library that contains the media item."); + + ResponseParam(response => response.IsSuccess, "Whether the operation succeeded."); + + Response(200, "The consumption records of the media item were deleted, or a JSON error with success set to false.", + example: new SuccessResponse(true) + ); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/GetAllUsersConsumptionStatistics/GetAllUsersConsumptionStatisticsEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/GetAllUsersConsumptionStatistics/GetAllUsersConsumptionStatisticsEndpoint.cs new file mode 100644 index 00000000..8cadf88d --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/GetAllUsersConsumptionStatistics/GetAllUsersConsumptionStatisticsEndpoint.cs @@ -0,0 +1,86 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.Authorization; +using Lumina.Presentation.Web.Common.DTO.MediaConsumption; +using Lumina.Presentation.Web.Common.Requests.Library.Statistics; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Library.Statistics.GetAllUsersConsumptionStatistics; + +/// +/// API endpoint for the /{culture}/library/statistics/api-get-all-users-statistics route. +/// +public class GetAllUsersConsumptionStatisticsEndpoint : BaseEndpoint +{ + private readonly IApiHttpClient _apiHttpClient; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for interactions with the API. + public GetAllUsersConsumptionStatisticsEndpoint(IApiHttpClient apiHttpClient) + { + _apiHttpClient = apiHttpClient; + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.GET); + Routes(WebRoutes.LibraryStatistics.GET_ALL_USERS_STATISTICS); + DontAutoTag(); + Options(options => options.WithTags("Statistics")); + Policies(AuthorizationPolicies.REQUIRE_ADMIN_ROLE); + } + + /// + /// Retrieves the combined consumption statistics of every user. + /// + /// The request containing the optional filters. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(GetAllUsersConsumptionStatisticsRequest request, CancellationToken cancellationToken) + { + // The statistics belong to every user of the server, so no intermediary may store them, and the response varies by the sign in cookie. + HttpContext.Response.Headers["Cache-Control"] = "private, no-store"; + HttpContext.Response.Headers["Vary"] = "Cookie"; + AllUsersConsumptionStatisticsDto response = await _apiHttpClient.GetAsync(BuildStatisticsEndpoint(request), cancellationToken).ConfigureAwait(false); + return JsonSuccess(response); + } + + /// + /// Builds the API endpoint used to retrieve the combined consumption statistics of every user. + /// + /// The request containing the optional filters. + /// The API endpoint to which the statistics request is sent. + private static string BuildStatisticsEndpoint(GetAllUsersConsumptionStatisticsRequest request) + { + // The query string is rebuilt from the typed request values instead of forwarding the raw one, so that crafted text can never alter the upstream URL. + StringBuilder endpoint = new(ApiRoutes.LibraryStatistics.GET_ALL_USERS_CONSUMPTION_STATISTICS); + List parameters = []; + if (!string.IsNullOrWhiteSpace(request.LibraryId)) + parameters.Add($"libraryId={Uri.EscapeDataString(request.LibraryId)}"); + if (request.MediaKind is not null) + parameters.Add($"mediaKind={Uri.EscapeDataString(request.MediaKind.Value.ToString())}"); + if (request.FromUtc is not null) + parameters.Add($"fromUtc={Uri.EscapeDataString(request.FromUtc.Value.ToString("O", CultureInfo.InvariantCulture))}"); + if (request.ToUtc is not null) + parameters.Add($"toUtc={Uri.EscapeDataString(request.ToUtc.Value.ToString("O", CultureInfo.InvariantCulture))}"); + if (parameters.Count > 0) + endpoint.Append('?').Append(string.Join('&', parameters)); + return endpoint.ToString(); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/GetAllUsersConsumptionStatistics/GetAllUsersConsumptionStatisticsEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/GetAllUsersConsumptionStatistics/GetAllUsersConsumptionStatisticsEndpointSummary.cs new file mode 100644 index 00000000..af94c620 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/GetAllUsersConsumptionStatistics/GetAllUsersConsumptionStatisticsEndpointSummary.cs @@ -0,0 +1,113 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.DTO.Common; +using Lumina.Presentation.Web.Common.DTO.MediaConsumption; +using Lumina.Presentation.Web.Common.Enums.MediaConsumption; +using Lumina.Presentation.Web.Common.Requests.Library.Statistics; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Library.Statistics.GetAllUsersConsumptionStatistics; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class GetAllUsersConsumptionStatisticsEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public GetAllUsersConsumptionStatisticsEndpointSummary() + { + Summary = "Gets the consumption statistics of every user."; + Description = "Proxies the request that gets the combined consumption statistics of every user, together with the statistics of each user, to the API server. Only an administrator can call it. The date range is inclusive. A failure is returned as a JSON object with success set to false and a localized errorMessage."; + + ExampleRequest = new GetAllUsersConsumptionStatisticsRequest( + LibraryId: null, + MediaKind: null, + FromUtc: new DateTime(2026, 10, 1, 0, 0, 0, DateTimeKind.Utc), + ToUtc: new DateTime(2026, 10, 31, 23, 59, 59, DateTimeKind.Utc) + ); + + RequestParam(request => request.LibraryId, "The Id of the media library to restrict the statistics to. Optional."); + RequestParam(request => request.MediaKind, "The kind of media to restrict the statistics to. Optional."); + RequestParam(request => request.FromUtc, "The inclusive start of the date range. Optional."); + RequestParam(request => request.ToUtc, "The inclusive end of the date range. Optional."); + + ResponseParam>(response => response.IsSuccess, "Whether the operation succeeded."); + ResponseParam(response => response.Total, "The combined consumption statistics of every user."); + ResponseParam(response => response.Users, "The consumption statistics of each user, ordered by user Id."); + ResponseParam(response => response.TotalConsumedDurationInSeconds, "The total duration consumed over every recorded session of every user, in seconds."); + ResponseParam(response => response.CountedSessionCount, "The number of recorded sessions of every user that count towards statistics."); + ResponseParam(response => response.CompletedSessionCount, "The number of recorded sessions of every user that completed."); + ResponseParam(response => response.StoppedSessionCount, "The number of recorded sessions of every user that stopped before they completed and count towards statistics."); + ResponseParam(response => response.CompletionRate, "The fraction of the counted sessions of every user that completed, between 0 and 1, or 0 when there is no counted session."); + ResponseParam(response => response.MediaKindSummaries, "The combined consumption statistics broken down by media kind."); + ResponseParam(response => response.UserId, "The Id of the user the summary belongs to."); + ResponseParam(response => response.TotalConsumedDurationInSeconds, "The total duration consumed over every recorded session of the user, in seconds."); + ResponseParam(response => response.CountedSessionCount, "The number of recorded sessions of the user that count towards statistics."); + ResponseParam(response => response.CompletedSessionCount, "The number of recorded sessions of the user that completed."); + ResponseParam(response => response.StoppedSessionCount, "The number of recorded sessions of the user that stopped before they completed and count towards statistics."); + ResponseParam(response => response.CompletionRate, "The fraction of the counted sessions of the user that completed, between 0 and 1, or 0 when there is no counted session."); + ResponseParam(response => response.MediaKindSummaries, "The consumption statistics of the user broken down by media kind."); + ResponseParam(response => response.MediaKind, "The kind of media the breakdown entry belongs to."); + ResponseParam(response => response.TotalConsumedDurationInSeconds, "The total duration consumed over every recorded session of the media kind, in seconds."); + ResponseParam(response => response.CountedSessionCount, "The number of recorded sessions of the media kind that count towards statistics."); + ResponseParam(response => response.CompletedSessionCount, "The number of recorded sessions of the media kind that completed."); + ResponseParam(response => response.StoppedSessionCount, "The number of recorded sessions of the media kind that stopped before they completed and count towards statistics."); + ResponseParam(response => response.CompletionRate, "The fraction of the counted sessions of the media kind that completed, between 0 and 1, or 0 when there is no counted session."); + + Response(200, "The consumption statistics of every user are returned, or a JSON error with success set to false.", + example: new SuccessResponse(true, new AllUsersConsumptionStatisticsDto( + Total: new ConsumptionTotalsDto( + TotalConsumedDurationInSeconds: 8744.5, + CountedSessionCount: 6, + CompletedSessionCount: 4, + StoppedSessionCount: 2, + CompletionRate: 0.6667, + MediaKindSummaries: + [ + new MediaKindConsumptionSummaryDto( + MediaKind: MediaKind.MusicTrack, + TotalConsumedDurationInSeconds: 1424.5, + CountedSessionCount: 4, + CompletedSessionCount: 3, + StoppedSessionCount: 1, + CompletionRate: 0.75 + ), + new MediaKindConsumptionSummaryDto( + MediaKind: MediaKind.Book, + TotalConsumedDurationInSeconds: 7320, + CountedSessionCount: 2, + CompletedSessionCount: 1, + StoppedSessionCount: 1, + CompletionRate: 0.5 + ) + ]), + Users: + [ + new ConsumptionSummaryDto( + UserId: Guid.Parse("1a2b3c4d-5e6f-4a1b-8c2d-3e4f5a6b7c8d"), + TotalConsumedDurationInSeconds: 8744.5, + CountedSessionCount: 6, + CompletedSessionCount: 4, + StoppedSessionCount: 2, + CompletionRate: 0.6667, + MediaKindSummaries: + [ + new MediaKindConsumptionSummaryDto( + MediaKind: MediaKind.MusicTrack, + TotalConsumedDurationInSeconds: 1424.5, + CountedSessionCount: 4, + CompletedSessionCount: 3, + StoppedSessionCount: 1, + CompletionRate: 0.75 + ) + ]) + ])) + ); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/GetConsumptionStatistics/GetConsumptionStatisticsEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/GetConsumptionStatistics/GetConsumptionStatisticsEndpoint.cs new file mode 100644 index 00000000..5db57330 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/GetConsumptionStatistics/GetConsumptionStatisticsEndpoint.cs @@ -0,0 +1,86 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.MediaConsumption; +using Lumina.Presentation.Web.Common.Requests.Library.Statistics; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Library.Statistics.GetConsumptionStatistics; + +/// +/// API endpoint for the /{culture}/library/statistics/api-get-statistics route. +/// +public class GetConsumptionStatisticsEndpoint : BaseEndpoint +{ + private readonly IApiHttpClient _apiHttpClient; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for interactions with the API. + public GetConsumptionStatisticsEndpoint(IApiHttpClient apiHttpClient) + { + _apiHttpClient = apiHttpClient; + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.GET); + Routes(WebRoutes.LibraryStatistics.GET_STATISTICS); + DontAutoTag(); + Options(options => options.WithTags("Statistics")); + } + + /// + /// Retrieves the consumption statistics of the selected user. + /// + /// The request containing the selected user and the optional filters. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(GetConsumptionStatisticsRequest request, CancellationToken cancellationToken) + { + // The statistics belong to the selected user, so no intermediary may store them, and the response varies by the sign in cookie. + HttpContext.Response.Headers["Cache-Control"] = "private, no-store"; + HttpContext.Response.Headers["Vary"] = "Cookie"; + ConsumptionSummaryDto response = await _apiHttpClient.GetAsync(BuildStatisticsEndpoint(request), cancellationToken).ConfigureAwait(false); + return JsonSuccess(response); + } + + /// + /// Builds the API endpoint used to retrieve the consumption statistics of the selected user. + /// + /// The request containing the selected user and the optional filters. + /// The API endpoint to which the statistics request is sent. + private static string BuildStatisticsEndpoint(GetConsumptionStatisticsRequest request) + { + // The query string is rebuilt from the typed request values instead of forwarding the raw one, so that crafted text can never alter the upstream URL. + StringBuilder endpoint = new(string.IsNullOrWhiteSpace(request.UserId) + ? ApiRoutes.LibraryStatistics.GET_CONSUMPTION_STATISTICS + : ApiRoutes.LibraryStatistics.GET_USER_CONSUMPTION_STATISTICS.Replace("{userId}", Uri.EscapeDataString(request.UserId), StringComparison.Ordinal)); + List parameters = []; + if (!string.IsNullOrWhiteSpace(request.LibraryId)) + parameters.Add($"libraryId={Uri.EscapeDataString(request.LibraryId)}"); + if (request.MediaKind is not null) + parameters.Add($"mediaKind={Uri.EscapeDataString(request.MediaKind.Value.ToString())}"); + if (request.FromUtc is not null) + parameters.Add($"fromUtc={Uri.EscapeDataString(request.FromUtc.Value.ToString("O", CultureInfo.InvariantCulture))}"); + if (request.ToUtc is not null) + parameters.Add($"toUtc={Uri.EscapeDataString(request.ToUtc.Value.ToString("O", CultureInfo.InvariantCulture))}"); + if (parameters.Count > 0) + endpoint.Append('?').Append(string.Join('&', parameters)); + return endpoint.ToString(); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/GetConsumptionStatistics/GetConsumptionStatisticsEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/GetConsumptionStatistics/GetConsumptionStatisticsEndpointSummary.cs new file mode 100644 index 00000000..9d8cb2c8 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/GetConsumptionStatistics/GetConsumptionStatisticsEndpointSummary.cs @@ -0,0 +1,86 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.DTO.Common; +using Lumina.Presentation.Web.Common.DTO.MediaConsumption; +using Lumina.Presentation.Web.Common.Enums.MediaConsumption; +using Lumina.Presentation.Web.Common.Requests.Library.Statistics; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Library.Statistics.GetConsumptionStatistics; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class GetConsumptionStatisticsEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public GetConsumptionStatisticsEndpointSummary() + { + Summary = "Gets the consumption statistics of the selected user."; + Description = "Proxies the request that gets the total consumed duration, the counted sessions, the completed sessions, the stopped sessions, the completion rate, and the per media kind breakdown of the selected user to the API server. When userId is omitted, the statistics of the current user are returned; an administrator can name another user. The date range is inclusive. A failure is returned as a JSON object with success set to false and a localized errorMessage."; + + ExampleRequest = new GetConsumptionStatisticsRequest( + UserId: null, + LibraryId: null, + MediaKind: null, + FromUtc: new DateTime(2026, 10, 1, 0, 0, 0, DateTimeKind.Utc), + ToUtc: new DateTime(2026, 10, 31, 23, 59, 59, DateTimeKind.Utc) + ); + + RequestParam(request => request.UserId, "The Id of the user whose statistics are retrieved. Optional; when omitted, the current user is used."); + RequestParam(request => request.LibraryId, "The Id of the media library to restrict the statistics to. Optional."); + RequestParam(request => request.MediaKind, "The kind of media to restrict the statistics to. Optional."); + RequestParam(request => request.FromUtc, "The inclusive start of the date range. Optional."); + RequestParam(request => request.ToUtc, "The inclusive end of the date range. Optional."); + + ResponseParam>(response => response.IsSuccess, "Whether the operation succeeded."); + ResponseParam(response => response.UserId, "The Id of the user the statistics belong to."); + ResponseParam(response => response.TotalConsumedDurationInSeconds, "The total duration consumed over every recorded session, in seconds."); + ResponseParam(response => response.CountedSessionCount, "The number of recorded sessions that count towards statistics."); + ResponseParam(response => response.CompletedSessionCount, "The number of recorded sessions that completed."); + ResponseParam(response => response.StoppedSessionCount, "The number of recorded sessions that stopped before they completed and count towards statistics."); + ResponseParam(response => response.CompletionRate, "The fraction of the counted sessions that completed, between 0 and 1, or 0 when there is no counted session."); + ResponseParam(response => response.MediaKindSummaries, "The consumption statistics broken down by media kind."); + ResponseParam(response => response.MediaKind, "The kind of media the breakdown entry belongs to."); + ResponseParam(response => response.TotalConsumedDurationInSeconds, "The total duration consumed over every recorded session of the media kind, in seconds."); + ResponseParam(response => response.CountedSessionCount, "The number of recorded sessions of the media kind that count towards statistics."); + ResponseParam(response => response.CompletedSessionCount, "The number of recorded sessions of the media kind that completed."); + ResponseParam(response => response.StoppedSessionCount, "The number of recorded sessions of the media kind that stopped before they completed and count towards statistics."); + ResponseParam(response => response.CompletionRate, "The fraction of the counted sessions of the media kind that completed, between 0 and 1, or 0 when there is no counted session."); + + Response(200, "The consumption statistics of the selected user are returned, or a JSON error with success set to false.", + example: new SuccessResponse(true, new ConsumptionSummaryDto( + UserId: Guid.Parse("1a2b3c4d-5e6f-4a1b-8c2d-3e4f5a6b7c8d"), + TotalConsumedDurationInSeconds: 8744.5, + CountedSessionCount: 6, + CompletedSessionCount: 4, + StoppedSessionCount: 2, + CompletionRate: 0.6667, + MediaKindSummaries: + [ + new MediaKindConsumptionSummaryDto( + MediaKind: MediaKind.MusicTrack, + TotalConsumedDurationInSeconds: 1424.5, + CountedSessionCount: 4, + CompletedSessionCount: 3, + StoppedSessionCount: 1, + CompletionRate: 0.75 + ), + new MediaKindConsumptionSummaryDto( + MediaKind: MediaKind.Book, + TotalConsumedDurationInSeconds: 7320, + CountedSessionCount: 2, + CompletedSessionCount: 1, + StoppedSessionCount: 1, + CompletionRate: 0.5 + ) + ])) + ); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/GetGenreConsumption/GetGenreConsumptionEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/GetGenreConsumption/GetGenreConsumptionEndpoint.cs new file mode 100644 index 00000000..b37f84d6 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/GetGenreConsumption/GetGenreConsumptionEndpoint.cs @@ -0,0 +1,86 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.MediaConsumption; +using Lumina.Presentation.Web.Common.Requests.Library.Statistics; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Library.Statistics.GetGenreConsumption; + +/// +/// API endpoint for the /{culture}/library/statistics/api-get-genre-consumption route. +/// +public class GetGenreConsumptionEndpoint : BaseEndpoint +{ + private readonly IApiHttpClient _apiHttpClient; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for interactions with the API. + public GetGenreConsumptionEndpoint(IApiHttpClient apiHttpClient) + { + _apiHttpClient = apiHttpClient; + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.GET); + Routes(WebRoutes.LibraryStatistics.GET_GENRE_CONSUMPTION); + DontAutoTag(); + Options(options => options.WithTags("Statistics")); + } + + /// + /// Retrieves the genre consumption of the selected user. + /// + /// The request containing the selected user and the optional filters. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(GetGenreConsumptionRequest request, CancellationToken cancellationToken) + { + // The statistics belong to the selected user, so no intermediary may store them, and the response varies by the sign in cookie. + HttpContext.Response.Headers["Cache-Control"] = "private, no-store"; + HttpContext.Response.Headers["Vary"] = "Cookie"; + GenreConsumptionDto[] response = await _apiHttpClient.GetAsync(BuildGenreConsumptionEndpoint(request), cancellationToken).ConfigureAwait(false); + return JsonSuccess(response); + } + + /// + /// Builds the API endpoint used to retrieve the genre consumption of the selected user. + /// + /// The request containing the selected user and the optional filters. + /// The API endpoint to which the genre request is sent. + private static string BuildGenreConsumptionEndpoint(GetGenreConsumptionRequest request) + { + // The query string is rebuilt from the typed request values instead of forwarding the raw one, so that crafted text can never alter the upstream URL. + StringBuilder endpoint = new(string.IsNullOrWhiteSpace(request.UserId) + ? ApiRoutes.LibraryStatistics.GET_GENRE_CONSUMPTION + : ApiRoutes.LibraryStatistics.GET_USER_GENRE_CONSUMPTION.Replace("{userId}", Uri.EscapeDataString(request.UserId), StringComparison.Ordinal)); + List parameters = []; + if (!string.IsNullOrWhiteSpace(request.LibraryId)) + parameters.Add($"libraryId={Uri.EscapeDataString(request.LibraryId)}"); + if (request.MediaKind is not null) + parameters.Add($"mediaKind={Uri.EscapeDataString(request.MediaKind.Value.ToString())}"); + if (request.FromUtc is not null) + parameters.Add($"fromUtc={Uri.EscapeDataString(request.FromUtc.Value.ToString("O", CultureInfo.InvariantCulture))}"); + if (request.ToUtc is not null) + parameters.Add($"toUtc={Uri.EscapeDataString(request.ToUtc.Value.ToString("O", CultureInfo.InvariantCulture))}"); + if (parameters.Count > 0) + endpoint.Append('?').Append(string.Join('&', parameters)); + return endpoint.ToString(); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/GetGenreConsumption/GetGenreConsumptionEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/GetGenreConsumption/GetGenreConsumptionEndpointSummary.cs new file mode 100644 index 00000000..f8a4d153 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/GetGenreConsumption/GetGenreConsumptionEndpointSummary.cs @@ -0,0 +1,64 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.DTO.Common; +using Lumina.Presentation.Web.Common.DTO.MediaConsumption; +using Lumina.Presentation.Web.Common.Requests.Library.Statistics; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Library.Statistics.GetGenreConsumption; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class GetGenreConsumptionEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public GetGenreConsumptionEndpointSummary() + { + Summary = "Gets the genre consumption of the selected user."; + Description = "Proxies the request that gets the genres carried by the media items the selected user consumed to the API server. When userId is omitted, the statistics of the current user are returned; an administrator can name another user. The names are lowercase and grouped across media kinds, so a genre shared by a book and a track appears in one bucket. The date range is inclusive. A failure is returned as a JSON object with success set to false and a localized errorMessage."; + + ExampleRequest = new GetGenreConsumptionRequest( + UserId: null, + LibraryId: null, + MediaKind: null, + FromUtc: new DateTime(2026, 10, 1, 0, 0, 0, DateTimeKind.Utc), + ToUtc: new DateTime(2026, 10, 31, 23, 59, 59, DateTimeKind.Utc) + ); + + RequestParam(request => request.UserId, "The Id of the user whose statistics are retrieved. Optional; when omitted, the current user is used."); + RequestParam(request => request.LibraryId, "The Id of the media library to restrict the statistics to. Optional."); + RequestParam(request => request.MediaKind, "The kind of media to restrict the statistics to. Optional."); + RequestParam(request => request.FromUtc, "The inclusive start of the date range. Optional."); + RequestParam(request => request.ToUtc, "The inclusive end of the date range. Optional."); + + ResponseParam>(response => response.IsSuccess, "Whether the operation succeeded."); + ResponseParam(response => response.Name, "The lowercase name of the genre."); + ResponseParam(response => response.ConsumedItemCount, "The number of distinct media items that carry the genre and were consumed."); + ResponseParam(response => response.ConsumedDurationInSeconds, "The active duration consumed in the media items that carry the genre, in seconds."); + + Response(200, "The genre consumption of the selected user is returned, or a JSON error with success set to false.", + example: new SuccessResponse(true, + [ + new GenreConsumptionDto( + Name: "horror", + ConsumedItemCount: 3, + ConsumedDurationInSeconds: 5400), + new GenreConsumptionDto( + Name: "fantasy", + ConsumedItemCount: 2, + ConsumedDurationInSeconds: 7320), + new GenreConsumptionDto( + Name: "science fiction", + ConsumedItemCount: 1, + ConsumedDurationInSeconds: 1424.5) + ]) + ); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/GetLibraries/GetLibrariesEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/GetLibraries/GetLibrariesEndpoint.cs new file mode 100644 index 00000000..a07a14da --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/GetLibraries/GetLibrariesEndpoint.cs @@ -0,0 +1,56 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.Libraries; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Library.Statistics.GetLibraries; + +/// +/// API endpoint for the /{culture}/library/statistics/api-get-libraries route. +/// +public class GetLibrariesEndpoint : BaseEndpoint +{ + private readonly IApiHttpClient _apiHttpClient; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for interactions with the API. + public GetLibrariesEndpoint(IApiHttpClient apiHttpClient) + { + _apiHttpClient = apiHttpClient; + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.GET); + Routes(WebRoutes.LibraryStatistics.GET_LIBRARIES); + DontAutoTag(); + Options(options => options.WithTags("Statistics")); + } + + /// + /// Retrieves the libraries available for the library filter. + /// + /// The request object. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(EmptyRequest request, CancellationToken cancellationToken) + { + // The library list belongs to the current user, so no intermediary may store it, and the response varies by the sign in cookie. + HttpContext.Response.Headers["Cache-Control"] = "private, no-store"; + HttpContext.Response.Headers["Vary"] = "Cookie"; + LibraryDto[] response = await _apiHttpClient.GetAsync(ApiRoutes.Libraries.GET_ENABLED_LIBRARIES, cancellationToken).ConfigureAwait(false); + return JsonSuccess(response); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/GetLibraries/GetLibrariesEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/GetLibraries/GetLibrariesEndpointSummary.cs new file mode 100644 index 00000000..de8d1393 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/GetLibraries/GetLibrariesEndpointSummary.cs @@ -0,0 +1,27 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.DTO.Common; +using Lumina.Presentation.Web.Common.DTO.Libraries; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Library.Statistics.GetLibraries; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class GetLibrariesEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public GetLibrariesEndpointSummary() + { + Summary = "Gets the enabled libraries available for the library filter."; + Description = "Proxies the request that gets the enabled media libraries available to the current user to the API server. A regular user receives only their own libraries; an administrator receives every enabled library. A failure is returned as a JSON object with success set to false and a localized errorMessage."; + + Response(200, "The enabled media libraries are returned, or a JSON error with success set to false.", + example: new SuccessResponse(true, default)); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/GetMostConsumed/GetMostConsumedEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/GetMostConsumed/GetMostConsumedEndpoint.cs new file mode 100644 index 00000000..8a62b830 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/GetMostConsumed/GetMostConsumedEndpoint.cs @@ -0,0 +1,92 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.Common; +using Lumina.Presentation.Web.Common.DTO.MediaConsumption; +using Lumina.Presentation.Web.Common.Requests.Library.Statistics; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Library.Statistics.GetMostConsumed; + +/// +/// API endpoint for the /{culture}/library/statistics/api-get-most-consumed route. +/// +public class GetMostConsumedEndpoint : BaseEndpoint +{ + private const int DEFAULT_PAGE_SIZE = 10; + + private readonly IApiHttpClient _apiHttpClient; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for interactions with the API. + public GetMostConsumedEndpoint(IApiHttpClient apiHttpClient) + { + _apiHttpClient = apiHttpClient; + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.GET); + Routes(WebRoutes.LibraryStatistics.GET_MOST_CONSUMED); + DontAutoTag(); + Options(options => options.WithTags("Statistics")); + } + + /// + /// Retrieves a page of the most consumed media items of the selected user. + /// + /// The request containing the selected user, the optional filters, and the page bounds. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(GetMostConsumedRequest request, CancellationToken cancellationToken) + { + // The history belongs to the selected user, so no intermediary may store it, and the response varies by the sign in cookie. + HttpContext.Response.Headers["Cache-Control"] = "private, no-store"; + HttpContext.Response.Headers["Vary"] = "Cookie"; + PaginatedDto response = await _apiHttpClient.GetAsync>(BuildHistoryEndpoint(request), cancellationToken).ConfigureAwait(false); + return JsonSuccess(response); + } + + /// + /// Builds the API endpoint used to retrieve the most consumed media items of the selected user. + /// + /// The request containing the selected user, the optional filters, and the page bounds. + /// The API endpoint to which the history request is sent. + private static string BuildHistoryEndpoint(GetMostConsumedRequest request) + { + // The query string is rebuilt from the typed request values instead of forwarding the raw one, so that crafted text can never alter the upstream URL. + StringBuilder endpoint = new(string.IsNullOrWhiteSpace(request.UserId) + ? ApiRoutes.LibraryStatistics.GET_MOST_CONSUMED + : ApiRoutes.LibraryStatistics.GET_USER_MOST_CONSUMED.Replace("{userId}", Uri.EscapeDataString(request.UserId), StringComparison.Ordinal)); + int currentPage = request.CurrentPage ?? 1; + int perPage = request.PerPage ?? DEFAULT_PAGE_SIZE; + List parameters = []; + if (!string.IsNullOrWhiteSpace(request.LibraryId)) + parameters.Add($"libraryId={Uri.EscapeDataString(request.LibraryId)}"); + if (request.MediaKind is not null) + parameters.Add($"mediaKind={Uri.EscapeDataString(request.MediaKind.Value.ToString())}"); + if (request.FromUtc is not null) + parameters.Add($"fromUtc={Uri.EscapeDataString(request.FromUtc.Value.ToString("O", CultureInfo.InvariantCulture))}"); + if (request.ToUtc is not null) + parameters.Add($"toUtc={Uri.EscapeDataString(request.ToUtc.Value.ToString("O", CultureInfo.InvariantCulture))}"); + parameters.Add($"currentPage={currentPage.ToString(CultureInfo.InvariantCulture)}"); + parameters.Add($"perPage={perPage.ToString(CultureInfo.InvariantCulture)}"); + endpoint.Append('?').Append(string.Join('&', parameters)); + return endpoint.ToString(); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/GetMostConsumed/GetMostConsumedEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/GetMostConsumed/GetMostConsumedEndpointSummary.cs new file mode 100644 index 00000000..fbf4896f --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/GetMostConsumed/GetMostConsumedEndpointSummary.cs @@ -0,0 +1,102 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.DTO.Common; +using Lumina.Presentation.Web.Common.DTO.MediaConsumption; +using Lumina.Presentation.Web.Common.Enums.MediaConsumption; +using Lumina.Presentation.Web.Common.Requests.Library.Statistics; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Library.Statistics.GetMostConsumed; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class GetMostConsumedEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public GetMostConsumedEndpointSummary() + { + Summary = "Gets the most consumed media items of the selected user."; + Description = "Proxies the request that gets a page of the most consumed media items of the selected user to the API server. When userId is omitted, the history of the current user is returned; an administrator can name another user. The items are ordered by counted sessions, consumed duration, last consumption date, and media item Id. Music and book sessions appear in the same list. The date range is inclusive. An item whose media item was deleted, or whose library is no longer accessible, is returned with isAvailable set to false and empty display fields. A failure is returned as a JSON object with success set to false and a localized errorMessage."; + + ExampleRequest = new GetMostConsumedRequest( + UserId: null, + LibraryId: null, + MediaKind: null, + FromUtc: new DateTime(2026, 10, 1, 0, 0, 0, DateTimeKind.Utc), + ToUtc: new DateTime(2026, 10, 31, 23, 59, 59, DateTimeKind.Utc), + CurrentPage: 1, + PerPage: 10 + ); + + RequestParam(request => request.UserId, "The Id of the user whose history is retrieved. Optional; when omitted, the current user is used."); + RequestParam(request => request.LibraryId, "The Id of the media library to restrict the history to. Optional."); + RequestParam(request => request.MediaKind, "The kind of media to restrict the history to. Optional."); + RequestParam(request => request.FromUtc, "The inclusive start of the date range. Optional."); + RequestParam(request => request.ToUtc, "The inclusive end of the date range. Optional."); + RequestParam(request => request.CurrentPage, "The one based page of media items to return. Optional. Defaults to 1."); + RequestParam(request => request.PerPage, "The number of media items per page. Optional. Defaults to 10."); + + ResponseParam>>(response => response.IsSuccess, "Whether the operation succeeded."); + ResponseParam>(response => response.Data, "The most consumed media items of the requested page, ordered by counted sessions, consumed duration, last consumption date, and media item Id."); + ResponseParam>(response => response.CurrentPage, "The current page number."); + ResponseParam>(response => response.PerPage, "The number of media items retrieved per page."); + ResponseParam>(response => response.Count, "The total number of distinct media items that match the filters."); + ResponseParam>(response => response.NumberOfPages, "The total number of pages."); + ResponseParam(response => response.MediaKind, "The kind of the consumed media item."); + ResponseParam(response => response.MediaItemId, "The Id of the consumed media item."); + ResponseParam(response => response.LibraryId, "The Id of the media library that contains the media item."); + ResponseParam(response => response.IsAvailable, "Whether the media item still exists and its library is accessible."); + ResponseParam(response => response.Title, "The title of the media item, or an empty string when the item is not available."); + ResponseParam(response => response.CollectionTitle, "The title of the collection that contains the media item, or an empty string when there is none."); + ResponseParam(response => response.CreatorName, "The name of the creator of the media item, or an empty string when there is none."); + ResponseParam(response => response.CoverPath, "The path of the cover art of the media item, if available."); + ResponseParam(response => response.LastConsumedOnUtc, "The date and time when the media item was last consumed."); + ResponseParam(response => response.CountedSessionCount, "The number of consumption sessions of the media item that count towards statistics."); + ResponseParam(response => response.CompletedSessionCount, "The number of consumption sessions of the media item that completed."); + ResponseParam(response => response.ConsumedDurationInSeconds, "The active duration consumed in the media item, over all of its sessions, in seconds."); + + Response(200, "The requested page of most consumed media items is returned, or a JSON error with success set to false.", + example: new SuccessResponse>(true, new PaginatedDto( + Data: + [ + new ConsumedItemDto( + MediaKind: MediaKind.MusicTrack, + MediaItemId: Guid.Parse("9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f"), + LibraryId: Guid.Parse("3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a"), + IsAvailable: true, + Title: "The Show Must Go On", + CollectionTitle: "Innuendo", + CreatorName: "Queen", + CoverPath: "/artwork/albums/e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f/cover.jpg", + LastConsumedOnUtc: new DateTime(2026, 10, 24, 12, 12, 0, DateTimeKind.Utc), + CountedSessionCount: 4, + CompletedSessionCount: 3, + ConsumedDurationInSeconds: 1424.5), + new ConsumedItemDto( + MediaKind: MediaKind.Book, + MediaItemId: Guid.Parse("7a6b5c4d-3e2f-4a1b-8c9d-0e1f2a3b4c5d"), + LibraryId: Guid.Parse("6c7d8e9f-0a1b-4c2d-9e3f-4a5b6c7d8e9f"), + IsAvailable: true, + Title: "The Fellowship of the Ring", + CollectionTitle: string.Empty, + CreatorName: "J. R. R. Tolkien", + CoverPath: "/artwork/books/7a6b5c4d-3e2f-4a1b-8c9d-0e1f2a3b4c5d/cover.jpg", + LastConsumedOnUtc: new DateTime(2026, 10, 23, 20, 40, 0, DateTimeKind.Utc), + CountedSessionCount: 2, + CompletedSessionCount: 1, + ConsumedDurationInSeconds: 7320) + ], + CurrentPage: 1, + PerPage: 10, + Count: 2, + NumberOfPages: 1)) + ); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/GetRecentlyConsumed/GetRecentlyConsumedEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/GetRecentlyConsumed/GetRecentlyConsumedEndpoint.cs new file mode 100644 index 00000000..d5ed57ce --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/GetRecentlyConsumed/GetRecentlyConsumedEndpoint.cs @@ -0,0 +1,92 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.Common; +using Lumina.Presentation.Web.Common.DTO.MediaConsumption; +using Lumina.Presentation.Web.Common.Requests.Library.Statistics; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Library.Statistics.GetRecentlyConsumed; + +/// +/// API endpoint for the /{culture}/library/statistics/api-get-recently-consumed route. +/// +public class GetRecentlyConsumedEndpoint : BaseEndpoint +{ + private const int DEFAULT_PAGE_SIZE = 10; + + private readonly IApiHttpClient _apiHttpClient; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for interactions with the API. + public GetRecentlyConsumedEndpoint(IApiHttpClient apiHttpClient) + { + _apiHttpClient = apiHttpClient; + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.GET); + Routes(WebRoutes.LibraryStatistics.GET_RECENTLY_CONSUMED); + DontAutoTag(); + Options(options => options.WithTags("Statistics")); + } + + /// + /// Retrieves a page of the recently consumed media items of the selected user. + /// + /// The request containing the selected user, the optional filters, and the page bounds. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(GetRecentlyConsumedRequest request, CancellationToken cancellationToken) + { + // The history belongs to the selected user, so no intermediary may store it, and the response varies by the sign in cookie. + HttpContext.Response.Headers["Cache-Control"] = "private, no-store"; + HttpContext.Response.Headers["Vary"] = "Cookie"; + PaginatedDto response = await _apiHttpClient.GetAsync>(BuildHistoryEndpoint(request), cancellationToken).ConfigureAwait(false); + return JsonSuccess(response); + } + + /// + /// Builds the API endpoint used to retrieve the recently consumed media items of the selected user. + /// + /// The request containing the selected user, the optional filters, and the page bounds. + /// The API endpoint to which the history request is sent. + private static string BuildHistoryEndpoint(GetRecentlyConsumedRequest request) + { + // The query string is rebuilt from the typed request values instead of forwarding the raw one, so that crafted text can never alter the upstream URL. + StringBuilder endpoint = new(string.IsNullOrWhiteSpace(request.UserId) + ? ApiRoutes.LibraryStatistics.GET_RECENTLY_CONSUMED + : ApiRoutes.LibraryStatistics.GET_USER_RECENTLY_CONSUMED.Replace("{userId}", Uri.EscapeDataString(request.UserId), StringComparison.Ordinal)); + int currentPage = request.CurrentPage ?? 1; + int perPage = request.PerPage ?? DEFAULT_PAGE_SIZE; + List parameters = []; + if (!string.IsNullOrWhiteSpace(request.LibraryId)) + parameters.Add($"libraryId={Uri.EscapeDataString(request.LibraryId)}"); + if (request.MediaKind is not null) + parameters.Add($"mediaKind={Uri.EscapeDataString(request.MediaKind.Value.ToString())}"); + if (request.FromUtc is not null) + parameters.Add($"fromUtc={Uri.EscapeDataString(request.FromUtc.Value.ToString("O", CultureInfo.InvariantCulture))}"); + if (request.ToUtc is not null) + parameters.Add($"toUtc={Uri.EscapeDataString(request.ToUtc.Value.ToString("O", CultureInfo.InvariantCulture))}"); + parameters.Add($"currentPage={currentPage.ToString(CultureInfo.InvariantCulture)}"); + parameters.Add($"perPage={perPage.ToString(CultureInfo.InvariantCulture)}"); + endpoint.Append('?').Append(string.Join('&', parameters)); + return endpoint.ToString(); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/GetRecentlyConsumed/GetRecentlyConsumedEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/GetRecentlyConsumed/GetRecentlyConsumedEndpointSummary.cs new file mode 100644 index 00000000..58a1ea01 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/GetRecentlyConsumed/GetRecentlyConsumedEndpointSummary.cs @@ -0,0 +1,102 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.DTO.Common; +using Lumina.Presentation.Web.Common.DTO.MediaConsumption; +using Lumina.Presentation.Web.Common.Enums.MediaConsumption; +using Lumina.Presentation.Web.Common.Requests.Library.Statistics; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Library.Statistics.GetRecentlyConsumed; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class GetRecentlyConsumedEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public GetRecentlyConsumedEndpointSummary() + { + Summary = "Gets the recently consumed media items of the selected user."; + Description = "Proxies the request that gets a page of the recently consumed media items of the selected user to the API server. When userId is omitted, the history of the current user is returned; an administrator can name another user. Music and book sessions appear in the same list. The date range is inclusive. An item whose media item was deleted, or whose library is no longer accessible, is returned with isAvailable set to false and empty display fields. A failure is returned as a JSON object with success set to false and a localized errorMessage."; + + ExampleRequest = new GetRecentlyConsumedRequest( + UserId: null, + LibraryId: null, + MediaKind: null, + FromUtc: new DateTime(2026, 10, 1, 0, 0, 0, DateTimeKind.Utc), + ToUtc: new DateTime(2026, 10, 31, 23, 59, 59, DateTimeKind.Utc), + CurrentPage: 1, + PerPage: 10 + ); + + RequestParam(request => request.UserId, "The Id of the user whose history is retrieved. Optional; when omitted, the current user is used."); + RequestParam(request => request.LibraryId, "The Id of the media library to restrict the history to. Optional."); + RequestParam(request => request.MediaKind, "The kind of media to restrict the history to. Optional."); + RequestParam(request => request.FromUtc, "The inclusive start of the date range. Optional."); + RequestParam(request => request.ToUtc, "The inclusive end of the date range. Optional."); + RequestParam(request => request.CurrentPage, "The one based page of media items to return. Optional. Defaults to 1."); + RequestParam(request => request.PerPage, "The number of media items per page. Optional. Defaults to 10."); + + ResponseParam>>(response => response.IsSuccess, "Whether the operation succeeded."); + ResponseParam>(response => response.Data, "The recently consumed media items of the requested page, from the most recently consumed."); + ResponseParam>(response => response.CurrentPage, "The current page number."); + ResponseParam>(response => response.PerPage, "The number of media items retrieved per page."); + ResponseParam>(response => response.Count, "The total number of distinct media items that match the filters."); + ResponseParam>(response => response.NumberOfPages, "The total number of pages."); + ResponseParam(response => response.MediaKind, "The kind of the consumed media item."); + ResponseParam(response => response.MediaItemId, "The Id of the consumed media item."); + ResponseParam(response => response.LibraryId, "The Id of the media library that contains the media item."); + ResponseParam(response => response.IsAvailable, "Whether the media item still exists and its library is accessible."); + ResponseParam(response => response.Title, "The title of the media item, or an empty string when the item is not available."); + ResponseParam(response => response.CollectionTitle, "The title of the collection that contains the media item, or an empty string when there is none."); + ResponseParam(response => response.CreatorName, "The name of the creator of the media item, or an empty string when there is none."); + ResponseParam(response => response.CoverPath, "The path of the cover art of the media item, if available."); + ResponseParam(response => response.LastConsumedOnUtc, "The date and time when the media item was last consumed."); + ResponseParam(response => response.CountedSessionCount, "The number of consumption sessions of the media item that count towards statistics."); + ResponseParam(response => response.CompletedSessionCount, "The number of consumption sessions of the media item that completed."); + ResponseParam(response => response.ConsumedDurationInSeconds, "The active duration consumed in the media item, over all of its sessions, in seconds."); + + Response(200, "The requested page of recently consumed media items is returned, or a JSON error with success set to false.", + example: new SuccessResponse>(true, new PaginatedDto( + Data: + [ + new ConsumedItemDto( + MediaKind: MediaKind.MusicTrack, + MediaItemId: Guid.Parse("9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f"), + LibraryId: Guid.Parse("3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a"), + IsAvailable: true, + Title: "The Show Must Go On", + CollectionTitle: "Innuendo", + CreatorName: "Queen", + CoverPath: "/artwork/albums/e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f/cover.jpg", + LastConsumedOnUtc: new DateTime(2026, 10, 24, 12, 12, 0, DateTimeKind.Utc), + CountedSessionCount: 4, + CompletedSessionCount: 3, + ConsumedDurationInSeconds: 1424.5), + new ConsumedItemDto( + MediaKind: MediaKind.Book, + MediaItemId: Guid.Parse("7a6b5c4d-3e2f-4a1b-8c9d-0e1f2a3b4c5d"), + LibraryId: Guid.Parse("6c7d8e9f-0a1b-4c2d-9e3f-4a5b6c7d8e9f"), + IsAvailable: true, + Title: "The Fellowship of the Ring", + CollectionTitle: string.Empty, + CreatorName: "J. R. R. Tolkien", + CoverPath: "/artwork/books/7a6b5c4d-3e2f-4a1b-8c9d-0e1f2a3b4c5d/cover.jpg", + LastConsumedOnUtc: new DateTime(2026, 10, 23, 20, 40, 0, DateTimeKind.Utc), + CountedSessionCount: 2, + CompletedSessionCount: 1, + ConsumedDurationInSeconds: 7320) + ], + CurrentPage: 1, + PerPage: 10, + Count: 2, + NumberOfPages: 1)) + ); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/GetTagConsumption/GetTagConsumptionEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/GetTagConsumption/GetTagConsumptionEndpoint.cs new file mode 100644 index 00000000..d14e93f3 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/GetTagConsumption/GetTagConsumptionEndpoint.cs @@ -0,0 +1,86 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.MediaConsumption; +using Lumina.Presentation.Web.Common.Requests.Library.Statistics; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Library.Statistics.GetTagConsumption; + +/// +/// API endpoint for the /{culture}/library/statistics/api-get-tag-consumption route. +/// +public class GetTagConsumptionEndpoint : BaseEndpoint +{ + private readonly IApiHttpClient _apiHttpClient; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for interactions with the API. + public GetTagConsumptionEndpoint(IApiHttpClient apiHttpClient) + { + _apiHttpClient = apiHttpClient; + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.GET); + Routes(WebRoutes.LibraryStatistics.GET_TAG_CONSUMPTION); + DontAutoTag(); + Options(options => options.WithTags("Statistics")); + } + + /// + /// Retrieves the tag consumption of the selected user. + /// + /// The request containing the selected user and the optional filters. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(GetTagConsumptionRequest request, CancellationToken cancellationToken) + { + // The statistics belong to the selected user, so no intermediary may store them, and the response varies by the sign in cookie. + HttpContext.Response.Headers["Cache-Control"] = "private, no-store"; + HttpContext.Response.Headers["Vary"] = "Cookie"; + TagConsumptionDto[] response = await _apiHttpClient.GetAsync(BuildTagConsumptionEndpoint(request), cancellationToken).ConfigureAwait(false); + return JsonSuccess(response); + } + + /// + /// Builds the API endpoint used to retrieve the tag consumption of the selected user. + /// + /// The request containing the selected user and the optional filters. + /// The API endpoint to which the tag request is sent. + private static string BuildTagConsumptionEndpoint(GetTagConsumptionRequest request) + { + // The query string is rebuilt from the typed request values instead of forwarding the raw one, so that crafted text can never alter the upstream URL. + StringBuilder endpoint = new(string.IsNullOrWhiteSpace(request.UserId) + ? ApiRoutes.LibraryStatistics.GET_TAG_CONSUMPTION + : ApiRoutes.LibraryStatistics.GET_USER_TAG_CONSUMPTION.Replace("{userId}", Uri.EscapeDataString(request.UserId), StringComparison.Ordinal)); + List parameters = []; + if (!string.IsNullOrWhiteSpace(request.LibraryId)) + parameters.Add($"libraryId={Uri.EscapeDataString(request.LibraryId)}"); + if (request.MediaKind is not null) + parameters.Add($"mediaKind={Uri.EscapeDataString(request.MediaKind.Value.ToString())}"); + if (request.FromUtc is not null) + parameters.Add($"fromUtc={Uri.EscapeDataString(request.FromUtc.Value.ToString("O", CultureInfo.InvariantCulture))}"); + if (request.ToUtc is not null) + parameters.Add($"toUtc={Uri.EscapeDataString(request.ToUtc.Value.ToString("O", CultureInfo.InvariantCulture))}"); + if (parameters.Count > 0) + endpoint.Append('?').Append(string.Join('&', parameters)); + return endpoint.ToString(); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/GetTagConsumption/GetTagConsumptionEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/GetTagConsumption/GetTagConsumptionEndpointSummary.cs new file mode 100644 index 00000000..43b82a19 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/GetTagConsumption/GetTagConsumptionEndpointSummary.cs @@ -0,0 +1,64 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.DTO.Common; +using Lumina.Presentation.Web.Common.DTO.MediaConsumption; +using Lumina.Presentation.Web.Common.Requests.Library.Statistics; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Library.Statistics.GetTagConsumption; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class GetTagConsumptionEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public GetTagConsumptionEndpointSummary() + { + Summary = "Gets the tag consumption of the selected user."; + Description = "Proxies the request that gets the tags carried by the media items the selected user consumed to the API server. When userId is omitted, the statistics of the current user are returned; an administrator can name another user. The names are lowercase and grouped across media kinds, so a tag shared by a book and a track appears in one bucket. The date range is inclusive. A failure is returned as a JSON object with success set to false and a localized errorMessage."; + + ExampleRequest = new GetTagConsumptionRequest( + UserId: null, + LibraryId: null, + MediaKind: null, + FromUtc: new DateTime(2026, 10, 1, 0, 0, 0, DateTimeKind.Utc), + ToUtc: new DateTime(2026, 10, 31, 23, 59, 59, DateTimeKind.Utc) + ); + + RequestParam(request => request.UserId, "The Id of the user whose statistics are retrieved. Optional; when omitted, the current user is used."); + RequestParam(request => request.LibraryId, "The Id of the media library to restrict the statistics to. Optional."); + RequestParam(request => request.MediaKind, "The kind of media to restrict the statistics to. Optional."); + RequestParam(request => request.FromUtc, "The inclusive start of the date range. Optional."); + RequestParam(request => request.ToUtc, "The inclusive end of the date range. Optional."); + + ResponseParam>(response => response.IsSuccess, "Whether the operation succeeded."); + ResponseParam(response => response.Name, "The lowercase name of the tag."); + ResponseParam(response => response.ConsumedItemCount, "The number of distinct media items that carry the tag and were consumed."); + ResponseParam(response => response.ConsumedDurationInSeconds, "The active duration consumed in the media items that carry the tag, in seconds."); + + Response(200, "The tag consumption of the selected user is returned, or a JSON error with success set to false.", + example: new SuccessResponse(true, + [ + new TagConsumptionDto( + Name: "favourite", + ConsumedItemCount: 3, + ConsumedDurationInSeconds: 5400), + new TagConsumptionDto( + Name: "book-club", + ConsumedItemCount: 2, + ConsumedDurationInSeconds: 7320), + new TagConsumptionDto( + Name: "comfort-read", + ConsumedItemCount: 1, + ConsumedDurationInSeconds: 1424.5) + ]) + ); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/GetUsers/GetUsersEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/GetUsers/GetUsersEndpoint.cs new file mode 100644 index 00000000..915519a0 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/GetUsers/GetUsersEndpoint.cs @@ -0,0 +1,58 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.Authorization; +using Lumina.Presentation.Web.Common.DTO.UsersManagement; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Library.Statistics.GetUsers; + +/// +/// API endpoint for the /{culture}/library/statistics/api-get-users route. +/// +public class GetUsersEndpoint : BaseEndpoint +{ + private readonly IApiHttpClient _apiHttpClient; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for interactions with the API. + public GetUsersEndpoint(IApiHttpClient apiHttpClient) + { + _apiHttpClient = apiHttpClient; + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.GET); + Routes(WebRoutes.LibraryStatistics.GET_USERS); + DontAutoTag(); + Options(options => options.WithTags("Statistics")); + Policies(AuthorizationPolicies.REQUIRE_ADMIN_ROLE); + } + + /// + /// Retrieves the users available for the administrator user selector. + /// + /// The request object. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(EmptyRequest request, CancellationToken cancellationToken) + { + // The user list is administrative data, so no intermediary may store it, and the response varies by the sign in cookie. + HttpContext.Response.Headers["Cache-Control"] = "private, no-store"; + HttpContext.Response.Headers["Vary"] = "Cookie"; + UserDto[] response = await _apiHttpClient.GetAsync(ApiRoutes.Authentication.USERS, cancellationToken).ConfigureAwait(false); + return JsonSuccess(response); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/GetUsers/GetUsersEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/GetUsers/GetUsersEndpointSummary.cs new file mode 100644 index 00000000..062fd67f --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/GetUsers/GetUsersEndpointSummary.cs @@ -0,0 +1,41 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.DTO.Common; +using Lumina.Presentation.Web.Common.DTO.UsersManagement; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Library.Statistics.GetUsers; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class GetUsersEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public GetUsersEndpointSummary() + { + Summary = "Gets the users available for the administrator user selector."; + Description = "Proxies the request that gets the list of users to the API server. Only an administrator can call it. A failure is returned as a JSON object with success set to false and a localized errorMessage."; + + ResponseParam>(response => response.IsSuccess, "Whether the operation succeeded."); + ResponseParam(response => response.Id, "The unique identifier of the user."); + ResponseParam(response => response.Username, "The username of the user."); + + Response(200, "The users available for the selector are returned, or a JSON error with success set to false.", + example: new SuccessResponse(true, + [ + new UserDto( + Id: Guid.Parse("1a2b3c4d-5e6f-4a1b-8c2d-3e4f5a6b7c8d"), + Username: "john.doe"), + new UserDto( + Id: Guid.Parse("2b3c4d5e-6f7a-4b8c-9d0e-1f2a3b4c5d6e"), + Username: "jane.doe") + ]) + ); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/Index/StatisticsIndexViewEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/Index/StatisticsIndexViewEndpoint.cs new file mode 100644 index 00000000..a94ed37b --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/Index/StatisticsIndexViewEndpoint.cs @@ -0,0 +1,129 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Authorization; +using Lumina.Presentation.Web.Common.DTO.MediaConsumption; +using Lumina.Presentation.Web.Common.DTO.Themes; +using Lumina.Presentation.Web.Common.Primitives; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Common.Services; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Lumina.Presentation.Web.Core.Themes; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.Localization; +using System; +using System.Collections.Generic; +using System.Security.Claims; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Library.Statistics.Index; + +/// +/// API endpoint for the /{culture}/library/statistics route. +/// +public class StatisticsIndexViewEndpoint : BaseEndpoint +{ + // The resource base name deliberately excludes the "Core.Resources" segment: the localization factory re-roots it with the configured ResourcesPath. + private const string VIEW_RESOURCE_BASE_NAME = "Lumina.Presentation.Web.Views.Library.Statistics.Index"; + private const string VIEW_RESOURCE_LOCATION = "Lumina.Presentation.Web"; + // The page key mirrors the path of the Razor view under Core/Views, so that theme templates can override it at the page, section or default scope. + private const string VIEW_PAGE_KEY = "library/statistics/index"; + + private readonly IUrlService _urlService; + private readonly ThemePageRenderer _themePageRenderer; + private readonly IStringLocalizer _localizer; + private readonly IAuthorizationService _authorizationService; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for generating URLs from action and controller names, with localization. + /// Injected service for rendering themed pages. + /// Injected factory used to create the localizer of the view resources. + /// Injected service used to resolve the role of the current user. + public StatisticsIndexViewEndpoint(IUrlService urlService, ThemePageRenderer themePageRenderer, IStringLocalizerFactory stringLocalizerFactory, IAuthorizationService authorizationService) + { + _urlService = urlService; + _themePageRenderer = themePageRenderer; + _localizer = stringLocalizerFactory.Create(VIEW_RESOURCE_BASE_NAME, VIEW_RESOURCE_LOCATION); + _authorizationService = authorizationService; + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.GET); + Routes(WebRoutes.LibraryStatistics.INDEX); + DontAutoTag(); + Options(options => options.WithTags("Statistics")); + } + + /// + /// Displays the statistics page, rendered by the active theme with a fallback to the Razor view. + /// + /// The request object. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(EmptyRequest request, CancellationToken cancellationToken) + { + // The page shows the statistics of the authenticated user, so no intermediary may store it, and the response varies by the sign in cookie. + SetCacheControl("private, no-store"); + HttpContext.Response.Headers["Vary"] = "Cookie"; + string title = _localizer["Title"].Value; + bool isAdmin = await _authorizationService.IsInRoleAsync("Admin", cancellationToken).ConfigureAwait(false); + string? currentUserId = HttpContext.User.FindFirst(ClaimTypes.NameIdentifier)?.Value; + Guid? parsedCurrentUserId = Guid.TryParse(currentUserId, out Guid userId) ? userId : null; + + StatisticsPageDto page = new( + Title: title, + IsAdmin: isAdmin, + CurrentUserId: parsedCurrentUserId, + Culture: Culture, + GetStatisticsUrl: _urlService.GetAbsoluteUrl(WebRoutes.LibraryStatistics.GET_STATISTICS) ?? string.Empty, + GetAllUsersStatisticsUrl: _urlService.GetAbsoluteUrl(WebRoutes.LibraryStatistics.GET_ALL_USERS_STATISTICS) ?? string.Empty, + GetRecentlyConsumedUrl: _urlService.GetAbsoluteUrl(WebRoutes.LibraryStatistics.GET_RECENTLY_CONSUMED) ?? string.Empty, + GetMostConsumedUrl: _urlService.GetAbsoluteUrl(WebRoutes.LibraryStatistics.GET_MOST_CONSUMED) ?? string.Empty, + GetTagConsumptionUrl: _urlService.GetAbsoluteUrl(WebRoutes.LibraryStatistics.GET_TAG_CONSUMPTION) ?? string.Empty, + GetGenreConsumptionUrl: _urlService.GetAbsoluteUrl(WebRoutes.LibraryStatistics.GET_GENRE_CONSUMPTION) ?? string.Empty, + GetLibrariesUrl: _urlService.GetAbsoluteUrl(WebRoutes.LibraryStatistics.GET_LIBRARIES) ?? string.Empty, + GetUsersUrl: isAdmin ? _urlService.GetAbsoluteUrl(WebRoutes.LibraryStatistics.GET_USERS) ?? string.Empty : string.Empty, + DeleteConsumptionItemHistoryUrl: _urlService.GetAbsoluteUrl(WebRoutes.LibraryStatistics.DELETE_CONSUMPTION_ITEM_HISTORY) ?? string.Empty, + ClearConsumptionHistoryUrl: _urlService.GetAbsoluteUrl(WebRoutes.LibraryStatistics.CLEAR_CONSUMPTION_HISTORY) ?? string.Empty, + ClearResumePointsUrl: _urlService.GetAbsoluteUrl(WebRoutes.LibraryStatistics.CLEAR_RESUME_POINTS) ?? string.Empty + ); + + ThemePageDto pageModel = new() + { + PageKey = VIEW_PAGE_KEY, + Title = title, + Description = string.Empty, + PageData = new Dictionary + { + ["getStatisticsUrl"] = page.GetStatisticsUrl, + ["getAllUsersStatisticsUrl"] = page.GetAllUsersStatisticsUrl, + ["getRecentlyConsumedUrl"] = page.GetRecentlyConsumedUrl, + ["getMostConsumedUrl"] = page.GetMostConsumedUrl, + ["getTagConsumptionUrl"] = page.GetTagConsumptionUrl, + ["getGenreConsumptionUrl"] = page.GetGenreConsumptionUrl, + ["getLibrariesUrl"] = page.GetLibrariesUrl, + ["getUsersUrl"] = page.GetUsersUrl, + ["deleteConsumptionItemHistoryUrl"] = page.DeleteConsumptionItemHistoryUrl, + ["clearConsumptionHistoryUrl"] = page.ClearConsumptionHistoryUrl, + ["clearResumePointsUrl"] = page.ClearResumePointsUrl, + ["culture"] = page.Culture, + ["isAdmin"] = page.IsAdmin, + ["currentUserId"] = page.CurrentUserId, + ["strings"] = ThemePageDataFactory.CreateLocalizedStrings(_localizer) + } + }; + + Result sectionResult = await _themePageRenderer.RenderAsync(pageModel, requestedThemeId: null, cancellationToken).ConfigureAwait(false); + if (sectionResult.IsFailure) + return View("/Core/Views/Library/Statistics/Index.cshtml", page, new Dictionary { ["Title"] = title }); + + return View("/Core/Views/Shared/_ThemedView.cshtml", new ThemeViewDto(sectionResult.Value.Content, sectionResult.Value.Script), new Dictionary { ["Title"] = title }); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/Index/StatisticsIndexViewEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/Index/StatisticsIndexViewEndpointSummary.cs new file mode 100644 index 00000000..28902d13 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/Index/StatisticsIndexViewEndpointSummary.cs @@ -0,0 +1,24 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Library.Statistics.Index; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class StatisticsIndexViewEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public StatisticsIndexViewEndpointSummary() + { + Summary = "Renders the statistics page."; + Description = "Renders the page that shows the consumption statistics of the selected user: the total consumed duration, the counted sessions, the completed sessions, the stopped sessions, the completion rate, the per media kind breakdown, the tag and genre breakdown, and the recently consumed and most consumed media items. The page filters by library, media kind, and date range. An administrator can select another user or all users; a regular user sees only their own statistics. The page also offers the deletion of a history row, the clearing of the history, and the removal of the resume points."; + + Response(200, "The statistics page is rendered."); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetLibraryItems/GetLibraryItemsEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetLibraryItems/GetLibraryItemsEndpoint.cs index ff26b11a..029743e8 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetLibraryItems/GetLibraryItemsEndpoint.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetLibraryItems/GetLibraryItemsEndpoint.cs @@ -1,6 +1,7 @@ #region ========================================================================= USING ===================================================================================== using FastEndpoints; using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.Common; using Lumina.Presentation.Web.Common.DTO.Libraries; using Lumina.Presentation.Web.Common.Requests.Libraries; using Lumina.Presentation.Web.Common.Routes; @@ -50,7 +51,7 @@ public class GetLibraryItemsEndpoint : BaseEndpointCancellation token that can be used to stop the execution. public override async Task ExecuteAsync(GetBooksLiteRequest request, CancellationToken cancellationToken) { - PaginatedBookLiteDto response = await _apiHttpClient.GetAsync(BuildItemsEndpoint(request), cancellationToken).ConfigureAwait(false); + PaginatedDto response = await _apiHttpClient.GetAsync>(BuildItemsEndpoint(request), cancellationToken).ConfigureAwait(false); return JsonSuccess(response); } diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetLibraryItems/GetLibraryItemsEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetLibraryItems/GetLibraryItemsEndpointSummary.cs index 4e610fb3..91e12d04 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetLibraryItems/GetLibraryItemsEndpointSummary.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetLibraryItems/GetLibraryItemsEndpointSummary.cs @@ -44,6 +44,6 @@ public class GetLibraryItemsEndpointSummary : Summary(true, default)); + Response(200, "The lightweight details of the books of the media library are returned.", example: new SuccessResponse>(true, default)); } } diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/MediaConsumption/CompleteConsumption/CompleteConsumptionEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/MediaConsumption/CompleteConsumption/CompleteConsumptionEndpoint.cs new file mode 100644 index 00000000..2dc19a9f --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/MediaConsumption/CompleteConsumption/CompleteConsumptionEndpoint.cs @@ -0,0 +1,66 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.MediaConsumption; +using Lumina.Presentation.Web.Common.Requests.MediaConsumption; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.MediaConsumption.CompleteConsumption; + +/// +/// API endpoint for the /{culture}/media-consumption/api-complete-consumption/{recordId} route. +/// +public class CompleteConsumptionEndpoint : BaseEndpoint +{ + private readonly IApiHttpClient _apiHttpClient; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for interactions with the API. + public CompleteConsumptionEndpoint(IApiHttpClient apiHttpClient) + { + _apiHttpClient = apiHttpClient; + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.POST); + Routes(WebRoutes.MediaConsumption.COMPLETE_CONSUMPTION); + DontAutoTag(); + Options(options => options.WithTags("MediaConsumption")); + EnableAntiforgery(); + } + + /// + /// Completes a consumption session of the current user. + /// + /// The request containing the final position, fraction, and consumed duration of the session. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(CompleteConsumptionRequest request, CancellationToken cancellationToken) + { + // The consumption record belongs to the current user, so no intermediary may store the response, and it varies by the sign in cookie. + HttpContext.Response.Headers["Cache-Control"] = "private, no-store"; + HttpContext.Response.Headers["Vary"] = "Cookie"; + // The record is identified by the route value, not by any id posted in the body. + string routeRecordId = HttpContext.Request.RouteValues["recordId"]?.ToString() ?? string.Empty; + string recordId = Guid.TryParse(routeRecordId, out Guid parsedRecordId) ? parsedRecordId.ToString() : Guid.Empty.ToString(); + ConsumptionRecordDto record = await _apiHttpClient + .PostAsync( + ApiRoutes.MediaConsumption.COMPLETE_CONSUMPTION.Replace("{recordId}", recordId, StringComparison.Ordinal), + request, + cancellationToken).ConfigureAwait(false); + return JsonSuccess(record); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/MediaConsumption/CompleteConsumption/CompleteConsumptionEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/MediaConsumption/CompleteConsumption/CompleteConsumptionEndpointSummary.cs new file mode 100644 index 00000000..1274e4fa --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/MediaConsumption/CompleteConsumption/CompleteConsumptionEndpointSummary.cs @@ -0,0 +1,56 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.DTO.Common; +using Lumina.Presentation.Web.Common.DTO.MediaConsumption; +using Lumina.Presentation.Web.Common.Enums.MediaConsumption; +using Lumina.Presentation.Web.Common.Requests.MediaConsumption; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.MediaConsumption.CompleteConsumption; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class CompleteConsumptionEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public CompleteConsumptionEndpointSummary() + { + Summary = "Completes a consumption session of the current user."; + Description = "Proxies the completion of an in-progress consumption session to the API server. The final position, progress fraction, and active consumed duration are stored, and the resume point of the media item is deleted. A record of another user is reported with the same not found result as a missing record."; + + Params["recordId"] = "The Id of the consumption record."; + + ExampleRequest = new CompleteConsumptionRequest( + Position: new MediaPositionRequest("TimeOffset", 100, null), + ProgressFraction: 1, + ConsumedDurationInSeconds: 100, + ConsecutivePagesRead: 0 + ); + RequestParam(request => request.Position, "The final position reported for the media item, if the client knows it. It carries the position Kind, and either TimeOffsetSeconds or Location. Optional."); + RequestParam(request => request.ProgressFraction, "The fraction of the media item that the client reached, between 0 and 1. Required."); + RequestParam(request => request.ConsumedDurationInSeconds, "The active duration consumed by the session, in seconds. Required."); + RequestParam(request => request.ConsecutivePagesRead, "The number of consecutive pages read in the session, used by page based media such as books. It must be omitted or zero for other kinds; a positive value is rejected with a forbidden error. When omitted, the count stored by the last progress report is kept. Optional."); + + Response(200, "The consumption session is completed and the updated record is returned.", + example: new SuccessResponse(true, new ConsumptionRecordDto( + Id: Guid.Parse("2c1b0a9f-8e7d-4c6b-5a4f-3e2d1c0b9a8f"), + LibraryId: Guid.Parse("3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a"), + MediaItemId: Guid.Parse("9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f"), + MediaKind: MediaKind.MusicTrack, + Status: ConsumptionStatus.Completed, + StartedOnUtc: new DateTime(2026, 10, 24, 12, 0, 0, DateTimeKind.Utc), + LastActivityOnUtc: new DateTime(2026, 10, 24, 12, 1, 40, DateTimeKind.Utc), + EndedOnUtc: new DateTime(2026, 10, 24, 12, 1, 40, DateTimeKind.Utc), + ConsumedDurationInSeconds: 100, + LastPosition: new MediaPositionDto(MediaPositionKind.TimeOffset, 100, null), + LastProgressFraction: 1, + ConsecutivePagesRead: 0)) + ); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/MediaConsumption/GetResumePoint/GetResumePointEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/MediaConsumption/GetResumePoint/GetResumePointEndpoint.cs new file mode 100644 index 00000000..b827eb65 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/MediaConsumption/GetResumePoint/GetResumePointEndpoint.cs @@ -0,0 +1,87 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.MediaConsumption; +using Lumina.Presentation.Web.Common.Enums.MediaConsumption; +using Lumina.Presentation.Web.Common.Exceptions; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System; +using System.Net; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.MediaConsumption.GetResumePoint; + +/// +/// API endpoint for the /{culture}/media-consumption/api-get-resume-point/{mediaKind}/{mediaItemId} route. +/// +public class GetResumePointEndpoint : BaseEndpoint +{ + // A value that is not a name of MediaKind, so the API rejects a crafted route value with its own validation error. + private const string INVALID_MEDIA_KIND_PLACEHOLDER = "Invalid"; + + private readonly IApiHttpClient _apiHttpClient; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for interactions with the API. + public GetResumePointEndpoint(IApiHttpClient apiHttpClient) + { + _apiHttpClient = apiHttpClient; + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.GET); + Routes(WebRoutes.MediaConsumption.GET_RESUME_POINT); + DontAutoTag(); + Options(options => options.WithTags("MediaConsumption")); + } + + /// + /// Retrieves the resume point of the current user for a media item. + /// + /// The request object. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(EmptyRequest request, CancellationToken cancellationToken) + { + // The resume point belongs to the current user, so no intermediary may store the response, and it varies by the sign in cookie. + HttpContext.Response.Headers["Cache-Control"] = "private, no-store"; + HttpContext.Response.Headers.Append("Vary", "Cookie"); + // The identifiers are taken from the route, so they cannot be replaced by values posted in the body. + // The media kind must be the name of a MediaKind member, which also rejects numeric strings, comma separated lists, and + // dot segments that escaping alone would leave in the relative path of the upstream request. + string routeMediaKind = HttpContext.Request.RouteValues["mediaKind"]?.ToString() ?? string.Empty; + string mediaKind = INVALID_MEDIA_KIND_PLACEHOLDER; + foreach (string mediaKindName in Enum.GetNames()) + if (string.Equals(mediaKindName, routeMediaKind, StringComparison.OrdinalIgnoreCase)) + mediaKind = mediaKindName; + string routeMediaItemId = HttpContext.Request.RouteValues["mediaItemId"]?.ToString() ?? string.Empty; + string mediaItemId = Guid.TryParse(routeMediaItemId, out Guid parsedMediaItemId) ? parsedMediaItemId.ToString() : Guid.Empty.ToString(); + string endpoint = ApiRoutes.MediaConsumption.GET_RESUME_POINT + .Replace("{mediaKind}", mediaKind, StringComparison.Ordinal) + .Replace("{mediaItemId}", mediaItemId, StringComparison.Ordinal); + try + { + ResumePointDto resumePoint = await _apiHttpClient.GetAsync(endpoint, cancellationToken).ConfigureAwait(false); + return JsonSuccess(resumePoint); + } + catch (ApiException apiException) when (apiException.HttpStatusCode == HttpStatusCode.NotFound && + apiException.ProblemDetails?.Detail is "MediaResumePointNotFound" or "BookNotFound" or "TrackNotFound") + { + // Only an absent resume point, and the missing or moved media item that turns an existing resume point into an orphan, + // mean that there is nothing to resume. Any other 404, such as a route or API version mismatch, is rethrown so it is + // logged and reported instead of being disguised as an empty resume point. + return JsonSuccess(null); + } + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/MediaConsumption/GetResumePoint/GetResumePointEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/MediaConsumption/GetResumePoint/GetResumePointEndpointSummary.cs new file mode 100644 index 00000000..e9e8d1cb --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/MediaConsumption/GetResumePoint/GetResumePointEndpointSummary.cs @@ -0,0 +1,40 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.DTO.Common; +using Lumina.Presentation.Web.Common.DTO.MediaConsumption; +using Lumina.Presentation.Web.Common.Enums.MediaConsumption; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.MediaConsumption.GetResumePoint; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class GetResumePointEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public GetResumePointEndpointSummary() + { + Summary = "Retrieves the resume point of the current user for a media item."; + Description = "Proxies the retrieval of the point at which the current user can resume a media item to the API server. The book reader calls it with the Book kind and the Id of the book it opens. A book resume point carries an opaque Location, while a music track resume point carries a TimeOffset. When the user has no resume point for the media item, or the media item no longer exists, the response succeeds without data instead of failing, so a reader can fall back to the beginning of the item. Any other upstream failure is rethrown to the application error handling, so a route or version mismatch is not mistaken for an absent resume point."; + + Params["mediaKind"] = "The kind of media to resume. Only the member names of MediaKind are accepted, such as Book or MusicTrack. Numeric values are rejected."; + Params["mediaItemId"] = "The Id of the media item to resume."; + + Response(200, "The resume point of the current user is returned, or no data when the user has none.", "application/json", + example: new SuccessResponse(true, new ResumePointDto( + Id: Guid.Parse("4d5e6f70-8192-4a3b-9c4d-5e6f708192a3"), + LibraryId: Guid.Parse("3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a"), + MediaItemId: Guid.Parse("7a6b5c4d-3e2f-4a1b-8c9d-0e1f2a3b4c5d"), + MediaKind: MediaKind.Book, + LastPosition: new MediaPositionDto(MediaPositionKind.Location, null, "epubcfi(/6/4[chapter-3]!/4/2/2)"), + LastProgressFraction: 0.42, + LastConsumedOnUtc: new DateTime(2026, 10, 24, 12, 12, 0, DateTimeKind.Utc))) + ); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/MediaConsumption/ReportConsumptionProgress/ReportConsumptionProgressEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/MediaConsumption/ReportConsumptionProgress/ReportConsumptionProgressEndpoint.cs new file mode 100644 index 00000000..9496839c --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/MediaConsumption/ReportConsumptionProgress/ReportConsumptionProgressEndpoint.cs @@ -0,0 +1,66 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.MediaConsumption; +using Lumina.Presentation.Web.Common.Requests.MediaConsumption; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.MediaConsumption.ReportConsumptionProgress; + +/// +/// API endpoint for the /{culture}/media-consumption/api-report-consumption-progress/{recordId} route. +/// +public class ReportConsumptionProgressEndpoint : BaseEndpoint +{ + private readonly IApiHttpClient _apiHttpClient; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for interactions with the API. + public ReportConsumptionProgressEndpoint(IApiHttpClient apiHttpClient) + { + _apiHttpClient = apiHttpClient; + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.PUT); + Routes(WebRoutes.MediaConsumption.REPORT_CONSUMPTION_PROGRESS); + DontAutoTag(); + Options(options => options.WithTags("MediaConsumption")); + EnableAntiforgery(); + } + + /// + /// Reports the progress of a consumption session of the current user. + /// + /// The request containing the latest position, fraction, and consumed duration of the session. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(ReportConsumptionProgressRequest request, CancellationToken cancellationToken) + { + // The consumption record belongs to the current user, so no intermediary may store the response, and it varies by the sign in cookie. + HttpContext.Response.Headers["Cache-Control"] = "private, no-store"; + HttpContext.Response.Headers["Vary"] = "Cookie"; + // The record is identified by the route value, not by any id posted in the body. + string routeRecordId = HttpContext.Request.RouteValues["recordId"]?.ToString() ?? string.Empty; + string recordId = Guid.TryParse(routeRecordId, out Guid parsedRecordId) ? parsedRecordId.ToString() : Guid.Empty.ToString(); + ConsumptionRecordDto record = await _apiHttpClient + .PutAsync( + ApiRoutes.MediaConsumption.REPORT_CONSUMPTION_PROGRESS.Replace("{recordId}", recordId, StringComparison.Ordinal), + request, + cancellationToken).ConfigureAwait(false); + return JsonSuccess(record); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/MediaConsumption/ReportConsumptionProgress/ReportConsumptionProgressEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/MediaConsumption/ReportConsumptionProgress/ReportConsumptionProgressEndpointSummary.cs new file mode 100644 index 00000000..9cfaa97e --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/MediaConsumption/ReportConsumptionProgress/ReportConsumptionProgressEndpointSummary.cs @@ -0,0 +1,62 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.DTO.Common; +using Lumina.Presentation.Web.Common.DTO.MediaConsumption; +using Lumina.Presentation.Web.Common.Enums.MediaConsumption; +using Lumina.Presentation.Web.Common.Requests.MediaConsumption; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.MediaConsumption.ReportConsumptionProgress; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class ReportConsumptionProgressEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public ReportConsumptionProgressEndpointSummary() + { + Summary = "Reports the progress of a consumption session of the current user."; + Description = "Proxies the latest position, progress fraction, and active consumed duration of an in-progress consumption session to the API server. The position and the progress fraction are the latest reported values and may move backwards. The consumed duration is the only monotonic measurement. A record of another user is reported with the same not found result as a missing record."; + + Params["recordId"] = "The Id of the consumption record."; + + ExampleRequest = new ReportConsumptionProgressRequest( + Position: new MediaPositionRequest("TimeOffset", 92.5, null), + ProgressFraction: 0.31, + ConsumedDurationInSeconds: 92.5, + ConsecutivePagesRead: 0 + ); + RequestExamples.Add(new RequestExample(new ReportConsumptionProgressRequest( + Position: new MediaPositionRequest("Location", null, "epubcfi(/6/4[chapter-3]!/4/2/2)"), + ProgressFraction: 0.42, + ConsumedDurationInSeconds: 240, + ConsecutivePagesRead: 2 + ))); + RequestParam(request => request.Position, "The last position reported for the media item, if the client knows it. It carries the position Kind, and either TimeOffsetSeconds or Location. Optional."); + RequestParam(request => request.ProgressFraction, "The fraction of the media item that the client reached, between 0 and 1. Required."); + RequestParam(request => request.ConsumedDurationInSeconds, "The active duration consumed by the session, in seconds. Required."); + RequestParam(request => request.ConsecutivePagesRead, "The number of consecutive pages read in the current session, used by page based media such as books. It must be zero for other kinds; a positive value is rejected with a forbidden error. Optional, defaults to 0."); + + Response(200, "The progress of the consumption session is reported and the updated record is returned.", + example: new SuccessResponse(true, new ConsumptionRecordDto( + Id: Guid.Parse("2c1b0a9f-8e7d-4c6b-5a4f-3e2d1c0b9a8f"), + LibraryId: Guid.Parse("3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a"), + MediaItemId: Guid.Parse("9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f"), + MediaKind: MediaKind.MusicTrack, + Status: ConsumptionStatus.InProgress, + StartedOnUtc: new DateTime(2026, 10, 24, 12, 0, 0, DateTimeKind.Utc), + LastActivityOnUtc: new DateTime(2026, 10, 24, 12, 1, 32, 500, DateTimeKind.Utc), + EndedOnUtc: null, + ConsumedDurationInSeconds: 92.5, + LastPosition: new MediaPositionDto(MediaPositionKind.TimeOffset, 92.5, null), + LastProgressFraction: 0.31, + ConsecutivePagesRead: 0)) + ); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/MediaConsumption/StartConsumption/StartConsumptionEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/MediaConsumption/StartConsumption/StartConsumptionEndpoint.cs new file mode 100644 index 00000000..1023d1a9 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/MediaConsumption/StartConsumption/StartConsumptionEndpoint.cs @@ -0,0 +1,78 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.MediaConsumption; +using Lumina.Presentation.Web.Common.Enums.MediaConsumption; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.MediaConsumption.StartConsumption; + +/// +/// API endpoint for the /{culture}/media-consumption/api-start-consumption/{libraryId}/{mediaKind}/{mediaItemId} route. +/// +public class StartConsumptionEndpoint : BaseEndpoint +{ + // A value that is not a name of MediaKind, so the API rejects a crafted route value with its own validation error. + private const string INVALID_MEDIA_KIND_PLACEHOLDER = "Invalid"; + + private readonly IApiHttpClient _apiHttpClient; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for interactions with the API. + public StartConsumptionEndpoint(IApiHttpClient apiHttpClient) + { + _apiHttpClient = apiHttpClient; + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.POST); + Routes(WebRoutes.MediaConsumption.START_CONSUMPTION); + DontAutoTag(); + Options(options => options.WithTags("MediaConsumption")); + EnableAntiforgery(); + } + + /// + /// Starts a consumption session of a media item for the current user. + /// + /// The request object. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(EmptyRequest request, CancellationToken cancellationToken) + { + // The consumption record belongs to the current user, so no intermediary may store the response, and it varies by the sign in cookie. + HttpContext.Response.Headers["Cache-Control"] = "private, no-store"; + HttpContext.Response.Headers["Vary"] = "Cookie"; + // The identifiers are taken from the route, so they cannot be replaced by values posted in the body. + // The media kind must be the name of a MediaKind member, which also rejects numeric strings, comma separated lists, and + // dot segments that escaping alone would leave in the relative path of the upstream request. + string routeLibraryId = HttpContext.Request.RouteValues["libraryId"]?.ToString() ?? string.Empty; + string libraryId = Guid.TryParse(routeLibraryId, out Guid parsedLibraryId) ? parsedLibraryId.ToString() : Guid.Empty.ToString(); + string routeMediaKind = HttpContext.Request.RouteValues["mediaKind"]?.ToString() ?? string.Empty; + string mediaKind = INVALID_MEDIA_KIND_PLACEHOLDER; + foreach (string mediaKindName in Enum.GetNames()) + if (string.Equals(mediaKindName, routeMediaKind, StringComparison.OrdinalIgnoreCase)) + mediaKind = mediaKindName; + string routeMediaItemId = HttpContext.Request.RouteValues["mediaItemId"]?.ToString() ?? string.Empty; + string mediaItemId = Guid.TryParse(routeMediaItemId, out Guid parsedMediaItemId) ? parsedMediaItemId.ToString() : Guid.Empty.ToString(); + string endpoint = ApiRoutes.MediaConsumption.START_CONSUMPTION + .Replace("{libraryId}", libraryId, StringComparison.Ordinal) + .Replace("{mediaKind}", mediaKind, StringComparison.Ordinal) + .Replace("{mediaItemId}", mediaItemId, StringComparison.Ordinal); + ConsumptionRecordDto record = await _apiHttpClient.PostAsync(endpoint, request, cancellationToken).ConfigureAwait(false); + return JsonSuccess(record); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/MediaConsumption/StartConsumption/StartConsumptionEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/MediaConsumption/StartConsumption/StartConsumptionEndpointSummary.cs new file mode 100644 index 00000000..0991e92f --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/MediaConsumption/StartConsumption/StartConsumptionEndpointSummary.cs @@ -0,0 +1,46 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.DTO.Common; +using Lumina.Presentation.Web.Common.DTO.MediaConsumption; +using Lumina.Presentation.Web.Common.Enums.MediaConsumption; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.MediaConsumption.StartConsumption; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class StartConsumptionEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public StartConsumptionEndpointSummary() + { + Summary = "Starts a media consumption session of the current user."; + Description = "Proxies the start of a consumption record to the API server. The audio player calls it when a track actually begins playback. When the library tracks progress, the returned record carries the stored resume position. A missing media item and a media item that belongs to another library are reported with the same not found result."; + + Params["libraryId"] = "The Id of the media library that contains the media item."; + Params["mediaKind"] = "The kind of media that is consumed. Only the member names of MediaKind are accepted, such as MusicTrack or Book. Numeric values are rejected."; + Params["mediaItemId"] = "The Id of the consumed media item."; + + Response(200, "The consumption record is started and returned.", + example: new SuccessResponse(true, new ConsumptionRecordDto( + Id: Guid.Parse("2c1b0a9f-8e7d-4c6b-5a4f-3e2d1c0b9a8f"), + LibraryId: Guid.Parse("3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a"), + MediaItemId: Guid.Parse("9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f"), + MediaKind: MediaKind.MusicTrack, + Status: ConsumptionStatus.InProgress, + StartedOnUtc: new DateTime(2026, 10, 24, 12, 0, 0, DateTimeKind.Utc), + LastActivityOnUtc: new DateTime(2026, 10, 24, 12, 0, 0, DateTimeKind.Utc), + EndedOnUtc: null, + ConsumedDurationInSeconds: 0, + LastPosition: null, + LastProgressFraction: 0, + ConsecutivePagesRead: 0)) + ); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/MediaConsumption/StopConsumption/StopConsumptionEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/MediaConsumption/StopConsumption/StopConsumptionEndpoint.cs new file mode 100644 index 00000000..19616e5b --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/MediaConsumption/StopConsumption/StopConsumptionEndpoint.cs @@ -0,0 +1,66 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.MediaConsumption; +using Lumina.Presentation.Web.Common.Requests.MediaConsumption; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.MediaConsumption.StopConsumption; + +/// +/// API endpoint for the /{culture}/media-consumption/api-stop-consumption/{recordId} route. +/// +public class StopConsumptionEndpoint : BaseEndpoint +{ + private readonly IApiHttpClient _apiHttpClient; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for interactions with the API. + public StopConsumptionEndpoint(IApiHttpClient apiHttpClient) + { + _apiHttpClient = apiHttpClient; + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.POST); + Routes(WebRoutes.MediaConsumption.STOP_CONSUMPTION); + DontAutoTag(); + Options(options => options.WithTags("MediaConsumption")); + EnableAntiforgery(); + } + + /// + /// Stops a consumption session of the current user. + /// + /// The request containing the final position, fraction, and consumed duration of the session. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(StopConsumptionRequest request, CancellationToken cancellationToken) + { + // The consumption record belongs to the current user, so no intermediary may store the response, and it varies by the sign in cookie. + HttpContext.Response.Headers["Cache-Control"] = "private, no-store"; + HttpContext.Response.Headers["Vary"] = "Cookie"; + // The record is identified by the route value, not by any id posted in the body. + string routeRecordId = HttpContext.Request.RouteValues["recordId"]?.ToString() ?? string.Empty; + string recordId = Guid.TryParse(routeRecordId, out Guid parsedRecordId) ? parsedRecordId.ToString() : Guid.Empty.ToString(); + ConsumptionRecordDto record = await _apiHttpClient + .PostAsync( + ApiRoutes.MediaConsumption.STOP_CONSUMPTION.Replace("{recordId}", recordId, StringComparison.Ordinal), + request, + cancellationToken).ConfigureAwait(false); + return JsonSuccess(record); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/MediaConsumption/StopConsumption/StopConsumptionEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/MediaConsumption/StopConsumption/StopConsumptionEndpointSummary.cs new file mode 100644 index 00000000..71e4b987 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/MediaConsumption/StopConsumption/StopConsumptionEndpointSummary.cs @@ -0,0 +1,56 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.DTO.Common; +using Lumina.Presentation.Web.Common.DTO.MediaConsumption; +using Lumina.Presentation.Web.Common.Enums.MediaConsumption; +using Lumina.Presentation.Web.Common.Requests.MediaConsumption; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.MediaConsumption.StopConsumption; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class StopConsumptionEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public StopConsumptionEndpointSummary() + { + Summary = "Stops a consumption session of the current user."; + Description = "Proxies the stop of an in-progress consumption session to the API server. The final position, progress fraction, and active consumed duration are stored. The API decides whether the session stopped below the completion threshold of its library, or completed at or above it. A record of another user is reported with the same not found result as a missing record."; + + Params["recordId"] = "The Id of the consumption record."; + + ExampleRequest = new StopConsumptionRequest( + Position: new MediaPositionRequest("TimeOffset", 92.5, null), + ProgressFraction: 0.31, + ConsumedDurationInSeconds: 92.5, + ConsecutivePagesRead: 0 + ); + RequestParam(request => request.Position, "The final position reported for the media item, if the client knows it. It carries the position Kind, and either TimeOffsetSeconds or Location. Optional."); + RequestParam(request => request.ProgressFraction, "The fraction of the media item that the client reached, between 0 and 1. Required."); + RequestParam(request => request.ConsumedDurationInSeconds, "The active duration consumed by the session, in seconds. Required."); + RequestParam(request => request.ConsecutivePagesRead, "The number of consecutive pages read in the session, used by page based media such as books. It must be omitted or zero for other kinds; a positive value is rejected with a forbidden error. When omitted, the count stored by the last progress report is kept. Optional."); + + Response(200, "The consumption session is stopped and the updated record is returned.", + example: new SuccessResponse(true, new ConsumptionRecordDto( + Id: Guid.Parse("2c1b0a9f-8e7d-4c6b-5a4f-3e2d1c0b9a8f"), + LibraryId: Guid.Parse("3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a"), + MediaItemId: Guid.Parse("9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f"), + MediaKind: MediaKind.MusicTrack, + Status: ConsumptionStatus.Stopped, + StartedOnUtc: new DateTime(2026, 10, 24, 12, 0, 0, DateTimeKind.Utc), + LastActivityOnUtc: new DateTime(2026, 10, 24, 12, 1, 32, 500, DateTimeKind.Utc), + EndedOnUtc: new DateTime(2026, 10, 24, 12, 1, 32, 500, DateTimeKind.Utc), + ConsumedDurationInSeconds: 92.5, + LastPosition: new MediaPositionDto(MediaPositionKind.TimeOffset, 92.5, null), + LastProgressFraction: 0.31, + ConsecutivePagesRead: 0)) + ); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/AddPlaylistEntries/AddPlaylistEntriesEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/AddPlaylistEntries/AddPlaylistEntriesEndpoint.cs new file mode 100644 index 00000000..e3a9921a --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/AddPlaylistEntries/AddPlaylistEntriesEndpoint.cs @@ -0,0 +1,60 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.Playlists; +using Lumina.Presentation.Web.Common.Requests.Playlists; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Playlists.AddPlaylistEntries; + +/// +/// API endpoint for the /{culture}/playlists/item/{playlistId}/api-add-entries route. +/// +public class AddPlaylistEntriesEndpoint : BaseEndpoint +{ + private readonly IApiHttpClient _apiHttpClient; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for interactions with the API. + public AddPlaylistEntriesEndpoint(IApiHttpClient apiHttpClient) + { + _apiHttpClient = apiHttpClient; + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.POST); + Routes(WebRoutes.Playlists.ADD_PLAYLIST_ENTRIES); + DontAutoTag(); + Options(options => options.WithTags("Playlists")); + EnableAntiforgery(); + } + + /// + /// Adds several tracks to a playlist of the current user, in order. + /// + /// The request containing the tracks to add. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(AddPlaylistEntriesRequest request, CancellationToken cancellationToken) + { + // The playlist is identified by the route value, not by any id posted in the body. + string routePlaylistId = HttpContext.Request.RouteValues["playlistId"]?.ToString() ?? string.Empty; + string playlistId = Guid.TryParse(routePlaylistId, out Guid parsedPlaylistId) ? parsedPlaylistId.ToString() : Guid.Empty.ToString(); + PlaylistEntriesAddedDto playlist = await _apiHttpClient + .PostAsync(ApiRoutes.Playlists.ADD_PLAYLIST_ENTRIES.Replace("{playlistId}", playlistId), request, cancellationToken).ConfigureAwait(false); + return JsonSuccess(playlist); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/AddPlaylistEntries/AddPlaylistEntriesEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/AddPlaylistEntries/AddPlaylistEntriesEndpointSummary.cs new file mode 100644 index 00000000..4d907f34 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/AddPlaylistEntries/AddPlaylistEntriesEndpointSummary.cs @@ -0,0 +1,41 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.DTO.Common; +using Lumina.Presentation.Web.Common.DTO.Playlists; +using Lumina.Presentation.Web.Common.Requests.Playlists; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Playlists.AddPlaylistEntries; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class AddPlaylistEntriesEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public AddPlaylistEntriesEndpointSummary() + { + Summary = "Adds several tracks to a playlist of the current user."; + Description = "Proxies the request that adds several tracks, in order, to a playlist to the API server. The audio player uses it to add its current queue to a playlist. The number of added entries and the playlist activity time are returned."; + + Params["playlistId"] = "The Id of the playlist to add the tracks to."; + + ExampleRequest = new AddPlaylistEntriesRequest( + TrackIds: + [ + Guid.Parse("9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f"), + Guid.Parse("8e1f2a3b-4c5d-4e6f-8a9b-0c1d2e3f4a5b") + ] + ); + RequestParam(request => request.TrackIds, "The Ids of the tracks to add, in the order they must take. Required."); + + Response(200, "The tracks were added and the number of added entries is returned.", + example: new SuccessResponse(true, default) + ); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/AddPlaylistEntry/AddPlaylistEntryEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/AddPlaylistEntry/AddPlaylistEntryEndpoint.cs new file mode 100644 index 00000000..b29cf49d --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/AddPlaylistEntry/AddPlaylistEntryEndpoint.cs @@ -0,0 +1,60 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.Playlists; +using Lumina.Presentation.Web.Common.Requests.Playlists; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Playlists.AddPlaylistEntry; + +/// +/// API endpoint for the /{culture}/playlists/item/{playlistId}/entries/api-add-entry route. +/// +public class AddPlaylistEntryEndpoint : BaseEndpoint +{ + private readonly IApiHttpClient _apiHttpClient; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for interactions with the API. + public AddPlaylistEntryEndpoint(IApiHttpClient apiHttpClient) + { + _apiHttpClient = apiHttpClient; + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.POST); + Routes(WebRoutes.Playlists.ADD_PLAYLIST_ENTRY); + DontAutoTag(); + Options(options => options.WithTags("Playlists")); + EnableAntiforgery(); + } + + /// + /// Adds a track to a playlist of the current user. + /// + /// The request containing the track to add. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(AddPlaylistEntryRequest request, CancellationToken cancellationToken) + { + // The playlist is identified by the route value, not by any id posted in the body. + string routePlaylistId = HttpContext.Request.RouteValues["playlistId"]?.ToString() ?? string.Empty; + string playlistId = Guid.TryParse(routePlaylistId, out Guid parsedPlaylistId) ? parsedPlaylistId.ToString() : Guid.Empty.ToString(); + PlaylistEntryAddedDto playlist = await _apiHttpClient + .PostAsync(ApiRoutes.Playlists.ADD_PLAYLIST_ENTRY.Replace("{playlistId}", playlistId), request, cancellationToken).ConfigureAwait(false); + return JsonSuccess(playlist); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/AddPlaylistEntry/AddPlaylistEntryEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/AddPlaylistEntry/AddPlaylistEntryEndpointSummary.cs new file mode 100644 index 00000000..e85c28ad --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/AddPlaylistEntry/AddPlaylistEntryEndpointSummary.cs @@ -0,0 +1,37 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.DTO.Common; +using Lumina.Presentation.Web.Common.DTO.Playlists; +using Lumina.Presentation.Web.Common.Requests.Playlists; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Playlists.AddPlaylistEntry; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class AddPlaylistEntryEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public AddPlaylistEntryEndpointSummary() + { + Summary = "Adds a track to a playlist of the current user."; + Description = "Proxies the request that adds a track to a playlist to the API server. The added entry and the playlist activity time are returned."; + + Params["playlistId"] = "The Id of the playlist to add the track to."; + + ExampleRequest = new AddPlaylistEntryRequest( + TrackId: Guid.Parse("9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f") + ); + RequestParam(request => request.TrackId, "The Id of the track to add. Required."); + + Response(200, "The track was added and the resulting entry is returned.", + example: new SuccessResponse(true, default) + ); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/AddPlaylistScopeEntries/AddPlaylistScopeEntriesEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/AddPlaylistScopeEntries/AddPlaylistScopeEntriesEndpoint.cs new file mode 100644 index 00000000..bbc1fe43 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/AddPlaylistScopeEntries/AddPlaylistScopeEntriesEndpoint.cs @@ -0,0 +1,60 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.Playlists; +using Lumina.Presentation.Web.Common.Requests.Playlists; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Playlists.AddPlaylistScopeEntries; + +/// +/// API endpoint for the /{culture}/playlists/item/{playlistId}/api-add-scope-entries route. +/// +public class AddPlaylistScopeEntriesEndpoint : BaseEndpoint +{ + private readonly IApiHttpClient _apiHttpClient; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for interactions with the API. + public AddPlaylistScopeEntriesEndpoint(IApiHttpClient apiHttpClient) + { + _apiHttpClient = apiHttpClient; + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.POST); + Routes(WebRoutes.Playlists.ADD_PLAYLIST_SCOPE_ENTRIES); + DontAutoTag(); + Options(options => options.WithTags("Playlists")); + EnableAntiforgery(); + } + + /// + /// Adds every track of a music library, an artist or an album to a playlist of the current user. + /// + /// The request containing the scope whose tracks are appended. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(AddPlaylistScopeEntriesRequest request, CancellationToken cancellationToken) + { + // The playlist is identified by the route value, not by any id posted in the body. + string routePlaylistId = HttpContext.Request.RouteValues["playlistId"]?.ToString() ?? string.Empty; + string playlistId = Guid.TryParse(routePlaylistId, out Guid parsedPlaylistId) ? parsedPlaylistId.ToString() : Guid.Empty.ToString(); + PlaylistEntriesAddedDto result = await _apiHttpClient + .PostAsync(ApiRoutes.Playlists.ADD_PLAYLIST_SCOPE_ENTRIES.Replace("{playlistId}", playlistId), request, cancellationToken).ConfigureAwait(false); + return JsonSuccess(result); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/AddPlaylistScopeEntries/AddPlaylistScopeEntriesEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/AddPlaylistScopeEntries/AddPlaylistScopeEntriesEndpointSummary.cs new file mode 100644 index 00000000..ade6f211 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/AddPlaylistScopeEntries/AddPlaylistScopeEntriesEndpointSummary.cs @@ -0,0 +1,41 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.DTO.Common; +using Lumina.Presentation.Web.Common.DTO.Playlists; +using Lumina.Presentation.Web.Common.Requests.Playlists; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Playlists.AddPlaylistScopeEntries; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class AddPlaylistScopeEntriesEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public AddPlaylistScopeEntriesEndpointSummary() + { + Summary = "Adds every track of a library, artist or album to a playlist of the current user."; + Description = "Proxies the request that appends every track of a music library, an artist or an album to a playlist to the API server, in catalogue order. The server resolves the scope in one set-based statement. An empty scope appends nothing and reports a zero count."; + + Params["playlistId"] = "The Id of the playlist to add the tracks to."; + + ExampleRequest = new AddPlaylistScopeEntriesRequest( + LibraryId: Guid.Parse("3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a"), + ArtistId: Guid.Parse("d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a"), + AlbumId: Guid.Parse("e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f") + ); + RequestParam(request => request.LibraryId, "The Id of the music library the scope belongs to. Required."); + RequestParam(request => request.ArtistId, "The Id of the artist the scope is limited to. Optional."); + RequestParam(request => request.AlbumId, "The Id of the album the scope is limited to. Optional."); + + Response(200, "The scope was appended to the playlist and the number of added entries is returned.", + example: new SuccessResponse(true, default) + ); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/CreatePlaylist/CreatePlaylistEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/CreatePlaylist/CreatePlaylistEndpoint.cs new file mode 100644 index 00000000..67d28c48 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/CreatePlaylist/CreatePlaylistEndpoint.cs @@ -0,0 +1,55 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.Playlists; +using Lumina.Presentation.Web.Common.Requests.Playlists; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Playlists.CreatePlaylist; + +/// +/// API endpoint for the /{culture}/playlists/api-create-playlist route. +/// +public class CreatePlaylistEndpoint : BaseEndpoint +{ + private readonly IApiHttpClient _apiHttpClient; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for interactions with the API. + public CreatePlaylistEndpoint(IApiHttpClient apiHttpClient) + { + _apiHttpClient = apiHttpClient; + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.POST); + Routes(WebRoutes.Playlists.CREATE_PLAYLIST); + DontAutoTag(); + Options(options => options.WithTags("Playlists")); + EnableAntiforgery(); + } + + /// + /// Creates a playlist of the current user. + /// + /// The request containing the details of the playlist to create. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(CreatePlaylistRequest request, CancellationToken cancellationToken) + { + PlaylistDto playlist = await _apiHttpClient.PostAsync(ApiRoutes.Playlists.CREATE_PLAYLIST, request, cancellationToken).ConfigureAwait(false); + return JsonSuccess(playlist); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/CreatePlaylist/CreatePlaylistEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/CreatePlaylist/CreatePlaylistEndpointSummary.cs new file mode 100644 index 00000000..7db08474 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/CreatePlaylist/CreatePlaylistEndpointSummary.cs @@ -0,0 +1,39 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.DTO.Common; +using Lumina.Presentation.Web.Common.DTO.Playlists; +using Lumina.Presentation.Web.Common.Enums.Playlists; +using Lumina.Presentation.Web.Common.Requests.Playlists; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Playlists.CreatePlaylist; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class CreatePlaylistEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public CreatePlaylistEndpointSummary() + { + Summary = "Creates a playlist of the current user."; + Description = "Proxies the request that creates a playlist of the current user to the API server. The new playlist starts empty."; + + ExampleRequest = new CreatePlaylistRequest( + Name: "Evening listening", + Description: "Quiet tracks for the end of the day.", + Type: PlaylistType.Music + ); + RequestParam(request => request.Name, "The name of the playlist. Required, maximum 255 characters."); + RequestParam(request => request.Description, "The description of the playlist. Optional, maximum 2000 characters."); + RequestParam(request => request.Type, "The kind of media the playlist holds. Required. Only Music is currently supported."); + + Response(200, "The playlist was created and is returned.", + example: new SuccessResponse(true, default) + ); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/DeletePlaylist/DeletePlaylistEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/DeletePlaylist/DeletePlaylistEndpoint.cs new file mode 100644 index 00000000..9fb09752 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/DeletePlaylist/DeletePlaylistEndpoint.cs @@ -0,0 +1,57 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Playlists.DeletePlaylist; + +/// +/// API endpoint for the /{culture}/playlists/item/{playlistId}/api-delete-playlist route. +/// +public class DeletePlaylistEndpoint : BaseEndpoint +{ + private readonly IApiHttpClient _apiHttpClient; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for interactions with the API. + public DeletePlaylistEndpoint(IApiHttpClient apiHttpClient) + { + _apiHttpClient = apiHttpClient; + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.DELETE); + Routes(WebRoutes.Playlists.DELETE_PLAYLIST); + DontAutoTag(); + Options(options => options.WithTags("Playlists")); + EnableAntiforgery(); + } + + /// + /// Deletes a playlist of the current user. + /// + /// The request object. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(FastEndpoints.EmptyRequest request, CancellationToken cancellationToken) + { + // The route value is normalized to a Guid before it is substituted into the upstream URL, so that a crafted value can never escape its URL segment. + string routePlaylistId = HttpContext.Request.RouteValues["playlistId"]?.ToString() ?? string.Empty; + string playlistId = Guid.TryParse(routePlaylistId, out Guid parsedPlaylistId) ? parsedPlaylistId.ToString() : Guid.Empty.ToString(); + await _apiHttpClient.DeleteAsync(ApiRoutes.Playlists.DELETE_PLAYLIST.Replace("{playlistId}", playlistId), cancellationToken).ConfigureAwait(false); + return JsonSuccess(); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/DeletePlaylist/DeletePlaylistEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/DeletePlaylist/DeletePlaylistEndpointSummary.cs new file mode 100644 index 00000000..c4cc56a0 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/DeletePlaylist/DeletePlaylistEndpointSummary.cs @@ -0,0 +1,29 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.DTO.Common; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Playlists.DeletePlaylist; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class DeletePlaylistEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public DeletePlaylistEndpointSummary() + { + Summary = "Deletes a playlist of the current user."; + Description = "Proxies the request that deletes a playlist and its entries to the API server. The tracks the playlist referenced are not deleted."; + + Params["playlistId"] = "The Id of the playlist to delete."; + + Response(200, "The playlist was deleted.", + example: new SuccessResponse(true) + ); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/GetPlaylist/GetPlaylistEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/GetPlaylist/GetPlaylistEndpoint.cs new file mode 100644 index 00000000..57039770 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/GetPlaylist/GetPlaylistEndpoint.cs @@ -0,0 +1,67 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.Playlists; +using Lumina.Presentation.Web.Common.Requests.Playlists; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Playlists.GetPlaylist; + +/// +/// API endpoint for the /{culture}/playlists/item/{playlistId}/api-get-playlist route. +/// +public class GetPlaylistEndpoint : BaseEndpoint +{ + private const int DEFAULT_ENTRY_PAGE_SIZE = 200; + + private readonly IApiHttpClient _apiHttpClient; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for interactions with the API. + public GetPlaylistEndpoint(IApiHttpClient apiHttpClient) + { + _apiHttpClient = apiHttpClient; + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.GET); + Routes(WebRoutes.Playlists.GET_PLAYLIST); + DontAutoTag(); + Options(options => options.WithTags("Playlists")); + } + + /// + /// Retrieves a page of the entries of a playlist of the current user. + /// + /// The request object. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(GetPlaylistRequest request, CancellationToken cancellationToken) + { + // The playlist belongs to the authenticated user, so no intermediary may store it, and the response varies by the sign in cookie. + HttpContext.Response.Headers["Cache-Control"] = "private, no-store"; + HttpContext.Response.Headers["Vary"] = "Cookie"; + // The route value is normalized to a Guid before it is substituted into the upstream URL, so that a crafted value can never escape its URL segment. + string routePlaylistId = HttpContext.Request.RouteValues["playlistId"]?.ToString() ?? string.Empty; + string playlistId = Guid.TryParse(routePlaylistId, out Guid parsedPlaylistId) ? parsedPlaylistId.ToString() : Guid.Empty.ToString(); + int currentPage = request.CurrentPage ?? 1; + // The page bounds are normalized by the API pagination data. + int perPage = request.PerPage ?? DEFAULT_ENTRY_PAGE_SIZE; + string url = ApiRoutes.Playlists.GET_PLAYLIST.Replace("{playlistId}", playlistId) + $"?currentPage={currentPage}&perPage={perPage}"; + PlaylistDto playlist = await _apiHttpClient.GetAsync(url, cancellationToken).ConfigureAwait(false); + return JsonSuccess(playlist); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/GetPlaylist/GetPlaylistEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/GetPlaylist/GetPlaylistEndpointSummary.cs new file mode 100644 index 00000000..7c45aaca --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/GetPlaylist/GetPlaylistEndpointSummary.cs @@ -0,0 +1,67 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.DTO.Common; +using Lumina.Presentation.Web.Common.DTO.Playlists; +using Lumina.Presentation.Web.Common.Enums.Playlists; +using Lumina.Presentation.Web.Common.Requests.Playlists; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Playlists.GetPlaylist; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class GetPlaylistEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public GetPlaylistEndpointSummary() + { + Summary = "Gets a playlist of the current user."; + Description = "Proxies the request that gets a playlist and a page of its ordered entries to the API server. The currentPage and perPage query parameters select the page, and entries.count reports the total number of entries."; + + Params["playlistId"] = "The Id of the playlist to get."; + + ExampleRequest = new GetPlaylistRequest( + CurrentPage: 1, + PerPage: 200 + ); + RequestParam(request => request.CurrentPage, "The one based page of entries to return. Optional; defaults to 1."); + RequestParam(request => request.PerPage, "The number of entries per page. Optional; defaults to 200."); + + Response(200, "The playlist and its ordered entries are returned.", + example: new SuccessResponse(true, new PlaylistDto( + Id: Guid.Parse("1f2e3d4c-5b6a-4978-8a9b-0c1d2e3f4a5b"), + Name: "Evening listening", + Description: "Quiet tracks for the end of the day.", + Type: PlaylistType.Music, + Entries: new PaginatedDto( + Data: + [ + new PlaylistEntryDto( + 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))) + ); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/GetPlaylists/GetPlaylistsEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/GetPlaylists/GetPlaylistsEndpoint.cs new file mode 100644 index 00000000..b8be307e --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/GetPlaylists/GetPlaylistsEndpoint.cs @@ -0,0 +1,55 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.Playlists; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Playlists.GetPlaylists; + +/// +/// API endpoint for the /{culture}/playlists/api-get-playlists route. +/// +public class GetPlaylistsEndpoint : BaseEndpoint +{ + private readonly IApiHttpClient _apiHttpClient; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for interactions with the API. + public GetPlaylistsEndpoint(IApiHttpClient apiHttpClient) + { + _apiHttpClient = apiHttpClient; + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.GET); + Routes(WebRoutes.Playlists.GET_PLAYLISTS); + DontAutoTag(); + Options(options => options.WithTags("Playlists")); + } + + /// + /// Retrieves the playlists of the current user. + /// + /// The request object. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(EmptyRequest request, CancellationToken cancellationToken) + { + // The playlists belong to the authenticated user, so no intermediary may store them, and the response varies by the sign in cookie. + HttpContext.Response.Headers["Cache-Control"] = "private, no-store"; + HttpContext.Response.Headers["Vary"] = "Cookie"; + PlaylistSummaryDto[] response = await _apiHttpClient.GetAsync(ApiRoutes.Playlists.GET_PLAYLISTS, cancellationToken).ConfigureAwait(false); + return JsonSuccess(response); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/GetPlaylists/GetPlaylistsEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/GetPlaylists/GetPlaylistsEndpointSummary.cs new file mode 100644 index 00000000..9f11437f --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/GetPlaylists/GetPlaylistsEndpointSummary.cs @@ -0,0 +1,28 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.DTO.Common; +using Lumina.Presentation.Web.Common.DTO.Playlists; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Playlists.GetPlaylists; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class GetPlaylistsEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public GetPlaylistsEndpointSummary() + { + Summary = "Gets the playlists of the current user."; + Description = "Proxies the request that lists the playlists of the current user to the API server."; + + Response(200, "The playlists of the current user are returned.", + example: new SuccessResponse(true, default) + ); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/Index/PlaylistsIndexViewEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/Index/PlaylistsIndexViewEndpoint.cs new file mode 100644 index 00000000..e2c28128 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/Index/PlaylistsIndexViewEndpoint.cs @@ -0,0 +1,100 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.Playlists; +using Lumina.Presentation.Web.Common.DTO.Themes; +using Lumina.Presentation.Web.Common.Primitives; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Common.Services; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Lumina.Presentation.Web.Core.Themes; +using Microsoft.AspNetCore.Antiforgery; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.Localization; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Playlists.Index; + +/// +/// API endpoint for the /{culture}/playlists route. +/// +public class PlaylistsIndexViewEndpoint : BaseEndpoint +{ + // The resource base name deliberately excludes the "Core.Resources" segment: the localization factory re-roots it with the configured ResourcesPath. + private const string VIEW_RESOURCE_BASE_NAME = "Lumina.Presentation.Web.Views.Playlists.Index"; + private const string VIEW_RESOURCE_LOCATION = "Lumina.Presentation.Web"; + // The page key mirrors the path of the Razor view under Core/Views, so that theme templates can override it at the page, section or default scope. + private const string VIEW_PAGE_KEY = "playlists/index"; + + private readonly IUrlService _urlService; + private readonly ThemePageRenderer _themePageRenderer; + private readonly IAntiforgery _antiforgery; + private readonly IStringLocalizer _localizer; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for generating URLs from action and controller names, with localization. + /// Injected service for rendering themed pages. + /// Injected service for anti-forgery token handling. + /// Injected factory used to create the localizer of the view resources. + public PlaylistsIndexViewEndpoint(IUrlService urlService, ThemePageRenderer themePageRenderer, IAntiforgery antiforgery, IStringLocalizerFactory stringLocalizerFactory) + { + _urlService = urlService; + _themePageRenderer = themePageRenderer; + _antiforgery = antiforgery; + _localizer = stringLocalizerFactory.Create(VIEW_RESOURCE_BASE_NAME, VIEW_RESOURCE_LOCATION); + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.GET); + Routes(WebRoutes.Playlists.INDEX); + DontAutoTag(); + Options(options => options.WithTags("Playlists")); + } + + /// + /// Displays the playlists of the current user, rendered by the active theme with a fallback to the Razor view. + /// + /// The request object. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(EmptyRequest request, CancellationToken cancellationToken) + { + // The page shows the playlists of the authenticated user, so no intermediary may store it, and the response varies by the sign in cookie. + SetCacheControl("private, no-store"); + HttpContext.Response.Headers["Vary"] = "Cookie"; + // The page creates and deletes playlists, which submit through the form anti-forgery token, so a fresh token is issued for it. + AntiforgeryTokenSet antiforgeryTokens = _antiforgery.GetAndStoreTokens(HttpContext); + string title = _localizer["Title"].Value; + + ThemePageDto pageModel = new() + { + PageKey = VIEW_PAGE_KEY, + Title = title, + Description = string.Empty, + PageData = new Dictionary + { + ["getPlaylistsUrl"] = _urlService.GetAbsoluteUrl(WebRoutes.Playlists.GET_PLAYLISTS) ?? string.Empty, + ["addUrl"] = _urlService.GetAbsoluteUrl(WebRoutes.Playlists.ADD) ?? string.Empty, + ["itemUrl"] = _urlService.GetAbsoluteUrl(WebRoutes.Playlists.ITEM, new { playlistId = default(System.Guid) }) ?? string.Empty, + ["deleteUrl"] = _urlService.GetAbsoluteUrl(WebRoutes.Playlists.DELETE_PLAYLIST, new { playlistId = default(System.Guid) }) ?? string.Empty, + ["antiforgeryToken"] = antiforgeryTokens.RequestToken, + ["strings"] = ThemePageDataFactory.CreateLocalizedStrings(_localizer) + } + }; + + Result sectionResult = await _themePageRenderer.RenderAsync(pageModel, requestedThemeId: null, cancellationToken).ConfigureAwait(false); + if (sectionResult.IsFailure) + return View("/Core/Views/Playlists/Index.cshtml", viewData: new Dictionary { ["Title"] = title }); + + return View("/Core/Views/Shared/_ThemedView.cshtml", new ThemeViewDto(sectionResult.Value.Content, sectionResult.Value.Script), new Dictionary { ["Title"] = title }); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/Index/PlaylistsIndexViewEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/Index/PlaylistsIndexViewEndpointSummary.cs new file mode 100644 index 00000000..67534ee7 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/Index/PlaylistsIndexViewEndpointSummary.cs @@ -0,0 +1,24 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Playlists.Index; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class PlaylistsIndexViewEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public PlaylistsIndexViewEndpointSummary() + { + Summary = "Renders the playlists page."; + Description = "Renders the page that lists and deletes the playlists of the current user."; + + Response(200, "The playlists page is rendered."); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/Item/AddPlaylistViewEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/Item/AddPlaylistViewEndpoint.cs new file mode 100644 index 00000000..34a54757 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/Item/AddPlaylistViewEndpoint.cs @@ -0,0 +1,134 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.DTO.Common; +using Lumina.Presentation.Web.Common.DTO.Playlists; +using Lumina.Presentation.Web.Common.DTO.Themes; +using Lumina.Presentation.Web.Common.Enums.Playlists; +using Lumina.Presentation.Web.Common.Primitives; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Common.Services; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Lumina.Presentation.Web.Core.Themes; +using Microsoft.AspNetCore.Antiforgery; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.Localization; +using System; +using System.Collections.Generic; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Playlists.Item; + +/// +/// API endpoint for the /{culture}/playlists/item route. +/// +public class AddPlaylistViewEndpoint : BaseEndpoint +{ + // The resource base name deliberately excludes the "Core.Resources" segment: the localization factory re-roots it with the configured ResourcesPath. + private const string VIEW_RESOURCE_BASE_NAME = "Lumina.Presentation.Web.Views.Playlists.Item"; + private const string VIEW_RESOURCE_LOCATION = "Lumina.Presentation.Web"; + // The page key mirrors the path of the Razor view under Core/Views, so that theme templates can override it at the page, section or default scope. + private const string VIEW_PAGE_KEY = "playlists/item"; + // A new playlist has no entries yet, but its serialized page still carries the shape the page script expects. + private const int DEFAULT_ENTRY_PAGE_SIZE = 200; + + private static readonly JsonSerializerOptions s_camelCaseJsonOptions = new() + { + PropertyNamingPolicy = JsonNamingPolicy.CamelCase, + Converters = { new JsonStringEnumConverter() } + }; + + private readonly IUrlService _urlService; + private readonly ThemePageRenderer _themePageRenderer; + private readonly IAntiforgery _antiforgery; + private readonly IStringLocalizer _localizer; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for generating URLs from action and controller names, with localization. + /// Injected service for rendering themed pages. + /// Injected service for anti-forgery token handling. + /// Injected factory used to create the localizer of the view resources. + public AddPlaylistViewEndpoint(IUrlService urlService, ThemePageRenderer themePageRenderer, IAntiforgery antiforgery, IStringLocalizerFactory stringLocalizerFactory) + { + _urlService = urlService; + _themePageRenderer = themePageRenderer; + _antiforgery = antiforgery; + _localizer = stringLocalizerFactory.Create(VIEW_RESOURCE_BASE_NAME, VIEW_RESOURCE_LOCATION); + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.GET); + Routes(WebRoutes.Playlists.ADD); + DontAutoTag(); + Options(options => options.WithTags("Playlists")); + } + + /// + /// Displays the page that creates a playlist of the current user, rendered by the active theme with a fallback to the Razor view. + /// + /// The request object. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(EmptyRequest request, CancellationToken cancellationToken) + { + // The page creates a playlist of the authenticated user, so no intermediary may store it, and the response varies by the sign in cookie. + SetCacheControl("private, no-store"); + HttpContext.Response.Headers["Vary"] = "Cookie"; + + // The page submits through the form anti-forgery token, so a fresh token is issued for it. + AntiforgeryTokenSet antiforgeryTokens = _antiforgery.GetAndStoreTokens(HttpContext); + PlaylistDto playlist = new( + Id: Guid.Empty, + Name: string.Empty, + Description: null, + Type: PlaylistType.Music, + Entries: new PaginatedDto( + Data: [], + CurrentPage: 1, + PerPage: DEFAULT_ENTRY_PAGE_SIZE, + Count: 0, + NumberOfPages: 0), + CreatedOnUtc: default, + UpdatedOnUtc: null + ); + string title = _localizer["CreatePlaylist"].Value; + + ThemePageDto pageModel = new() + { + PageKey = VIEW_PAGE_KEY, + Title = title, + Description = string.Empty, + PageData = new Dictionary + { + ["isNew"] = true, + ["playlistId"] = playlist.Id.ToString(), + ["playlistJson"] = JsonSerializer.Serialize(playlist, s_camelCaseJsonOptions), + ["entriesPerPage"] = DEFAULT_ENTRY_PAGE_SIZE, + ["createPlaylistUrl"] = _urlService.GetAbsoluteUrl(WebRoutes.Playlists.CREATE_PLAYLIST) ?? string.Empty, + ["itemUrl"] = _urlService.GetAbsoluteUrl(WebRoutes.Playlists.ITEM, new { playlistId = default(Guid) }) ?? string.Empty, + ["getEnabledLibrariesUrl"] = _urlService.GetAbsoluteUrl(WebRoutes.LibraryManagement.GET_ENABLED_LIBRARIES) ?? string.Empty, + ["getArtistsUrl"] = _urlService.GetAbsoluteUrl(WebRoutes.Music.GET_ARTISTS) ?? string.Empty, + ["getArtistAlbumsUrl"] = _urlService.GetAbsoluteUrl(WebRoutes.Music.GET_ARTIST_ALBUMS, new { artistId = default(Guid) }) ?? string.Empty, + ["getAlbumTracksUrl"] = _urlService.GetAbsoluteUrl(WebRoutes.Music.GET_ALBUM_TRACKS, new { artistId = default(Guid), albumId = default(Guid) }) ?? string.Empty, + ["indexUrl"] = _urlService.GetAbsoluteUrl(WebRoutes.Playlists.INDEX) ?? string.Empty, + ["antiforgeryToken"] = antiforgeryTokens.RequestToken, + ["strings"] = ThemePageDataFactory.CreateLocalizedStrings(_localizer) + } + }; + + Result sectionResult = await _themePageRenderer.RenderAsync(pageModel, requestedThemeId: null, cancellationToken).ConfigureAwait(false); + if (sectionResult.IsFailure) + return View("/Core/Views/Playlists/Item.cshtml", playlist, new Dictionary { ["Title"] = title, ["IsNew"] = true }); + + return View("/Core/Views/Shared/_ThemedView.cshtml", new ThemeViewDto(sectionResult.Value.Content, sectionResult.Value.Script), new Dictionary { ["Title"] = title, ["IsNew"] = true }); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/Item/AddPlaylistViewEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/Item/AddPlaylistViewEndpointSummary.cs new file mode 100644 index 00000000..9737beaf --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/Item/AddPlaylistViewEndpointSummary.cs @@ -0,0 +1,24 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Playlists.Item; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class AddPlaylistViewEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public AddPlaylistViewEndpointSummary() + { + Summary = "Renders the create playlist page."; + Description = "Renders the page that creates a playlist of the current user."; + + Response(200, "The create playlist page is rendered."); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/Item/PlaylistItemViewEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/Item/PlaylistItemViewEndpoint.cs new file mode 100644 index 00000000..e97b6247 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/Item/PlaylistItemViewEndpoint.cs @@ -0,0 +1,135 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.Playlists; +using Lumina.Presentation.Web.Common.DTO.Themes; +using Lumina.Presentation.Web.Common.Primitives; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Common.Services; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Lumina.Presentation.Web.Core.Themes; +using Microsoft.AspNetCore.Antiforgery; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.Localization; +using System; +using System.Collections.Generic; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Playlists.Item; + +/// +/// API endpoint for the /{culture}/playlists/item/{playlistId} route. +/// +public class PlaylistItemViewEndpoint : BaseEndpoint +{ + // The resource base name deliberately excludes the "Core.Resources" segment: the localization factory re-roots it with the configured ResourcesPath. + private const string VIEW_RESOURCE_BASE_NAME = "Lumina.Presentation.Web.Views.Playlists.Item"; + private const string VIEW_RESOURCE_LOCATION = "Lumina.Presentation.Web"; + // The page key mirrors the path of the Razor view under Core/Views, so that theme templates can override it at the page, section or default scope. + private const string VIEW_PAGE_KEY = "playlists/item"; + // The page renders one page at a time; the client asks for the next page through getPlaylistUrl. + private const int ENTRY_PAGE_SIZE = 200; + + private static readonly JsonSerializerOptions s_camelCaseJsonOptions = new() + { + PropertyNamingPolicy = JsonNamingPolicy.CamelCase, + Converters = { new JsonStringEnumConverter() } + }; + + private readonly IApiHttpClient _apiHttpClient; + private readonly IUrlService _urlService; + private readonly ThemePageRenderer _themePageRenderer; + private readonly IAntiforgery _antiforgery; + private readonly IStringLocalizer _localizer; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for interactions with the API. + /// Injected service for generating URLs from action and controller names, with localization. + /// Injected service for rendering themed pages. + /// Injected service for anti-forgery token handling. + /// Injected factory used to create the localizer of the view resources. + public PlaylistItemViewEndpoint(IApiHttpClient apiHttpClient, IUrlService urlService, ThemePageRenderer themePageRenderer, IAntiforgery antiforgery, IStringLocalizerFactory stringLocalizerFactory) + { + _apiHttpClient = apiHttpClient; + _urlService = urlService; + _themePageRenderer = themePageRenderer; + _antiforgery = antiforgery; + _localizer = stringLocalizerFactory.Create(VIEW_RESOURCE_BASE_NAME, VIEW_RESOURCE_LOCATION); + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.GET); + Routes(WebRoutes.Playlists.ITEM); + DontAutoTag(); + Options(options => options.WithTags("Playlists")); + } + + /// + /// Displays a playlist of the current user, rendered by the active theme with a fallback to the Razor view. + /// + /// The request object. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(EmptyRequest request, CancellationToken cancellationToken) + { + // The page shows a playlist of the authenticated user, so no intermediary may store it, and the response varies by the sign in cookie. + SetCacheControl("private, no-store"); + HttpContext.Response.Headers["Vary"] = "Cookie"; + // The route value is normalized to a Guid before it is substituted into the upstream URL, so that a crafted value can never escape + // its URL segment, and an unparseable id is reported by the API as a missing playlist id. + string routePlaylistId = HttpContext.Request.RouteValues["playlistId"]?.ToString() ?? string.Empty; + string playlistId = Guid.TryParse(routePlaylistId, out Guid parsedPlaylistId) ? parsedPlaylistId.ToString() : Guid.Empty.ToString(); + PlaylistDto playlist = await _apiHttpClient + .GetAsync( + ApiRoutes.Playlists.GET_PLAYLIST.Replace("{playlistId}", playlistId) + $"?currentPage=1&perPage={ENTRY_PAGE_SIZE}", + cancellationToken).ConfigureAwait(false); + + // The page edits, reorders and deletes the playlist, which submit through the form anti-forgery token, so a fresh token is issued for it. + AntiforgeryTokenSet antiforgeryTokens = _antiforgery.GetAndStoreTokens(HttpContext); + + ThemePageDto pageModel = new() + { + PageKey = VIEW_PAGE_KEY, + Title = playlist.Name, + Description = playlist.Description ?? string.Empty, + PageData = new Dictionary + { + ["isNew"] = false, + ["playlistId"] = playlist.Id.ToString(), + ["playlistJson"] = JsonSerializer.Serialize(playlist, s_camelCaseJsonOptions), + ["entriesPerPage"] = ENTRY_PAGE_SIZE, + ["createPlaylistUrl"] = _urlService.GetAbsoluteUrl(WebRoutes.Playlists.CREATE_PLAYLIST) ?? string.Empty, + ["itemUrl"] = _urlService.GetAbsoluteUrl(WebRoutes.Playlists.ITEM, new { playlistId = default(Guid) }) ?? string.Empty, + ["getPlaylistUrl"] = _urlService.GetAbsoluteUrl(WebRoutes.Playlists.GET_PLAYLIST, new { playlistId = playlist.Id }) ?? string.Empty, + ["updatePlaylistUrl"] = _urlService.GetAbsoluteUrl(WebRoutes.Playlists.UPDATE_PLAYLIST, new { playlistId = playlist.Id }) ?? string.Empty, + ["deletePlaylistUrl"] = _urlService.GetAbsoluteUrl(WebRoutes.Playlists.DELETE_PLAYLIST, new { playlistId = playlist.Id }) ?? string.Empty, + ["addEntryUrl"] = _urlService.GetAbsoluteUrl(WebRoutes.Playlists.ADD_PLAYLIST_ENTRY, new { playlistId = playlist.Id }) ?? string.Empty, + ["removeEntryUrl"] = _urlService.GetAbsoluteUrl(WebRoutes.Playlists.REMOVE_PLAYLIST_ENTRY, new { playlistId = playlist.Id, playlistEntryId = default(Guid) }) ?? string.Empty, + ["moveEntryUrl"] = _urlService.GetAbsoluteUrl(WebRoutes.Playlists.MOVE_PLAYLIST_ENTRY, new { playlistId = playlist.Id, playlistEntryId = default(Guid) }) ?? string.Empty, + ["getEnabledLibrariesUrl"] = _urlService.GetAbsoluteUrl(WebRoutes.LibraryManagement.GET_ENABLED_LIBRARIES) ?? string.Empty, + ["getArtistsUrl"] = _urlService.GetAbsoluteUrl(WebRoutes.Music.GET_ARTISTS) ?? string.Empty, + ["getArtistAlbumsUrl"] = _urlService.GetAbsoluteUrl(WebRoutes.Music.GET_ARTIST_ALBUMS, new { artistId = default(Guid) }) ?? string.Empty, + ["getAlbumTracksUrl"] = _urlService.GetAbsoluteUrl(WebRoutes.Music.GET_ALBUM_TRACKS, new { artistId = default(Guid), albumId = default(Guid) }) ?? string.Empty, + ["indexUrl"] = _urlService.GetAbsoluteUrl(WebRoutes.Playlists.INDEX) ?? string.Empty, + ["antiforgeryToken"] = antiforgeryTokens.RequestToken, + ["strings"] = ThemePageDataFactory.CreateLocalizedStrings(_localizer) + } + }; + + Result sectionResult = await _themePageRenderer.RenderAsync(pageModel, requestedThemeId: null, cancellationToken).ConfigureAwait(false); + if (sectionResult.IsFailure) + return View("/Core/Views/Playlists/Item.cshtml", playlist, new Dictionary { ["Title"] = playlist.Name, ["IsNew"] = false }); + + return View("/Core/Views/Shared/_ThemedView.cshtml", new ThemeViewDto(sectionResult.Value.Content, sectionResult.Value.Script), new Dictionary { ["Title"] = playlist.Name, ["IsNew"] = false }); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/Item/PlaylistItemViewEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/Item/PlaylistItemViewEndpointSummary.cs new file mode 100644 index 00000000..95bd4264 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/Item/PlaylistItemViewEndpointSummary.cs @@ -0,0 +1,26 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Playlists.Item; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class PlaylistItemViewEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public PlaylistItemViewEndpointSummary() + { + Summary = "Renders a playlist page."; + Description = "Renders the page that edits, reorders, plays and deletes a playlist of the current user."; + + Params["playlistId"] = "The Id of the playlist to display."; + + Response(200, "The playlist page is rendered."); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/MovePlaylistEntry/MovePlaylistEntryEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/MovePlaylistEntry/MovePlaylistEntryEndpoint.cs new file mode 100644 index 00000000..23a17363 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/MovePlaylistEntry/MovePlaylistEntryEndpoint.cs @@ -0,0 +1,67 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.Playlists; +using Lumina.Presentation.Web.Common.Requests.Playlists; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Playlists.MovePlaylistEntry; + +/// +/// API endpoint for the /{culture}/playlists/item/{playlistId}/entries/{playlistEntryId}/api-move-entry route. +/// +public class MovePlaylistEntryEndpoint : BaseEndpoint +{ + private readonly IApiHttpClient _apiHttpClient; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for interactions with the API. + public MovePlaylistEntryEndpoint(IApiHttpClient apiHttpClient) + { + _apiHttpClient = apiHttpClient; + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.PUT); + Routes(WebRoutes.Playlists.MOVE_PLAYLIST_ENTRY); + DontAutoTag(); + Options(options => options.WithTags("Playlists")); + EnableAntiforgery(); + } + + /// + /// Moves one entry of a playlist of the current user to a new position. + /// + /// The request containing the new position of the entry. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(MovePlaylistEntryRequest request, CancellationToken cancellationToken) + { + // The playlist and the entry are identified by the route values, not by any id posted in the body. + string routePlaylistId = HttpContext.Request.RouteValues["playlistId"]?.ToString() ?? string.Empty; + string playlistId = Guid.TryParse(routePlaylistId, out Guid parsedPlaylistId) ? parsedPlaylistId.ToString() : Guid.Empty.ToString(); + string routePlaylistEntryId = HttpContext.Request.RouteValues["playlistEntryId"]?.ToString() ?? string.Empty; + string playlistEntryId = Guid.TryParse(routePlaylistEntryId, out Guid parsedPlaylistEntryId) ? parsedPlaylistEntryId.ToString() : Guid.Empty.ToString(); + PlaylistEntryMovedDto entry = await _apiHttpClient + .PutAsync( + ApiRoutes.Playlists.MOVE_PLAYLIST_ENTRY + .Replace("{playlistId}", playlistId) + .Replace("{playlistEntryId}", playlistEntryId), + request, + cancellationToken).ConfigureAwait(false); + return JsonSuccess(entry); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/MovePlaylistEntry/MovePlaylistEntryEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/MovePlaylistEntry/MovePlaylistEntryEndpointSummary.cs new file mode 100644 index 00000000..5faea45b --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/MovePlaylistEntry/MovePlaylistEntryEndpointSummary.cs @@ -0,0 +1,37 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.DTO.Common; +using Lumina.Presentation.Web.Common.DTO.Playlists; +using Lumina.Presentation.Web.Common.Requests.Playlists; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Playlists.MovePlaylistEntry; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class MovePlaylistEntryEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public MovePlaylistEntryEndpointSummary() + { + Summary = "Moves one entry of a playlist of the current user."; + Description = "Proxies the request that moves one entry of a playlist to a new position to the API server. The moved entry and its new position are returned."; + + Params["playlistId"] = "The Id of the playlist whose entry is moved."; + Params["playlistEntryId"] = "The Id of the entry to move."; + + ExampleRequest = new MovePlaylistEntryRequest( + TargetPosition: 3 + ); + RequestParam(request => request.TargetPosition, "The new zero based position of the entry. Required, zero or greater."); + + Response(200, "The moved entry and its new position are returned.", + example: new SuccessResponse(true, default) + ); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/RemovePlaylistEntry/RemovePlaylistEntryEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/RemovePlaylistEntry/RemovePlaylistEntryEndpoint.cs new file mode 100644 index 00000000..98de3a80 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/RemovePlaylistEntry/RemovePlaylistEntryEndpoint.cs @@ -0,0 +1,63 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Playlists.RemovePlaylistEntry; + +/// +/// API endpoint for the /{culture}/playlists/item/{playlistId}/entries/{playlistEntryId}/api-remove-entry route. +/// +public class RemovePlaylistEntryEndpoint : BaseEndpoint +{ + private readonly IApiHttpClient _apiHttpClient; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for interactions with the API. + public RemovePlaylistEntryEndpoint(IApiHttpClient apiHttpClient) + { + _apiHttpClient = apiHttpClient; + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.DELETE); + Routes(WebRoutes.Playlists.REMOVE_PLAYLIST_ENTRY); + DontAutoTag(); + Options(options => options.WithTags("Playlists")); + EnableAntiforgery(); + } + + /// + /// Removes an entry from a playlist of the current user. + /// + /// The request object. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(EmptyRequest request, CancellationToken cancellationToken) + { + // The route values are normalized to Guids before they are substituted into the upstream URL, so that a crafted value can never escape its URL segment. + string routePlaylistId = HttpContext.Request.RouteValues["playlistId"]?.ToString() ?? string.Empty; + string playlistId = Guid.TryParse(routePlaylistId, out Guid parsedPlaylistId) ? parsedPlaylistId.ToString() : Guid.Empty.ToString(); + string routePlaylistEntryId = HttpContext.Request.RouteValues["playlistEntryId"]?.ToString() ?? string.Empty; + string playlistEntryId = Guid.TryParse(routePlaylistEntryId, out Guid parsedPlaylistEntryId) ? parsedPlaylistEntryId.ToString() : Guid.Empty.ToString(); + await _apiHttpClient.DeleteAsync( + ApiRoutes.Playlists.REMOVE_PLAYLIST_ENTRY + .Replace("{playlistId}", playlistId) + .Replace("{playlistEntryId}", playlistEntryId), + cancellationToken).ConfigureAwait(false); + return JsonSuccess(); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/RemovePlaylistEntry/RemovePlaylistEntryEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/RemovePlaylistEntry/RemovePlaylistEntryEndpointSummary.cs new file mode 100644 index 00000000..970f6a7c --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/RemovePlaylistEntry/RemovePlaylistEntryEndpointSummary.cs @@ -0,0 +1,30 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.DTO.Common; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Playlists.RemovePlaylistEntry; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class RemovePlaylistEntryEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public RemovePlaylistEntryEndpointSummary() + { + Summary = "Removes an entry from a playlist of the current user."; + Description = "Proxies the request that removes an entry from a playlist to the API server. The page removes the row from its current window without reading the playlist back."; + + Params["playlistId"] = "The Id of the playlist the entry belongs to."; + Params["playlistEntryId"] = "The Id of the entry to remove."; + + Response(200, "The entry was removed.", + example: new SuccessResponse(true) + ); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/UpdatePlaylist/UpdatePlaylistEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/UpdatePlaylist/UpdatePlaylistEndpoint.cs new file mode 100644 index 00000000..4b848a25 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/UpdatePlaylist/UpdatePlaylistEndpoint.cs @@ -0,0 +1,60 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.Playlists; +using Lumina.Presentation.Web.Common.Requests.Playlists; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Playlists.UpdatePlaylist; + +/// +/// API endpoint for the /{culture}/playlists/item/{playlistId}/api-update-playlist route. +/// +public class UpdatePlaylistEndpoint : BaseEndpoint +{ + private readonly IApiHttpClient _apiHttpClient; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for interactions with the API. + public UpdatePlaylistEndpoint(IApiHttpClient apiHttpClient) + { + _apiHttpClient = apiHttpClient; + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.PUT); + Routes(WebRoutes.Playlists.UPDATE_PLAYLIST); + DontAutoTag(); + Options(options => options.WithTags("Playlists")); + EnableAntiforgery(); + } + + /// + /// Updates the details of a playlist of the current user. + /// + /// The request containing the new details of the playlist. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(UpdatePlaylistRequest request, CancellationToken cancellationToken) + { + // The playlist is identified by the route value, not by any id posted in the body. + string routePlaylistId = HttpContext.Request.RouteValues["playlistId"]?.ToString() ?? string.Empty; + string playlistId = Guid.TryParse(routePlaylistId, out Guid parsedPlaylistId) ? parsedPlaylistId.ToString() : Guid.Empty.ToString(); + PlaylistDetailsDto playlist = await _apiHttpClient + .PutAsync(ApiRoutes.Playlists.UPDATE_PLAYLIST.Replace("{playlistId}", playlistId), request, cancellationToken).ConfigureAwait(false); + return JsonSuccess(playlist); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/UpdatePlaylist/UpdatePlaylistEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/UpdatePlaylist/UpdatePlaylistEndpointSummary.cs new file mode 100644 index 00000000..17b9b811 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/UpdatePlaylist/UpdatePlaylistEndpointSummary.cs @@ -0,0 +1,38 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.DTO.Common; +using Lumina.Presentation.Web.Common.DTO.Playlists; +using Lumina.Presentation.Web.Common.Requests.Playlists; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Playlists.UpdatePlaylist; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class UpdatePlaylistEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public UpdatePlaylistEndpointSummary() + { + Summary = "Updates the details of a playlist of the current user."; + Description = "Proxies the request that updates the name and description of a playlist to the API server. The ordered entries of the playlist are left untouched."; + + Params["playlistId"] = "The Id of the playlist to update."; + + ExampleRequest = new UpdatePlaylistRequest( + Name: "Evening listening", + Description: "Quiet tracks for the end of the day." + ); + RequestParam(request => request.Name, "The name of the playlist. Required, maximum 255 characters."); + RequestParam(request => request.Description, "The description of the playlist. Optional, maximum 2000 characters."); + + Response(200, "The updated playlist details are returned.", + example: new SuccessResponse(true, default) + ); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Tools/Settings/GetPlaybackState/GetPlaybackStateEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Tools/Settings/GetPlaybackState/GetPlaybackStateEndpoint.cs new file mode 100644 index 00000000..ed497ad3 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Tools/Settings/GetPlaybackState/GetPlaybackStateEndpoint.cs @@ -0,0 +1,53 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.UsersManagement; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Tools.Settings.GetPlaybackState; + +/// +/// API endpoint for the /{culture}/tools/settings/api-get-playback-state route. +/// +public class GetPlaybackStateEndpoint : BaseEndpoint +{ + private readonly IApiHttpClient _apiHttpClient; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for interactions with the API. + public GetPlaybackStateEndpoint(IApiHttpClient apiHttpClient) + { + _apiHttpClient = apiHttpClient; + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.GET); + Routes(WebRoutes.Settings.GET_PLAYBACK_STATE); + DontAutoTag(); + Options(options => options.WithTags("Settings")); + } + + /// + /// Retrieves the playback state the player reported for the current user automatically. + /// + /// The request object. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(EmptyRequest request, CancellationToken cancellationToken) + { + PlaybackStateDto response = await _apiHttpClient.GetAsync(ApiRoutes.Users.GET_PLAYBACK_STATE, cancellationToken).ConfigureAwait(false); + return JsonSuccess(response); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Tools/Settings/GetPlaybackState/GetPlaybackStateEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Tools/Settings/GetPlaybackState/GetPlaybackStateEndpointSummary.cs new file mode 100644 index 00000000..5984cb06 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Tools/Settings/GetPlaybackState/GetPlaybackStateEndpointSummary.cs @@ -0,0 +1,26 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.DTO.Common; +using Lumina.Presentation.Web.Common.DTO.UsersManagement; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Tools.Settings.GetPlaybackState; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class GetPlaybackStateEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public GetPlaybackStateEndpointSummary() + { + Summary = "Retrieves the playback state the player reported for the current user."; + Description = "Retrieves the last volume and mute state the player reported for the current user. These values are not part of the settings the user edits."; + + Response(200, "The playback state of the current user is returned.", example: new SuccessResponse(true, default)); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Tools/Settings/UpdatePlaybackState/UpdatePlaybackStateEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Tools/Settings/UpdatePlaybackState/UpdatePlaybackStateEndpoint.cs new file mode 100644 index 00000000..8c0be3be --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Tools/Settings/UpdatePlaybackState/UpdatePlaybackStateEndpoint.cs @@ -0,0 +1,54 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.UsersManagement; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Tools.Settings.UpdatePlaybackState; + +/// +/// API endpoint for the /{culture}/tools/settings/api-update-playback-state route. +/// +public class UpdatePlaybackStateEndpoint : BaseEndpoint +{ + private readonly IApiHttpClient _apiHttpClient; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for interactions with the API. + public UpdatePlaybackStateEndpoint(IApiHttpClient apiHttpClient) + { + _apiHttpClient = apiHttpClient; + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.POST); + Routes(WebRoutes.Settings.UPDATE_PLAYBACK_STATE); + DontAutoTag(); + Options(options => options.WithTags("Settings")); + EnableAntiforgery(); + } + + /// + /// Updates the playback state the player reported for the current user automatically. + /// + /// The request containing the latest playback state of the current user. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(PlaybackStateDto request, CancellationToken cancellationToken) + { + await _apiHttpClient.PutAsync(ApiRoutes.Users.UPDATE_PLAYBACK_STATE, request, cancellationToken).ConfigureAwait(false); + return JsonSuccess(new { isUpdated = true }); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Tools/Settings/UpdatePlaybackState/UpdatePlaybackStateEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Tools/Settings/UpdatePlaybackState/UpdatePlaybackStateEndpointSummary.cs new file mode 100644 index 00000000..d68c0530 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Tools/Settings/UpdatePlaybackState/UpdatePlaybackStateEndpointSummary.cs @@ -0,0 +1,30 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.DTO.UsersManagement; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Tools.Settings.UpdatePlaybackState; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class UpdatePlaybackStateEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public UpdatePlaybackStateEndpointSummary() + { + Summary = "Updates the playback state the player reported for the current user."; + Description = "Updates the last volume and mute state the player reported for the current user. This is written automatically by the player and is not part of the settings the user edits."; + + RequestParam(r => r.Volume, "The last volume the player reported, as a value between 0 and 1. Required."); + RequestParam(r => r.IsMuted, "The last mute state the player reported. Required."); + + ExampleRequest = new PlaybackStateDto { Volume = 1.0, IsMuted = false }; + + Response(200, "The playback state of the current user is updated.", example: new { success = true, data = new { isUpdated = true } }); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ar-SA.resx b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ar-SA.resx index ac29e5d3..d3c3df28 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ar-SA.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ar-SA.resx @@ -813,4 +813,496 @@ نوع الجدول غير صالح! - \ No newline at end of file + + وضع ReplayGain غير صالح! + + + جودة البث غير صالحة! + + + لا يمكن أن تكون حالة الكتم فارغة! + + + لا يمكن أن يكون مستوى الصوت فارغًا! + + + يجب أن يكون مستوى الصوت بين 0 و 1! + + + لا يمكن أن يكون إعداد متابعة التنزيل أثناء الإيقاف المؤقت فارغًا! + + + لا يمكن أن يكون إعداد التشغيل التلقائي فارغًا! + + + لا يمكن أن يكون إعداد التشغيل دون فواصل فارغًا! + + + لا يمكن أن يكون وضع ReplayGain فارغًا! + + + لا يمكن أن تكون جودة البث فارغة! + + + يجب أن يكون عدد المقطوعات العشوائية أكبر من صفر! + + + يجب ألا يتجاوز عدد المقطوعات العشوائية 500! + + + لا يمكن أن يكون انخفاض مقياس VU فارغًا! + + + لا يمكن أن يكون عدد مقاطع مقياس VU فارغًا! + + + يجب أن يكون انخفاض مقياس VU بين 0 و100 في الثانية! + + + يجب أن تكون مدة تثبيت القمم لمقياس VU بين 0 و10000 مللي ثانية! + + + اتجاه مقياس VU غير صالح! + + + يجب أن يكون عدد مقاطع مقياس VU بين 1 و128! + + + لا يمكن أن يكون تفضيل عرض القمم لمقياس VU فارغًا! + + + يجب أن تكون العتبة المتوسطة لمقياس VU بين 0 و1! + + + يجب أن يكون انخفاض القمم لمقياس VU بين 0 و100 في الثانية! + + + لا يمكن أن تكون المسافة بين مقاطع مقياس VU فارغة! + + + يجب أن تكون المسافة بين مقاطع مقياس VU بين 0 و32! + + + لا يمكن أن تكون مدة تثبيت القمم لمقياس VU فارغة! + + + لا يمكن أن تكون اتجاهات مقياس VU فارغة! + + + لا يمكن أن تكون العتبة المتوسطة لمقياس VU فارغة! + + + يجب أن تكون العتبة العالية لمقياس VU بين 0 و1! + + + لا يمكن أن يكون انخفاض القمم لمقياس VU فارغًا! + + + يجب أن تكون العتبة العالية لمقياس VU أكبر من أو تساوي العتبة المتوسطة! + + + لا يمكن أن تكون العتبة العالية لمقياس VU فارغة! + + + الألبوم موجود بالفعل! + + + لا يمكن أن يكون معرف الألبوم فارغًا! + + + لم يتم العثور على الألبوم! + + + لا يمكن أن يكون عنوان الألبوم فارغًا! + + + يجب أن يكون طول عنوان الألبوم 255 حرفًا كحد أقصى! + + + لا يمكن أن تكون قائمة الألبومات فارغة! + + + لا يمكن أن يكون اسم المنطقة فارغًا! + + + يجب أن يبلغ طول اسم المنطقة 255 حرفًا كحد أقصى! + + + لا يمكن أن يكون الاسم المستعار للفنان فارغًا! + + + يجب أن يبلغ طول الاسم المستعار للفنان 255 حرفًا كحد أقصى! + + + الفنان موجود بالفعل! + + + لا يمكن أن يكون معرف الفنان فارغًا! + + + يجب أن يكون لدى الفنان ألبوم واحد على الأقل! + + + لا يمكن أن يكون اسم الفنان فارغًا! + + + يجب أن لا يزيد طول اسم الفنان عن 255 حرفًا! + + + لم يتم العثور على الفنان! + + + يجب أن يبلغ طول موقع الفنان 2048 حرفًا كحد أقصى! + + + لا يمكن أن تكون قيمة الباركود فارغة! + + + يجب أن يكون BPM أكبر من الصفر! + + + يجب أن يبلغ طول رقم الكتالوج 50 حرفًا كحد أقصى! + + + يجب أن يكون حد الإكمال بين 0 و100! + + + يجب أن يكون حد الإكمال فارغًا عندما يكون تتبع التقدم معطلاً! + + + حدث تعارض في التزامن أثناء حفظ التغييرات! + + + عدد الصفحات المتتالية المقروءة مدعوم فقط للوسائط ذات الصفحات! + + + لا يمكن أن يكون عدد الصفحات المتتالية المقروءة سالبًا! + + + لا يمكن أن تنخفض المدة المستهلكة! + + + المدة المستهلكة خارج النطاق! + + + لا يمكن أن تكون المدة المستهلكة سالبة! + + + نطاق تواريخ الاستهلاك غير صالح! + + + انتهى الاستهلاك بالفعل! + + + الاستهلاك ليس قيد التقدم! + + + لا يمكن أن يكون معرّف سجل الاستهلاك فارغًا! + + + لم يتم العثور على سجل الاستهلاك! + + + يجب أن يتكون البلد من حرفين كحد أقصى! + + + لا يمكن أن يكون الغلاف فارغًا! + + + لا يمكن أن يكون معرف التسليم فارغًا! + + + معرف التسليم غير صالح! + + + يجب أن يكون رقم القرص أكبر من الصفر! + + + لا يمكن أن يسبق وقت الانتهاء آخر نشاط! + + + يجب أن يكون للاستهلاك المنتهي وقت انتهاء! + + + المفضلة موجودة بالفعل! + + + لا يمكن أن يكون معرف عنصر الوسائط المفضل فارغًا! + + + لا يمكن أن تكون قائمة معرفات عناصر الوسائط المفضلة فارغة! + + + قائمة معرفات عناصر الوسائط المفضلة تتجاوز الحد الأقصى! + + + نوع الوسائط المفضل غير صالح! + + + نوع الوسائط المفضل غير مدعوم! + + + لم يتم العثور على المفضلة! + + + الملف كبير جدًا! + + + لا يمكن أن يكون للاستهلاك قيد التقدم وقت انتهاء! + + + تنسيق الباركود غير صالح! + + + موضع الوسائط غير صالح! + + + كسر التقدم غير صالح! + + + لا يمكن أن تكون قيمة IPI فارغة! + + + يجب أن يبلغ طول قيمة IPI 20 حرفًا كحد أقصى! + + + لا يمكن أن تكون قيمة ISNI فارغة! + + + يجب أن تكون قيمة ISNI بحد أقصى 20 حرفًا! + + + تنسيق ISRC غير صالح! + + + لا يمكن أن تكون قيمة ISRC فارغة! + + + لا يمكن أن يسبق آخر نشاط البداية! + + + لا يمكن أن يكون مرجع الموقع فارغًا! + + + المساهم الإعلامي موجود بالفعل! + + + لا يمكن أن يكون اسم المساهم بالوسائط فارغًا! + + + لا يمكن أن يكون اسم دور المساهم الإعلامي فارغًا! + + + لا يمكن أن يكون معرّف عنصر الوسائط فارغًا! + + + لا يمكن استئناف الوسائط من هذا النوع! + + + لا يمكن بدء الوسائط من هذا النوع كمكتملة! + + + لم يتم العثور على نقطة استئناف الوسائط! + + + لا يمكن أن يكون اسم الحالة فارغًا! + + + تنسيق معرف MusicBrainz غير صالح! + + + لا يوجد قارئ كتب متاح لهذا الكتاب! + + + لم يتم العثور على تنسيق تشغيل مدعوم! + + + تم تجاوز حد ذاكرة التخزين المؤقت للتطبيع! + + + فشل تطبيع المقطع! + + + التطبيع غير مطلوب للتشغيل المباشر! + + + انتهت مهلة تطبيع المقطع! + + + تطبيع المقطع غير متوفر حاليًا! + + + لم يتم العثور على إدخال ذاكرة التخزين المؤقت للمقطع المطبع! + + + لم يتم العثور على المقطع المطبع! + + + قالب المسار غير مدعوم لهذا النوع من المكتبة! + + + لا يمكن أن يكون الجزء الحرفي من قالب المسار فارغًا! + + + نوع جزء قالب المسار غير مدعوم لهذا النوع من المكتبة! + + + يجب أن يحتوي جزء القيمة من قالب المسار على عنصر نائب واحد بالضبط! + + + لم يتم العثور على الإذن! + + + لقد تغير تسليم التشغيل! + + + لم يتم العثور على تسليم التشغيل! + + + لم يتم تنفيذ تنسيق التشغيل! + + + قائمة التشغيل موجودة بالفعل! + + + يجب أن يبلغ طول وصف قائمة التشغيل 2000 حرف كحد أقصى! + + + قائمة التشغيل لا تقبل عناصر الوسائط! + + + لا يمكن أن يكون معرف إدخال قائمة التشغيل فارغًا! + + + لم يتم العثور على إدخال قائمة التشغيل! + + + مواضع إدخال قائمة التشغيل غير صالحة! + + + لا يمكن أن يكون معرف قائمة التشغيل فارغًا! + + + موضع هدف نقل قائمة التشغيل غير صالح! + + + لا يمكن أن يكون اسم قائمة التشغيل فارغًا! + + + يجب أن يبلغ طول اسم قائمة التشغيل 255 حرفًا كحد أقصى! + + + لم يتم العثور على قائمة التشغيل! + + + نوع قائمة التشغيل غير صالح! + + + قارئ الكتب معطل لهذه المكتبة! + + + لا يمكن أن يكون مفتاح المورد فارغًا! + + + لم يتم العثور على المورد! + + + يجب أن يبلغ طول النص 50 حرفًا كحد أقصى! + + + لم يتم العثور على القسم! + + + يجب أن تكون مدة المقطع موجبة! + + + لا يمكن أن يكون فهرس المقطع فارغًا! + + + فهرس المقطع غير صالح! + + + معرّف المستخدم الهدف غير صالح! + + + الفنان لديه الألبوم بالفعل! + + + الفنان ليس لديه الألبوم! + + + المقطع موجود بالفعل في الألبوم! + + + المقطع ليس في الألبوم! + + + لم يتم العثور على قالب الموضوع! + + + يجب أن يكون العدد الإجمالي للأقراص أكبر من الصفر! + + + يجب أن يكون العدد الإجمالي للمقاطع أكبر من صفر! + + + المقطع موجود بالفعل! + + + يجب أن تكون مدة المقطع موجبة! + + + لم يتم العثور على ملف المقطع! + + + لا يمكن أن يكون معرّف المقطع فارغًا! + + + لم يتم العثور على المقطع! + + + يجب أن يكون رقم المقطع أكبر من صفر! + + + لا يمكن أن يكون مسار المقطع فارغًا! + + + يجب ألا يتجاوز مسار المقطع 2048 حرفًا! + + + يجب أن يكون مسار المقطع داخل أحد مواقع محتوى المكتبة! + + + لا يمكن أن تكون قائمة المقاطع فارغة! + + + جنس الفنان الموسيقي غير معروف! + + + نوع فنان الموسيقى غير معروف! + + + مفتاح الموسيقى غير معروف! + + + تنسيق الوسائط الموسيقية غير معروف! + + + عبوة إصدار الموسيقى غير معروفة! + + + حالة إصدار الموسيقى غير معروفة! + + + نوع إصدار الموسيقى غير معروف! + + + نوع الوسائط غير مدعوم! + + + يجب أن يبلغ طول العمل 255 حرفًا كحد أقصى! + + + لا يمكن أن يكون عنوان العمل فارغًا! + + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.de-DE.resx b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.de-DE.resx index c8647bcc..7acf27db 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.de-DE.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.de-DE.resx @@ -813,4 +813,496 @@ Der Zeitplantyp ist ungültig! - \ No newline at end of file + + Ungültiger ReplayGain-Modus! + + + Ungültige Streaming-Qualität! + + + Der Stummschaltungsstatus darf nicht null sein! + + + Die Lautstärke darf nicht null sein! + + + Die Lautstärke muss zwischen 0 und 1 liegen! + + + Die Einstellung zum Weiterherunterladen beim Pausieren darf nicht null sein! + + + Die Einstellung für die automatische Wiedergabe darf nicht null sein! + + + Die Einstellung für die lückenlose Wiedergabe darf nicht null sein! + + + Der ReplayGain-Modus darf nicht null sein! + + + Die Streaming-Qualität darf nicht null sein! + + + Die Anzahl der Shuffle-Titel muss größer als null sein! + + + Die Anzahl der Shuffle-Titel darf höchstens 500 betragen! + + + Der Rückgang des VU-Meters darf nicht null sein! + + + Die Segmentanzahl des VU-Meters darf nicht null sein! + + + Der Rückgang des VU-Meters muss zwischen 0 und 100 pro Sekunde liegen! + + + Die Haltedauer der Spitzenwerte des VU-Meters muss zwischen 0 und 10000 Millisekunden liegen! + + + Ungültige Ausrichtung des VU-Meters! + + + Die Segmentanzahl des VU-Meters muss zwischen 1 und 128 liegen! + + + Die Einstellung zum Anzeigen der Spitzenwerte des VU-Meters darf nicht null sein! + + + Der mittlere Schwellenwert des VU-Meters muss zwischen 0 und 1 liegen! + + + Der Rückgang der Spitzenwerte des VU-Meters muss zwischen 0 und 100 pro Sekunde liegen! + + + Der Segmentabstand des VU-Meters darf nicht null sein! + + + Der Segmentabstand des VU-Meters muss zwischen 0 und 32 liegen! + + + Die Haltedauer der Spitzenwerte des VU-Meters darf nicht null sein! + + + Die Ausrichtung des VU-Meters darf nicht null sein! + + + Der mittlere Schwellenwert des VU-Meters darf nicht null sein! + + + Der hohe Schwellenwert des VU-Meters muss zwischen 0 und 1 liegen! + + + Der Rückgang der Spitzenwerte des VU-Meters darf nicht null sein! + + + Der hohe Schwellenwert des VU-Meters muss größer oder gleich dem mittleren Schwellenwert sein! + + + Der hohe Schwellenwert des VU-Meters darf nicht null sein! + + + Das Album existiert bereits! + + + Die Album-Id darf nicht leer sein! + + + Das Album wurde nicht gefunden! + + + Der Albumtitel darf nicht leer sein! + + + Der Albumtitel darf maximal 255 Zeichen lang sein! + + + Die Albumliste darf nicht null sein! + + + Der Gebietsname darf nicht leer sein! + + + Der Gebietsname darf maximal 255 Zeichen lang sein! + + + Der Aliasname des Künstlers darf nicht leer sein! + + + Der Aliasname des Künstlers darf maximal 255 Zeichen lang sein! + + + Der Künstler existiert bereits! + + + Die Künstler-Id darf nicht leer sein! + + + Der Künstler muss mindestens ein Album haben! + + + Der Künstlername darf nicht leer sein! + + + Der Künstlername darf maximal 255 Zeichen lang sein! + + + Der Künstler wurde nicht gefunden! + + + Die Künstler-Website darf maximal 2048 Zeichen lang sein! + + + Der Barcode-Wert darf nicht leer sein! + + + Die BPM muss größer als null sein! + + + Die Katalognummer darf maximal 50 Zeichen lang sein! + + + Die Abschlussschwelle muss zwischen 0 und 100 liegen! + + + Die Abschlussschwelle muss null sein, wenn die Fortschrittsverfolgung deaktiviert ist! + + + Beim Speichern der Änderungen ist ein Parallelitätskonflikt aufgetreten! + + + Die Anzahl der aufeinanderfolgenden gelesenen Seiten wird nur für seitenbasierte Medien unterstützt! + + + Die Anzahl der aufeinanderfolgenden gelesenen Seiten darf nicht negativ sein! + + + Die konsumierte Dauer darf nicht abnehmen! + + + Die konsumierte Dauer liegt außerhalb des zulässigen Bereichs! + + + Die konsumierte Dauer darf nicht negativ sein! + + + Der Konsumzeitraum ist ungültig! + + + Der Konsum ist bereits beendet! + + + Der Konsum ist nicht in Bearbeitung! + + + Die Konsumdatensatz-Id darf nicht leer sein! + + + Der Konsumdatensatz wurde nicht gefunden! + + + Das Land darf maximal 2 Zeichen lang sein! + + + Das Cover darf nicht null sein! + + + Die Bereitstellungs-Id darf nicht leer sein! + + + Die Bereitstellungs-Id ist ungültig! + + + Die Disknummer muss größer als null sein! + + + Die Endzeit darf nicht vor der letzten Aktivität liegen! + + + Ein beendeter Konsum muss eine Endzeit haben! + + + Der Favorit existiert bereits! + + + Die Favoriten-Medienelement-Id darf nicht leer sein! + + + Die Liste der Favoriten-Medienelement-Ids darf nicht leer sein! + + + Die Liste der Favoriten-Medienelement-Ids überschreitet die maximale Anzahl! + + + Die Favoriten-Medienart ist ungültig! + + + Die Favoriten-Medienart wird nicht unterstützt! + + + Der Favorit wurde nicht gefunden! + + + Die Datei ist zu groß! + + + Ein laufender Konsum darf keine Endzeit haben! + + + Das Barcode-Format ist ungültig! + + + Die Medienposition ist ungültig! + + + Der Fortschrittsanteil ist ungültig! + + + Der IPI-Wert darf nicht leer sein! + + + Der IPI-Wert darf maximal 20 Zeichen lang sein! + + + Der ISNI-Wert darf nicht leer sein! + + + Der ISNI-Wert darf maximal 20 Zeichen lang sein! + + + Das ISRC-Format ist ungültig! + + + Der ISRC-Wert darf nicht leer sein! + + + Die letzte Aktivität darf nicht vor dem Start liegen! + + + Der Standortverweis darf nicht leer sein! + + + Der Medienbeitragende existiert bereits! + + + Der Name des Medienbeitragenden darf nicht leer sein! + + + Der Rollenname des Medienbeitragenden darf nicht leer sein! + + + Die Medienelement-Id darf nicht leer sein! + + + Medien dieser Art können nicht fortgesetzt werden! + + + Medien dieser Art können nicht als abgeschlossen gestartet werden! + + + Der Medienfortsetzungspunkt wurde nicht gefunden! + + + Der Stimmungsname darf nicht leer sein! + + + Das MusicBrainz-Id-Format ist ungültig! + + + Für dieses Buch ist kein Buchleser verfügbar! + + + Es wurde kein unterstütztes Wiedergabeformat gefunden! + + + Das Limit des Normalisierungs-Caches wurde überschritten! + + + Die Normalisierung des Titels ist fehlgeschlagen! + + + Für die direkte Wiedergabe ist keine Normalisierung erforderlich! + + + Die Normalisierung des Titels ist abgelaufen! + + + Die Titel-Normalisierung ist derzeit nicht verfügbar! + + + Der Eintrag im normalisierten Titel-Cache wurde nicht gefunden! + + + Das normalisierte Titelsegment wurde nicht gefunden! + + + Die Pfadvorlage wird für diesen Bibliothekstyp nicht unterstützt! + + + Ein Literalteil der Pfadvorlage darf nicht leer sein! + + + Der Teiltyp der Pfadvorlage wird für diesen Bibliothekstyp nicht unterstützt! + + + Ein Wertteil der Pfadvorlage muss genau einen Platzhalter enthalten! + + + Die Berechtigung wurde nicht gefunden! + + + Die Wiedergabebereitstellung wurde geändert! + + + Die Wiedergabebereitstellung wurde nicht gefunden! + + + Das Wiedergabeformat ist nicht implementiert! + + + Die Wiedergabeliste existiert bereits! + + + Die Wiedergabelistenbeschreibung darf maximal 2000 Zeichen lang sein! + + + Die Wiedergabeliste akzeptiert keine Medienelemente! + + + Die Wiedergabelisteneintrags-Id darf nicht leer sein! + + + Der Wiedergabelisteneintrag wurde nicht gefunden! + + + Die Positionen der Wiedergabelisteneinträge sind ungültig! + + + Die Wiedergabelisten-Id darf nicht leer sein! + + + Die Zielposition der Wiedergabelistenverschiebung ist ungültig! + + + Der Wiedergabelistenname darf nicht leer sein! + + + Der Wiedergabelistenname darf maximal 255 Zeichen lang sein! + + + Die Wiedergabeliste wurde nicht gefunden! + + + Der Wiedergabelistentyp ist ungültig! + + + Der Buchleser, der dieses Buch öffnet, ist für diese Bibliothek deaktiviert! + + + Der Ressourcenschlüssel darf nicht leer sein! + + + Die Ressource wurde nicht gefunden! + + + Das Skript darf maximal 50 Zeichen lang sein! + + + Der Abschnitt wurde nicht gefunden! + + + Die Segmentdauer muss positiv sein! + + + Der Segmentindex darf nicht leer sein! + + + Der Segmentindex ist ungültig! + + + Die Zielbenutzer-Id ist ungültig! + + + Der Künstler hat das Album bereits! + + + Der Künstler hat das Album nicht! + + + Der Titel ist bereits im Album! + + + Der Titel ist nicht im Album! + + + Die Theme-Vorlage wurde nicht gefunden! + + + Die Gesamtzahl der Disks muss größer als null sein! + + + Die Gesamtzahl der Titel muss größer als null sein! + + + Der Titel existiert bereits! + + + Die Titeldauer muss positiv sein! + + + Die Titeldatei wurde nicht gefunden! + + + Die Titel-Id darf nicht leer sein! + + + Der Titel wurde nicht gefunden! + + + Die Titelnummer muss größer als null sein! + + + Der Titelpfad darf nicht leer sein! + + + Der Titelpfad darf maximal 2048 Zeichen lang sein! + + + Der Titelpfad muss sich in einem der Inhaltsorte der Bibliothek befinden! + + + Die Titelliste darf nicht null sein! + + + Das Geschlecht des Musik-Künstlers ist unbekannt! + + + Der Typ des Musik-Künstlers ist unbekannt! + + + Der Musikschlüssel ist unbekannt! + + + Das Musik-Medienformat ist unbekannt! + + + Die Verpackung der Musikveröffentlichung ist unbekannt! + + + Der Status der Musikveröffentlichung ist unbekannt! + + + Der Typ der Musikveröffentlichung ist unbekannt! + + + Die Medienart wird nicht unterstützt! + + + Das Werk darf maximal 255 Zeichen lang sein! + + + Der Werktitel darf nicht leer sein! + + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.en-US.resx b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.en-US.resx index f13e7548..81d5e56c 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.en-US.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.en-US.resx @@ -813,4 +813,496 @@ The schedule type is invalid! - \ No newline at end of file + + Invalid ReplayGain mode! + + + Invalid streaming quality! + + + The mute state cannot be null! + + + The volume cannot be null! + + + The volume must be between 0 and 1! + + + The keep-downloading-while-paused preference cannot be null! + + + The autoplay preference cannot be null! + + + The gapless playback preference cannot be null! + + + The ReplayGain mode cannot be null! + + + The streaming quality cannot be null! + + + The shuffle track count must be greater than zero! + + + The shuffle track count must be at most 500! + + + The VU meter release cannot be null! + + + The VU meter segment count cannot be null! + + + The VU meter release must be between 0 and 100 per second! + + + The VU meter peak hold duration must be between 0 and 10000 milliseconds! + + + Invalid VU meter orientation! + + + The VU meter segment count must be between 1 and 128! + + + The VU meter show peak preference cannot be null! + + + The VU meter medium threshold must be between 0 and 1! + + + The VU meter peak release must be between 0 and 100 per second! + + + The VU meter segment gap cannot be null! + + + The VU meter segment gap must be between 0 and 32! + + + The VU meter peak hold duration cannot be null! + + + The VU meter orientation cannot be null! + + + The VU meter medium threshold cannot be null! + + + The VU meter high threshold must be between 0 and 1! + + + The VU meter peak release cannot be null! + + + The VU meter high threshold must be greater than or equal to the medium threshold! + + + The VU meter high threshold cannot be null! + + + The album already exists! + + + The album Id cannot be empty! + + + The album was not found! + + + The album title cannot be empty! + + + The album title must be maximum 255 characters long! + + + The albums list cannot be null! + + + The area name cannot be empty! + + + The area name must be maximum 255 characters long! + + + The artist alias name cannot be empty! + + + The artist alias name must be maximum 255 characters long! + + + The artist already exists! + + + The artist Id cannot be empty! + + + The artist must have at least one album! + + + The artist name cannot be empty! + + + The artist name must be maximum 255 characters long! + + + The artist was not found! + + + The artist website must be maximum 2048 characters long! + + + The barcode value cannot be empty! + + + The BPM must be greater than zero! + + + The catalog number must be maximum 50 characters long! + + + The completion threshold must be between 0 and 100! + + + The completion threshold must be null when progress tracking is off! + + + A concurrency conflict occurred while saving the changes! + + + The number of consecutive pages read is only supported for page based media! + + + The number of consecutive pages read cannot be negative! + + + The consumed duration cannot decrease! + + + The consumed duration is out of range! + + + The consumed duration cannot be negative! + + + The consumption date range is invalid! + + + The consumption has already ended! + + + The consumption is not in progress! + + + The consumption record Id cannot be empty! + + + The consumption record was not found! + + + The country must be maximum 2 characters long! + + + The cover cannot be null! + + + The delivery Id cannot be empty! + + + The delivery Id is invalid! + + + The disc number must be greater than zero! + + + The end time cannot precede the last activity! + + + An ended consumption must have an end time! + + + The favorite already exists! + + + The favorite media item Id cannot be empty! + + + The favorite media item Ids list cannot be empty! + + + The favorite media item Ids list exceeds the maximum count! + + + The favorite media kind is invalid! + + + The favorite media kind is not supported! + + + The favorite was not found! + + + The file is too large! + + + A consumption that is in progress cannot have an end time! + + + The barcode format is invalid! + + + The media position is invalid! + + + The progress fraction is invalid! + + + The IPI value cannot be empty! + + + The IPI value must be maximum 20 characters long! + + + The ISNI value cannot be empty! + + + The ISNI value must be maximum 20 characters long! + + + The ISRC format is invalid! + + + The ISRC value cannot be empty! + + + The last activity cannot precede the start! + + + The location reference cannot be empty! + + + The media contributor already exists! + + + The media contributor name cannot be empty! + + + The media contributor role name cannot be empty! + + + The media item Id cannot be empty! + + + Media of this kind cannot be resumed! + + + Media of this kind cannot be started as completed! + + + The media resume point was not found! + + + The mood name cannot be empty! + + + The MusicBrainz Id format is invalid! + + + No reader is available for this book! + + + No supported playback format was found! + + + The normalization cache limit was exceeded! + + + The track normalization failed! + + + Normalization is not required for direct playback! + + + The track normalization timed out! + + + Track normalization is currently unavailable! + + + The normalized track cache entry was not found! + + + The normalized track segment was not found! + + + The path template is not supported for this library type! + + + A literal part of the path template cannot be empty! + + + The path template part kind is not supported for this library type! + + + A value part of the path template must contain exactly one placeholder! + + + The permission was not found! + + + The playback delivery changed! + + + The playback delivery was not found! + + + The playback format is not implemented! + + + The playlist already exists! + + + The playlist description must be maximum 2000 characters long! + + + The playlist does not accept media items! + + + The playlist entry Id cannot be empty! + + + The playlist entry was not found! + + + The playlist entry positions are invalid! + + + The playlist Id cannot be empty! + + + The playlist move target position is invalid! + + + The playlist name cannot be empty! + + + The playlist name must be maximum 255 characters long! + + + The playlist was not found! + + + The playlist type is invalid! + + + The reader is disabled for this library! + + + The resource key cannot be empty! + + + The resource was not found! + + + The script must be maximum 50 characters long! + + + The section was not found! + + + The segment duration must be positive! + + + The segment index cannot be empty! + + + The segment index is invalid! + + + The target user Id is invalid! + + + The artist already has the album! + + + The artist does not have the album! + + + The track is already in the album! + + + The track is not in the album! + + + The theme template was not found! + + + The total number of discs must be greater than zero! + + + The total number of tracks must be greater than zero! + + + The track already exists! + + + The track duration must be positive! + + + The track file was not found! + + + The track Id cannot be empty! + + + The track was not found! + + + The track number must be greater than zero! + + + The track path cannot be empty! + + + The track path must be maximum 2048 characters long! + + + The track path must be inside one of the library content locations! + + + The tracks list cannot be null! + + + The music artist gender is unknown! + + + The music artist type is unknown! + + + The music key is unknown! + + + The music media format is unknown! + + + The music release packaging is unknown! + + + The music release status is unknown! + + + The music release type is unknown! + + + The media kind is not supported! + + + The work must be maximum 255 characters long! + + + The work title cannot be empty! + + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.es-ES.resx b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.es-ES.resx index faafc50f..b36fedaf 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.es-ES.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.es-ES.resx @@ -813,4 +813,496 @@ El tipo de programación no es válido! - \ No newline at end of file + + ¡Modo ReplayGain no válido! + + + ¡Calidad de transmisión no válida! + + + ¡El estado de silencio no puede ser nulo! + + + ¡El volumen no puede ser nulo! + + + ¡El volumen debe estar entre 0 y 1! + + + ¡La preferencia de seguir descargando en pausa no puede ser nula! + + + ¡La preferencia de reproducción automática no puede ser nula! + + + ¡La preferencia de reproducción sin pausas no puede ser nula! + + + ¡El modo ReplayGain no puede ser nulo! + + + ¡La calidad de transmisión no puede ser nula! + + + ¡La cantidad de pistas de reproducción aleatoria debe ser mayor que cero! + + + ¡La cantidad de pistas de reproducción aleatoria no debe superar 500! + + + La caída del vúmetro no puede ser nula. + + + El número de segmentos del vúmetro no puede ser nulo. + + + La caída del vúmetro debe estar entre 0 y 100 por segundo. + + + La duración de retención de los picos del vúmetro debe estar entre 0 y 10000 milisegundos. + + + ¡Orientación del vúmetro no válida! + + + El número de segmentos del vúmetro debe estar entre 1 y 128. + + + La preferencia de mostrar los picos del vúmetro no puede ser nula. + + + El umbral medio del vúmetro debe estar entre 0 y 1. + + + La caída de los picos del vúmetro debe estar entre 0 y 100 por segundo. + + + La separación de los segmentos del vúmetro no puede ser nula. + + + La separación de los segmentos del vúmetro debe estar entre 0 y 32. + + + La duración de retención de los picos del vúmetro no puede ser nula. + + + La orientación del vúmetro no puede ser nula. + + + El umbral medio del vúmetro no puede ser nulo. + + + El umbral alto del vúmetro debe estar entre 0 y 1. + + + La caída de los picos del vúmetro no puede ser nula. + + + El umbral alto del vúmetro debe ser mayor o igual que el umbral medio. + + + El umbral alto del vúmetro no puede ser nulo. + + + ¡El álbum ya existe! + + + ¡El ID del álbum no puede estar vacío! + + + ¡El álbum no fue encontrado! + + + ¡El título del álbum no puede estar vacío! + + + ¡El título del álbum debe tener un máximo de 255 caracteres! + + + ¡La lista de álbumes no puede ser nula! + + + ¡El nombre del área no puede estar vacío! + + + ¡El nombre del área debe tener un máximo de 255 caracteres! + + + ¡El nombre del alias del artista no puede estar vacío! + + + ¡El nombre del alias del artista debe tener un máximo de 255 caracteres! + + + ¡El artista ya existe! + + + ¡El ID del artista no puede estar vacío! + + + ¡El artista debe tener al menos un álbum! + + + ¡El nombre del artista no puede estar vacío! + + + ¡El nombre del artista debe tener un máximo de 255 caracteres! + + + ¡El artista no fue encontrado! + + + ¡El sitio web del artista debe tener un máximo de 2048 caracteres! + + + ¡El valor del código de barras no puede estar vacío! + + + ¡El BPM debe ser mayor que cero! + + + ¡El número de catálogo debe tener como máximo 50 caracteres! + + + ¡El umbral de finalización debe estar entre 0 y 100! + + + ¡El umbral de finalización debe ser nulo cuando el seguimiento del progreso está desactivado! + + + ¡Se produjo un conflicto de simultaneidad al guardar los cambios! + + + ¡El número de páginas consecutivas leídas solo se admite para medios paginados! + + + ¡El número de páginas consecutivas leídas no puede ser negativo! + + + ¡La duración consumida no puede disminuir! + + + ¡La duración consumida está fuera de rango! + + + ¡La duración consumida no puede ser negativa! + + + ¡El rango de fechas de consumo no es válido! + + + ¡El consumo ya ha finalizado! + + + ¡El consumo no está en curso! + + + ¡El Id del registro de consumo no puede estar vacío! + + + ¡El registro de consumo no fue encontrado! + + + ¡El país debe tener un máximo de 2 caracteres! + + + ¡La portada no puede ser nula! + + + ¡El ID de entrega no puede estar vacío! + + + ¡El ID de entrega no es válido! + + + ¡El número de disco debe ser mayor que cero! + + + ¡La hora de finalización no puede ser anterior a la última actividad! + + + ¡Un consumo finalizado debe tener una hora de finalización! + + + ¡El favorito ya existe! + + + ¡El ID del elemento multimedia favorito no puede estar vacío! + + + ¡La lista de ID de elementos multimedia favoritos no puede estar vacía! + + + ¡La lista de ID de elementos multimedia favoritos supera el recuento máximo! + + + ¡El tipo de medio favorito no es válido! + + + ¡El tipo de medio favorito no es compatible! + + + ¡El favorito no fue encontrado! + + + ¡El archivo es demasiado grande! + + + ¡Un consumo en curso no puede tener una hora de finalización! + + + ¡El formato del código de barras no es válido! + + + ¡La posición multimedia no es válida! + + + ¡La fracción de progreso no es válida! + + + ¡El valor del IPI no puede estar vacío! + + + ¡El valor IPI debe tener un máximo de 20 caracteres! + + + ¡El valor ISNI no puede estar vacío! + + + ¡El valor ISNI debe tener un máximo de 20 caracteres! + + + ¡El formato ISRC no es válido! + + + ¡El valor ISRC no puede estar vacío! + + + ¡La última actividad no puede ser anterior al inicio! + + + ¡La referencia de ubicación no puede estar vacía! + + + ¡El colaborador de medios ya existe! + + + ¡El nombre del colaborador de medios no puede estar vacío! + + + ¡El nombre del rol de colaborador de medios no puede estar vacío! + + + ¡El Id del elemento multimedia no puede estar vacío! + + + ¡Los medios de este tipo no se pueden reanudar! + + + ¡Los medios de este tipo no se pueden iniciar como completados! + + + ¡El punto de reanudación multimedia no fue encontrado! + + + ¡El nombre del estado de ánimo no puede estar vacío! + + + ¡El formato de ID de MusicBrainz no es válido! + + + ¡No hay ningún lector de libros disponible para este libro! + + + ¡No se encontró ningún formato de reproducción compatible! + + + ¡Se superó el límite de caché de normalización! + + + ¡La normalización de la pista falló! + + + ¡No se requiere normalización para la reproducción directa! + + + ¡Se agotó el tiempo de normalización de la pista! + + + ¡La normalización de pistas no está disponible actualmente! + + + ¡No se encontró la entrada de caché de pista normalizada! + + + ¡No se encontró el segmento de pista normalizado! + + + ¡La plantilla de ruta no es compatible con este tipo de biblioteca! + + + ¡Una parte literal de la plantilla de ruta no puede estar vacía! + + + ¡El tipo de pieza de plantilla de ruta no es compatible con este tipo de biblioteca! + + + ¡Una parte de valor de la plantilla de ruta debe contener exactamente un marcador de posición! + + + ¡No se encontró el permiso! + + + ¡La entrega de la reproducción cambió! + + + ¡No se encontró la entrega de reproducción! + + + ¡El formato de reproducción no está implementado! + + + ¡La lista de reproducción ya existe! + + + ¡La descripción de la lista de reproducción debe tener un máximo de 2000 caracteres! + + + ¡La lista de reproducción no acepta elementos multimedia! + + + ¡El ID de entrada de la lista de reproducción no puede estar vacío! + + + ¡No se encontró la entrada de la lista de reproducción! + + + ¡Las posiciones de entrada de la lista de reproducción no son válidas! + + + ¡El ID de la lista de reproducción no puede estar vacío! + + + ¡La posición de destino del movimiento de la lista de reproducción no es válida! + + + ¡El nombre de la lista de reproducción no puede estar vacío! + + + ¡El nombre de la lista de reproducción debe tener un máximo de 255 caracteres! + + + ¡La lista de reproducción no fue encontrada! + + + ¡El tipo de lista de reproducción no es válido! + + + ¡El lector de libros está deshabilitado para esta biblioteca! + + + ¡La clave de recurso no puede estar vacía! + + + ¡El recurso no fue encontrado! + + + ¡El guión debe tener un máximo de 50 caracteres! + + + ¡La sección no fue encontrada! + + + ¡La duración del segmento debe ser positiva! + + + ¡El índice del segmento no puede estar vacío! + + + ¡El índice del segmento no es válido! + + + ¡El Id del usuario de destino no es válido! + + + ¡El artista ya tiene el álbum! + + + ¡El artista no tiene el álbum! + + + ¡La pista ya está en el álbum! + + + ¡La pista no está en el álbum! + + + ¡No se encontró la plantilla del tema! + + + ¡El número total de discos debe ser mayor que cero! + + + ¡El número total de pistas debe ser mayor que cero! + + + ¡La pista ya existe! + + + ¡La duración de la pista debe ser positiva! + + + ¡No se encontró el archivo de la pista! + + + ¡El ID de la pista no puede estar vacío! + + + ¡La pista no fue encontrada! + + + ¡El número de pista debe ser mayor que cero! + + + ¡La ruta de la pista no puede estar vacía! + + + ¡La ruta de la pista debe tener una longitud máxima de 2048 caracteres! + + + ¡La ruta de la pista debe estar dentro de una de las ubicaciones de contenido de la biblioteca! + + + ¡La lista de pistas no puede ser nula! + + + ¡Se desconoce el género del artista musical! + + + ¡Se desconoce el tipo de artista musical! + + + ¡La clave musical es desconocida! + + + ¡Se desconoce el formato del medio musical! + + + ¡Se desconoce el empaque del lanzamiento musical! + + + ¡Se desconoce el estado del lanzamiento de la música! + + + ¡Se desconoce el tipo de lanzamiento musical! + + + ¡El tipo de medio no es compatible! + + + ¡El trabajo debe tener una extensión máxima de 255 caracteres! + + + ¡El título de la obra no puede estar vacío! + + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.fr-FR.resx b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.fr-FR.resx index 1d433f85..fc764a80 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.fr-FR.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.fr-FR.resx @@ -813,4 +813,496 @@ Le type de planification n'est pas valide ! - \ No newline at end of file + + Mode ReplayGain non valide ! + + + Qualité de diffusion non valide ! + + + L'état de sourdine ne peut pas être nul ! + + + Le volume ne peut pas être nul ! + + + Le volume doit être compris entre 0 et 1 ! + + + La préférence de téléchargement en pause ne peut pas être nulle ! + + + La préférence de lecture automatique ne peut pas être nulle ! + + + La préférence de lecture sans interruption ne peut pas être nulle ! + + + Le mode ReplayGain ne peut pas être nul ! + + + La qualité de diffusion ne peut pas être nulle ! + + + Le nombre de pistes du shuffle doit être supérieur à zéro ! + + + Le nombre de pistes du shuffle ne doit pas dépasser 500 ! + + + La décroissance du vumètre ne peut pas être nulle ! + + + Le nombre de segments du vumètre ne peut pas être nul ! + + + La décroissance du vumètre doit être comprise entre 0 et 100 par seconde ! + + + La durée de maintien des crêtes du vumètre doit être comprise entre 0 et 10000 millisecondes ! + + + Orientation du vumètre non valide ! + + + Le nombre de segments du vumètre doit être compris entre 1 et 128 ! + + + La préférence d'affichage des crêtes du vumètre ne peut pas être nulle ! + + + Le seuil moyen du vumètre doit être compris entre 0 et 1 ! + + + La décroissance des crêtes du vumètre doit être comprise entre 0 et 100 par seconde ! + + + L'espacement des segments du vumètre ne peut pas être nul ! + + + L'espacement des segments du vumètre doit être compris entre 0 et 32 ! + + + La durée de maintien des crêtes du vumètre ne peut pas être nulle ! + + + L'orientation du vumètre ne peut pas être nulle ! + + + Le seuil moyen du vumètre ne peut pas être nul ! + + + Le seuil élevé du vumètre doit être compris entre 0 et 1 ! + + + La décroissance des crêtes du vumètre ne peut pas être nulle ! + + + Le seuil élevé du vumètre doit être supérieur ou égal au seuil moyen ! + + + Le seuil élevé du vumètre ne peut pas être nul ! + + + L'album existe déjà ! + + + L'album Id ne peut pas être vide ! + + + L'album n'a pas été trouvé ! + + + Le titre de l'album ne peut pas être vide ! + + + Le titre de l’album doit comporter au maximum 255 caractères ! + + + La liste des albums ne peut pas être nulle ! + + + Le nom de la zone ne peut pas être vide ! + + + Le nom de la zone doit comporter au maximum 255 caractères ! + + + Le nom d'alias de l'artiste ne peut pas être vide ! + + + Le nom d’alias de l’artiste doit comporter au maximum 255 caractères ! + + + L'artiste existe déjà ! + + + L'identifiant de l'artiste ne peut pas être vide ! + + + L'artiste doit avoir au moins un album ! + + + Le nom de l'artiste ne peut pas être vide ! + + + Le nom de l’artiste doit comporter au maximum 255 caractères ! + + + L'artiste n'a pas été retrouvé ! + + + Le site Web de l’artiste doit contenir au maximum 2048 caractères ! + + + La valeur du code-barres ne peut pas être vide ! + + + Le BPM doit être supérieur à zéro ! + + + Le numéro de catalogue doit comporter au maximum 50 caractères ! + + + Le seuil d'achèvement doit être compris entre 0 et 100 ! + + + Le seuil d'achèvement doit être nul lorsque le suivi de la progression est désactivé ! + + + Un conflit de concurrence s'est produit lors de l'enregistrement des modifications ! + + + Le nombre de pages consécutives lues n'est pris en charge que pour les médias paginés ! + + + Le nombre de pages consécutives lues ne peut pas être négatif ! + + + La durée consommée ne peut pas diminuer ! + + + La durée consommée est hors limites ! + + + La durée consommée ne peut pas être négative ! + + + La plage de dates de consommation est invalide ! + + + La consommation est déjà terminée ! + + + La consommation n'est pas en cours ! + + + L'Id de l'enregistrement de consommation ne peut pas être vide ! + + + L'enregistrement de consommation est introuvable ! + + + Le pays doit comporter au maximum 2 caractères ! + + + La couverture ne peut pas être nulle ! + + + L’identifiant de livraison ne peut pas être vide ! + + + L'identifiant de livraison n'est pas valide ! + + + Le numéro du disque doit être supérieur à zéro ! + + + L'heure de fin ne peut pas précéder la dernière activité ! + + + Une consommation terminée doit avoir une heure de fin ! + + + Le favori existe déjà ! + + + L’identifiant de l’élément multimédia favori ne peut pas être vide ! + + + La liste des identifiants des éléments multimédias favoris ne peut pas être vide ! + + + La liste des identifiants des éléments multimédias favoris dépasse le nombre maximum ! + + + Le type de média favori n'est pas valide ! + + + Le type de média favori n'est pas pris en charge ! + + + Le favori n'a pas été trouvé ! + + + Le fichier est trop volumineux ! + + + Une consommation en cours ne peut pas avoir d'heure de fin ! + + + Le format du code-barres n'est pas valide ! + + + La position multimédia est invalide ! + + + La fraction de progression est invalide ! + + + La valeur IPI ne peut pas être vide ! + + + La valeur IPI doit comporter au maximum 20 caractères ! + + + La valeur ISNI ne peut pas être vide ! + + + La valeur ISNI doit comporter au maximum 20 caractères ! + + + Le format ISRC n'est pas valide ! + + + La valeur ISRC ne peut pas être vide ! + + + La dernière activité ne peut pas précéder le début ! + + + La référence de localisation ne peut pas être vide ! + + + Le contributeur média existe déjà ! + + + Le nom du contributeur média ne peut pas être vide ! + + + Le nom du rôle de contributeur média ne peut pas être vide ! + + + L'Id de l'élément multimédia ne peut pas être vide ! + + + Les médias de ce type ne peuvent pas être repris ! + + + Les médias de ce type ne peuvent pas être démarrés comme terminés ! + + + Le point de reprise multimédia est introuvable ! + + + Le nom de l'ambiance ne peut pas être vide ! + + + Le format MusicBrainz Id n’est pas valide ! + + + Aucun lecteur de livres n'est disponible pour ce livre ! + + + Aucun format de lecture pris en charge n'a été trouvé ! + + + La limite du cache de normalisation a été dépassée ! + + + La normalisation de la piste a échoué ! + + + La normalisation n'est pas requise pour la lecture directe ! + + + Le délai de normalisation de la piste a expiré ! + + + La normalisation des pistes n'est actuellement pas disponible ! + + + L'entrée du cache de piste normalisée est introuvable ! + + + Le segment de piste normalisé est introuvable ! + + + Le modèle de chemin n'est pas pris en charge pour ce type de bibliothèque ! + + + Une partie littérale du modèle de chemin ne peut pas être vide ! + + + Le type de partie de modèle de chemin n'est pas pris en charge pour ce type de bibliothèque ! + + + Une partie valeur du modèle de chemin doit contenir exactement un espace réservé ! + + + La permission n'a pas été trouvée ! + + + La diffusion de la lecture a changé ! + + + La livraison de lecture n'a pas été trouvée ! + + + Le format de lecture n'est pas implémenté ! + + + La liste de lecture existe déjà ! + + + La description de la liste de lecture ne doit pas dépasser 2000 caractères ! + + + La liste de lecture n'accepte pas d'éléments multimédias ! + + + L'Id de l'entrée de la liste de lecture ne peut pas être vide ! + + + L'entrée de la liste de lecture est introuvable ! + + + Les positions des entrées de la liste de lecture sont invalides ! + + + L'Id de la liste de lecture ne peut pas être vide ! + + + La position cible du déplacement dans la liste de lecture est invalide ! + + + Le nom de la liste de lecture ne peut pas être vide ! + + + Le nom de la liste de lecture ne doit pas dépasser 255 caractères ! + + + La liste de lecture est introuvable ! + + + Le type de liste de lecture est invalide ! + + + Le lecteur de livres est désactivé pour cette bibliothèque ! + + + La clé de ressource ne peut pas être vide ! + + + La ressource n'a pas été trouvée ! + + + Le script doit comporter au maximum 50 caractères ! + + + La section n'a pas été trouvée ! + + + La durée du segment doit être positive ! + + + L'index du segment ne peut pas être vide ! + + + L'index du segment n'est pas valide ! + + + L'Id de l'utilisateur cible est invalide ! + + + L'artiste possède déjà l'album ! + + + L'artiste n'a pas l'album ! + + + La piste est déjà dans l'album ! + + + La piste n'est pas dans l'album ! + + + Le modèle de thème n'a pas été trouvé ! + + + Le nombre total de disques doit être supérieur à zéro ! + + + Le nombre total de pistes doit être supérieur à zéro ! + + + La piste existe déjà ! + + + La durée de la piste doit être positive ! + + + Le fichier de la piste est introuvable ! + + + L'Id de la piste ne peut pas être vide ! + + + La piste est introuvable ! + + + Le numéro de piste doit être supérieur à zéro ! + + + Le chemin de la piste ne peut pas être vide ! + + + Le chemin de la piste ne doit pas dépasser 2048 caractères ! + + + Le chemin de la piste doit se trouver dans l'un des emplacements de contenu de la bibliothèque ! + + + La liste des pistes ne peut pas être nulle ! + + + Le sexe de l’artiste musical est inconnu ! + + + Le type d'artiste musical est inconnu ! + + + La tonalité musicale est inconnue ! + + + Le format du média musical est inconnu ! + + + Le packaging de la sortie musicale est inconnu ! + + + Le statut de sortie de la musique est inconnu ! + + + Le type de sortie musicale est inconnu ! + + + Le type de média n'est pas pris en charge ! + + + L’œuvre doit comporter au maximum 255 caractères ! + + + Le titre de l’œuvre ne peut pas être vide ! + + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.it-IT.resx b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.it-IT.resx index e41878ca..56c362f1 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.it-IT.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.it-IT.resx @@ -813,4 +813,496 @@ Il tipo di pianificazione non è valido! - \ No newline at end of file + + Modalità ReplayGain non valida! + + + Qualità dello streaming non valida! + + + Lo stato di silenziamento non può essere nullo! + + + Il volume non può essere nullo! + + + Il volume deve essere compreso tra 0 e 1! + + + La preferenza di continuare il download in pausa non può essere nulla! + + + La preferenza di riproduzione automatica non può essere nulla! + + + La preferenza di riproduzione senza interruzioni non può essere nulla! + + + La modalità ReplayGain non può essere nulla! + + + La qualità dello streaming non può essere nulla! + + + Il numero di brani dello shuffle deve essere maggiore di zero! + + + Il numero di brani dello shuffle non può superare 500! + + + La caduta del vumetro non può essere nulla. + + + Il numero di segmenti del vumetro non può essere nullo. + + + La caduta del vumetro deve essere compresa tra 0 e 100 al secondo. + + + La durata di mantenimento dei picchi del vumetro deve essere compresa tra 0 e 10000 millisecondi. + + + Orientamento del vumetro non valido! + + + Il numero di segmenti del vumetro deve essere compreso tra 1 e 128. + + + La preferenza di mostrare i picchi del vumetro non può essere nulla. + + + La soglia media del vumetro deve essere compresa tra 0 e 1. + + + La caduta dei picchi del vumetro deve essere compresa tra 0 e 100 al secondo. + + + La spaziatura dei segmenti del vumetro non può essere nulla. + + + La spaziatura dei segmenti del vumetro deve essere compresa tra 0 e 32. + + + La durata di mantenimento dei picchi del vumetro non può essere nulla. + + + L'orientamento del vumetro non può essere nullo. + + + La soglia media del vumetro non può essere nulla. + + + La soglia alta del vumetro deve essere compresa tra 0 e 1. + + + La caduta dei picchi del vumetro non può essere nulla. + + + La soglia alta del vumetro deve essere maggiore o uguale alla soglia media. + + + La soglia alta del vumetro non può essere nulla. + + + L'album esiste già! + + + L'ID dell'album non può essere vuoto! + + + L'album non è stato trovato! + + + Il titolo dell'album non può essere vuoto! + + + Il titolo dell'album deve contenere al massimo 255 caratteri! + + + L'elenco degli album non può essere nullo! + + + Il nome dell'area non può essere vuoto! + + + Il nome dell'area deve contenere al massimo 255 caratteri! + + + Il nome alias dell'artista non può essere vuoto! + + + L'alias dell'artista deve contenere al massimo 255 caratteri! + + + L'artista esiste già! + + + L'ID artista non può essere vuoto! + + + L'artista deve avere almeno un album! + + + Il nome dell'artista non può essere vuoto! + + + Il nome dell'artista deve contenere al massimo 255 caratteri! + + + L'artista non è stato trovato! + + + Il sito web dell'artista deve contenere al massimo 2048 caratteri! + + + Il valore del codice a barre non può essere vuoto! + + + Il BPM deve essere maggiore di zero! + + + Il numero di catalogo deve contenere al massimo 50 caratteri! + + + La soglia di completamento deve essere compresa tra 0 e 100! + + + La soglia di completamento deve essere nulla quando il monitoraggio del progresso è disattivato! + + + Si è verificato un conflitto di concorrenza durante il salvataggio delle modifiche! + + + Il numero di pagine consecutive lette è supportato solo per i contenuti paginati! + + + Il numero di pagine consecutive lette non può essere negativo! + + + La durata consumata non può diminuire! + + + La durata consumata è fuori intervallo! + + + La durata consumata non può essere negativa! + + + L'intervallo di date di consumo non è valido! + + + Il consumo è già terminato! + + + Il consumo non è in corso! + + + L'Id del record di consumo non può essere vuoto! + + + Il record di consumo non è stato trovato! + + + Il paese deve contenere al massimo 2 caratteri! + + + La copertina non può essere nulla! + + + L'ID di consegna non può essere vuoto! + + + L'ID di consegna non è valido! + + + Il numero del disco deve essere maggiore di zero! + + + L'ora di fine non può precedere l'ultima attività! + + + Un consumo terminato deve avere un'ora di fine! + + + Il preferito esiste già! + + + L'ID dell'elemento multimediale preferito non può essere vuoto! + + + L'elenco degli ID degli elementi multimediali preferiti non può essere vuoto! + + + L'elenco degli ID degli elementi multimediali preferiti supera il conteggio massimo! + + + Il tipo di supporto preferito non è valido! + + + Il tipo multimediale preferito non è supportato! + + + Il preferito non è stato trovato! + + + Il file è troppo grande! + + + Un consumo in corso non può avere un'ora di fine! + + + Il formato del codice a barre non è valido! + + + La posizione multimediale non è valida! + + + La frazione di progresso non è valida! + + + Il valore IPI non può essere vuoto! + + + Il valore IPI deve contenere al massimo 20 caratteri! + + + Il valore ISNI non può essere vuoto! + + + Il valore ISNI deve contenere al massimo 20 caratteri! + + + Il formato ISRC non è valido! + + + Il valore ISRC non può essere vuoto! + + + L'ultima attività non può precedere l'inizio! + + + Il riferimento alla posizione non può essere vuoto! + + + Il collaboratore multimediale esiste già! + + + Il nome del collaboratore multimediale non può essere vuoto! + + + Il nome del ruolo di collaboratore multimediale non può essere vuoto! + + + L'Id dell'elemento multimediale non può essere vuoto! + + + I contenuti di questo tipo non possono essere ripresi! + + + I contenuti di questo tipo non possono essere avviati come completati! + + + Il punto di ripresa multimediale non è stato trovato! + + + Il nome dello stato d'animo non può essere vuoto! + + + Il formato dell'ID MusicBrainz non è valido! + + + Nessun lettore di libri disponibile per questo libro! + + + Non è stato trovato alcun formato di riproduzione supportato! + + + Il limite della cache di normalizzazione è stato superato! + + + La normalizzazione del brano è fallita! + + + La normalizzazione non è necessaria per la riproduzione diretta! + + + La normalizzazione del brano è scaduta! + + + La normalizzazione del brano non è attualmente disponibile! + + + La voce della cache del brano normalizzato non è stata trovata! + + + Il segmento del brano normalizzato non è stato trovato! + + + Il modello di percorso non è supportato per questo tipo di libreria! + + + Una parte letterale del modello di percorso non può essere vuota! + + + Il tipo di parte del modello di percorso non è supportato per questo tipo di libreria! + + + Una parte del valore del modello del percorso deve contenere esattamente un segnaposto! + + + Il permesso non è stato trovato! + + + La consegna della riproduzione è cambiata! + + + La consegna della riproduzione non è stata trovata! + + + Il formato di riproduzione non è implementato! + + + La playlist esiste già! + + + La descrizione della playlist deve contenere al massimo 2000 caratteri! + + + La playlist non accetta elementi multimediali! + + + L'ID della voce della playlist non può essere vuoto! + + + La voce della playlist non è stata trovata! + + + Le posizioni delle voci della playlist non sono valide! + + + L'ID della playlist non può essere vuoto! + + + La posizione di destinazione dello spostamento della playlist non è valida! + + + Il nome della playlist non può essere vuoto! + + + Il nome della playlist deve contenere al massimo 255 caratteri! + + + La playlist non è stata trovata! + + + Il tipo di playlist non è valido! + + + Il lettore di libri è disabilitato per questa libreria! + + + La chiave della risorsa non può essere vuota! + + + La risorsa non è stata trovata! + + + Lo script deve contenere al massimo 50 caratteri! + + + La sezione non è stata trovata! + + + La durata del segmento deve essere positiva! + + + L'indice del segmento non può essere vuoto! + + + L'indice del segmento non è valido! + + + L'Id dell'utente di destinazione non è valido! + + + L'artista ha già l'album! + + + L'artista non ha l'album! + + + Il brano è già nell'album! + + + Il brano non è nell'album! + + + Il modello del tema non è stato trovato! + + + Il numero totale di dischi deve essere maggiore di zero! + + + Il numero totale di brani deve essere maggiore di zero! + + + Il brano esiste già! + + + La durata del brano deve essere positiva! + + + Il file del brano non è stato trovato! + + + L'Id del brano non può essere vuoto! + + + Il brano non è stato trovato! + + + Il numero del brano deve essere maggiore di zero! + + + Il percorso del brano non può essere vuoto! + + + Il percorso del brano deve essere lungo al massimo 2048 caratteri! + + + Il percorso del brano deve trovarsi all'interno di una delle posizioni di contenuto della libreria! + + + La lista dei brani non può essere nulla! + + + Il sesso dell'artista musicale è sconosciuto! + + + Il tipo di artista musicale è sconosciuto! + + + La chiave musicale è sconosciuta! + + + Il formato multimediale musicale è sconosciuto! + + + La confezione dell'uscita della musica è sconosciuta! + + + Lo stato di pubblicazione della musica è sconosciuto! + + + Il tipo di pubblicazione della musica è sconosciuto! + + + Il tipo di contenuto non è supportato! + + + L'opera deve essere lunga al massimo 255 caratteri! + + + Il titolo dell'opera non può essere vuoto! + + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ja-JP.resx b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ja-JP.resx index 2cd57da7..804b2b90 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ja-JP.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ja-JP.resx @@ -217,22 +217,22 @@ 完了したスキャンジョブ数は正の値でなければなりません! - 出演者の表示名を空にすることはできません! + 寄稿者の表示名を空にすることはできません。 - 出演者の表示名は最大100文字までです! + 寄稿者の表示名は最大100文字までです! - 出演者の本名は最大100文字までです! + 寄稿者の本名は最大100文字までです! - 出演者名を空にすることはできません! + 寄稿者名を空にすることはできません。 - 出演者の役割をnullにすることはできません! + 寄稿者の役割をnullにすることはできません。 - 出演者リストをnullにすることはできません! + 寄稿者リストをnullにすることはできません。 CORSオリジンが無効です! @@ -813,4 +813,496 @@ スケジュールタイプが無効です! - \ No newline at end of file + + ReplayGain モードが無効です。 + + + ストリーミング品質が無効です。 + + + ミュート状態は null にできません。 + + + 音量は null にできません。 + + + 音量は 0 から 1 の間でなければなりません。 + + + 一時停止中のダウンロード継続の設定は null にできません。 + + + 自動再生の設定は null にできません。 + + + ギャップレス再生の設定は null にできません。 + + + ReplayGain モードは null にできません。 + + + ストリーミング品質は null にできません。 + + + シャッフルするトラック数は 0 より大きい必要があります。 + + + シャッフルするトラック数は 500 以下である必要があります。 + + + VUメーターの減衰はnullにできません。 + + + VUメーターのセグメント数はnullにできません。 + + + VUメーターの減衰は毎秒0から100の間である必要があります。 + + + VUメーターのピーク保持時間は0から10000ミリ秒の間である必要があります。 + + + VUメーターの向きが無効です。 + + + VUメーターのセグメント数は1から128の間である必要があります。 + + + VUメーターのピーク表示設定はnullにできません。 + + + VUメーターの中間しきい値は0から1の間である必要があります。 + + + VUメーターのピーク減衰は毎秒0から100の間である必要があります。 + + + VUメーターのセグメント間隔はnullにできません。 + + + VUメーターのセグメント間隔は0から32の間である必要があります。 + + + VUメーターのピーク保持時間はnullにできません。 + + + VUメーターの向きはnullにできません。 + + + VUメーターの中間しきい値はnullにできません。 + + + VUメーターの高いしきい値は0から1の間である必要があります。 + + + VUメーターのピーク減衰はnullにできません。 + + + VUメーターの高いしきい値は中間しきい値以上である必要があります。 + + + VUメーターの高いしきい値はnullにできません。 + + + アルバムはすでに存在します! + + + アルバム ID を空にすることはできません。 + + + アルバムが見つかりませんでした! + + + アルバム タイトルを空にすることはできません。 + + + アルバム タイトルの長さは最大 255 文字にする必要があります。 + + + アルバム リストを null にすることはできません。 + + + エリア名を空にすることはできません。 + + + エリア名は最大 255 文字までにしてください。 + + + アーティストのエイリアス名を空にすることはできません。 + + + アーティストのエイリアス名は最大 255 文字である必要があります。 + + + アーティストはすでに存在します! + + + アーティスト ID を空にすることはできません。 + + + アーティストは少なくとも 1 枚のアルバムを持っている必要があります。 + + + アーティスト名を空にすることはできません。 + + + アーティスト名は最大 255 文字である必要があります。 + + + アーティストが見つかりませんでした! + + + アーティストの Web サイトの長さは最大 2048 文字でなければなりません。 + + + バーコード値を空にすることはできません。 + + + BPM はゼロより大きくなければなりません。 + + + カタログ番号は最大 50 文字である必要があります。 + + + 完了しきい値は0から100の間である必要があります! + + + 進行状況の追跡がオフの場合、完了しきい値はnullである必要があります! + + + 変更を保存中に同時実行の競合が発生しました。 + + + 連続して読んだページ数は、ページベースのメディアでのみサポートされます! + + + 連続して読んだページ数は負にできません! + + + 消費時間は減少できません! + + + 消費時間が範囲外です! + + + 消費時間は負にできません! + + + 消費期間が無効です! + + + 消費はすでに終了しています! + + + 消費は進行中ではありません! + + + 消費記録 Idは空にできません。 + + + 消費記録が見つかりません! + + + 国の長さは最大 2 文字である必要があります。 + + + カバーを null にすることはできません。 + + + 配信 ID を空にすることはできません。 + + + 配信 ID が無効です。 + + + ディスク番号は 0 より大きくなければなりません。 + + + 終了時刻は最後のアクティビティより前にできません! + + + 終了した消費には終了時刻が必要です! + + + お気に入りはすでに存在します! + + + お気に入りのメディア アイテム ID を空にすることはできません。 + + + お気に入りのメディア アイテム ID リストを空にすることはできません。 + + + お気に入りのメディア アイテム ID リストが最大数を超えています。 + + + お気に入りのメディアの種類が無効です。 + + + お気に入りのメディアの種類はサポートされていません。 + + + お気に入りが見つかりませんでした! + + + ファイルが大きすぎます! + + + 進行中の消費には終了時刻を設定できません! + + + バーコードの形式が無効です。 + + + メディア位置が無効です! + + + 進行率が無効です! + + + IPI 値を空にすることはできません。 + + + IPI 値は最大 20 文字である必要があります。 + + + ISNI 値を空にすることはできません。 + + + ISNI 値の長さは最大 20 文字である必要があります。 + + + ISRC 形式が無効です。 + + + ISRC 値を空にすることはできません。 + + + 最後のアクティビティは開始より前にできません! + + + 場所の参照を空にすることはできません。 + + + メディア寄稿者はすでに存在します。 + + + メディア寄稿者名を空にすることはできません。 + + + メディア寄稿者のロール名を空にすることはできません。 + + + メディア項目 Idは空にできません。 + + + この種別のメディアは再開できません! + + + この種別のメディアは完了として開始できません! + + + メディア再開ポイントが見つかりません! + + + ムード名を空にすることはできません。 + + + MusicBrainz ID の形式が無効です。 + + + この本の形式を開けるブックリーダーがありません。 + + + サポートされている再生フォーマットが見つかりませんでした。 + + + 正規化キャッシュの制限を超えました。 + + + トラックの正規化に失敗しました! + + + 直接再生する場合は正規化は必要ありません。 + + + トラックの正規化がタイムアウトになりました。 + + + トラックの正規化は現在利用できません。 + + + 正規化されたトラック キャッシュ エントリが見つかりませんでした。 + + + 正規化されたトラック セグメントが見つかりませんでした。 + + + パス テンプレートはこのライブラリ タイプではサポートされていません。 + + + パス テンプレートのリテラル部分を空にすることはできません。 + + + パス テンプレート パーツの種類は、このライブラリ タイプではサポートされていません。 + + + パス テンプレートの値部分には、プレースホルダーを 1 つだけ含める必要があります。 + + + 権限が見つかりませんでした。 + + + 再生配信が変わりました! + + + 再生配信が見つかりませんでした! + + + 再生フォーマットが実装されていません! + + + プレイリストはすでに存在します。 + + + プレイリストの説明は最大 2000 文字にする必要があります。 + + + プレイリストはメディア アイテムを受け入れません。 + + + プレイリスト エントリ ID を空にすることはできません。 + + + プレイリストのエントリが見つかりませんでした。 + + + プレイリストのエントリ位置が無効です。 + + + プレイリスト ID を空にすることはできません。 + + + プレイリストの移動対象位置が不正です! + + + プレイリスト名を空にすることはできません。 + + + プレイリスト名は最大 255 文字である必要があります。 + + + プレイリストが見つかりませんでした! + + + プレイリストのタイプが無効です。 + + + この本を開くブックリーダーは、このライブラリで無効になっています。ライブラリ設定で有効にすると本を読めます。 + + + リソース キーを空にすることはできません。 + + + リソースが見つかりませんでした。 + + + スクリプトの長さは最大 50 文字にする必要があります。 + + + セクションが見つかりませんでした。 + + + セグメントの継続時間は正の値である必要があります。 + + + セグメントインデックスを空にすることはできません。 + + + セグメントインデックスが無効です! + + + 対象ユーザー Idが無効です! + + + そのアーティストはすでにアルバムを持っています! + + + アーティストはアルバムを持っていません! + + + この曲はすでにアルバムに入っています! + + + この曲はアルバムに入ってません! + + + テーマのテンプレートが見つかりませんでした。 + + + ディスクの総数は 0 より大きくなければなりません。 + + + トラックの総数は 0 より大きくなければなりません。 + + + トラックはすでに存在します。 + + + トラックの長さは正の値でなければなりません。 + + + トラック ファイルが見つかりませんでした。 + + + トラック ID を空にすることはできません。 + + + トラックが見つかりませんでした! + + + トラック番号は 0 より大きくなければなりません。 + + + トラック パスを空にすることはできません。 + + + トラック パスの長さは最大 2048 文字である必要があります。 + + + トラック パスは、ライブラリ コンテンツの場所のいずれか内にある必要があります。 + + + トラックリストを null にすることはできません。 + + + 音楽アーティストの性別は不明です! + + + 音楽アーティストのタイプは不明です。 + + + 音楽キーが不明です! + + + 音楽メディア形式が不明です。 + + + 音楽リリースのパッケージは不明です! + + + 楽曲リリース状況は不明! + + + 音楽リリースの種類は不明です。 + + + メディア種別はサポートされていません! + + + 作品の長さは最大 255 文字である必要があります。 + + + 作品タイトルを空白にすることはできません。 + + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.resx b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.resx index fe193be8..8d705929 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.resx @@ -813,4 +813,496 @@ The schedule type is invalid! - \ No newline at end of file + + Invalid ReplayGain mode! + + + Invalid streaming quality! + + + The mute state cannot be null! + + + The volume cannot be null! + + + The volume must be between 0 and 1! + + + The keep-downloading-while-paused preference cannot be null! + + + The autoplay preference cannot be null! + + + The gapless playback preference cannot be null! + + + The ReplayGain mode cannot be null! + + + The streaming quality cannot be null! + + + The shuffle track count must be greater than zero! + + + The shuffle track count must be at most 500! + + + The VU meter release cannot be null! + + + The VU meter segment count cannot be null! + + + The VU meter release must be between 0 and 100 per second! + + + The VU meter peak hold duration must be between 0 and 10000 milliseconds! + + + Invalid VU meter orientation! + + + The VU meter segment count must be between 1 and 128! + + + The VU meter show peak preference cannot be null! + + + The VU meter medium threshold must be between 0 and 1! + + + The VU meter peak release must be between 0 and 100 per second! + + + The VU meter segment gap cannot be null! + + + The VU meter segment gap must be between 0 and 32! + + + The VU meter peak hold duration cannot be null! + + + The VU meter orientation cannot be null! + + + The VU meter medium threshold cannot be null! + + + The VU meter high threshold must be between 0 and 1! + + + The VU meter peak release cannot be null! + + + The VU meter high threshold must be greater than or equal to the medium threshold! + + + The VU meter high threshold cannot be null! + + + The album already exists! + + + The album Id cannot be empty! + + + The album was not found! + + + The album title cannot be empty! + + + The album title must be maximum 255 characters long! + + + The albums list cannot be null! + + + The area name cannot be empty! + + + The area name must be maximum 255 characters long! + + + The artist alias name cannot be empty! + + + The artist alias name must be maximum 255 characters long! + + + The artist already exists! + + + The artist Id cannot be empty! + + + The artist must have at least one album! + + + The artist name cannot be empty! + + + The artist name must be maximum 255 characters long! + + + The artist was not found! + + + The artist website must be maximum 2048 characters long! + + + The barcode value cannot be empty! + + + The BPM must be greater than zero! + + + The catalog number must be maximum 50 characters long! + + + The completion threshold must be between 0 and 100! + + + The completion threshold must be null when progress tracking is off! + + + A concurrency conflict occurred while saving the changes! + + + The number of consecutive pages read is only supported for page based media! + + + The number of consecutive pages read cannot be negative! + + + The consumed duration cannot decrease! + + + The consumed duration is out of range! + + + The consumed duration cannot be negative! + + + The consumption date range is invalid! + + + The consumption has already ended! + + + The consumption is not in progress! + + + The consumption record Id cannot be empty! + + + The consumption record was not found! + + + The country must be maximum 2 characters long! + + + The cover cannot be null! + + + The delivery Id cannot be empty! + + + The delivery Id is invalid! + + + The disc number must be greater than zero! + + + The end time cannot precede the last activity! + + + An ended consumption must have an end time! + + + The favorite already exists! + + + The favorite media item Id cannot be empty! + + + The favorite media item Ids list cannot be empty! + + + The favorite media item Ids list exceeds the maximum count! + + + The favorite media kind is invalid! + + + The favorite media kind is not supported! + + + The favorite was not found! + + + The file is too large! + + + A consumption that is in progress cannot have an end time! + + + The barcode format is invalid! + + + The media position is invalid! + + + The progress fraction is invalid! + + + The IPI value cannot be empty! + + + The IPI value must be maximum 20 characters long! + + + The ISNI value cannot be empty! + + + The ISNI value must be maximum 20 characters long! + + + The ISRC format is invalid! + + + The ISRC value cannot be empty! + + + The last activity cannot precede the start! + + + The location reference cannot be empty! + + + The media contributor already exists! + + + The media contributor name cannot be empty! + + + The media contributor role name cannot be empty! + + + The media item Id cannot be empty! + + + Media of this kind cannot be resumed! + + + Media of this kind cannot be started as completed! + + + The media resume point was not found! + + + The mood name cannot be empty! + + + The MusicBrainz Id format is invalid! + + + No reader is available for this book! + + + No supported playback format was found! + + + The normalization cache limit was exceeded! + + + The track normalization failed! + + + Normalization is not required for direct playback! + + + The track normalization timed out! + + + Track normalization is currently unavailable! + + + The normalized track cache entry was not found! + + + The normalized track segment was not found! + + + The path template is not supported for this library type! + + + A literal part of the path template cannot be empty! + + + The path template part kind is not supported for this library type! + + + A value part of the path template must contain exactly one placeholder! + + + The permission was not found! + + + The playback delivery changed! + + + The playback delivery was not found! + + + The playback format is not implemented! + + + The playlist already exists! + + + The playlist description must be maximum 2000 characters long! + + + The playlist does not accept media items! + + + The playlist entry Id cannot be empty! + + + The playlist entry was not found! + + + The playlist entry positions are invalid! + + + The playlist Id cannot be empty! + + + The playlist move target position is invalid! + + + The playlist name cannot be empty! + + + The playlist name must be maximum 255 characters long! + + + The playlist was not found! + + + The playlist type is invalid! + + + The reader is disabled for this library! + + + The resource key cannot be empty! + + + The resource was not found! + + + The script must be maximum 50 characters long! + + + The section was not found! + + + The segment duration must be positive! + + + The segment index cannot be empty! + + + The segment index is invalid! + + + The target user Id is invalid! + + + The artist already has the album! + + + The artist does not have the album! + + + The track is already in the album! + + + The track is not in the album! + + + The theme template was not found! + + + The total number of discs must be greater than zero! + + + The total number of tracks must be greater than zero! + + + The track already exists! + + + The track duration must be positive! + + + The track file was not found! + + + The track Id cannot be empty! + + + The track was not found! + + + The track number must be greater than zero! + + + The track path cannot be empty! + + + The track path must be maximum 2048 characters long! + + + The track path must be inside one of the library content locations! + + + The tracks list cannot be null! + + + The music artist gender is unknown! + + + The music artist type is unknown! + + + The music key is unknown! + + + The music media format is unknown! + + + The music release packaging is unknown! + + + The music release status is unknown! + + + The music release type is unknown! + + + The media kind is not supported! + + + The work must be maximum 255 characters long! + + + The work title cannot be empty! + + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ro-RO.resx b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ro-RO.resx index 2aa1c5dd..ae2450db 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ro-RO.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ro-RO.resx @@ -813,4 +813,496 @@ Tipul de programare este invalid! - \ No newline at end of file + + Mod ReplayGain invalid! + + + Calitate de streaming invalidă! + + + Starea de mut nu poate fi nulă! + + + Volumul nu poate fi nul! + + + Volumul trebuie să fie între 0 și 1! + + + Preferința de a continua descărcarea în pauză nu poate fi nulă! + + + Preferința de redare automată nu poate fi nulă! + + + Preferința de redare fără întreruperi nu poate fi nulă! + + + Modul ReplayGain nu poate fi nul! + + + Calitatea fluxului nu poate fi nulă! + + + Numărul de piese pentru redare aleatorie trebuie să fie mai mare decât zero! + + + Numărul de piese pentru redare aleatorie nu poate depăși 500! + + + Scăderea vumetrului nu poate fi nulă! + + + Numărul de segmente al vumetrului nu poate fi nul! + + + Scăderea vumetrului trebuie să fie între 0 și 100 pe secundă! + + + Durata de menținere a vârfurilor vumetrului trebuie să fie între 0 și 10000 de milisecunde! + + + Orientare nevalidă a vumetrului! + + + Numărul de segmente al vumetrului trebuie să fie între 1 și 128! + + + Preferința de afișare a vârfurilor vumetrului nu poate fi nulă! + + + Pragul mediu al vumetrului trebuie să fie între 0 și 1! + + + Scăderea vârfurilor vumetrului trebuie să fie între 0 și 100 pe secundă! + + + Spațiul dintre segmentele vumetrului nu poate fi nul! + + + Spațiul dintre segmentele vumetrului trebuie să fie între 0 și 32! + + + Durata de menținere a vârfurilor vumetrului nu poate fi nulă! + + + Orientarea vumetrului nu poate fi nulă! + + + Pragul mediu al vumetrului nu poate fi nul! + + + Pragul ridicat al vumetrului trebuie să fie între 0 și 1! + + + Scăderea vârfurilor vumetrului nu poate fi nulă! + + + Pragul ridicat al vumetrului trebuie să fie mai mare sau egal cu pragul mediu! + + + Pragul ridicat al vumetrului nu poate fi nul! + + + Albumul există deja! + + + Id-ul albumului nu poate fi gol! + + + Albumul nu a fost găsit! + + + Titlul albumului nu poate fi gol! + + + Titlul albumului trebuie să aibă maximum 255 de caractere! + + + Lista de albume nu poate fi nulă! + + + Numele zonei nu poate fi gol! + + + Numele zonei trebuie să aibă maximum 255 de caractere! + + + Aliasul artistului nu poate fi gol! + + + Aliasul artistului trebuie să aibă maximum 255 de caractere! + + + Artistul există deja! + + + Id-ul artistului nu poate fi gol! + + + Artistul trebuie să aibă cel puțin un album! + + + Numele artistului nu poate fi gol! + + + Numele artistului trebuie să aibă maximum 255 de caractere! + + + Artistul nu a fost găsit! + + + Site-ul web al artistului trebuie să aibă maximum 2048 de caractere! + + + Valoarea codului de bare nu poate fi goală! + + + BPM-ul trebuie să fie mai mare decât zero! + + + Numărul de catalog trebuie să aibă maximum 50 de caractere! + + + Pragul de finalizare trebuie să fie între 0 și 100! + + + Pragul de finalizare trebuie să fie nul când urmărirea progresului este dezactivată! + + + A apărut un conflict de concurență la salvarea modificărilor! + + + Numărul de pagini consecutive citite este acceptat numai pentru conținutul paginat! + + + Numărul de pagini consecutive citite nu poate fi negativ! + + + Durata consumată nu poate scădea! + + + Durata consumată este în afara intervalului! + + + Durata consumată nu poate fi negativă! + + + Intervalul de date de consum este invalid! + + + Consumul s-a încheiat deja! + + + Consumul nu este în curs! + + + Id-ul înregistrării de consum nu poate fi gol! + + + Înregistrarea de consum nu a fost găsită! + + + Țara trebuie să aibă maximum 2 caractere! + + + Coperta nu poate fi nulă! + + + Id-ul de livrare nu poate fi gol! + + + Id-ul de livrare este invalid! + + + Numărul discului trebuie să fie mai mare decât zero! + + + Ora de sfârșit nu poate precede ultima activitate! + + + Un consum încheiat trebuie să aibă o oră de sfârșit! + + + Favorita există deja! + + + Id-ul elementului media favorit nu poate fi gol! + + + Lista de ID-uri a elementelor media favorite nu poate fi goală! + + + Lista de ID-uri a articolelor media favorite depășește numărul maxim! + + + Tipul media preferat este invalid! + + + Tipul media preferat nu este acceptat! + + + Favoritul nu a fost găsit! + + + Fișierul este prea mare! + + + Un consum în curs nu poate avea o oră de sfârșit! + + + Formatul codului de bare este nevalid! + + + Poziția media este invalidă! + + + Fracția de progres este invalidă! + + + Valoarea IPI nu poate fi goală! + + + Valoarea IPI trebuie să aibă maximum 20 de caractere! + + + Valoarea ISNI nu poate fi goală! + + + Valoarea ISNI trebuie să aibă maximum 20 de caractere! + + + Formatul ISRC este invalid! + + + Valoarea ISRC nu poate fi goală! + + + Ultima activitate nu poate precede începutul! + + + Referința locației nu poate fi goală! + + + Colaboratorul media există deja! + + + Numele colaboratorului media nu poate fi gol! + + + Numele rolului de colaborator media nu poate fi gol! + + + Id-ul elementului media nu poate fi gol! + + + Conținutul de acest tip nu poate fi reluat! + + + Conținutul de acest tip nu poate fi pornit ca finalizat! + + + Punctul de reluare media nu a fost găsit! + + + Numele de dispoziție nu poate fi gol! + + + Formatul MusicBrainz Id este nevalid! + + + Niciun cititor de cărți nu este disponibil pentru această carte! + + + Nu a fost găsit niciun format de redare acceptat! + + + Limita cache-ului de normalizare a fost depășită! + + + Normalizarea piesei a eșuat! + + + Normalizarea nu este necesară pentru redarea directă! + + + Normalizarea piesei a expirat! + + + Normalizarea piesei este indisponibilă momentan! + + + Intrarea normalizată în memoria cache a piesei nu a fost găsită! + + + Segmentul normalizat al piesei nu a fost găsit! + + + Șablonul de cale nu este acceptat pentru acest tip de bibliotecă! + + + O parte literală a șablonului de cale nu poate fi goală! + + + Tipul de parte șablon de cale nu este acceptat pentru acest tip de bibliotecă! + + + O parte de valoare a șablonului de cale trebuie să conțină exact un substituent! + + + Permisiunea nu a fost găsită! + + + Livrarea redării s-a schimbat! + + + Livrarea redării nu a fost găsită! + + + Formatul de redare nu este implementat! + + + Lista de redare există deja! + + + Descrierea listei de redare trebuie să aibă maximum 2000 de caractere! + + + Lista de redare nu acceptă elemente media! + + + Id-ul intrării listei de redare nu poate fi gol! + + + Intrarea în lista de redare nu a fost găsită! + + + Pozițiile de intrare în lista de redare sunt nevalide! + + + Id-ul playlistului nu poate fi gol! + + + Poziția țintă a mutarii listei de redare este nevalidă! + + + Numele playlistului nu poate fi gol! + + + Numele playlistului trebuie să aibă maximum 255 de caractere! + + + Lista de redare nu a fost găsită! + + + Tipul playlistului este nevalid! + + + Cititorul de cărți este dezactivat pentru această bibliotecă! + + + Cheia de resurse nu poate fi goală! + + + Resursa nu a fost găsită! + + + Scriptul trebuie să aibă maximum 50 de caractere! + + + Secțiunea nu a fost găsită! + + + Durata segmentului trebuie să fie pozitivă! + + + Indexul segmentului nu poate fi gol! + + + Indexul segmentului este nevalid! + + + Id-ul utilizatorului țintă este invalid! + + + Artistul are deja albumul! + + + Artistul nu are albumul! + + + Piesa este deja în album! + + + Piesa nu este în album! + + + Șablonul de temă nu a fost găsit! + + + Numărul total de discuri trebuie să fie mai mare decât zero! + + + Numărul total de piese trebuie să fie mai mare decât zero! + + + Piesa există deja! + + + Durata piesei trebuie să fie pozitivă! + + + Fișierul piesei nu a fost găsit! + + + ID-ul piesei nu poate fi gol! + + + Piesa nu a fost găsită! + + + Numărul piesei trebuie să fie mai mare decât zero! + + + Calea piesei nu poate fi goală! + + + Calea piesei trebuie să aibă maximum 2048 de caractere! + + + Calea piesei trebuie să fie în interiorul uneia dintre locațiile conținutului bibliotecii! + + + Lista de piese nu poate fi nulă! + + + Genul artistului muzical este necunoscut! + + + Tipul de artist muzical este necunoscut! + + + Cheia muzicală este necunoscută! + + + Formatul media muzical este necunoscut! + + + Pachetul pentru lansarea muzicii este necunoscut! + + + Starea lansării muzicii este necunoscută! + + + Tipul de lansare a muzicii este necunoscut! + + + Tipul de conținut nu este acceptat! + + + Lucrarea trebuie să aibă maximum 255 de caractere! + + + Titlul lucrării nu poate fi gol! + + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.uk-UA.resx b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.uk-UA.resx index ea2e4393..197e157e 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.uk-UA.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.uk-UA.resx @@ -813,4 +813,496 @@ Тип розкладу недійсний! - \ No newline at end of file + + Неприпустимий режим ReplayGain! + + + Неприпустима якість потокового передавання! + + + Стан без звуку не може бути порожнім! + + + Гучність не може бути порожньою! + + + Гучність має бути між 0 і 1! + + + Налаштування продовження завантаження на паузі не може бути порожнім! + + + Налаштування автовідтворення не може бути порожнім! + + + Налаштування відтворення без пауз не може бути порожнім! + + + Режим ReplayGain не може бути порожнім! + + + Якість потокового передавання не може бути порожньою! + + + Кількість треків для перемішування має бути більшою за нуль! + + + Кількість треків для перемішування не може перевищувати 500! + + + Спад VU-метра не може бути порожнім! + + + Кількість сегментів VU-метра не може бути порожньою! + + + Спад VU-метра має бути від 0 до 100 за секунду! + + + Тривалість утримання піків VU-метра має бути від 0 до 10000 мілісекунд! + + + Недійсна орієнтація VU-метра! + + + Кількість сегментів VU-метра має бути від 1 до 128! + + + Налаштування показу піків VU-метра не може бути порожнім! + + + Середній поріг VU-метра має бути від 0 до 1! + + + Спад піків VU-метра має бути від 0 до 100 за секунду! + + + Проміжок між сегментами VU-метра не може бути порожнім! + + + Проміжок між сегментами VU-метра має бути від 0 до 32! + + + Тривалість утримання піків VU-метра не може бути порожньою! + + + Орієнтація VU-метра не може бути порожньою! + + + Середній поріг VU-метра не може бути порожнім! + + + Високий поріг VU-метра має бути від 0 до 1! + + + Спад піків VU-метра не може бути порожнім! + + + Високий поріг VU-метра має бути більшим або дорівнювати середньому порогу! + + + Високий поріг VU-метра не може бути порожнім! + + + Альбом вже є! + + + Ідентифікатор альбому не може бути порожнім! + + + Альбом не знайдено! + + + Назва альбому не може бути пустою! + + + Назва альбому має містити максимум 255 символів! + + + Список альбомів не може бути нульовим! + + + Назва області не може бути пустою! + + + Назва області має містити максимум 255 символів! + + + Псевдонім виконавця не може бути пустим! + + + Псевдонім виконавця має містити максимум 255 символів! + + + Виконавець уже існує! + + + Ідентифікатор виконавця не може бути порожнім! + + + Виконавець повинен мати хоча б один альбом! + + + Ім'я виконавця не може бути пустим! + + + Ім'я виконавця має містити максимум 255 символів! + + + Виконавця не знайдено! + + + Веб-сайт виконавця має містити максимум 2048 символів! + + + Значення штрих-коду не може бути порожнім! + + + BPM має бути більше нуля! + + + Каталожний номер має містити максимум 50 символів! + + + Поріг завершення має бути між 0 і 100! + + + Поріг завершення має бути null, коли відстеження прогресу вимкнено! + + + Під час збереження змін стався конфлікт паралельного доступу! + + + Кількість послідовно прочитаних сторінок підтримується лише для сторінкових медіа! + + + Кількість послідовно прочитаних сторінок не може бути від'ємною! + + + Спожита тривалість не може зменшуватися! + + + Спожита тривалість виходить за межі діапазону! + + + Спожита тривалість не може бути від'ємною! + + + Діапазон дат споживання недійсний! + + + Споживання вже завершено! + + + Споживання не в процесі! + + + Ідентифікатор запису споживання не може бути порожнім! + + + Запис споживання не знайдено! + + + Країна має містити максимум 2 символи! + + + Обкладинка не може бути null! + + + Ідентифікатор доставки не може бути порожнім! + + + Ідентифікатор доставки недійсний! + + + Номер диска має бути більше нуля! + + + Час завершення не може передувати останній активності! + + + Завершене споживання повинно мати час завершення! + + + Фаворит вже існує! + + + Ідентифікатор улюбленого мультимедійного елемента не може бути порожнім! + + + Список ідентифікаторів улюблених медіа-елементів не може бути порожнім! + + + Список ідентифікаторів улюблених медіа-елементів перевищує максимальну кількість! + + + Улюблений тип медіа недійсний! + + + Улюблений тип медіа не підтримується! + + + Фаворит не знайдено! + + + Файл завеликий! + + + Споживання в процесі не може мати час завершення! + + + Формат штрих-коду недійсний! + + + Медіапозиція недійсна! + + + Частка прогресу недійсна! + + + Значення IPI не може бути порожнім! + + + Значення IPI має містити максимум 20 символів! + + + Значення ISNI не може бути порожнім! + + + Значення ISNI має містити максимум 20 символів! + + + Формат ISRC недійсний! + + + Значення ISRC не може бути порожнім! + + + Остання активність не може передувати початку! + + + Посилання на місцезнаходження не може бути порожнім! + + + Медіадописувач уже існує! + + + Ім’я медіа-учасника не може бути пустим! + + + Назва ролі учасника медіа не може бути пустою! + + + Ідентифікатор медіаелемента не може бути порожнім! + + + Медіа цього типу не можна продовжити! + + + Медіа цього типу не можна запустити як завершені! + + + Точку продовження медіа не знайдено! + + + Назва настрою не може бути пустою! + + + Формат ідентифікатора MusicBrainz недійсний! + + + Немає читача книг для цієї книги! + + + Не знайдено жодного підтримуваного формату відтворення! + + + Ліміт кешу нормалізації перевищено! + + + Не вдалося нормалізувати трек! + + + Для прямого відтворення нормалізація не потрібна! + + + Час очікування нормалізації треку минув! + + + Нормалізація треку наразі недоступна! + + + Запис кешу нормалізованого треку не знайдено! + + + Сегмент нормалізованого треку не знайдено! + + + Шаблон шляху не підтримується для цього типу бібліотеки! + + + Літеральна частина шаблону шляху не може бути порожньою! + + + Тип частини шаблону шляху не підтримується для цього типу бібліотеки! + + + Частина значення шаблону шляху повинна містити рівно один заповнювач! + + + Дозвіл не знайдено! + + + Подача відтворення змінена! + + + Доставка відтворення не знайдена! + + + Формат відтворення не реалізовано! + + + Список відтворення вже існує! + + + Опис списку відтворення має містити максимум 2000 символів! + + + Список відтворення не приймає медіаелементи! + + + Ідентифікатор запису списку відтворення не може бути порожнім! + + + Запис у списку відтворення не знайдено! + + + Позиції в списку відтворення недійсні! + + + Ідентифікатор списку відтворення не може бути порожнім! + + + Цільова позиція переміщення списку відтворення недійсна! + + + Назва списку відтворення не може бути пустою! + + + Назва списку відтворення має містити максимум 255 символів! + + + Список відтворення не знайдено! + + + Тип списку відтворення недійсний! + + + Читач книг вимкнено для цієї бібліотеки! + + + Ключ ресурсу не може бути порожнім! + + + Ресурс не знайдено! + + + Довжина сценарію не повинна перевищувати 50 символів! + + + Розділ не знайдено! + + + Тривалість сегмента має бути позитивною! + + + Індекс сегмента не може бути порожнім! + + + Індекс сегмента недійсний! + + + Ідентифікатор цільового користувача недійсний! + + + У виконавця вже є альбом! + + + У виконавця немає альбому! + + + Трек уже є в альбомі! + + + Треку немає в альбомі! + + + Шаблон теми не знайдено! + + + Загальна кількість дисків має бути більше нуля! + + + Загальна кількість треків має бути більшою за нуль! + + + Трек уже існує! + + + Тривалість треку має бути додатною! + + + Файл треку не знайдено! + + + Ідентифікатор треку не може бути порожнім! + + + Трек не знайдено! + + + Номер треку має бути більшим за нуль! + + + Шлях треку не може бути порожнім! + + + Шлях треку не має перевищувати 2048 символів! + + + Шлях треку має бути всередині одного з розташувань вмісту бібліотеки! + + + Список треків не може бути порожнім! + + + Стать виконавця невідома! + + + Тип музичного виконавця невідомий! + + + Музичний ключ невідомий! + + + Формат музичного носія невідомий! + + + Упаковка музичного випуску невідома! + + + Статус випуску музики невідомий! + + + Тип випуску музики невідомий! + + + Тип медіа не підтримується! + + + Робота має бути не більше 255 символів! + + + Назва роботи не може бути пустою! + + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.zh-CN.resx b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.zh-CN.resx index 0b05709e..cdcf3979 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.zh-CN.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.zh-CN.resx @@ -217,22 +217,22 @@ 已完成扫描任务数量必须为正数! - 参与者显示名称不能为空! + 贡献者显示名称不能为空! - 参与者显示名称最多只能有100个字符! + 贡献者显示名称最多只能有100个字符! - 参与者法定姓名最多只能有100个字符! + 贡献者法定姓名最多只能有100个字符! - 参与者姓名不能为空! + 贡献者姓名不能为空! - 参与者角色不能为空! + 贡献者角色不能为空! - 参与者列表不能为空! + 贡献者列表不能为空! CORS来源无效! @@ -813,4 +813,496 @@ 调度类型无效! - \ No newline at end of file + + 无效的 ReplayGain 模式! + + + 无效的流媒体质量! + + + 静音状态不能为空! + + + 音量不能为空! + + + 音量必须介于 0 和 1 之间! + + + 暂停时继续下载的偏好设置不能为空! + + + 自动播放的偏好设置不能为空! + + + 无缝播放的偏好设置不能为空! + + + ReplayGain 模式不能为空! + + + 流媒体质量不能为空! + + + 随机播放曲目数必须大于零! + + + 随机播放曲目数不能超过 500! + + + VU 表的衰落速度不能为空! + + + VU 表的段数不能为空! + + + VU 表的衰落速度必须介于每秒 0 到 100 之间! + + + VU 表的峰值保持时间必须在 0 到 10000 毫秒之间! + + + VU 表的方向无效! + + + VU 表的段数必须在 1 到 128 之间! + + + VU 表的峰值显示首选项不能为空! + + + VU 表的中等阈值必须在 0 到 1 之间! + + + VU 表的峰值衰落速度必须介于每秒 0 到 100 之间! + + + VU 表的段间距不能为空! + + + VU 表的段间距必须在 0 到 32 之间! + + + VU 表的峰值保持时间不能为空! + + + VU 表的方向不能为空! + + + VU 表的中等阈值不能为空! + + + VU 表的高阈值必须在 0 到 1 之间! + + + VU 表的峰值衰落速度不能为空! + + + VU 表的高阈值必须大于或等于中等阈值! + + + VU 表的高阈值不能为空! + + + 该专辑已经存在! + + + 专辑ID不能为空! + + + 找不到专辑! + + + 专辑名称不能为空! + + + 专辑名称的长度不得超过 255 个字符! + + + 专辑列表不能为空! + + + 区域名称不能为空! + + + 区域名称的长度不得超过 255 个字符! + + + 艺人别名不能为空! + + + 艺术家别名的长度不得超过 255 个字符! + + + 这位艺术家已经存在了! + + + 艺人ID不能为空! + + + 艺术家必须至少拥有一张专辑! + + + 艺人姓名不能为空! + + + 艺术家姓名的长度不得超过 255 个字符! + + + 未找到该艺术家! + + + 艺术家网站的长度不得超过 2048 个字符! + + + 条形码值不能为空! + + + BPM 必须大于零! + + + 目录号的长度不得超过 50 个字符! + + + 完成阈值必须在0到100之间! + + + 关闭进度跟踪时,完成阈值必须为 null! + + + 保存更改时发生并发冲突! + + + 连续阅读页数仅支持基于页面的媒体! + + + 连续阅读页数不能为负数! + + + 消费时长不能减少! + + + 消费时长超出范围! + + + 消费时长不能为负数! + + + 消费日期范围无效! + + + 消费已结束! + + + 消费不在进行中! + + + 消费记录 Id不能为空! + + + 找不到消费记录! + + + 国家/地区的长度不得超过 2 个字符! + + + 封面不能为空! + + + 发货ID不能为空! + + + 送货ID无效! + + + 光盘编号必须大于零! + + + 结束时间不能早于最后活动时间! + + + 已结束的消费必须有结束时间! + + + 收藏已存在! + + + 收藏的媒体项 ID 不能为空! + + + 收藏的媒体项 ID 列表不能为空! + + + 收藏的媒体项 ID 列表超出最大数量! + + + 收藏的媒体类型无效! + + + 不支持收藏的媒体类型! + + + 找不到收藏! + + + 文件太大! + + + 进行中的消费不能有结束时间! + + + 条形码格式无效! + + + 媒体位置无效! + + + 进度比例无效! + + + IPI值不能为空! + + + IPI 值的长度不得超过 20 个字符! + + + ISNI 值不能为空! + + + ISNI 值的长度不得超过 20 个字符! + + + ISRC 格式无效! + + + ISRC 值不能为空! + + + 最后活动时间不能早于开始时间! + + + 位置参考不能为空! + + + 媒体贡献者已存在! + + + 媒体贡献者名称不能为空! + + + 媒体贡献者角色名称不能为空! + + + 媒体项 Id不能为空! + + + 此类媒体无法继续! + + + 此类媒体不能以已完成状态开始! + + + 找不到媒体继续点! + + + 心情名称不能为空! + + + MusicBrainz Id 格式无效! + + + 没有可用的图书阅读器能够打开此图书。 + + + 未找到支持的播放格式! + + + 超出规范化缓存限制! + + + 曲目规范化失败! + + + 直接播放不需要规范化! + + + 曲目规范化超时! + + + 曲目规范化目前不可用! + + + 找不到规范化曲目缓存项! + + + 找不到规范化曲目片段! + + + 此库类型不支持路径模板! + + + 路径模板的文字部分不能为空! + + + 此库类型不支持路径模板部分类型! + + + 路径模板的值部分必须恰好包含一个占位符! + + + 没有找到权限! + + + 播放交付方式发生变化! + + + 找不到播放传送! + + + 播放格式未实现! + + + 播放列表已经存在! + + + 播放列表描述的长度不得超过 2000 个字符! + + + 该播放列表不接受媒体项目! + + + 播放列表条目 ID 不能为空! + + + 找不到播放列表条目! + + + 播放列表条目位置无效! + + + 播放列表ID不能为空! + + + 播放列表移动目标位置无效! + + + 播放列表名称不能为空! + + + 播放列表名称的长度不得超过 255 个字符! + + + 找不到播放列表! + + + 播放列表类型无效! + + + 打开此图书的图书阅读器已在此媒体库中禁用。在媒体库设置中启用它即可阅读该图书。 + + + 资源键不能为空! + + + 没有找到资源! + + + 脚本长度不得超过 50 个字符! + + + 未找到该部分! + + + 分段持续时间必须为正! + + + 段索引不能为空! + + + 段索引无效! + + + 目标用户 Id无效! + + + 艺术家已经拥有专辑了! + + + 该艺术家没有专辑! + + + 曲目已在专辑中! + + + 该曲目不在专辑中! + + + 找不到主题模板! + + + 光盘总数必须大于零! + + + 曲目总数必须大于零! + + + 该曲目已经存在! + + + 曲目时长必须为正数! + + + 未找到曲目文件! + + + 曲目 ID 不能为空! + + + 未找到曲目! + + + 曲目编号必须大于零! + + + 曲目路径不能为空! + + + 曲目路径最多只能有 2048 个字符! + + + 曲目路径必须在库内容位置之一内! + + + 曲目列表不能为空! + + + 音乐人性别未知! + + + 音乐艺术家类型未知! + + + 音乐调未知! + + + 音乐媒体格式未知! + + + 音乐发行包装未知! + + + 音乐发行状态未知! + + + 音乐发行类型未知! + + + 媒体类型不受支持! + + + 作品长度不得超过 255 个字符! + + + 作品名称不能为空! + + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Favorites/Index.ar-SA.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Favorites/Index.ar-SA.resx new file mode 100644 index 00000000..79accd37 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Favorites/Index.ar-SA.resx @@ -0,0 +1,66 @@ + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + المفضلة + + + ليست لديك أي عناصر مفضلة بعد. + + + ليست لديك أي عناصر مفضلة من هذا النوع بعد. + + + هذا العنصر لم يعد متاحًا. + + + الكل + + + الفنانون + + + الألبومات + + + المقاطع + + + الكتب + + + فنان + + + ألبوم + + + مقطع + + + كتاب + + + تحميل المزيد + + + عناصر + + + تعذر تحميل المفضلة. + + + إعادة المحاولة + + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Favorites/Index.de-DE.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Favorites/Index.de-DE.resx new file mode 100644 index 00000000..803ad0f7 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Favorites/Index.de-DE.resx @@ -0,0 +1,66 @@ + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Favoriten + + + Du hast noch keine Favoriten. + + + Du hast noch keine Favoriten dieser Art. + + + Dieses Element ist nicht mehr verfügbar. + + + Alle + + + Künstler + + + Alben + + + Titel + + + Bücher + + + Künstler + + + Album + + + Titel + + + Buch + + + Mehr laden + + + Einträge + + + Die Favoriten konnten nicht geladen werden. + + + Wiederholen + + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Favorites/Index.en-US.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Favorites/Index.en-US.resx new file mode 100644 index 00000000..0e9fa75e --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Favorites/Index.en-US.resx @@ -0,0 +1,66 @@ + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Favorites + + + You have no favorites yet. + + + You have no favorites of this kind yet. + + + This item is no longer available. + + + All + + + Artists + + + Albums + + + Tracks + + + Books + + + Artist + + + Album + + + Track + + + Book + + + Load more + + + items + + + The favorites could not be loaded. + + + Retry + + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Favorites/Index.es-ES.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Favorites/Index.es-ES.resx new file mode 100644 index 00000000..6aabc3f4 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Favorites/Index.es-ES.resx @@ -0,0 +1,66 @@ + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Favoritos + + + Todavía no tienes favoritos. + + + Todavía no tienes favoritos de este tipo. + + + Este elemento ya no está disponible. + + + Todos + + + Artistas + + + Álbumes + + + Pistas + + + Libros + + + Artista + + + Álbum + + + Pista + + + Libro + + + Cargar más + + + elementos + + + No se pudieron cargar los favoritos. + + + Reintentar + + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Favorites/Index.fr-FR.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Favorites/Index.fr-FR.resx new file mode 100644 index 00000000..eb2bb104 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Favorites/Index.fr-FR.resx @@ -0,0 +1,66 @@ + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Favoris + + + Vous n'avez encore aucun favori. + + + Vous n'avez encore aucun favori de ce type. + + + Cet élément n'est plus disponible. + + + Tous + + + Artistes + + + Albums + + + Pistes + + + Livres + + + Artiste + + + Album + + + Piste + + + Livre + + + Charger plus + + + éléments + + + Les favoris n'ont pas pu être chargés. + + + Réessayer + + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Favorites/Index.it-IT.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Favorites/Index.it-IT.resx new file mode 100644 index 00000000..150812de --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Favorites/Index.it-IT.resx @@ -0,0 +1,66 @@ + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Preferiti + + + Non hai ancora preferiti. + + + Non hai ancora preferiti di questo tipo. + + + Questo elemento non è più disponibile. + + + Tutti + + + Artisti + + + Album + + + Brani + + + Libri + + + Artista + + + Album + + + Brano + + + Libro + + + Carica altri + + + elementi + + + Non è stato possibile caricare i preferiti. + + + Riprova + + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Favorites/Index.ja-JP.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Favorites/Index.ja-JP.resx new file mode 100644 index 00000000..a108d82e --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Favorites/Index.ja-JP.resx @@ -0,0 +1,66 @@ + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + お気に入り + + + お気に入りはまだありません。 + + + この種類のお気に入りはまだありません。 + + + この項目は利用できなくなりました。 + + + すべて + + + アーティスト + + + アルバム + + + 曲 + + + 書籍 + + + アーティスト + + + アルバム + + + 曲 + + + 書籍 + + + さらに読み込む + + + 件 + + + お気に入りを読み込めませんでした。 + + + 再試行 + + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Favorites/Index.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Favorites/Index.resx new file mode 100644 index 00000000..0e9fa75e --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Favorites/Index.resx @@ -0,0 +1,66 @@ + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Favorites + + + You have no favorites yet. + + + You have no favorites of this kind yet. + + + This item is no longer available. + + + All + + + Artists + + + Albums + + + Tracks + + + Books + + + Artist + + + Album + + + Track + + + Book + + + Load more + + + items + + + The favorites could not be loaded. + + + Retry + + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Favorites/Index.ro-RO.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Favorites/Index.ro-RO.resx new file mode 100644 index 00000000..836e1e16 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Favorites/Index.ro-RO.resx @@ -0,0 +1,66 @@ + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Favorite + + + Nu ai încă favorite. + + + Nu ai încă favorite de acest fel. + + + Acest element nu mai este disponibil. + + + Toate + + + Artiști + + + Albume + + + Piese + + + Cărți + + + Artist + + + Album + + + Piesă + + + Carte + + + Încarcă mai multe + + + elemente + + + Favoritele nu au putut fi încărcate. + + + Reîncercare + + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Favorites/Index.uk-UA.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Favorites/Index.uk-UA.resx new file mode 100644 index 00000000..279a0f00 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Favorites/Index.uk-UA.resx @@ -0,0 +1,66 @@ + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Улюблене + + + У вас ще немає улюбленого. + + + У вас ще немає улюбленого цього типу. + + + Цей елемент більше недоступний. + + + Усе + + + Виконавці + + + Альбоми + + + Треки + + + Книги + + + Виконавець + + + Альбом + + + Трек + + + Книга + + + Завантажити ще + + + елементів + + + Не вдалося завантажити улюблене. + + + Повторити + + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Favorites/Index.zh-CN.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Favorites/Index.zh-CN.resx new file mode 100644 index 00000000..51b2f888 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Favorites/Index.zh-CN.resx @@ -0,0 +1,66 @@ + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + 收藏夹 + + + 你还没有收藏。 + + + 你还没有此类收藏。 + + + 此项目已不可用。 + + + 全部 + + + 艺术家 + + + 专辑 + + + 曲目 + + + 图书 + + + 艺术家 + + + 专辑 + + + 曲目 + + + 图书 + + + 加载更多 + + + 项 + + + 无法加载收藏。 + + + 重试 + + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Home/Index.ar-SA.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Home/Index.ar-SA.resx index 5eeb7c13..ff3cda79 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Home/Index.ar-SA.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Home/Index.ar-SA.resx @@ -120,4 +120,16 @@ لا توجد مكتبات + + تشغيل عشوائي + + + تشغيل + + + الإجراءات + + + إضافة إلى قائمة التشغيل + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Home/Index.de-DE.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Home/Index.de-DE.resx index 45dca514..c743433f 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Home/Index.de-DE.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Home/Index.de-DE.resx @@ -120,4 +120,16 @@ Keine Bibliotheken + + Zufällige Wiedergabe + + + Abspielen + + + Aktionen + + + Zur Wiedergabeliste hinzufügen + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Home/Index.en-US.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Home/Index.en-US.resx index d3883307..1c9fa57e 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Home/Index.en-US.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Home/Index.en-US.resx @@ -120,4 +120,16 @@ No libraries + + Shuffle + + + Play + + + Actions + + + Add to playlist + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Home/Index.es-ES.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Home/Index.es-ES.resx index 5eb2e603..318fe196 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Home/Index.es-ES.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Home/Index.es-ES.resx @@ -120,4 +120,16 @@ Sin bibliotecas + + Aleatorio + + + Reproducir + + + Acciones + + + Añadir a la lista de reproducción + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Home/Index.fr-FR.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Home/Index.fr-FR.resx index 4fb27e5a..6c3ca82e 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Home/Index.fr-FR.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Home/Index.fr-FR.resx @@ -120,4 +120,16 @@ Aucune bibliothèque + + Lecture aléatoire + + + Lecture + + + Actions + + + Ajouter à la liste de lecture + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Home/Index.it-IT.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Home/Index.it-IT.resx index a018f86d..6cb4db05 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Home/Index.it-IT.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Home/Index.it-IT.resx @@ -120,4 +120,16 @@ Nessuna libreria + + Riproduzione casuale + + + Riproduci + + + Azioni + + + Aggiungi alla playlist + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Home/Index.ja-JP.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Home/Index.ja-JP.resx index b826da97..d42580a2 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Home/Index.ja-JP.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Home/Index.ja-JP.resx @@ -120,4 +120,16 @@ ライブラリがありません + + シャッフル + + + 再生 + + + 操作 + + + プレイリストに追加 + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Home/Index.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Home/Index.resx index 5bc23ade..f36b87c8 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Home/Index.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Home/Index.resx @@ -120,4 +120,16 @@ No libraries + + Shuffle + + + Play + + + Actions + + + Add to playlist + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Home/Index.ro-RO.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Home/Index.ro-RO.resx index c44563bc..f151004b 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Home/Index.ro-RO.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Home/Index.ro-RO.resx @@ -120,4 +120,16 @@ Nicio bibliotecă + + Aleatoriu + + + Redare + + + Acțiuni + + + Adaugă în listă de redare + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Home/Index.uk-UA.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Home/Index.uk-UA.resx index 0af25ca8..85ef450d 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Home/Index.uk-UA.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Home/Index.uk-UA.resx @@ -120,4 +120,16 @@ Немає бібліотек + + Перемішати + + + Відтворити + + + Дії + + + Додати до списку відтворення + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Home/Index.zh-CN.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Home/Index.zh-CN.resx index 9552d9c3..9b6d6bac 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Home/Index.zh-CN.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Home/Index.zh-CN.resx @@ -120,4 +120,16 @@ 无库 + + 随机播放 + + + 播放 + + + 操作 + + + 添加到播放列表 + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Albums/Item.ar-SA.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Albums/Item.ar-SA.resx index b7449ba6..3bd47122 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Albums/Item.ar-SA.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Albums/Item.ar-SA.resx @@ -1506,4 +1506,22 @@ المعرّفات + + تشغيل الألبوم + + + تشغيل المقطع + + + الإجراءات + + + إضافة إلى قائمة التشغيل + + + إضافة إلى قائمة الانتظار + + + تشغيل الكل من هنا + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Albums/Item.de-DE.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Albums/Item.de-DE.resx index 15e1f3f3..aff9b474 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Albums/Item.de-DE.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Albums/Item.de-DE.resx @@ -1506,4 +1506,22 @@ Kennungen + + Album abspielen + + + Titel abspielen + + + Aktionen + + + Zur Wiedergabeliste hinzufügen + + + Zur Warteschlange hinzufügen + + + Alles ab hier abspielen + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Albums/Item.en-US.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Albums/Item.en-US.resx index 880ed67d..2382c00f 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Albums/Item.en-US.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Albums/Item.en-US.resx @@ -703,7 +703,7 @@ Costa Rica - Côte d’Ivoire + Côte d’Ivoire Croatia @@ -1030,7 +1030,7 @@ San Marino - São Tomé & Príncipe + São Tomé & Príncipe Saudi Arabia @@ -1117,7 +1117,7 @@ Tunisia - Türkiye + Türkiye Turkmenistan @@ -1506,4 +1506,22 @@ Identifiers + + Play album + + + Play track + + + Actions + + + Add to playlist + + + Add to play queue + + + Play all from here + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Albums/Item.es-ES.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Albums/Item.es-ES.resx index 1259fd1d..189dd913 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Albums/Item.es-ES.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Albums/Item.es-ES.resx @@ -1506,4 +1506,22 @@ Identificadores + + Reproducir el álbum + + + Reproducir la pista + + + Acciones + + + Añadir a la lista de reproducción + + + Añadir a la cola de reproducción + + + Reproducir todo desde aquí + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Albums/Item.fr-FR.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Albums/Item.fr-FR.resx index 0b38058a..777913bf 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Albums/Item.fr-FR.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Albums/Item.fr-FR.resx @@ -1506,4 +1506,22 @@ Identifiants + + Lire l'album + + + Lire la piste + + + Actions + + + Ajouter à la liste de lecture + + + Ajouter à la file d'attente + + + Lire tout à partir d'ici + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Albums/Item.it-IT.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Albums/Item.it-IT.resx index 80112399..b3d55ce8 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Albums/Item.it-IT.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Albums/Item.it-IT.resx @@ -1506,4 +1506,22 @@ Identificatori + + Riproduci l'album + + + Riproduci il brano + + + Azioni + + + Aggiungi alla playlist + + + Aggiungi alla coda di riproduzione + + + Riproduci tutto da qui + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Albums/Item.ja-JP.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Albums/Item.ja-JP.resx index 8dff23f1..810da193 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Albums/Item.ja-JP.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Albums/Item.ja-JP.resx @@ -1506,4 +1506,22 @@ 識別子 + + アルバムを再生 + + + トラックを再生 + + + 操作 + + + プレイリストに追加 + + + 再生キューに追加 + + + ここからすべて再生 + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Albums/Item.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Albums/Item.resx index 880ed67d..2382c00f 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Albums/Item.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Albums/Item.resx @@ -703,7 +703,7 @@ Costa Rica - Côte d’Ivoire + Côte d’Ivoire Croatia @@ -1030,7 +1030,7 @@ San Marino - São Tomé & Príncipe + São Tomé & Príncipe Saudi Arabia @@ -1117,7 +1117,7 @@ Tunisia - Türkiye + Türkiye Turkmenistan @@ -1506,4 +1506,22 @@ Identifiers + + Play album + + + Play track + + + Actions + + + Add to playlist + + + Add to play queue + + + Play all from here + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Albums/Item.ro-RO.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Albums/Item.ro-RO.resx index 68b6915d..55fb6618 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Albums/Item.ro-RO.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Albums/Item.ro-RO.resx @@ -1506,4 +1506,22 @@ Identificatori + + Redă albumul + + + Redă piesa + + + Acțiuni + + + Adaugă în listă de redare + + + Adaugă la coada de redare + + + Redă tot de aici + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Albums/Item.uk-UA.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Albums/Item.uk-UA.resx index 45d369f7..68684f8d 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Albums/Item.uk-UA.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Albums/Item.uk-UA.resx @@ -1506,4 +1506,22 @@ Ідентифікатори + + Відтворити альбом + + + Відтворити трек + + + Дії + + + Додати до списку відтворення + + + Додати до черги відтворення + + + Відтворити все звідси + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Albums/Item.zh-CN.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Albums/Item.zh-CN.resx index f215465e..43685e57 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Albums/Item.zh-CN.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Albums/Item.zh-CN.resx @@ -1506,4 +1506,22 @@ 标识符 + + 播放专辑 + + + 播放曲目 + + + 操作 + + + 添加到播放列表 + + + 添加到播放队列 + + + 从这里开始播放全部 + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Index.ar-SA.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Index.ar-SA.resx index d99952cb..51c3d569 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Index.ar-SA.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Index.ar-SA.resx @@ -1,4 +1,4 @@ - + text/microsoft-resx @@ -57,4 +57,16 @@ تعذر حذف العنصر. + + تشغيل عشوائي + + + تشغيل + + + الإجراءات + + + إضافة إلى قائمة التشغيل + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Index.de-DE.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Index.de-DE.resx index f0b0fab2..9629c2e8 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Index.de-DE.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Index.de-DE.resx @@ -1,4 +1,4 @@ - + text/microsoft-resx @@ -57,4 +57,16 @@ Das Element konnte nicht gelöscht werden. + + Zufällige Wiedergabe + + + Abspielen + + + Aktionen + + + Zur Wiedergabeliste hinzufügen + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Index.en-US.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Index.en-US.resx index 1120e9db..70edc6b1 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Index.en-US.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Index.en-US.resx @@ -1,4 +1,4 @@ - + text/microsoft-resx @@ -57,4 +57,16 @@ The item could not be deleted. + + Shuffle + + + Play + + + Actions + + + Add to playlist + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Index.es-ES.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Index.es-ES.resx index 58ceea6a..ef56aa55 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Index.es-ES.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Index.es-ES.resx @@ -1,4 +1,4 @@ - + text/microsoft-resx @@ -57,4 +57,16 @@ No se ha podido eliminar el elemento. + + Aleatorio + + + Reproducir + + + Acciones + + + Añadir a la lista de reproducción + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Index.fr-FR.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Index.fr-FR.resx index 7d497880..54a1c039 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Index.fr-FR.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Index.fr-FR.resx @@ -1,4 +1,4 @@ - + text/microsoft-resx @@ -57,4 +57,16 @@ L'élément n'a pas pu être supprimé. + + Lecture aléatoire + + + Lecture + + + Actions + + + Ajouter à la liste de lecture + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Index.it-IT.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Index.it-IT.resx index cfbcec6f..3a94a7da 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Index.it-IT.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Index.it-IT.resx @@ -1,4 +1,4 @@ - + text/microsoft-resx @@ -57,4 +57,16 @@ Non è stato possibile eliminare l'elemento. + + Riproduzione casuale + + + Riproduci + + + Azioni + + + Aggiungi alla playlist + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Index.ja-JP.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Index.ja-JP.resx index 16875e52..e1f3718d 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Index.ja-JP.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Index.ja-JP.resx @@ -1,4 +1,4 @@ - + text/microsoft-resx @@ -57,4 +57,16 @@ 項目を削除できませんでした。 + + シャッフル + + + 再生 + + + 操作 + + + プレイリストに追加 + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Index.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Index.resx index 1120e9db..70edc6b1 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Index.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Index.resx @@ -1,4 +1,4 @@ - + text/microsoft-resx @@ -57,4 +57,16 @@ The item could not be deleted. + + Shuffle + + + Play + + + Actions + + + Add to playlist + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Index.ro-RO.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Index.ro-RO.resx index 8ec59558..4860c230 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Index.ro-RO.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Index.ro-RO.resx @@ -1,4 +1,4 @@ - + text/microsoft-resx @@ -57,4 +57,16 @@ Elementul nu a putut fi șters. + + Aleatoriu + + + Redare + + + Acțiuni + + + Adaugă în listă de redare + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Index.uk-UA.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Index.uk-UA.resx index be1c4469..9ceafb1b 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Index.uk-UA.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Index.uk-UA.resx @@ -1,4 +1,4 @@ - + text/microsoft-resx @@ -57,4 +57,16 @@ Не вдалося видалити елемент. + + Перемішати + + + Відтворити + + + Дії + + + Додати до списку відтворення + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Index.zh-CN.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Index.zh-CN.resx index 35ed518d..18859dc1 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Index.zh-CN.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Index.zh-CN.resx @@ -1,4 +1,4 @@ - + text/microsoft-resx @@ -57,4 +57,16 @@ 无法删除该项目。 + + 随机播放 + + + 播放 + + + 操作 + + + 添加到播放列表 + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Item.ar-SA.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Item.ar-SA.resx index 14698b57..55834262 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Item.ar-SA.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Item.ar-SA.resx @@ -1083,4 +1083,16 @@ إضافة ISNI + + تشغيل الكل + + + تشغيل + + + تشغيل عشوائي + + + إضافة إلى قائمة التشغيل + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Item.de-DE.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Item.de-DE.resx index 58bf363f..8b0540ed 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Item.de-DE.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Item.de-DE.resx @@ -1083,4 +1083,16 @@ ISNI hinzufügen + + Alle abspielen + + + Abspielen + + + Zufällige Wiedergabe + + + Zur Wiedergabeliste hinzufügen + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Item.en-US.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Item.en-US.resx index bbf79a82..9752bc4d 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Item.en-US.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Item.en-US.resx @@ -445,7 +445,7 @@ Costa Rica - Côte d’Ivoire + Côte d’Ivoire Croatia @@ -772,7 +772,7 @@ San Marino - São Tomé & Príncipe + São Tomé & Príncipe Saudi Arabia @@ -859,7 +859,7 @@ Tunisia - Türkiye + Türkiye Turkmenistan @@ -1083,4 +1083,16 @@ Add ISNI + + Play all + + + Play + + + Shuffle + + + Add to playlist + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Item.es-ES.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Item.es-ES.resx index e9476462..9ba90f4d 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Item.es-ES.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Item.es-ES.resx @@ -1083,4 +1083,16 @@ Añadir ISNI + + Reproducir todo + + + Reproducir + + + Aleatorio + + + Añadir a la lista de reproducción + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Item.fr-FR.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Item.fr-FR.resx index 08fe26ea..db7d04ec 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Item.fr-FR.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Item.fr-FR.resx @@ -1083,4 +1083,16 @@ Ajouter un ISNI + + Tout lire + + + Lire + + + Lecture aléatoire + + + Ajouter à la liste de lecture + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Item.it-IT.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Item.it-IT.resx index e2bf7d51..1e23fd35 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Item.it-IT.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Item.it-IT.resx @@ -1083,4 +1083,16 @@ Aggiungi ISNI + + Riproduci tutto + + + Riproduci + + + Riproduzione casuale + + + Aggiungi alla playlist + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Item.ja-JP.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Item.ja-JP.resx index 490821f4..53aea91d 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Item.ja-JP.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Item.ja-JP.resx @@ -1083,4 +1083,16 @@ ISNI を追加 + + すべて再生 + + + 再生 + + + シャッフル + + + プレイリストに追加 + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Item.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Item.resx index bbf79a82..9752bc4d 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Item.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Item.resx @@ -445,7 +445,7 @@ Costa Rica - Côte d’Ivoire + Côte d’Ivoire Croatia @@ -772,7 +772,7 @@ San Marino - São Tomé & Príncipe + São Tomé & Príncipe Saudi Arabia @@ -859,7 +859,7 @@ Tunisia - Türkiye + Türkiye Turkmenistan @@ -1083,4 +1083,16 @@ Add ISNI + + Play all + + + Play + + + Shuffle + + + Add to playlist + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Item.ro-RO.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Item.ro-RO.resx index 6f23f468..f23f4ff7 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Item.ro-RO.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Item.ro-RO.resx @@ -1083,4 +1083,16 @@ Adaugă ISNI + + Redă tot + + + Redă + + + Aleatoriu + + + Adaugă în listă de redare + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Item.uk-UA.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Item.uk-UA.resx index 5bbfe32d..edeb5536 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Item.uk-UA.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Item.uk-UA.resx @@ -1083,4 +1083,16 @@ Додати ISNI + + Відтворити все + + + Відтворити + + + Перемішати + + + Додати до списку відтворення + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Item.zh-CN.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Item.zh-CN.resx index e1f06152..868949d8 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Item.zh-CN.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Item.zh-CN.resx @@ -1083,4 +1083,16 @@ 添加 ISNI + + 全部播放 + + + 播放 + + + 随机播放 + + + 添加到播放列表 + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Tracks/Item.ar-SA.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Tracks/Item.ar-SA.resx index 2bf6599a..3a2af1dd 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Tracks/Item.ar-SA.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Tracks/Item.ar-SA.resx @@ -1179,4 +1179,7 @@ إضافة ISWC + + تشغيل المقطع + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Tracks/Item.de-DE.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Tracks/Item.de-DE.resx index 43c6973b..225c4a88 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Tracks/Item.de-DE.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Tracks/Item.de-DE.resx @@ -1179,4 +1179,7 @@ ISWC hinzufügen + + Titel abspielen + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Tracks/Item.en-US.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Tracks/Item.en-US.resx index 252da4a1..9b2c7185 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Tracks/Item.en-US.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Tracks/Item.en-US.resx @@ -655,7 +655,7 @@ Switzerland - Côte d’Ivoire + Côte d’Ivoire Chile @@ -1048,7 +1048,7 @@ South Sudan - São Tomé & Príncipe + São Tomé & Príncipe El Salvador @@ -1084,7 +1084,7 @@ Tonga - Türkiye + Türkiye Trinidad & Tobago @@ -1179,4 +1179,7 @@ Add ISWC + + Play track + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Tracks/Item.es-ES.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Tracks/Item.es-ES.resx index a431f4cd..c05e7939 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Tracks/Item.es-ES.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Tracks/Item.es-ES.resx @@ -1179,4 +1179,7 @@ Añadir ISWC + + Reproducir la pista + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Tracks/Item.fr-FR.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Tracks/Item.fr-FR.resx index 8734fe07..33308539 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Tracks/Item.fr-FR.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Tracks/Item.fr-FR.resx @@ -1179,4 +1179,7 @@ Ajouter un ISWC + + Lire la piste + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Tracks/Item.it-IT.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Tracks/Item.it-IT.resx index b3163394..4caf389b 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Tracks/Item.it-IT.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Tracks/Item.it-IT.resx @@ -1179,4 +1179,7 @@ Aggiungi ISWC + + Riproduci il brano + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Tracks/Item.ja-JP.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Tracks/Item.ja-JP.resx index 9a91da4d..21ab31ce 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Tracks/Item.ja-JP.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Tracks/Item.ja-JP.resx @@ -1179,4 +1179,7 @@ ISWC を追加 + + トラックを再生 + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Tracks/Item.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Tracks/Item.resx index 252da4a1..9b2c7185 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Tracks/Item.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Tracks/Item.resx @@ -655,7 +655,7 @@ Switzerland - Côte d’Ivoire + Côte d’Ivoire Chile @@ -1048,7 +1048,7 @@ South Sudan - São Tomé & Príncipe + São Tomé & Príncipe El Salvador @@ -1084,7 +1084,7 @@ Tonga - Türkiye + Türkiye Trinidad & Tobago @@ -1179,4 +1179,7 @@ Add ISWC + + Play track + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Tracks/Item.ro-RO.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Tracks/Item.ro-RO.resx index 58f0296d..8f46cfe9 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Tracks/Item.ro-RO.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Tracks/Item.ro-RO.resx @@ -1179,4 +1179,7 @@ Adaugă ISWC + + Redă piesa + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Tracks/Item.uk-UA.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Tracks/Item.uk-UA.resx index e18711ea..a63764fb 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Tracks/Item.uk-UA.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Tracks/Item.uk-UA.resx @@ -1179,4 +1179,7 @@ Додати ISWC + + Відтворити трек + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Tracks/Item.zh-CN.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Tracks/Item.zh-CN.resx index ba893c16..a1bfcbb1 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Tracks/Item.zh-CN.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Tracks/Item.zh-CN.resx @@ -1179,4 +1179,7 @@ 添加 ISWC + + 播放曲目 + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.ar-SA.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.ar-SA.resx index 4d546005..763d270e 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.ar-SA.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.ar-SA.resx @@ -294,7 +294,7 @@ نعم - - يوتيوب + + YouTube diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.de-DE.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.de-DE.resx index 93d2db81..b8da7f60 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.de-DE.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.de-DE.resx @@ -294,7 +294,7 @@ Ja - + YouTube \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.en-US.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.en-US.resx index 844849bc..d108cf96 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.en-US.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.en-US.resx @@ -294,7 +294,7 @@ Yes - + YouTube \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.es-ES.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.es-ES.resx index 5059ef16..fec23bfe 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.es-ES.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.es-ES.resx @@ -294,7 +294,7 @@ Sí - + YouTube \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.fr-FR.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.fr-FR.resx index c3cf79e8..9d8650d5 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.fr-FR.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.fr-FR.resx @@ -294,7 +294,7 @@ Oui - + YouTube \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.it-IT.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.it-IT.resx index 1e6c8f19..1e8e8fb1 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.it-IT.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.it-IT.resx @@ -294,7 +294,7 @@ Sì - + YouTube \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.ja-JP.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.ja-JP.resx index 1ceebafa..82f9c3c6 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.ja-JP.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.ja-JP.resx @@ -294,7 +294,7 @@ はい - - ユーチューブ + + YouTube \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.resx index 844849bc..d108cf96 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.resx @@ -294,7 +294,7 @@ Yes - + YouTube \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.ro-RO.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.ro-RO.resx index c34fc20d..7c108058 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.ro-RO.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.ro-RO.resx @@ -294,7 +294,7 @@ Da - + YouTube \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.uk-UA.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.uk-UA.resx index 16135874..03dcaa9e 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.uk-UA.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.uk-UA.resx @@ -294,7 +294,7 @@ Так - - Ютуб + + YouTube diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.zh-CN.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.zh-CN.resx index 349cb9fc..1e58d782 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.zh-CN.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.zh-CN.resx @@ -294,7 +294,7 @@ 是 - - 油管 + + YouTube \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.ar-SA.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.ar-SA.resx index d02b272f..d3d14645 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.ar-SA.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.ar-SA.resx @@ -312,9 +312,6 @@ محتوى مكتوب - - YouTube - الاسم @@ -414,4 +411,22 @@ معرف الكتاب + + تتبع تقدم الاستهلاك + + + ما إذا كان يتم تذكر موضع التشغيل أو القراءة لعناصر هذه المكتبة، حتى يتمكن المستخدم من المتابعة من حيث توقف. + + + حد الإكمال (%) + + + النسبة المئوية من العنصر التي يجب استهلاكها لاعتبار جلسته مكتملة. عند تركه فارغًا، تُستخدم القيمة الافتراضية لنوع المكتبة عند إنشاء مكتبة أو عند تفعيل تتبع التقدم، وتُحتفظ القيمة المخزنة عند تحرير مكتبة تتبع التقدم بالفعل. الأنواع التي ليس لها حد افتراضي تسجل الإكمال فقط عند الإبلاغ عنه صراحةً. + + + يجب أن يكون حد الإكمال عددًا صحيحًا بين 0 و100. + + + YouTube + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.de-DE.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.de-DE.resx index a342f348..c6661aa2 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.de-DE.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.de-DE.resx @@ -312,9 +312,6 @@ Schriftliche Inhalte - - YouTube - Name @@ -414,4 +411,22 @@ Buch-ID - \ No newline at end of file + + Konsumfortschritt Verfolgen + + + Ob die Wiedergabe- oder Leseposition der Elemente dieser Bibliothek gespeichert wird, damit der Benutzer dort fortsetzen kann, wo er aufgehört hat. + + + Abschlussschwelle (%) + + + Der Prozentsatz eines Elements, der konsumiert werden muss, damit seine Sitzung als abgeschlossen gilt. Wenn das Feld leer bleibt, wird der Standardwert des Bibliothekstyps beim Erstellen einer Bibliothek oder beim Aktivieren der Fortschrittsverfolgung verwendet; beim Bearbeiten einer Bibliothek, die den Fortschritt bereits verfolgt, bleibt die gespeicherte Schwelle erhalten. Typen ohne Standardschwelle erfassen den Abschluss nur bei ausdrücklicher Meldung. + + + Die Abschlussschwelle muss eine ganze Zahl zwischen 0 und 100 sein. + + + YouTube + + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.en-US.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.en-US.resx index 0356503d..55cf7fc0 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.en-US.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.en-US.resx @@ -312,9 +312,6 @@ Written Content - - YouTube - Name @@ -414,4 +411,22 @@ Book id - \ No newline at end of file + + Track Consumption Progress + + + Whether the playback or reading position of this library's items is remembered, so the user can resume where they left off. + + + Completion Threshold (%) + + + The percentage of an item that must be consumed for its session to be considered completed. When empty, the default of the library type is used when creating a library or enabling progress tracking, and the stored threshold is kept when editing a library that already tracks progress. Types without a default threshold record completion only when it is reported explicitly. + + + The completion threshold must be a whole number between 0 and 100. + + + YouTube + + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.es-ES.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.es-ES.resx index 1beb7bbe..4393c46b 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.es-ES.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.es-ES.resx @@ -312,9 +312,6 @@ Contenido Escrito - - YouTube - Nombre @@ -414,4 +411,22 @@ Id del libro - \ No newline at end of file + + Rastrear El Progreso Del Consumo + + + Si se recuerda la posición de reproducción o lectura de los elementos de esta biblioteca, para que el usuario pueda continuar donde lo dejó. + + + Umbral De Finalización (%) + + + El porcentaje de un elemento que debe consumirse para que su sesión se considere completada. Si se deja vacío, se usa el valor predeterminado del tipo de biblioteca al crear una biblioteca o al activar el seguimiento del progreso, y se conserva el valor almacenado al editar una biblioteca que ya lo sigue. Los tipos sin umbral predeterminado registran la finalización solo cuando se informa explícitamente. + + + El umbral de finalización debe ser un número entero entre 0 y 100. + + + YouTube + + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.fr-FR.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.fr-FR.resx index 57a4f545..21012df1 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.fr-FR.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.fr-FR.resx @@ -312,9 +312,6 @@ Contenu Écrit - - YouTube - Nom @@ -414,4 +411,22 @@ Id du livre - \ No newline at end of file + + Suivre La Progression De Consommation + + + Si la position de lecture ou de visionnage des éléments de cette bibliothèque est mémorisée, afin que l'utilisateur puisse reprendre là où il s'est arrêté. + + + Seuil d'achèvement (%) + + + Le pourcentage d'un élément qui doit être consommé pour que sa session soit considérée comme terminée. S'il est vide, la valeur par défaut du type de bibliothèque est utilisée lors de la création d'une bibliothèque ou de l'activation du suivi de la progression, et la valeur enregistrée est conservée lors de la modification d'une bibliothèque qui suit déjà la progression. Les types sans seuil par défaut enregistrent l'achèvement uniquement lorsqu'il est signalé explicitement. + + + Le seuil d'achèvement doit être un nombre entier compris entre 0 et 100. + + + YouTube + + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.it-IT.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.it-IT.resx index 506068d3..187f2f32 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.it-IT.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.it-IT.resx @@ -312,9 +312,6 @@ Contenuto Scritto - - YouTube - Nome @@ -414,4 +411,22 @@ Id del libro - \ No newline at end of file + + Monitora Il Progresso Di Consumo + + + Se la posizione di riproduzione o di lettura degli elementi di questa libreria viene ricordata, così che l'utente possa riprendere da dove si era interrotto. + + + Soglia Di Completamento (%) + + + La percentuale di un elemento che deve essere consumata perché la sua sessione sia considerata completata. Se lasciato vuoto, viene usato il valore predefinito del tipo di libreria quando si crea una libreria o si attiva il monitoraggio del progresso, mentre il valore salvato viene mantenuto quando si modifica una libreria che monitora già il progresso. I tipi senza soglia predefinita registrano il completamento solo quando viene segnalato esplicitamente. + + + La soglia di completamento deve essere un numero intero compreso tra 0 e 100. + + + YouTube + + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.ja-JP.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.ja-JP.resx index fab3ff88..14f61cd4 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.ja-JP.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.ja-JP.resx @@ -312,9 +312,6 @@ 文字コンテンツ - - ユーチューブ - 名前 @@ -414,4 +411,22 @@ 書籍ID - \ No newline at end of file + + 進行状況を記録 + + + このライブラリの項目の再生位置または閲覧位置を記憶し、ユーザーが中断した場所から再開できるようにするかどうか。 + + + 完了しきい値 (%) + + + 項目のセッションを完了とみなすために消費する必要がある割合。空欄の場合、ライブラリの作成時または進行状況の追跡を有効にするときはライブラリの種類の既定値が使用され、すでに進行状況を追跡しているライブラリの編集時は保存されているしきい値が維持されます。既定のしきい値がない種類では、明示的に報告された場合にのみ完了を記録します。 + + + 完了しきい値は 0 から 100 の間の整数である必要があります。 + + + YouTube + + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.resx index 0356503d..55cf7fc0 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.resx @@ -312,9 +312,6 @@ Written Content - - YouTube - Name @@ -414,4 +411,22 @@ Book id - \ No newline at end of file + + Track Consumption Progress + + + Whether the playback or reading position of this library's items is remembered, so the user can resume where they left off. + + + Completion Threshold (%) + + + The percentage of an item that must be consumed for its session to be considered completed. When empty, the default of the library type is used when creating a library or enabling progress tracking, and the stored threshold is kept when editing a library that already tracks progress. Types without a default threshold record completion only when it is reported explicitly. + + + The completion threshold must be a whole number between 0 and 100. + + + YouTube + + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.ro-RO.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.ro-RO.resx index 21d9c9d1..2543870b 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.ro-RO.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.ro-RO.resx @@ -312,9 +312,6 @@ Conținut Scris - - YouTube - Nume @@ -414,4 +411,22 @@ Id-ul cărții - \ No newline at end of file + + Urmărește Progresul Consumului + + + Dacă poziția de redare sau de citire a elementelor acestei biblioteci este reținută, astfel încât utilizatorul să poată relua de unde a rămas. + + + Prag De Finalizare (%) + + + Procentul unui element care trebuie consumat pentru ca sesiunea sa să fie considerată finalizată. Dacă este lăsat gol, se folosește valoarea implicită a tipului de bibliotecă la crearea unei biblioteci sau la activarea urmăririi progresului, iar valoarea salvată este păstrată la editarea unei biblioteci care urmărește deja progresul. Tipurile fără un prag implicit înregistrează finalizarea doar când este raportată explicit. + + + Pragul de finalizare trebuie să fie un număr întreg între 0 și 100. + + + YouTube + + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.uk-UA.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.uk-UA.resx index d33923b7..5e1c4241 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.uk-UA.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.uk-UA.resx @@ -312,9 +312,6 @@ Письмовий контент - - Ютуб - Ім'я @@ -414,4 +411,22 @@ Ідентифікатор книги - \ No newline at end of file + + Відстежувати прогрес споживання + + + Чи запам'ятовується позиція відтворення або читання елементів цієї бібліотеки, щоб користувач міг продовжити з того місця, де зупинився. + + + Поріг завершення (%) + + + Відсоток елемента, який потрібно спожити, щоб його сеанс вважався завершеним. Якщо залишити порожнім, типове значення типу бібліотеки використовується під час створення бібліотеки або ввімкнення відстеження прогресу, а збережене значення зберігається під час редагування бібліотеки, яка вже відстежує прогрес. Типи без типового порогу фіксують завершення лише тоді, коли його явно повідомлено. + + + Поріг завершення має бути цілим числом від 0 до 100. + + + YouTube + + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.zh-CN.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.zh-CN.resx index 882a7a51..ec7ff75a 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.zh-CN.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.zh-CN.resx @@ -312,9 +312,6 @@ 文字内容 - - 油管 - 名称 @@ -414,4 +411,22 @@ 书籍编号 - \ No newline at end of file + + 跟踪消费进度 + + + 是否记住此媒体库项目的播放或阅读位置,以便用户可以从上次停止的地方继续。 + + + 完成阈值 (%) + + + 为了使某个项目的会话被视为已完成,必须消费的百分比。留空时,创建媒体库或启用进度跟踪会使用该类型的默认值,而编辑已在跟踪进度的媒体库时会保留已存储的阈值。没有默认阈值的类型仅在明确报告时记录完成。 + + + 完成阈值必须是介于 0 和 100 之间的整数。 + + + YouTube + + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Statistics/Index.ar-SA.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Statistics/Index.ar-SA.resx new file mode 100644 index 00000000..68110173 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Statistics/Index.ar-SA.resx @@ -0,0 +1,201 @@ + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + الإحصائيات + + + إجمالي وقت الاستهلاك + + + الجلسات المحتسبة + + + الجلسات المكتملة + + + معدل الإكمال + + + حسب نوع الوسائط + + + نوع الوسائط + + + الوقت + + + متوقفة + + + محتسبة + + + مكتملة + + + الأنواع + + + العلامات + + + لا توجد بيانات أنواع لهذه عوامل التصفية. + + + لا توجد بيانات علامات لهذه عوامل التصفية. + + + عناصر + + + المستهلك مؤخراً + + + الأكثر استهلاكاً + + + لا توجد عناصر مستهلكة مؤخراً. + + + لا توجد عناصر أكثر استهلاكاً. + + + آخر استهلاك + + + هذا العنصر لم يعد متاحاً. + + + حذف من السجل + + + هل تريد حذف كل الجلسات المسجلة لهذا العنصر من السجل؟ + + + تم حذف إدخال السجل. + + + مسح السجل + + + هل تريد حذف سجل الاستهلاك بالكامل للمستخدم المحدد؟ + + + تم مسح سجل الاستهلاك. + + + إزالة من متابعة المشاهدة + + + هل تريد إزالة كل نقاط الاستئناف للمستخدم المحدد؟ يتم الاحتفاظ بالسجل. + + + تمت إزالة نقاط الاستئناف. + + + عوامل التصفية + + + المكتبة + + + كل المكتبات + + + كل أنواع الوسائط + + + من + + + إلى + + + تطبيق + + + إعادة تعيين + + + يجب ألا يكون تاريخ البداية بعد تاريخ النهاية. + + + المستخدم + + + كل المستخدمين + + + أنا + + + السجل وتفصيل العلامات متاحان لكل مستخدم. اختر مستخدماً لعرضهما. + + + لكل مستخدم + + + لا يوجد مستخدمون لديهم إحصائيات استهلاك لهذه عوامل التصفية. + + + لا توجد بيانات نوع وسائط لهذه عوامل التصفية. + + + لا يوجد سجل استهلاك لهذه عوامل التصفية. + + + جارٍ التحميل... + + + تعذر تحميل الإحصائيات. + + + إعادة المحاولة + + + مقطع + + + حلقة بودكاست + + + كتاب صوتي + + + فيلم + + + حلقة تلفزيونية + + + كتاب + + + صورة + + + فيديو + + + س + + + د + + + ث + + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Statistics/Index.de-DE.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Statistics/Index.de-DE.resx new file mode 100644 index 00000000..0bad0952 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Statistics/Index.de-DE.resx @@ -0,0 +1,201 @@ + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Statistik + + + Gesamte konsumierte Zeit + + + Gezählte Sitzungen + + + Abgeschlossene Sitzungen + + + Abschlussrate + + + Nach Medienart + + + Medienart + + + Zeit + + + Gestoppt + + + Gezählt + + + Abgeschlossen + + + Genres + + + Tags + + + Keine Genre-Daten für diese Filter. + + + Keine Tag-Daten für diese Filter. + + + Elemente + + + Kürzlich konsumiert + + + Meistkonsumiert + + + Keine kürzlich konsumierten Elemente. + + + Keine meistkonsumierten Elemente. + + + Zuletzt konsumiert + + + Dieses Element ist nicht mehr verfügbar. + + + Aus dem Verlauf löschen + + + Alle aufgezeichneten Sitzungen dieses Elements aus dem Verlauf löschen? + + + Der Verlaufseintrag wurde gelöscht. + + + Verlauf löschen + + + Den gesamten Konsumverlauf des ausgewählten Benutzers löschen? + + + Der Konsumverlauf wurde gelöscht. + + + Aus Weiterschauen entfernen + + + Alle Fortsetzungspunkte des ausgewählten Benutzers entfernen? Der Verlauf bleibt erhalten. + + + Die Fortsetzungspunkte wurden entfernt. + + + Filter + + + Bibliothek + + + Alle Bibliotheken + + + Alle Medienarten + + + Von + + + Bis + + + Anwenden + + + Zurücksetzen + + + Das Startdatum darf nicht nach dem Enddatum liegen. + + + Benutzer + + + Alle Benutzer + + + Ich + + + Der Verlauf und die Tag-Aufschlüsselung sind pro Benutzer verfügbar. Wählen Sie einen Benutzer aus, um sie zu sehen. + + + Pro Benutzer + + + Keine Benutzer haben Konsumstatistiken für diese Filter. + + + Keine Medienart-Daten für diese Filter. + + + Es gibt keinen Konsumverlauf für diese Filter. + + + Wird geladen... + + + Die Statistik konnte nicht geladen werden. + + + Erneut versuchen + + + Titel + + + Podcast-Episode + + + Hörbuch + + + Film + + + TV-Episode + + + Buch + + + Foto + + + Video + + + Std. + + + Min. + + + Sek. + + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Statistics/Index.en-US.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Statistics/Index.en-US.resx new file mode 100644 index 00000000..ea2d7993 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Statistics/Index.en-US.resx @@ -0,0 +1,201 @@ + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Statistics + + + Total consumed time + + + Counted sessions + + + Completed sessions + + + Completion rate + + + By media kind + + + Media kind + + + Time + + + Stopped + + + Counted + + + Completed + + + Genres + + + Tags + + + No genre data for these filters. + + + No tag data for these filters. + + + items + + + Recently consumed + + + Most consumed + + + No recently consumed items. + + + No most consumed items. + + + Last consumed + + + This item is no longer available. + + + Delete from history + + + Delete every recorded session of this item from the history? + + + The history entry was deleted. + + + Clear history + + + Delete the entire consumption history of the selected user? + + + The consumption history was cleared. + + + Remove from continue watching + + + Remove every resume point of the selected user? The history is kept. + + + The resume points were removed. + + + Filters + + + Library + + + All libraries + + + All media kinds + + + From + + + To + + + Apply + + + Reset + + + The start date must not be after the end date. + + + User + + + All users + + + Me + + + The history and the tag breakdown are available per user. Select a user to see them. + + + Per user + + + No users have consumption statistics for these filters. + + + No media kind data for these filters. + + + There is no consumption history for these filters. + + + Loading... + + + The statistics could not be loaded. + + + Retry + + + Track + + + Podcast episode + + + Audiobook + + + Movie + + + TV episode + + + Book + + + Photo + + + Video + + + h + + + m + + + s + + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Statistics/Index.es-ES.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Statistics/Index.es-ES.resx new file mode 100644 index 00000000..78562d59 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Statistics/Index.es-ES.resx @@ -0,0 +1,201 @@ + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Estadísticas + + + Tiempo total consumido + + + Sesiones contabilizadas + + + Sesiones completadas + + + Tasa de finalización + + + Por tipo de medio + + + Tipo de medio + + + Tiempo + + + Detenidas + + + Contabilizadas + + + Completadas + + + Géneros + + + Etiquetas + + + No hay datos de géneros para estos filtros. + + + No hay datos de etiquetas para estos filtros. + + + elementos + + + Consumido recientemente + + + Más consumido + + + No hay elementos consumidos recientemente. + + + No hay elementos más consumidos. + + + Último consumo + + + Este elemento ya no está disponible. + + + Eliminar del historial + + + ¿Eliminar todas las sesiones registradas de este elemento del historial? + + + La entrada del historial fue eliminada. + + + Borrar historial + + + ¿Borrar todo el historial de consumo del usuario seleccionado? + + + El historial de consumo fue borrado. + + + Quitar de continuar viendo + + + ¿Quitar todos los puntos de reanudación del usuario seleccionado? El historial se conserva. + + + Los puntos de reanudación fueron eliminados. + + + Filtros + + + Biblioteca + + + Todas las bibliotecas + + + Todos los tipos de medio + + + Desde + + + Hasta + + + Aplicar + + + Restablecer + + + La fecha de inicio no debe ser posterior a la fecha de fin. + + + Usuario + + + Todos los usuarios + + + Yo + + + El historial y el desglose de etiquetas están disponibles por usuario. Seleccione un usuario para verlos. + + + Por usuario + + + Ningún usuario tiene estadísticas de consumo para estos filtros. + + + No hay datos de tipo de medio para estos filtros. + + + No hay historial de consumo para estos filtros. + + + Cargando... + + + No se pudieron cargar las estadísticas. + + + Reintentar + + + Pista + + + Episodio de podcast + + + Audiolibro + + + Película + + + Episodio de TV + + + Libro + + + Foto + + + Vídeo + + + h + + + min + + + s + + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Statistics/Index.fr-FR.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Statistics/Index.fr-FR.resx new file mode 100644 index 00000000..b19b3418 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Statistics/Index.fr-FR.resx @@ -0,0 +1,201 @@ + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Statistiques + + + Temps total consommé + + + Sessions comptabilisées + + + Sessions terminées + + + Taux d'achèvement + + + Par type de média + + + Type de média + + + Temps + + + Arrêtées + + + Comptabilisées + + + Terminées + + + Genres + + + Étiquettes + + + Aucune donnée de genre pour ces filtres. + + + Aucune donnée d'étiquette pour ces filtres. + + + éléments + + + Consommé récemment + + + Le plus consommé + + + Aucun élément consommé récemment. + + + Aucun élément le plus consommé. + + + Dernière consommation + + + Cet élément n'est plus disponible. + + + Supprimer de l'historique + + + Supprimer toutes les sessions enregistrées de cet élément de l'historique ? + + + L'entrée de l'historique a été supprimée. + + + Effacer l'historique + + + Effacer tout l'historique de consommation de l'utilisateur sélectionné ? + + + L'historique de consommation a été effacé. + + + Retirer de la reprise + + + Retirer tous les points de reprise de l'utilisateur sélectionné ? L'historique est conservé. + + + Les points de reprise ont été retirés. + + + Filtres + + + Bibliothèque + + + Toutes les bibliothèques + + + Tous les types de média + + + Du + + + Au + + + Appliquer + + + Réinitialiser + + + La date de début ne doit pas être postérieure à la date de fin. + + + Utilisateur + + + Tous les utilisateurs + + + Moi + + + L'historique et la répartition des étiquettes sont disponibles par utilisateur. Sélectionnez un utilisateur pour les voir. + + + Par utilisateur + + + Aucun utilisateur n'a de statistiques de consommation pour ces filtres. + + + Aucune donnée de type de média pour ces filtres. + + + Aucun historique de consommation pour ces filtres. + + + Chargement... + + + Les statistiques n'ont pas pu être chargées. + + + Réessayer + + + Piste + + + Épisode de podcast + + + Livre audio + + + Film + + + Épisode TV + + + Livre + + + Photo + + + Vidéo + + + h + + + min + + + s + + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Statistics/Index.it-IT.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Statistics/Index.it-IT.resx new file mode 100644 index 00000000..151393ae --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Statistics/Index.it-IT.resx @@ -0,0 +1,201 @@ + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Statistiche + + + Tempo totale consumato + + + Sessioni conteggiate + + + Sessioni completate + + + Tasso di completamento + + + Per tipo di contenuto + + + Tipo di contenuto + + + Tempo + + + Interrotte + + + Conteggiate + + + Completate + + + Generi + + + Tag + + + Nessun dato sui generi per questi filtri. + + + Nessun dato sui tag per questi filtri. + + + elementi + + + Consumati di recente + + + Più consumati + + + Nessun elemento consumato di recente. + + + Nessun elemento più consumato. + + + Ultimo consumo + + + Questo elemento non è più disponibile. + + + Elimina dalla cronologia + + + Eliminare dalla cronologia tutte le sessioni registrate di questo elemento? + + + La voce della cronologia è stata eliminata. + + + Cancella cronologia + + + Cancellare l'intera cronologia di consumo dell'utente selezionato? + + + La cronologia di consumo è stata cancellata. + + + Rimuovi da continua a guardare + + + Rimuovere tutti i punti di ripresa dell'utente selezionato? La cronologia viene mantenuta. + + + I punti di ripresa sono stati rimossi. + + + Filtri + + + Libreria + + + Tutte le librerie + + + Tutti i tipi di contenuto + + + Da + + + A + + + Applica + + + Reimposta + + + La data di inizio non deve essere successiva alla data di fine. + + + Utente + + + Tutti gli utenti + + + Io + + + La cronologia e la suddivisione dei tag sono disponibili per utente. Seleziona un utente per visualizzarle. + + + Per utente + + + Nessun utente ha statistiche di consumo per questi filtri. + + + Nessun dato sul tipo di contenuto per questi filtri. + + + Nessuna cronologia di consumo per questi filtri. + + + Caricamento... + + + Impossibile caricare le statistiche. + + + Riprova + + + Brano + + + Episodio di podcast + + + Audiolibro + + + Film + + + Episodio TV + + + Libro + + + Foto + + + Video + + + h + + + min + + + s + + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Statistics/Index.ja-JP.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Statistics/Index.ja-JP.resx new file mode 100644 index 00000000..41f9e201 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Statistics/Index.ja-JP.resx @@ -0,0 +1,201 @@ + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + 統計 + + + 総消費時間 + + + 集計対象セッション + + + 完了セッション + + + 完了率 + + + メディア種別ごと + + + メディア種別 + + + 時間 + + + 停止 + + + 集計対象 + + + 完了 + + + ジャンル + + + タグ + + + このフィルターのジャンルデータはありません。 + + + このフィルターのタグデータはありません。 + + + 件 + + + 最近消費したもの + + + 最も消費したもの + + + 最近消費したものはありません。 + + + 最も消費したものはありません。 + + + 最終消費 + + + このアイテムはもう利用できません。 + + + 履歴から削除 + + + このアイテムの記録されたすべてのセッションを履歴から削除しますか? + + + 履歴の項目を削除しました。 + + + 履歴を消去 + + + 選択したユーザーの消費履歴をすべて削除しますか? + + + 消費履歴を消去しました。 + + + 続きを見るから削除 + + + 選択したユーザーの再開ポイントをすべて削除しますか? 履歴は保持されます。 + + + 再開ポイントを削除しました。 + + + フィルター + + + ライブラリ + + + すべてのライブラリ + + + すべてのメディア種別 + + + 開始 + + + 終了 + + + 適用 + + + リセット + + + 開始日は終了日より後にできません。 + + + ユーザー + + + すべてのユーザー + + + 自分 + + + 履歴とタグの内訳はユーザーごとに表示されます。表示するユーザーを選択してください。 + + + ユーザーごと + + + このフィルターの消費統計を持つユーザーはいません。 + + + このフィルターのメディア種別データはありません。 + + + このフィルターの消費履歴はありません。 + + + 読み込み中... + + + 統計を読み込めませんでした。 + + + 再試行 + + + トラック + + + ポッドキャストエピソード + + + オーディオブック + + + 映画 + + + TVエピソード + + + 本 + + + 写真 + + + 動画 + + + 時間 + + + 分 + + + 秒 + + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Statistics/Index.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Statistics/Index.resx new file mode 100644 index 00000000..ea2d7993 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Statistics/Index.resx @@ -0,0 +1,201 @@ + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Statistics + + + Total consumed time + + + Counted sessions + + + Completed sessions + + + Completion rate + + + By media kind + + + Media kind + + + Time + + + Stopped + + + Counted + + + Completed + + + Genres + + + Tags + + + No genre data for these filters. + + + No tag data for these filters. + + + items + + + Recently consumed + + + Most consumed + + + No recently consumed items. + + + No most consumed items. + + + Last consumed + + + This item is no longer available. + + + Delete from history + + + Delete every recorded session of this item from the history? + + + The history entry was deleted. + + + Clear history + + + Delete the entire consumption history of the selected user? + + + The consumption history was cleared. + + + Remove from continue watching + + + Remove every resume point of the selected user? The history is kept. + + + The resume points were removed. + + + Filters + + + Library + + + All libraries + + + All media kinds + + + From + + + To + + + Apply + + + Reset + + + The start date must not be after the end date. + + + User + + + All users + + + Me + + + The history and the tag breakdown are available per user. Select a user to see them. + + + Per user + + + No users have consumption statistics for these filters. + + + No media kind data for these filters. + + + There is no consumption history for these filters. + + + Loading... + + + The statistics could not be loaded. + + + Retry + + + Track + + + Podcast episode + + + Audiobook + + + Movie + + + TV episode + + + Book + + + Photo + + + Video + + + h + + + m + + + s + + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Statistics/Index.ro-RO.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Statistics/Index.ro-RO.resx new file mode 100644 index 00000000..f4e9cdaf --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Statistics/Index.ro-RO.resx @@ -0,0 +1,201 @@ + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Statistici + + + Timp total consumat + + + Sesiuni contorizate + + + Sesiuni finalizate + + + Rată de finalizare + + + După tipul de conținut + + + Tip de conținut + + + Timp + + + Oprite + + + Contorizate + + + Finalizate + + + Genuri + + + Etichete + + + Nu există date despre genuri pentru aceste filtre. + + + Nu există date despre etichete pentru aceste filtre. + + + elemente + + + Consumate recent + + + Cele mai consumate + + + Nu există elemente consumate recent. + + + Nu există elemente cele mai consumate. + + + Ultima consumare + + + Acest element nu mai este disponibil. + + + Șterge din istoric + + + Ștergi toate sesiunile înregistrate ale acestui element din istoric? + + + Intrarea din istoric a fost ștearsă. + + + Golește istoricul + + + Ștergi întregul istoric de consum al utilizatorului selectat? + + + Istoricul de consum a fost golit. + + + Elimină din continuă vizionarea + + + Elimini toate punctele de reluare ale utilizatorului selectat? Istoricul este păstrat. + + + Punctele de reluare au fost eliminate. + + + Filtre + + + Bibliotecă + + + Toate bibliotecile + + + Toate tipurile de conținut + + + De la + + + Până la + + + Aplică + + + Resetează + + + Data de început nu trebuie să fie după data de sfârșit. + + + Utilizator + + + Toți utilizatorii + + + Eu + + + Istoricul și defalcarea etichetelor sunt disponibile pentru fiecare utilizator. Selectează un utilizator pentru a le vedea. + + + Per utilizator + + + Niciun utilizator nu are statistici de consum pentru aceste filtre. + + + Nu există date despre tipul de conținut pentru aceste filtre. + + + Nu există istoric de consum pentru aceste filtre. + + + Se încarcă... + + + Statisticile nu au putut fi încărcate. + + + Reîncearcă + + + Pistă + + + Episod de podcast + + + Carte audio + + + Film + + + Episod TV + + + Carte + + + Fotografie + + + Videoclip + + + h + + + min + + + s + + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Statistics/Index.uk-UA.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Statistics/Index.uk-UA.resx new file mode 100644 index 00000000..f4293c6b --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Statistics/Index.uk-UA.resx @@ -0,0 +1,201 @@ + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Статистика + + + Загальний спожитий час + + + Зараховані сеанси + + + Завершені сеанси + + + Відсоток завершення + + + За типом медіа + + + Тип медіа + + + Час + + + Зупинені + + + Зараховані + + + Завершені + + + Жанри + + + Теги + + + Немає даних про жанри для цих фільтрів. + + + Немає даних про теги для цих фільтрів. + + + елементів + + + Нещодавно спожиті + + + Найбільш спожиті + + + Немає нещодавно спожитих елементів. + + + Немає найбільш спожитих елементів. + + + Останнє споживання + + + Цей елемент більше недоступний. + + + Видалити з історії + + + Видалити з історії всі записані сеанси цього елемента? + + + Запис історії видалено. + + + Очистити історію + + + Видалити всю історію споживання вибраного користувача? + + + Історію споживання очищено. + + + Видалити з продовження перегляду + + + Видалити всі точки продовження вибраного користувача? Історія зберігається. + + + Точки продовження видалено. + + + Фільтри + + + Бібліотека + + + Усі бібліотеки + + + Усі типи медіа + + + Від + + + До + + + Застосувати + + + Скинути + + + Дата початку не може бути пізніше дати завершення. + + + Користувач + + + Усі користувачі + + + Я + + + Історія та розподіл тегів доступні для кожного користувача. Виберіть користувача, щоб переглянути їх. + + + Для кожного користувача + + + Жоден користувач не має статистики споживання для цих фільтрів. + + + Немає даних про тип медіа для цих фільтрів. + + + Немає історії споживання для цих фільтрів. + + + Завантаження... + + + Не вдалося завантажити статистику. + + + Повторити + + + Трек + + + Епізод подкасту + + + Аудіокнига + + + Фільм + + + Епізод телесеріалу + + + Книга + + + Фото + + + Відео + + + год + + + хв + + + с + + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Statistics/Index.zh-CN.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Statistics/Index.zh-CN.resx new file mode 100644 index 00000000..fa14bd14 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Statistics/Index.zh-CN.resx @@ -0,0 +1,201 @@ + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + 统计 + + + 总消费时长 + + + 计入的会话 + + + 已完成的会话 + + + 完成率 + + + 按媒体类型 + + + 媒体类型 + + + 时长 + + + 已停止 + + + 已计入 + + + 已完成 + + + 类型 + + + 标签 + + + 这些筛选条件下没有类型数据。 + + + 这些筛选条件下没有标签数据。 + + + 项 + + + 最近消费 + + + 最常消费 + + + 没有最近消费的项目。 + + + 没有最常消费的项目。 + + + 最近消费时间 + + + 此项目已不可用。 + + + 从历史记录中删除 + + + 要从历史记录中删除此项目的所有已记录会话吗? + + + 历史记录项已删除。 + + + 清除历史记录 + + + 要删除所选用户的全部消费历史记录吗? + + + 消费历史记录已清除。 + + + 从继续观看中移除 + + + 要移除所选用户的全部继续播放点吗?历史记录会保留。 + + + 继续播放点已移除。 + + + 筛选 + + + 媒体库 + + + 所有媒体库 + + + 所有媒体类型 + + + 从 + + + 到 + + + 应用 + + + 重置 + + + 开始日期不能晚于结束日期。 + + + 用户 + + + 所有用户 + + + 我 + + + 历史记录和标签明细按用户提供。请选择用户以查看。 + + + 按用户 + + + 没有用户在这些筛选条件下有消费统计。 + + + 这些筛选条件下没有媒体类型数据。 + + + 这些筛选条件下没有消费历史记录。 + + + 正在加载... + + + 无法加载统计。 + + + 重试 + + + 曲目 + + + 播客单集 + + + 有声书 + + + 电影 + + + 电视单集 + + + 书籍 + + + 照片 + + + 视频 + + + 小时 + + + 分 + + + 秒 + + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Playlists/Index.ar-SA.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Playlists/Index.ar-SA.resx new file mode 100644 index 00000000..9d9c41dd --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Playlists/Index.ar-SA.resx @@ -0,0 +1,51 @@ + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + قوائم التشغيل + + + الاسم + + + الوصف + + + إنشاء + + + ليست لديك أي قوائم تشغيل بعد. + + + مقاطع + + + حذف + + + هل تريد حذف قائمة التشغيل هذه؟ لا يمكن التراجع عن هذا الإجراء. + + + تعذر حذف قائمة التشغيل. + + + تعذر إنشاء قائمة التشغيل. + + + تحتاج قائمة التشغيل إلى اسم. + + + عناصر + + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Playlists/Index.de-DE.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Playlists/Index.de-DE.resx new file mode 100644 index 00000000..d4f25689 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Playlists/Index.de-DE.resx @@ -0,0 +1,51 @@ + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Wiedergabelisten + + + Name + + + Beschreibung + + + Erstellen + + + Du hast noch keine Wiedergabelisten. + + + Titel + + + Löschen + + + Diese Wiedergabeliste löschen? Das kann nicht rückgängig gemacht werden. + + + Die Wiedergabeliste konnte nicht gelöscht werden. + + + Die Wiedergabeliste konnte nicht erstellt werden. + + + Eine Wiedergabeliste braucht einen Namen. + + + Einträge + + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Playlists/Index.en-US.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Playlists/Index.en-US.resx new file mode 100644 index 00000000..b9fda170 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Playlists/Index.en-US.resx @@ -0,0 +1,51 @@ + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Playlists + + + Name + + + Description + + + Create + + + You have no playlists yet. + + + tracks + + + Delete + + + Delete this playlist? This cannot be undone. + + + The playlist could not be deleted. + + + The playlist could not be created. + + + A playlist needs a name. + + + items + + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Playlists/Index.es-ES.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Playlists/Index.es-ES.resx new file mode 100644 index 00000000..2451e8c3 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Playlists/Index.es-ES.resx @@ -0,0 +1,51 @@ + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Listas de reproducción + + + Nombre + + + Descripción + + + Crear + + + Todavía no tienes listas de reproducción. + + + pistas + + + Eliminar + + + ¿Eliminar esta lista de reproducción? No se puede deshacer. + + + No se pudo eliminar la lista de reproducción. + + + No se pudo crear la lista de reproducción. + + + Una lista de reproducción necesita un nombre. + + + elementos + + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Playlists/Index.fr-FR.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Playlists/Index.fr-FR.resx new file mode 100644 index 00000000..826e8342 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Playlists/Index.fr-FR.resx @@ -0,0 +1,51 @@ + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Listes de lecture + + + Nom + + + Description + + + Créer + + + Vous n'avez encore aucune liste de lecture. + + + pistes + + + Supprimer + + + Supprimer cette liste de lecture ? Cette action est irréversible. + + + La liste de lecture n'a pas pu être supprimée. + + + La liste de lecture n'a pas pu être créée. + + + Une liste de lecture doit avoir un nom. + + + éléments + + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Playlists/Index.it-IT.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Playlists/Index.it-IT.resx new file mode 100644 index 00000000..a019457b --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Playlists/Index.it-IT.resx @@ -0,0 +1,51 @@ + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Playlist + + + Nome + + + Descrizione + + + Crea + + + Non hai ancora playlist. + + + brani + + + Elimina + + + Eliminare questa playlist? L'operazione non può essere annullata. + + + Non è stato possibile eliminare la playlist. + + + Non è stato possibile creare la playlist. + + + Una playlist deve avere un nome. + + + elementi + + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Playlists/Index.ja-JP.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Playlists/Index.ja-JP.resx new file mode 100644 index 00000000..ed9196d1 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Playlists/Index.ja-JP.resx @@ -0,0 +1,51 @@ + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + プレイリスト + + + 名前 + + + 説明 + + + 作成 + + + プレイリストはまだありません。 + + + 曲 + + + 削除 + + + このプレイリストを削除しますか?この操作は元に戻せません。 + + + プレイリストを削除できませんでした。 + + + プレイリストを作成できませんでした。 + + + プレイリストには名前が必要です。 + + + 件 + + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Playlists/Index.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Playlists/Index.resx new file mode 100644 index 00000000..b9fda170 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Playlists/Index.resx @@ -0,0 +1,51 @@ + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Playlists + + + Name + + + Description + + + Create + + + You have no playlists yet. + + + tracks + + + Delete + + + Delete this playlist? This cannot be undone. + + + The playlist could not be deleted. + + + The playlist could not be created. + + + A playlist needs a name. + + + items + + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Playlists/Index.ro-RO.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Playlists/Index.ro-RO.resx new file mode 100644 index 00000000..21fa9387 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Playlists/Index.ro-RO.resx @@ -0,0 +1,51 @@ + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Liste de redare + + + Nume + + + Descriere + + + Creează + + + Nu ai încă liste de redare. + + + piese + + + Șterge + + + Ștergi această listă de redare? Această acțiune nu poate fi anulată. + + + Lista de redare nu a putut fi ștearsă. + + + Lista de redare nu a putut fi creată. + + + O listă de redare are nevoie de un nume. + + + elemente + + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Playlists/Index.uk-UA.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Playlists/Index.uk-UA.resx new file mode 100644 index 00000000..d4003617 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Playlists/Index.uk-UA.resx @@ -0,0 +1,51 @@ + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Списки відтворення + + + Назва + + + Опис + + + Створити + + + У вас ще немає списків відтворення. + + + треків + + + Видалити + + + Видалити цей список відтворення? Цю дію неможливо скасувати. + + + Не вдалося видалити список відтворення. + + + Не вдалося створити список відтворення. + + + Список відтворення повинен мати назву. + + + елементів + + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Playlists/Index.zh-CN.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Playlists/Index.zh-CN.resx new file mode 100644 index 00000000..a9792e57 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Playlists/Index.zh-CN.resx @@ -0,0 +1,51 @@ + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + 播放列表 + + + 名称 + + + 描述 + + + 创建 + + + 你还没有播放列表。 + + + 首曲目 + + + 删除 + + + 删除此播放列表?此操作无法撤销。 + + + 无法删除播放列表。 + + + 无法创建播放列表。 + + + 播放列表需要名称。 + + + 项 + + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Playlists/Item.ar-SA.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Playlists/Item.ar-SA.resx new file mode 100644 index 00000000..992043f4 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Playlists/Item.ar-SA.resx @@ -0,0 +1,144 @@ + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + تشغيل + + + تشغيل قائمة التشغيل + + + حفظ + + + تم حفظ قائمة التشغيل. + + + تعذر حفظ قائمة التشغيل. + + + حذف + + + هل تريد حذف قائمة التشغيل هذه؟ لا يمكن التراجع عن هذا الإجراء. + + + تعذر حذف قائمة التشغيل. + + + العودة إلى قوائم التشغيل + + + المقاطع + + + لا تحتوي قائمة التشغيل هذه على مقاطع بعد. + + + إضافة مقطع + + + المكتبة + + + الفنان + + + الألبوم + + + المقطع + + + إضافة + + + تعذر إضافة المقطع. + + + تم تحديث قائمة التشغيل، لكن تعذر تحديث القائمة. أعد تحميل الصفحة لرؤية التغيير. + + + اختر مكتبة + + + اختر فنانًا + + + اختر ألبومًا + + + اختر مقطعًا + + + نقل لأعلى + + + نقل لأسفل + + + إزالة + + + هل تريد إزالة هذا المقطع من قائمة التشغيل؟ + + + تعذرت إزالة المقطع. + + + تعذر إعادة ترتيب قائمة التشغيل. + + + مقطع غير متاح + + + تحتاج قائمة التشغيل إلى اسم. + + + لا تحتوي قائمة التشغيل هذه على مقاطع قابلة للتشغيل. + + + مشغل الصوت غير متاح. + + + تفاصيل قائمة التشغيل + + + الاسم + + + الوصف + + + ليست لديك مكتبات موسيقى بعد. + + + جارٍ التحميل... + + + اسحب لإعادة الترتيب + + + إنشاء قائمة تشغيل + + + إلغاء + + + تحميل المزيد + + + إضافة إلى قائمة التشغيل + + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Playlists/Item.de-DE.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Playlists/Item.de-DE.resx new file mode 100644 index 00000000..f4fcee48 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Playlists/Item.de-DE.resx @@ -0,0 +1,144 @@ + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Abspielen + + + Wiedergabeliste abspielen + + + Speichern + + + Die Wiedergabeliste wurde gespeichert. + + + Die Wiedergabeliste konnte nicht gespeichert werden. + + + Löschen + + + Diese Wiedergabeliste löschen? Das kann nicht rückgängig gemacht werden. + + + Die Wiedergabeliste konnte nicht gelöscht werden. + + + Zurück zu den Wiedergabelisten + + + Titel + + + Diese Wiedergabeliste hat noch keine Titel. + + + Titel hinzufügen + + + Bibliothek + + + Künstler + + + Album + + + Titel + + + Hinzufügen + + + Der Titel konnte nicht hinzugefügt werden. + + + Die Wiedergabeliste wurde aktualisiert, aber die Liste konnte nicht neu geladen werden. Laden Sie die Seite neu, um die Änderung zu sehen. + + + Bibliothek auswählen + + + Künstler auswählen + + + Album auswählen + + + Titel auswählen + + + Nach oben + + + Nach unten + + + Entfernen + + + Diesen Titel aus der Wiedergabeliste entfernen? + + + Der Titel konnte nicht entfernt werden. + + + Die Wiedergabeliste konnte nicht neu sortiert werden. + + + Nicht verfügbarer Titel + + + Eine Wiedergabeliste braucht einen Namen. + + + Diese Wiedergabeliste enthält keine abspielbaren Titel. + + + Der Audioplayer ist nicht verfügbar. + + + Details der Wiedergabeliste + + + Name + + + Beschreibung + + + Du hast noch keine Musikbibliotheken. + + + Wird geladen... + + + Ziehen zum Sortieren + + + Wiedergabeliste erstellen + + + Abbrechen + + + Mehr laden + + + Zur Wiedergabeliste hinzufügen + + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Playlists/Item.en-US.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Playlists/Item.en-US.resx new file mode 100644 index 00000000..6dd3826d --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Playlists/Item.en-US.resx @@ -0,0 +1,144 @@ + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Play + + + Play playlist + + + Save + + + The playlist was saved. + + + The playlist could not be saved. + + + Delete + + + Delete this playlist? This cannot be undone. + + + The playlist could not be deleted. + + + Back to playlists + + + Tracks + + + This playlist has no tracks yet. + + + Add a track + + + Library + + + Artist + + + Album + + + Track + + + Add + + + The track could not be added. + + + The playlist was updated, but the list could not be refreshed. Reload the page to see the change. + + + Select a library + + + Select an artist + + + Select an album + + + Select a track + + + Move up + + + Move down + + + Remove + + + Remove this track from the playlist? + + + The track could not be removed. + + + The playlist could not be reordered. + + + Unavailable track + + + A playlist needs a name. + + + There are no playable tracks in this playlist. + + + The audio player is not available. + + + Playlist details + + + Name + + + Description + + + You have no music libraries yet. + + + Loading... + + + Drag to reorder + + + Create playlist + + + Cancel + + + Load more + + + Add to playlist + + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Playlists/Item.es-ES.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Playlists/Item.es-ES.resx new file mode 100644 index 00000000..8276d6e8 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Playlists/Item.es-ES.resx @@ -0,0 +1,144 @@ + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Reproducir + + + Reproducir lista + + + Guardar + + + La lista de reproducción se guardó. + + + No se pudo guardar la lista de reproducción. + + + Eliminar + + + ¿Eliminar esta lista de reproducción? No se puede deshacer. + + + No se pudo eliminar la lista de reproducción. + + + Volver a las listas + + + Pistas + + + Esta lista de reproducción todavía no tiene pistas. + + + Añadir una pista + + + Biblioteca + + + Artista + + + Álbum + + + Pista + + + Añadir + + + No se pudo añadir la pista. + + + La lista de reproducción se actualizó, pero no se pudo actualizar la lista. Recarga la página para ver el cambio. + + + Selecciona una biblioteca + + + Selecciona un artista + + + Selecciona un álbum + + + Selecciona una pista + + + Subir + + + Bajar + + + Quitar + + + ¿Quitar esta pista de la lista de reproducción? + + + No se pudo quitar la pista. + + + No se pudo reordenar la lista de reproducción. + + + Pista no disponible + + + Una lista de reproducción necesita un nombre. + + + Esta lista de reproducción no contiene pistas reproducibles. + + + El reproductor de audio no está disponible. + + + Detalles de la lista + + + Nombre + + + Descripción + + + Todavía no tienes bibliotecas de música. + + + Cargando... + + + Arrastra para reordenar + + + Crear lista de reproducción + + + Cancelar + + + Cargar más + + + Añadir a la lista de reproducción + + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Playlists/Item.fr-FR.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Playlists/Item.fr-FR.resx new file mode 100644 index 00000000..a6fdc638 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Playlists/Item.fr-FR.resx @@ -0,0 +1,144 @@ + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Lire + + + Lire la liste de lecture + + + Enregistrer + + + La liste de lecture a été enregistrée. + + + La liste de lecture n'a pas pu être enregistrée. + + + Supprimer + + + Supprimer cette liste de lecture ? Cette action est irréversible. + + + La liste de lecture n'a pas pu être supprimée. + + + Retour aux listes de lecture + + + Pistes + + + Cette liste de lecture n'a encore aucune piste. + + + Ajouter une piste + + + Bibliothèque + + + Artiste + + + Album + + + Piste + + + Ajouter + + + La piste n'a pas pu être ajoutée. + + + La liste de lecture a été mise à jour, mais la liste n'a pas pu être actualisée. Rechargez la page pour voir la modification. + + + Choisir une bibliothèque + + + Choisir un artiste + + + Choisir un album + + + Choisir une piste + + + Monter + + + Descendre + + + Retirer + + + Retirer cette piste de la liste de lecture ? + + + La piste n'a pas pu être retirée. + + + La liste de lecture n'a pas pu être réorganisée. + + + Piste indisponible + + + Une liste de lecture doit avoir un nom. + + + Cette liste de lecture ne contient aucune piste lisible. + + + Le lecteur audio n'est pas disponible. + + + Détails de la liste de lecture + + + Nom + + + Description + + + Vous n'avez encore aucune bibliothèque musicale. + + + Chargement... + + + Faire glisser pour réorganiser + + + Créer une liste de lecture + + + Annuler + + + Charger plus + + + Ajouter à la liste de lecture + + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Playlists/Item.it-IT.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Playlists/Item.it-IT.resx new file mode 100644 index 00000000..b2197b7b --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Playlists/Item.it-IT.resx @@ -0,0 +1,144 @@ + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Riproduci + + + Riproduci playlist + + + Salva + + + La playlist è stata salvata. + + + Non è stato possibile salvare la playlist. + + + Elimina + + + Eliminare questa playlist? L'operazione non può essere annullata. + + + Non è stato possibile eliminare la playlist. + + + Torna alle playlist + + + Brani + + + Questa playlist non contiene ancora brani. + + + Aggiungi un brano + + + Libreria + + + Artista + + + Album + + + Brano + + + Aggiungi + + + Non è stato possibile aggiungere il brano. + + + La playlist è stata aggiornata, ma non è stato possibile aggiornare l'elenco. Ricarica la pagina per vedere la modifica. + + + Seleziona una libreria + + + Seleziona un artista + + + Seleziona un album + + + Seleziona un brano + + + Sposta su + + + Sposta giù + + + Rimuovi + + + Rimuovere questo brano dalla playlist? + + + Non è stato possibile rimuovere il brano. + + + Non è stato possibile riordinare la playlist. + + + Brano non disponibile + + + Una playlist deve avere un nome. + + + Questa playlist non contiene brani riproducibili. + + + Il lettore audio non è disponibile. + + + Dettagli della playlist + + + Nome + + + Descrizione + + + Non hai ancora librerie musicali. + + + Caricamento... + + + Trascina per riordinare + + + Crea playlist + + + Annulla + + + Carica altro + + + Aggiungi alla playlist + + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Playlists/Item.ja-JP.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Playlists/Item.ja-JP.resx new file mode 100644 index 00000000..98898d83 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Playlists/Item.ja-JP.resx @@ -0,0 +1,144 @@ + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + 再生 + + + プレイリストを再生 + + + 保存 + + + プレイリストを保存しました。 + + + プレイリストを保存できませんでした。 + + + 削除 + + + このプレイリストを削除しますか?この操作は元に戻せません。 + + + プレイリストを削除できませんでした。 + + + プレイリストに戻る + + + 曲 + + + このプレイリストにはまだ曲がありません。 + + + 曲を追加 + + + ライブラリ + + + アーティスト + + + アルバム + + + 曲 + + + 追加 + + + 曲を追加できませんでした。 + + + プレイリストは更新されましたが、一覧を更新できませんでした。変更を確認するにはページを再読み込みしてください。 + + + ライブラリを選択 + + + アーティストを選択 + + + アルバムを選択 + + + 曲を選択 + + + 上へ + + + 下へ + + + 削除 + + + この曲をプレイリストから削除しますか? + + + 曲を削除できませんでした。 + + + プレイリストを並べ替えできませんでした。 + + + 利用できない曲 + + + プレイリストには名前が必要です。 + + + このプレイリストには再生できる曲がありません。 + + + オーディオプレーヤーを利用できません。 + + + プレイリストの詳細 + + + 名前 + + + 説明 + + + 音楽ライブラリはまだありません。 + + + 読み込み中... + + + ドラッグして並べ替え + + + プレイリストを作成 + + + キャンセル + + + さらに読み込む + + + プレイリストに追加 + + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Playlists/Item.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Playlists/Item.resx new file mode 100644 index 00000000..6dd3826d --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Playlists/Item.resx @@ -0,0 +1,144 @@ + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Play + + + Play playlist + + + Save + + + The playlist was saved. + + + The playlist could not be saved. + + + Delete + + + Delete this playlist? This cannot be undone. + + + The playlist could not be deleted. + + + Back to playlists + + + Tracks + + + This playlist has no tracks yet. + + + Add a track + + + Library + + + Artist + + + Album + + + Track + + + Add + + + The track could not be added. + + + The playlist was updated, but the list could not be refreshed. Reload the page to see the change. + + + Select a library + + + Select an artist + + + Select an album + + + Select a track + + + Move up + + + Move down + + + Remove + + + Remove this track from the playlist? + + + The track could not be removed. + + + The playlist could not be reordered. + + + Unavailable track + + + A playlist needs a name. + + + There are no playable tracks in this playlist. + + + The audio player is not available. + + + Playlist details + + + Name + + + Description + + + You have no music libraries yet. + + + Loading... + + + Drag to reorder + + + Create playlist + + + Cancel + + + Load more + + + Add to playlist + + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Playlists/Item.ro-RO.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Playlists/Item.ro-RO.resx new file mode 100644 index 00000000..1dfa961f --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Playlists/Item.ro-RO.resx @@ -0,0 +1,144 @@ + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Redă + + + Redă lista de redare + + + Salvează + + + Lista de redare a fost salvată. + + + Lista de redare nu a putut fi salvată. + + + Șterge + + + Ștergi această listă de redare? Această acțiune nu poate fi anulată. + + + Lista de redare nu a putut fi ștearsă. + + + Înapoi la liste de redare + + + Piese + + + Această listă de redare nu are încă piese. + + + Adaugă o piesă + + + Bibliotecă + + + Artist + + + Album + + + Piesă + + + Adaugă + + + Piesa nu a putut fi adăugată. + + + Lista de redare a fost actualizată, dar lista nu a putut fi reîmprospătată. Reîncarcă pagina pentru a vedea modificarea. + + + Selectează o bibliotecă + + + Selectează un artist + + + Selectează un album + + + Selectează o piesă + + + Mută în sus + + + Mută în jos + + + Elimină + + + Elimini această piesă din lista de redare? + + + Piesa nu a putut fi eliminată. + + + Lista de redare nu a putut fi reordonată. + + + Piesă indisponibilă + + + O listă de redare are nevoie de un nume. + + + Această listă de redare nu conține piese care pot fi redate. + + + Playerul audio nu este disponibil. + + + Detalii listă de redare + + + Nume + + + Descriere + + + Nu ai încă biblioteci muzicale. + + + Se încarcă... + + + Trage pentru a reordona + + + Creează listă de redare + + + Anulează + + + Încarcă mai multe + + + Adaugă în listă de redare + + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Playlists/Item.uk-UA.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Playlists/Item.uk-UA.resx new file mode 100644 index 00000000..6934f45f --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Playlists/Item.uk-UA.resx @@ -0,0 +1,144 @@ + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Відтворити + + + Відтворити список + + + Зберегти + + + Список відтворення збережено. + + + Не вдалося зберегти список відтворення. + + + Видалити + + + Видалити цей список відтворення? Цю дію неможливо скасувати. + + + Не вдалося видалити список відтворення. + + + Назад до списків відтворення + + + Треки + + + У цьому списку відтворення ще немає треків. + + + Додати трек + + + Бібліотека + + + Виконавець + + + Альбом + + + Трек + + + Додати + + + Не вдалося додати трек. + + + Список відтворення оновлено, але список не вдалося оновити. Перезавантажте сторінку, щоб побачити зміну. + + + Виберіть бібліотеку + + + Виберіть виконавця + + + Виберіть альбом + + + Виберіть трек + + + Вгору + + + Вниз + + + Прибрати + + + Прибрати цей трек зі списку відтворення? + + + Не вдалося прибрати трек. + + + Не вдалося змінити порядок списку відтворення. + + + Недоступний трек + + + Список відтворення повинен мати назву. + + + У цьому списку відтворення немає треків для відтворення. + + + Аудіоплеєр недоступний. + + + Деталі списку відтворення + + + Назва + + + Опис + + + У вас ще немає музичних бібліотек. + + + Завантаження... + + + Перетягніть, щоб змінити порядок + + + Створити список відтворення + + + Скасувати + + + Завантажити більше + + + Додати до списку відтворення + + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Playlists/Item.zh-CN.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Playlists/Item.zh-CN.resx new file mode 100644 index 00000000..4b8f29aa --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Playlists/Item.zh-CN.resx @@ -0,0 +1,144 @@ + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + 播放 + + + 播放列表 + + + 保存 + + + 播放列表已保存。 + + + 无法保存播放列表。 + + + 删除 + + + 删除此播放列表?此操作无法撤销。 + + + 无法删除播放列表。 + + + 返回播放列表 + + + 曲目 + + + 此播放列表还没有曲目。 + + + 添加曲目 + + + 库 + + + 艺术家 + + + 专辑 + + + 曲目 + + + 添加 + + + 无法添加曲目。 + + + 播放列表已更新,但无法刷新列表。请重新加载页面以查看更改。 + + + 选择库 + + + 选择艺术家 + + + 选择专辑 + + + 选择曲目 + + + 上移 + + + 下移 + + + 移除 + + + 从此播放列表中移除此曲目? + + + 无法移除曲目。 + + + 无法重新排序播放列表。 + + + 不可用的曲目 + + + 播放列表需要名称。 + + + 此播放列表中没有可播放的曲目。 + + + 音频播放器不可用。 + + + 播放列表详情 + + + 名称 + + + 描述 + + + 你还没有音乐库。 + + + 加载中... + + + 拖动以重新排序 + + + 创建播放列表 + + + 取消 + + + 加载更多 + + + 添加到播放列表 + + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/Components/FileSystemBrowser/Default.ar-SA.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/Components/FileSystemBrowser/Default.ar-SA.resx index f6868039..6fdc03d0 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/Components/FileSystemBrowser/Default.ar-SA.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/Components/FileSystemBrowser/Default.ar-SA.resx @@ -147,7 +147,7 @@ أمام - + عرض الأيقونات الكبيرة diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/Components/FileSystemBrowser/Default.de-DE.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/Components/FileSystemBrowser/Default.de-DE.resx index c4d18087..75f0b79b 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/Components/FileSystemBrowser/Default.de-DE.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/Components/FileSystemBrowser/Default.de-DE.resx @@ -147,7 +147,7 @@ Vorwärts - + Große Symbolansicht diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/Components/FileSystemBrowser/Default.en-US.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/Components/FileSystemBrowser/Default.en-US.resx index 88e38636..11b3f881 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/Components/FileSystemBrowser/Default.en-US.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/Components/FileSystemBrowser/Default.en-US.resx @@ -147,7 +147,7 @@ Forward - + Large Icons View diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/Components/FileSystemBrowser/Default.es-ES.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/Components/FileSystemBrowser/Default.es-ES.resx index ab9749b0..301de57b 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/Components/FileSystemBrowser/Default.es-ES.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/Components/FileSystemBrowser/Default.es-ES.resx @@ -147,7 +147,7 @@ Adelante - + Vista iconos grandes diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/Components/FileSystemBrowser/Default.fr-FR.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/Components/FileSystemBrowser/Default.fr-FR.resx index 3fbaf1d8..03684471 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/Components/FileSystemBrowser/Default.fr-FR.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/Components/FileSystemBrowser/Default.fr-FR.resx @@ -147,7 +147,7 @@ Suivant - + Vue grandes icônes diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/Components/FileSystemBrowser/Default.it-IT.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/Components/FileSystemBrowser/Default.it-IT.resx index e488c2b3..98ae97a8 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/Components/FileSystemBrowser/Default.it-IT.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/Components/FileSystemBrowser/Default.it-IT.resx @@ -147,7 +147,7 @@ Avanti - + Vista icone grandi diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/Components/FileSystemBrowser/Default.ja-JP.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/Components/FileSystemBrowser/Default.ja-JP.resx index a6a9146e..858b13f9 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/Components/FileSystemBrowser/Default.ja-JP.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/Components/FileSystemBrowser/Default.ja-JP.resx @@ -147,7 +147,7 @@ 進む - + 大きいアイコン表示 diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/Components/FileSystemBrowser/Default.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/Components/FileSystemBrowser/Default.resx index 0e3ba1c7..11b3f881 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/Components/FileSystemBrowser/Default.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/Components/FileSystemBrowser/Default.resx @@ -147,8 +147,8 @@ Forward - - LargeIconsView + + Large Icons View List View diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/Components/FileSystemBrowser/Default.ro-RO.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/Components/FileSystemBrowser/Default.ro-RO.resx index ea1a45cf..70fbc0c5 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/Components/FileSystemBrowser/Default.ro-RO.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/Components/FileSystemBrowser/Default.ro-RO.resx @@ -147,7 +147,7 @@ Înainte - + Vizualizare pictograme mari diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/Components/FileSystemBrowser/Default.uk-UA.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/Components/FileSystemBrowser/Default.uk-UA.resx index 7ee5e9b0..a1a5c702 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/Components/FileSystemBrowser/Default.uk-UA.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/Components/FileSystemBrowser/Default.uk-UA.resx @@ -147,7 +147,7 @@ Вперед - + Великі значки diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/Components/FileSystemBrowser/Default.zh-CN.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/Components/FileSystemBrowser/Default.zh-CN.resx index babfbcf0..7deeda43 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/Components/FileSystemBrowser/Default.zh-CN.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/Components/FileSystemBrowser/Default.zh-CN.resx @@ -147,7 +147,7 @@ 前进 - + 大图标视图 diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.ar-SA.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.ar-SA.resx index 6a9daef8..c8a3a711 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.ar-SA.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.ar-SA.resx @@ -120,6 +120,27 @@ إيقاف + + جارٍ التخزين المؤقت + + + كتم الصوت + + + إيقاف مؤقت + + + تشغيل + + + موضع التشغيل + + + إلغاء كتم الصوت + + + مستوى الصوت + إلغاء @@ -147,8 +168,8 @@ إعادة المحاولة - - تبديل الارتفاع الكامل + + توسيع المشغل أو طيه تبديل الرؤية @@ -159,4 +180,85 @@ نعم + + المقطع السابق + + + المقطع التالي + + + تشغيل عشوائي + + + تشغيل الألبوم عشوائياً + + + تشغيل الفنان عشوائياً + + + تشغيل المكتبة عشوائياً + + + تكرار + + + التكرار متوقف + + + تكرار الكل + + + تكرار مقطع واحد + + + قائمة التشغيل + + + تشغيل عشوائي متوقف + + + إيقاف + + + أعمال فنية للألبوم + + + إضافة قائمة الانتظار إلى قائمة تشغيل + + + تعذرت إضافة قائمة الانتظار إلى قائمة التشغيل. + + + اختر قائمة تشغيل + + + إضافة + + + تمت إضافة قائمة الانتظار إلى قائمة التشغيل. + + + ليست لديك قوائم تشغيل بعد. + + + إضافة إلى قائمة التشغيل + + + إنشاء قائمة تشغيل + + + تمت إضافة المقاطع إلى قائمة التشغيل. + + + تعذر إضافة المقاطع إلى قائمة التشغيل. + + + لا توجد مقاطع لإضافتها. + + + إضافة إلى المفضلة + + + إزالة من المفضلة + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.de-DE.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.de-DE.resx index e9ac8596..63c3df36 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.de-DE.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.de-DE.resx @@ -120,6 +120,27 @@ Abbrechen + + Wird gepuffert + + + Stummschalten + + + Pause + + + Abspielen + + + Wiedergabeposition + + + Stummschaltung aufheben + + + Lautstärke + Abbrechen @@ -147,8 +168,8 @@ Wiederholen - - Vollhöhe Umschalten + + Player ein- oder ausklappen Sichtbarkeit Umschalten @@ -159,4 +180,85 @@ Ja + + Vorheriger Titel + + + Nächster Titel + + + Zufallswiedergabe + + + Release zufällig abspielen + + + Interpret zufällig abspielen + + + Bibliothek zufällig abspielen + + + Wiederholen + + + Wiederholung aus + + + Alle wiederholen + + + Titel wiederholen + + + Warteschlange + + + Zufallswiedergabe aus + + + Stopp + + + Albumcover + + + Warteschlange zu Wiedergabeliste hinzufügen + + + Die Warteschlange konnte nicht zur Wiedergabeliste hinzugefügt werden. + + + Wiedergabeliste auswählen + + + Hinzufügen + + + Die Warteschlange wurde der Wiedergabeliste hinzugefügt. + + + Du hast noch keine Wiedergabelisten. + + + Zur Wiedergabeliste hinzufügen + + + Wiedergabeliste erstellen + + + Die Titel wurden zur Wiedergabeliste hinzugefügt. + + + Die Titel konnten nicht zur Wiedergabeliste hinzugefügt werden. + + + Es gibt keine Titel zum Hinzufügen. + + + Zu Favoriten hinzufügen + + + Aus Favoriten entfernen + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.en-US.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.en-US.resx index 6b99cf65..9de9fcdb 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.en-US.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.en-US.resx @@ -120,6 +120,27 @@ Abort + + Buffering + + + Mute + + + Pause + + + Play + + + Playback position + + + Unmute + + + Volume + Cancel @@ -147,8 +168,8 @@ Retry - - Toggle Full Height + + Expand or collapse player Toggle Visibility @@ -159,4 +180,85 @@ Yes + + Previous track + + + Next track + + + Shuffle + + + Shuffle release + + + Shuffle artist + + + Shuffle library + + + Repeat + + + Repeat off + + + Repeat all + + + Repeat one + + + Play queue + + + Shuffle off + + + Stop + + + Album artwork + + + Add queue to playlist + + + The queue could not be added to the playlist. + + + Select a playlist + + + Add + + + The queue was added to the playlist. + + + You have no playlists yet. + + + Add to playlist + + + Create playlist + + + The tracks were added to the playlist. + + + The tracks could not be added to the playlist. + + + There are no tracks to add. + + + Add to favorites + + + Remove from favorites + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.es-ES.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.es-ES.resx index 4f09682d..163914b0 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.es-ES.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.es-ES.resx @@ -120,6 +120,27 @@ Anular + + Cargando + + + Silenciar + + + Pausa + + + Reproducir + + + Posición de reproducción + + + Activar sonido + + + Volumen + Cancelar @@ -147,8 +168,8 @@ Reintentar - - Alternar Altura Completa + + Expandir o contraer el reproductor Alternar Visibilidad @@ -159,4 +180,85 @@ Sí + + Pista anterior + + + Pista siguiente + + + Reproducción aleatoria + + + Aleatorio por álbum + + + Aleatorio por artista + + + Aleatorio por biblioteca + + + Repetir + + + Repetición desactivada + + + Repetir todo + + + Repetir pista + + + Cola de reproducción + + + Reproducción aleatoria desactivada + + + Detener + + + Ilustraciones del álbum + + + Añadir la cola a una lista de reproducción + + + No se pudo añadir la cola a la lista de reproducción. + + + Selecciona una lista de reproducción + + + Añadir + + + La cola se añadió a la lista de reproducción. + + + Todavía no tienes listas de reproducción. + + + Añadir a la lista de reproducción + + + Crear lista de reproducción + + + Las pistas se añadieron a la lista de reproducción. + + + No se pudieron añadir las pistas a la lista de reproducción. + + + No hay pistas para añadir. + + + Añadir a favoritos + + + Quitar de favoritos + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.fr-FR.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.fr-FR.resx index 70581855..08eda57f 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.fr-FR.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.fr-FR.resx @@ -120,6 +120,27 @@ Abandonner + + Mise en mémoire tampon + + + Muet + + + Pause + + + Lecture + + + Position de lecture + + + Activer le son + + + Volume + Annuler @@ -147,8 +168,8 @@ Réessayer - - Basculer Hauteur Complète + + Développer ou réduire le lecteur Basculer Visibilité @@ -159,4 +180,85 @@ Oui + + Piste précédente + + + Piste suivante + + + Lecture aléatoire + + + Aléatoire sur la sortie + + + Aléatoire sur l’artiste + + + Aléatoire sur la bibliothèque + + + Répéter + + + Répétition désactivée + + + Tout répéter + + + Répéter la piste + + + File de lecture + + + Lecture aléatoire désactivée + + + Arrêter + + + Illustrations de l'album + + + Ajouter la file d'attente à une liste de lecture + + + La file d'attente n'a pas pu être ajoutée à la liste de lecture. + + + Choisir une liste de lecture + + + Ajouter + + + La file d'attente a été ajoutée à la liste de lecture. + + + Vous n'avez encore aucune liste de lecture. + + + Ajouter à la liste de lecture + + + Créer une liste de lecture + + + Les pistes ont été ajoutées à la liste de lecture. + + + Les pistes n'ont pas pu être ajoutées à la liste de lecture. + + + Il n'y a aucune piste à ajouter. + + + Ajouter aux favoris + + + Retirer des favoris + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.it-IT.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.it-IT.resx index 3e510bb1..d5d44b24 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.it-IT.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.it-IT.resx @@ -120,6 +120,27 @@ Interrompi + + Caricamento in corso + + + Disattiva audio + + + Pausa + + + Riproduci + + + Posizione di riproduzione + + + Riattiva audio + + + Volume + Annulla @@ -147,8 +168,8 @@ Riprova - - Attiva/Disattiva Altezza Piena + + Espandi o comprimi il lettore Attiva/Disattiva Visibilità @@ -159,4 +180,85 @@ Sì + + Brano precedente + + + Brano successivo + + + Riproduzione casuale + + + Casuale per album + + + Casuale per artista + + + Casuale per libreria + + + Ripeti + + + Ripetizione disattivata + + + Ripeti tutto + + + Ripeti brano + + + Coda di riproduzione + + + Riproduzione casuale disattivata + + + Ferma + + + Illustrazioni dell'album + + + Aggiungi la coda a una playlist + + + Non è stato possibile aggiungere la coda alla playlist. + + + Seleziona una playlist + + + Aggiungi + + + La coda è stata aggiunta alla playlist. + + + Non hai ancora playlist. + + + Aggiungi alla playlist + + + Crea playlist + + + Le tracce sono state aggiunte alla playlist. + + + Non è stato possibile aggiungere le tracce alla playlist. + + + Non ci sono tracce da aggiungere. + + + Aggiungi ai preferiti + + + Rimuovi dai preferiti + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.ja-JP.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.ja-JP.resx index 25aed7bb..b73e0545 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.ja-JP.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.ja-JP.resx @@ -120,6 +120,27 @@ 中止する + + バッファリング中 + + + ミュート + + + 一時停止 + + + 再生 + + + 再生位置 + + + ミュート解除 + + + 音量 + キャンセル @@ -147,8 +168,8 @@ 再試行 - - 全高表示切替 + + プレーヤーを展開または折りたたむ 表示切替 @@ -159,4 +180,85 @@ はい + + 前の曲 + + + 次の曲 + + + シャッフル + + + アルバムをシャッフル + + + アーティストをシャッフル + + + ライブラリをシャッフル + + + リピート + + + リピートなし + + + すべてリピート + + + 1曲リピート + + + 再生キュー + + + シャッフルなし + + + 停止 + + + アルバムアートワーク + + + キューをプレイリストに追加 + + + キューをプレイリストに追加できませんでした。 + + + プレイリストを選択 + + + 追加 + + + キューをプレイリストに追加しました。 + + + プレイリストはまだありません。 + + + プレイリストに追加 + + + プレイリストを作成 + + + トラックをプレイリストに追加しました。 + + + トラックをプレイリストに追加できませんでした。 + + + 追加するトラックがありません。 + + + お気に入りに追加 + + + お気に入りから削除 + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.resx index 6b99cf65..9de9fcdb 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.resx @@ -120,6 +120,27 @@ Abort + + Buffering + + + Mute + + + Pause + + + Play + + + Playback position + + + Unmute + + + Volume + Cancel @@ -147,8 +168,8 @@ Retry - - Toggle Full Height + + Expand or collapse player Toggle Visibility @@ -159,4 +180,85 @@ Yes + + Previous track + + + Next track + + + Shuffle + + + Shuffle release + + + Shuffle artist + + + Shuffle library + + + Repeat + + + Repeat off + + + Repeat all + + + Repeat one + + + Play queue + + + Shuffle off + + + Stop + + + Album artwork + + + Add queue to playlist + + + The queue could not be added to the playlist. + + + Select a playlist + + + Add + + + The queue was added to the playlist. + + + You have no playlists yet. + + + Add to playlist + + + Create playlist + + + The tracks were added to the playlist. + + + The tracks could not be added to the playlist. + + + There are no tracks to add. + + + Add to favorites + + + Remove from favorites + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.ro-RO.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.ro-RO.resx index 24855322..14c96319 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.ro-RO.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.ro-RO.resx @@ -120,6 +120,27 @@ Anulare + + Se încarcă + + + Fără sunet + + + Pauză + + + Redare + + + Poziția de redare + + + Activează sunetul + + + Volum + Anulare @@ -147,8 +168,8 @@ Reîncercare - - Comutare Înălțime Completă + + Extinde sau restrânge playerul Comutare Vizibilitate @@ -159,4 +180,85 @@ Da + + Piesa anterioară + + + Piesa următoare + + + Redare aleatorie + + + Aleatoriu pe album + + + Aleatoriu pe artist + + + Aleatoriu pe bibliotecă + + + Repetă + + + Repetare oprită + + + Repetă tot + + + Repetă piesa + + + Coada de redare + + + Redare aleatorie oprită + + + Oprește + + + Ilustrații album + + + Adaugă coada la o listă de redare + + + Coada nu a putut fi adăugată în lista de redare. + + + Selectează o listă de redare + + + Adaugă + + + Coada a fost adăugată în lista de redare. + + + Nu ai încă liste de redare. + + + Adaugă în listă de redare + + + Creează listă de redare + + + Piesele au fost adăugate în lista de redare. + + + Piesele nu au putut fi adăugate în lista de redare. + + + Nu există piese de adăugat. + + + Adaugă la favorite + + + Elimină din favorite + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.uk-UA.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.uk-UA.resx index 40c86c8f..5d0637f9 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.uk-UA.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.uk-UA.resx @@ -120,6 +120,27 @@ Перервати + + Буферизація + + + Вимкнути звук + + + Пауза + + + Відтворити + + + Позиція відтворення + + + Увімкнути звук + + + Гучність + Скасувати @@ -147,8 +168,8 @@ Повторити - - Перемкнути Повну Висоту + + Розгорнути або згорнути плеєр Перемкнути Видимість @@ -159,4 +180,85 @@ Так + + Попередній трек + + + Наступний трек + + + Перемішати + + + Перемішати альбом + + + Перемішати виконавця + + + Перемішати бібліотеку + + + Повтор + + + Повтор вимкнено + + + Повторити все + + + Повторити трек + + + Черга відтворення + + + Перемішування вимкнено + + + Зупинити + + + Обкладинки альбому + + + Додати чергу до списку відтворення + + + Не вдалося додати чергу до списку відтворення. + + + Виберіть список відтворення + + + Додати + + + Чергу додано до списку відтворення. + + + У вас ще немає списків відтворення. + + + Додати до списку відтворення + + + Створити список відтворення + + + Треки додано до списку відтворення. + + + Не вдалося додати треки до списку відтворення. + + + Немає треків для додавання. + + + Додати до улюбленого + + + Видалити з улюбленого + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.zh-CN.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.zh-CN.resx index 12bb510a..b1b0cc51 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.zh-CN.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.zh-CN.resx @@ -120,6 +120,27 @@ 中止 + + 缓冲中 + + + 静音 + + + 暂停 + + + 播放 + + + 播放位置 + + + 取消静音 + + + 音量 + 取消 @@ -147,8 +168,8 @@ 重试 - - 切换全高 + + 展开或折叠播放器 切换可见性 @@ -159,4 +180,85 @@ 是 + + 上一首 + + + 下一首 + + + 随机播放 + + + 随机播放专辑 + + + 随机播放艺术家 + + + 随机播放音乐库 + + + 循环播放 + + + 不循环 + + + 列表循环 + + + 单曲循环 + + + 播放队列 + + + 关闭随机播放 + + + 停止 + + + 专辑插图 + + + 将队列添加到播放列表 + + + 无法将队列添加到播放列表。 + + + 选择播放列表 + + + 添加 + + + 队列已添加到播放列表。 + + + 你还没有播放列表。 + + + 添加到播放列表 + + + 创建播放列表 + + + 曲目已添加到播放列表。 + + + 无法将曲目添加到播放列表。 + + + 没有可添加的曲目。 + + + 添加到收藏 + + + 取消收藏 + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.ar-SA.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.ar-SA.resx index 021c346f..21a6e6bc 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.ar-SA.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.ar-SA.resx @@ -219,4 +219,13 @@ المهام المجدولة + + قوائم التشغيل + + + المفضلة + + + الإحصائيات + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.de-DE.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.de-DE.resx index 659af2bb..c2969e29 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.de-DE.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.de-DE.resx @@ -219,4 +219,13 @@ Geplante Aufgaben + + Wiedergabelisten + + + Favoriten + + + Statistik + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.en-US.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.en-US.resx index ec0f3849..2d111347 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.en-US.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.en-US.resx @@ -219,4 +219,13 @@ Scheduled jobs + + Playlists + + + Favorites + + + Statistics + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.es-ES.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.es-ES.resx index 0b9eadbd..5d867caa 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.es-ES.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.es-ES.resx @@ -219,4 +219,13 @@ Tareas programadas + + Listas de reproducción + + + Favoritos + + + Estadísticas + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.fr-FR.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.fr-FR.resx index 584fc220..4b3ed8bb 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.fr-FR.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.fr-FR.resx @@ -219,4 +219,13 @@ Tâches planifiées + + Listes de lecture + + + Favoris + + + Statistiques + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.it-IT.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.it-IT.resx index 01f50714..1a1d7088 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.it-IT.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.it-IT.resx @@ -219,4 +219,13 @@ Attività pianificate + + Playlist + + + Preferiti + + + Statistiche + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.ja-JP.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.ja-JP.resx index e1fed3a1..5fd79cf5 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.ja-JP.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.ja-JP.resx @@ -219,4 +219,13 @@ スケジュール済みジョブ + + プレイリスト + + + お気に入り + + + 統計 + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.resx index ec0f3849..2d111347 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.resx @@ -219,4 +219,13 @@ Scheduled jobs + + Playlists + + + Favorites + + + Statistics + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.ro-RO.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.ro-RO.resx index 3ec9eeaf..2dc127f8 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.ro-RO.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.ro-RO.resx @@ -219,4 +219,13 @@ Sarcini programate + + Liste de redare + + + Favorite + + + Statistici + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.uk-UA.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.uk-UA.resx index 7583f730..54ba03bd 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.uk-UA.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.uk-UA.resx @@ -219,4 +219,13 @@ Заплановані завдання + + Списки відтворення + + + Улюблене + + + Статистика + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.zh-CN.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.zh-CN.resx index 6cd03b6d..930087ea 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.zh-CN.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.zh-CN.resx @@ -219,4 +219,13 @@ 计划任务 + + 播放列表 + + + 收藏夹 + + + 统计 + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.ar-SA.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.ar-SA.resx index 96b79082..11d5e739 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.ar-SA.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.ar-SA.resx @@ -69,4 +69,121 @@ عند التفعيل، تُستكمل الأعمال الفنية لعناصر المكتبة التي لا يوفرها مزود الأعمال الفنية الأول من المزودين التاليين. + + التشغيل + + + متابعة التنزيل أثناء الإيقاف المؤقت + + + ما إذا كان المشغل يواصل تنزيل المقطع أثناء إيقاف التشغيل مؤقتًا، حتى الملف كاملاً، بحيث لا ينتظر الاستئناف البيانات أبدًا. + + + التشغيل التلقائي + + + ما إذا كان التشغيل يستمر تلقائيًا بالمقاطع التالية عند انتهاء الألبوم أو الفنان. + + + تشغيل دون فواصل + + + ما إذا كانت المقاطع المتتالية تُشغَّل دون صمت بينها. + + + ReplayGain + + + كيفية تطبيق تسوية ReplayGain على المقاطع التي تشغّلها. + + + إيقاف + + + لكل مقطع + + + لكل ألبوم + + + جودة البث + + + حد الجودة الذي يُطبَّق عندما يضطر الخادم إلى تسوية مقطع للتشغيل. لا يتغير التشغيل المباشر أبدًا. + + + تلقائي + + + منخفضة (96 kbps) + + + متوسطة (160 kbps) + + + عالية (320 kbps) + + + عدد المقاطع التي تنقسم إليها كل قناة من مقياس VU، بين 1 و128. + + + انخفاض القمم + + + المستوى بين 0 و1 الذي يُرسم فوقه المقطع بالحالة العالية. يجب أن يكون على الأقل مساويًا للعتبة المتوسطة. + + + ما إذا كانت قنوات مقياس VU تنمو من الأسفل إلى الأعلى أو من اليسار إلى اليمين. + + + المستوى بين 0 و1 الذي يُرسم فوقه المقطع بالحالة المتوسطة. + + + عمودي + + + انخفاض المستوى + + + أفقي + + + الاتجاه + + + العتبة العالية + + + المقاطع لكل قناة + + + العتبة المتوسطة + + + مقياس VU + + + تثبيت القمم (مللي ثانية) + + + ما إذا كانت كل قناة تحتفظ بعلامة عند أعلى مستوى حديث لها. + + + عدد وحدات المستوى التي تنخفضها علامة القمة في الثانية بعد مدة تثبيتها، بين 0 و100. القيم الأعلى تنخفض أسرع. + + + مدة تثبيت علامة القمة بالمللي ثانية قبل أن تبدأ في الانخفاض، بين 0 و10000. + + + إظهار القمم + + + المسافة بالبكسل بين مقاطع مقياس VU وقنواته، بين 0 و32. + + + المسافة بين المقاطع + + + عدد وحدات المستوى التي تنخفضها القناة في الثانية بعد انخفاض الصوت، بين 0 و100. القيم الأعلى تنخفض أسرع. + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.de-DE.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.de-DE.resx index e2d3bb19..5b1753b0 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.de-DE.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.de-DE.resx @@ -69,4 +69,121 @@ Wenn aktiviert, wird das Artwork von Bibliothekselementen, das der erste Artwork-Anbieter nicht liefert, aus den nachfolgenden Anbietern ergänzt. + + Wiedergabe + + + Beim Pausieren weiter herunterladen + + + Ob der Player den Titel auch bei pausierter Wiedergabe weiter herunterlädt, bis zur gesamten Datei, damit die Fortsetzung nie auf Daten warten muss. + + + Automatische Wiedergabe + + + Ob die Wiedergabe am Ende eines Albums oder Interpreten automatisch mit den folgenden Titeln fortgesetzt wird. + + + Lückenlose Wiedergabe + + + Ob aufeinanderfolgende Titel ohne stille Lücke zwischen ihnen abgespielt werden. + + + ReplayGain + + + Wie die ReplayGain-Normalisierung auf die abgespielten Titel angewendet wird. + + + Aus + + + Pro Titel + + + Pro Album + + + Streaming-Qualität + + + Die Qualitätsobergrenze, die angewendet wird, wenn der Server einen Titel für die Wiedergabe normalisieren muss. Die direkte Wiedergabe wird nie verändert. + + + Automatisch + + + Niedrig (96 kbit/s) + + + Mittel (160 kbit/s) + + + Hoch (320 kbit/s) + + + In wie viele Segmente jeder Kanal des VU-Meters unterteilt wird, zwischen 1 und 128. + + + Rückgang der Spitzenwerte + + + Der Pegel zwischen 0 und 1, ab dem ein Segment mit dem hohen Zustand gezeichnet wird. Er muss mindestens dem mittleren Schwellenwert entsprechen. + + + Ob die Kanäle des VU-Meters von unten nach oben oder von links nach rechts wachsen. + + + Der Pegel zwischen 0 und 1, ab dem ein Segment mit dem mittleren Zustand gezeichnet wird. + + + Vertikal + + + Pegelrückgang + + + Horizontal + + + Ausrichtung + + + Hoher Schwellenwert + + + Segmente pro Kanal + + + Mittlerer Schwellenwert + + + VU-Meter + + + Spitzenwert halten (ms) + + + Ob jeder Kanal eine Markierung bei seinem lautesten letzten Pegel behält. + + + Wie viele Pegel-Einheiten eine Spitzenmarkierung pro Sekunde nach ihrer Haltezeit fällt, zwischen 0 und 100. Höhere Werte fallen schneller. + + + Wie lange eine Spitzenmarkierung in Millisekunden gehalten wird, bevor sie zu fallen beginnt, zwischen 0 und 10000. + + + Spitzenwerte anzeigen + + + Der Abstand in Pixeln zwischen den Segmenten und den Kanälen des VU-Meters, zwischen 0 und 32. + + + Segmentabstand + + + Wie viele Pegel-Einheiten ein Kanal pro Sekunde nach dem Abklingen des Tons fällt, zwischen 0 und 100. Höhere Werte fallen schneller. + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.en-US.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.en-US.resx index 2778bb63..d08f5f21 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.en-US.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.en-US.resx @@ -69,4 +69,121 @@ When enabled, the artwork of library items that the first artwork provider does not supply is filled in from the following providers. + + Playback + + + Keep downloading while paused + + + Whether the player keeps downloading the track while playback is paused, up to the entire file, so resuming never waits for data. + + + Autoplay + + + Whether playback continues automatically with the following tracks when an album or artist finishes. + + + Gapless playback + + + Whether consecutive tracks play without a silent gap between them. + + + ReplayGain + + + How ReplayGain normalization is applied to the tracks you play. + + + Off + + + Per track + + + Per album + + + Streaming quality + + + The quality cap applied when the server has to normalize a track for playback. Direct playback is never changed. + + + Automatic + + + Low (96 kbps) + + + Medium (160 kbps) + + + High (320 kbps) + + + How many segments each channel of the VU meter is divided into, between 1 and 128. + + + Peak falloff + + + The level, between 0 and 1, above which a segment is drawn with the high state. It must be at least the medium threshold. + + + Whether the channels of the VU meter grow upwards from the bottom, or rightwards from the left. + + + The level, between 0 and 1, above which a segment is drawn with the medium state. + + + Vertical + + + Level falloff + + + Horizontal + + + Orientation + + + High threshold + + + Segments per channel + + + Medium threshold + + + VU meter + + + Peak hold (ms) + + + Whether each channel holds a mark at its loudest recent level. + + + How many level units a peak mark falls per second after its hold time, between 0 and 100. Higher values fall faster. + + + How long, in milliseconds, a peak mark is held before it starts falling, between 0 and 10000. + + + Show peak + + + The gap, in pixels, between the segments and the channels of the VU meter, between 0 and 32. + + + Segment gap + + + How many level units a channel falls per second after the sound drops, between 0 and 100. Higher values fall faster. + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.es-ES.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.es-ES.resx index fc36ab24..0a8d4f18 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.es-ES.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.es-ES.resx @@ -69,4 +69,121 @@ Cuando está habilitado, las ilustraciones de los elementos de la biblioteca que el primer proveedor de ilustraciones no proporciona se completan desde los proveedores siguientes. + + Reproducción + + + Seguir descargando en pausa + + + Indica si el reproductor sigue descargando la pista mientras la reproducción está en pausa, hasta el archivo completo, para que reanudar nunca espere datos. + + + Reproducción automática + + + Indica si la reproducción continúa automáticamente con las pistas siguientes al terminar un álbum o un artista. + + + Reproducción sin pausas + + + Indica si las pistas consecutivas se reproducen sin un silencio entre ellas. + + + ReplayGain + + + Cómo se aplica la normalización ReplayGain a las pistas que reproduces. + + + Desactivado + + + Por pista + + + Por álbum + + + Calidad de transmisión + + + El límite de calidad que se aplica cuando el servidor tiene que normalizar una pista para reproducirla. La reproducción directa nunca se modifica. + + + Automática + + + Baja (96 kbps) + + + Media (160 kbps) + + + Alta (320 kbps) + + + En cuántos segmentos se divide cada canal del vúmetro, entre 1 y 128. + + + Caída de los picos + + + El nivel, entre 0 y 1, por encima del cual un segmento se dibuja con el estado alto. Debe ser al menos el umbral medio. + + + Indica si los canales del vúmetro crecen de abajo hacia arriba o de izquierda a derecha. + + + El nivel, entre 0 y 1, por encima del cual un segmento se dibuja con el estado medio. + + + Vertical + + + Caída del nivel + + + Horizontal + + + Orientación + + + Umbral alto + + + Segmentos por canal + + + Umbral medio + + + Vúmetro + + + Retención de picos (ms) + + + Indica si cada canal mantiene una marca en su nivel reciente más alto. + + + Cuántas unidades de nivel cae una marca de pico por segundo después de su tiempo de retención, entre 0 y 100. Los valores más altos caen más rápido. + + + Cuánto tiempo, en milisegundos, se mantiene una marca de pico antes de empezar a caer, entre 0 y 10000. + + + Mostrar picos + + + La separación, en píxeles, entre los segmentos y los canales del vúmetro, entre 0 y 32. + + + Separación de segmentos + + + Cuántas unidades de nivel cae un canal por segundo después de que el sonido baje, entre 0 y 100. Los valores más altos caen más rápido. + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.fr-FR.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.fr-FR.resx index 0366f7b8..ee9c853a 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.fr-FR.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.fr-FR.resx @@ -69,4 +69,121 @@ Lorsque cette option est activée, les illustrations des éléments de la bibliothèque que le premier fournisseur d'illustrations ne fournit pas sont complétées par les fournisseurs suivants. + + Lecture + + + Continuer le téléchargement en pause + + + Indique si le lecteur continue de télécharger le morceau lorsque la lecture est en pause, jusqu'au fichier entier, afin que la reprise n'attende jamais les données. + + + Lecture automatique + + + Indique si la lecture se poursuit automatiquement avec les morceaux suivants à la fin d'un album ou d'un artiste. + + + Lecture sans interruption + + + Indique si les morceaux consécutifs sont lus sans silence entre eux. + + + ReplayGain + + + La manière dont la normalisation ReplayGain est appliquée aux morceaux que vous écoutez. + + + Désactivé + + + Par morceau + + + Par album + + + Qualité de diffusion + + + Le plafond de qualité appliqué lorsque le serveur doit normaliser un morceau pour la lecture. La lecture directe n'est jamais modifiée. + + + Automatique + + + Basse (96 kbit/s) + + + Moyenne (160 kbit/s) + + + Élevée (320 kbit/s) + + + Le nombre de segments dans lesquels chaque canal du vumètre est divisé, entre 1 et 128. + + + Décroissance des crêtes + + + Le niveau, entre 0 et 1, au-dessus duquel un segment est dessiné avec l'état élevé. Il doit être au moins égal au seuil moyen. + + + Indique si les canaux du vumètre croissent du bas vers le haut ou de la gauche vers la droite. + + + Le niveau, entre 0 et 1, au-dessus duquel un segment est dessiné avec l'état moyen. + + + Verticale + + + Décroissance du niveau + + + Horizontale + + + Orientation + + + Seuil élevé + + + Segments par canal + + + Seuil moyen + + + Vumètre + + + Maintien des crêtes (ms) + + + Indique si chaque canal conserve un repère à son niveau récent le plus fort. + + + Le nombre d'unités de niveau dont un repère de crête descend par seconde après sa durée de maintien, entre 0 et 100. Des valeurs plus élevées descendent plus vite. + + + La durée, en millisecondes, pendant laquelle un repère de crête est maintenu avant de commencer à descendre, entre 0 et 10000. + + + Afficher les crêtes + + + L'espacement, en pixels, entre les segments et les canaux du vumètre, entre 0 et 32. + + + Espacement des segments + + + Le nombre d'unités de niveau dont un canal descend par seconde après la baisse du son, entre 0 et 100. Des valeurs plus élevées descendent plus vite. + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.it-IT.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.it-IT.resx index 70ab422f..50afc447 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.it-IT.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.it-IT.resx @@ -69,4 +69,121 @@ Se abilitato, le illustrazioni degli elementi della libreria che il primo provider di illustrazioni non fornisce vengono integrate dai provider successivi. + + Riproduzione + + + Continua il download in pausa + + + Indica se il lettore continua a scaricare il brano mentre la riproduzione è in pausa, fino all'intero file, così che la ripresa non debba mai attendere i dati. + + + Riproduzione automatica + + + Indica se la riproduzione continua automaticamente con i brani successivi al termine di un album o di un artista. + + + Riproduzione senza interruzioni + + + Indica se i brani consecutivi vengono riprodotti senza un silenzio tra loro. + + + ReplayGain + + + Come la normalizzazione ReplayGain viene applicata ai brani che riproduci. + + + Disattivato + + + Per brano + + + Per album + + + Qualità dello streaming + + + Il limite di qualità applicato quando il server deve normalizzare un brano per la riproduzione. La riproduzione diretta non viene mai modificata. + + + Automatica + + + Bassa (96 kbps) + + + Media (160 kbps) + + + Alta (320 kbps) + + + In quanti segmenti è diviso ogni canale del vumetro, tra 1 e 128. + + + Caduta dei picchi + + + Il livello, tra 0 e 1, oltre il quale un segmento viene disegnato con lo stato alto. Deve essere almeno la soglia media. + + + Indica se i canali del vumetro crescono dal basso verso l'alto o da sinistra verso destra. + + + Il livello, tra 0 e 1, oltre il quale un segmento viene disegnato con lo stato medio. + + + Verticale + + + Caduta del livello + + + Orizzontale + + + Orientamento + + + Soglia alta + + + Segmenti per canale + + + Soglia media + + + Vumetro + + + Mantenimento dei picchi (ms) + + + Indica se ogni canale mantiene un segno al suo livello recente più alto. + + + Quante unità di livello scende un segno di picco al secondo dopo il suo tempo di mantenimento, tra 0 e 100. Valori più alti scendono più rapidamente. + + + Per quanto tempo, in millisecondi, un segno di picco viene mantenuto prima di iniziare a scendere, tra 0 e 10000. + + + Mostra picchi + + + La spaziatura, in pixel, tra i segmenti e i canali del vumetro, tra 0 e 32. + + + Spaziatura dei segmenti + + + Quante unità di livello scende un canale al secondo dopo che il suono cala, tra 0 e 100. Valori più alti scendono più rapidamente. + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.ja-JP.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.ja-JP.resx index 6b24406d..7ab99e64 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.ja-JP.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.ja-JP.resx @@ -69,4 +69,121 @@ 有効にすると、最初のアートワークプロバイダーが提供しないライブラリ項目のアートワークが、後続のプロバイダーから補完されます。 + + 再生 + + + 一時停止中もダウンロードを続ける + + + 再生を一時停止している間もプレーヤーがトラックのダウンロードをファイル全体まで続けるかどうか。再開時にデータを待たずに済みます。 + + + 自動再生 + + + アルバムまたはアーティストの再生が終わったときに、続くトラックを自動的に再生するかどうか。 + + + ギャップレス再生 + + + 連続するトラックを間に無音を挟まずに再生するかどうか。 + + + ReplayGain + + + 再生するトラックに ReplayGain の正規化をどのように適用するか。 + + + オフ + + + トラックごと + + + アルバムごと + + + ストリーミング品質 + + + サーバーが再生のためにトラックを正規化する必要がある場合に適用される品質の上限。直接再生は決して変更されません。 + + + 自動 + + + 低 (96 kbps) + + + 中 (160 kbps) + + + 高 (320 kbps) + + + VUメーターの各チャンネルを分割するセグメント数です。1から128の間で指定します。 + + + ピークの減衰 + + + セグメントを高い状態で描画するレベルです。0から1の間で指定し、中間しきい値以上である必要があります。 + + + VUメーターの各チャンネルが下から上へ伸びるか、左から右へ伸びるかを指定します。 + + + セグメントを中間状態で描画するレベルです。0から1の間で指定します。 + + + 垂直 + + + レベルの減衰 + + + 水平 + + + 向き + + + 高いしきい値 + + + チャンネルあたりのセグメント数 + + + 中間しきい値 + + + VUメーター + + + ピーク保持 (ms) + + + 各チャンネルに直近の最大レベルの印を残すかどうかを指定します。 + + + 保持時間の後、ピークの印が1秒あたりに下がるレベルの量です。0から100の間で指定します。値が大きいほど速く下がります。 + + + ピークの印が下がり始めるまで保持される時間をミリ秒単位で指定します。0から10000の間です。 + + + ピークを表示 + + + VUメーターのセグメントとチャンネルの間隔をピクセル単位で指定します。0から32の間です。 + + + セグメント間隔 + + + 音が下がった後にチャンネルが1秒あたりに下がるレベルの量です。0から100の間で指定します。値が大きいほど速く下がります。 + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.resx index 2778bb63..d08f5f21 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.resx @@ -69,4 +69,121 @@ When enabled, the artwork of library items that the first artwork provider does not supply is filled in from the following providers. + + Playback + + + Keep downloading while paused + + + Whether the player keeps downloading the track while playback is paused, up to the entire file, so resuming never waits for data. + + + Autoplay + + + Whether playback continues automatically with the following tracks when an album or artist finishes. + + + Gapless playback + + + Whether consecutive tracks play without a silent gap between them. + + + ReplayGain + + + How ReplayGain normalization is applied to the tracks you play. + + + Off + + + Per track + + + Per album + + + Streaming quality + + + The quality cap applied when the server has to normalize a track for playback. Direct playback is never changed. + + + Automatic + + + Low (96 kbps) + + + Medium (160 kbps) + + + High (320 kbps) + + + How many segments each channel of the VU meter is divided into, between 1 and 128. + + + Peak falloff + + + The level, between 0 and 1, above which a segment is drawn with the high state. It must be at least the medium threshold. + + + Whether the channels of the VU meter grow upwards from the bottom, or rightwards from the left. + + + The level, between 0 and 1, above which a segment is drawn with the medium state. + + + Vertical + + + Level falloff + + + Horizontal + + + Orientation + + + High threshold + + + Segments per channel + + + Medium threshold + + + VU meter + + + Peak hold (ms) + + + Whether each channel holds a mark at its loudest recent level. + + + How many level units a peak mark falls per second after its hold time, between 0 and 100. Higher values fall faster. + + + How long, in milliseconds, a peak mark is held before it starts falling, between 0 and 10000. + + + Show peak + + + The gap, in pixels, between the segments and the channels of the VU meter, between 0 and 32. + + + Segment gap + + + How many level units a channel falls per second after the sound drops, between 0 and 100. Higher values fall faster. + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.ro-RO.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.ro-RO.resx index 1a6e38b5..55c1aaa1 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.ro-RO.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.ro-RO.resx @@ -69,4 +69,121 @@ Când este activat, ilustrațiile elementelor din bibliotecă pe care primul furnizor de ilustrații nu le oferă sunt completate de la furnizorii următori. + + Redare + + + Continuă descărcarea în pauză + + + Dacă playerul continuă să descarce piesa în timp ce redarea este în pauză, până la întregul fișier, astfel încât reluarea să nu aștepte niciodată datele. + + + Redare automată + + + Dacă redarea continuă automat cu piesele următoare la sfârșitul unui album sau al unui artist. + + + Redare fără întreruperi + + + Dacă piesele consecutive sunt redate fără o pauză de sunet între ele. + + + ReplayGain + + + Modul în care normalizarea ReplayGain este aplicată pieselor pe care le redai. + + + Dezactivat + + + Per piesă + + + Per album + + + Calitatea fluxului + + + Limita de calitate aplicată atunci când serverul trebuie să normalizeze o piesă pentru redare. Redarea directă nu este niciodată modificată. + + + Automată + + + Redusă (96 kbps) + + + Medie (160 kbps) + + + Ridicată (320 kbps) + + + În câte segmente este împărțit fiecare canal al vumetrului, între 1 și 128. + + + Scăderea vârfurilor + + + Nivelul, între 0 și 1, peste care un segment este desenat cu starea ridicată. Trebuie să fie cel puțin pragul mediu. + + + Dacă canalele vumetrului cresc de jos în sus sau de la stânga la dreapta. + + + Nivelul, între 0 și 1, peste care un segment este desenat cu starea medie. + + + Verticală + + + Scăderea nivelului + + + Orizontală + + + Orientare + + + Prag ridicat + + + Segmente pe canal + + + Prag mediu + + + Vumetru + + + Menținerea vârfurilor (ms) + + + Dacă fiecare canal păstrează un marcaj la cel mai puternic nivel recent. + + + Câte unități de nivel scade un marcaj de vârf pe secundă după durata de menținere, între 0 și 100. Valorile mai mari scad mai repede. + + + Cât timp, în milisecunde, este menținut un marcaj de vârf înainte de a începe să scadă, între 0 și 10000. + + + Afișează vârfurile + + + Spațiul, în pixeli, dintre segmente și canalele vumetrului, între 0 și 32. + + + Spațiu între segmente + + + Câte unități de nivel scade un canal pe secundă după ce sunetul scade, între 0 și 100. Valorile mai mari scad mai repede. + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.uk-UA.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.uk-UA.resx index 74bf06a6..82c36378 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.uk-UA.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.uk-UA.resx @@ -69,4 +69,121 @@ Коли ввімкнено, ілюстрації елементів бібліотеки, які не надає перший постачальник ілюстрацій, доповнюються від наступних постачальників. + + Відтворення + + + Продовжувати завантаження на паузі + + + Чи продовжує програвач завантажувати трек, поки відтворення призупинено, аж до всього файлу, щоб відновлення ніколи не чекало на дані. + + + Автовідтворення + + + Чи продовжується відтворення автоматично наступними треками після завершення альбому або виконавця. + + + Відтворення без пауз + + + Чи відтворюються послідовні треки без тихої паузи між ними. + + + ReplayGain + + + Як нормалізація ReplayGain застосовується до треків, які ви відтворюєте. + + + Вимкнено + + + Для кожного треку + + + Для кожного альбому + + + Якість потокового передавання + + + Обмеження якості, що застосовується, коли сервер має нормалізувати трек для відтворення. Пряме відтворення ніколи не змінюється. + + + Автоматично + + + Низька (96 kbps) + + + Середня (160 kbps) + + + Висока (320 kbps) + + + На скільки сегментів поділено кожен канал VU-метра, від 1 до 128. + + + Спад піків + + + Рівень від 0 до 1, вище якого сегмент малюється у високому стані. Він має бути не меншим за середній поріг. + + + Чи ростуть канали VU-метра знизу вгору або зліва направо. + + + Рівень від 0 до 1, вище якого сегмент малюється в середньому стані. + + + Вертикальна + + + Спад рівня + + + Горизонтальна + + + Орієнтація + + + Високий поріг + + + Сегментів на канал + + + Середній поріг + + + VU-метр + + + Утримання піків (мс) + + + Чи залишає кожен канал позначку на своєму найгучнішому недавньому рівні. + + + Скільки одиниць рівня позначка піку спадає за секунду після часу утримання, від 0 до 100. Більші значення спадають швидше. + + + Скільки мілісекунд позначка піку утримується перед тим, як почати спадати, від 0 до 10000. + + + Показувати піки + + + Проміжок у пікселях між сегментами та каналами VU-метра, від 0 до 32. + + + Проміжок між сегментами + + + Скільки одиниць рівня канал спадає за секунду після зниження звуку, від 0 до 100. Більші значення спадають швидше. + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.zh-CN.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.zh-CN.resx index 592699f7..e665e765 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.zh-CN.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.zh-CN.resx @@ -69,4 +69,121 @@ 启用后,首个图片提供程序未提供的媒体库项目图片将由后续提供程序补齐。 + + 播放 + + + 暂停时继续下载 + + + 播放暂停时播放器是否继续下载曲目直到整个文件,这样恢复播放时无需等待数据。 + + + 自动播放 + + + 专辑或艺术家播放结束后是否自动继续播放后续曲目。 + + + 无缝播放 + + + 连续曲目之间是否无静默间隔地播放。 + + + ReplayGain + + + 如何对您播放的曲目应用 ReplayGain 音量标准化。 + + + 关闭 + + + 按曲目 + + + 按专辑 + + + 流媒体质量 + + + 当服务器需要为播放对曲目进行标准化时应用的质量上限。直接播放永远不会被更改。 + + + 自动 + + + 低 (96 kbps) + + + 中 (160 kbps) + + + 高 (320 kbps) + + + VU 表的每个通道分为多少段,介于 1 到 128 之间。 + + + 峰值衰落 + + + 以高状态绘制段时所超过的电平,介于 0 到 1 之间。它必须大于或等于中等阈值。 + + + VU 表的通道是从下向上增长,还是从左向右增长。 + + + 以中等状态绘制段时所超过的电平,介于 0 到 1 之间。 + + + 垂直 + + + 电平衰落 + + + 水平 + + + 方向 + + + 高阈值 + + + 每通道段数 + + + 中等阈值 + + + VU 表 + + + 峰值保持(毫秒) + + + 每个通道是否在其最近的最大电平处保留标记。 + + + 峰值标记在保持时间过后每秒下降的电平单位数,介于 0 到 100 之间。数值越大下降越快。 + + + 峰值标记在开始下降之前保持的时间(以毫秒为单位),介于 0 到 10000 之间。 + + + 显示峰值 + + + VU 表的段与通道之间的间距(以像素为单位),介于 0 到 32 之间。 + + + 段间距 + + + 声音下降后通道每秒下降的电平单位数,介于 0 到 100 之间。数值越大下降越快。 + diff --git a/src/Lumina.Presentation.Web/Core/Themes/ThemeAudioPlayerBuilder.cs b/src/Lumina.Presentation.Web/Core/Themes/ThemeAudioPlayerBuilder.cs new file mode 100644 index 00000000..49dedda4 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Themes/ThemeAudioPlayerBuilder.cs @@ -0,0 +1,93 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.Themes; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.Localization; +using System.Collections.Generic; +#endregion + +namespace Lumina.Presentation.Web.Core.Themes; + +/// +/// Builds the audio player model for the themed component template, resolving the localized strings and theme asset URLs server side. +/// +public sealed class ThemeAudioPlayerBuilder +{ + // The resource base name deliberately excludes the "Core.Resources" segment: the localization factory re-roots it with the configured ResourcesPath. + private const string VIEW_RESOURCE_BASE_NAME = "Lumina.Presentation.Web.Views.Shared._Layout"; + private const string VIEW_RESOURCE_LOCATION = "Lumina.Presentation.Web"; + + private readonly IHttpContextAccessor _httpContextAccessor; + private readonly IStringLocalizer _localizer; + + /// + /// Initializes a new instance of the class. + /// + /// Injected factory used to create the localizer of the audio player resources. + /// Injected accessor for the current HTTP context. + public ThemeAudioPlayerBuilder(IStringLocalizerFactory stringLocalizerFactory, IHttpContextAccessor httpContextAccessor) + { + _httpContextAccessor = httpContextAccessor; + _localizer = stringLocalizerFactory.Create(VIEW_RESOURCE_BASE_NAME, VIEW_RESOURCE_LOCATION); + } + + /// + /// Builds the model of the audio player for the given theme. + /// + /// The base URL of the assets of the active theme. + /// The raw template source of a queue item, or an empty string when the theme does not provide one. + /// The raw template source of a playlist item, or an empty string when the theme does not provide one. + /// The model available to the themed audio player template. + public ThemeAudioPlayerDto Build(string assetBase, string queueItemTemplate, string playlistItemTemplate) + { + Dictionary strings = new() + { + ["toggleExpanded"] = Localize("ToggleExpanded"), + ["previous"] = Localize("AudioPlayerPrevious"), + ["next"] = Localize("AudioPlayerNext"), + ["stop"] = Localize("AudioPlayerStop"), + ["repeat"] = Localize("AudioPlayerRepeat"), + ["repeatOff"] = Localize("AudioPlayerRepeatOff"), + ["repeatAll"] = Localize("AudioPlayerRepeatAll"), + ["repeatOne"] = Localize("AudioPlayerRepeatOne"), + ["queue"] = Localize("AudioPlayerQueue"), + ["albumArtwork"] = Localize("AudioPlayerAlbumArtwork"), + ["addQueueToPlaylist"] = Localize("AudioPlayerAddQueueToPlaylist"), + ["addToPlaylist"] = Localize("PlaylistAddToPlaylist"), + ["selectPlaylist"] = Localize("AudioPlayerSelectPlaylist"), + ["noPlaylists"] = Localize("AudioPlayerNoPlaylists"), + ["add"] = Localize("AudioPlayerAdd"), + ["playlistQueueAdded"] = Localize("AudioPlayerPlaylistQueueAdded"), + ["playlistQueueAddFailed"] = Localize("AudioPlayerPlaylistQueueAddFailed") + }; + + return new ThemeAudioPlayerDto( + AppBase: GetAppBaseUrl(), + AssetBase: assetBase, + QueueItemTemplate: queueItemTemplate, + PlaylistItemTemplate: playlistItemTemplate, + Strings: strings); + } + + /// + /// Gets the absolute base URL of the current Web application request, used to reference the application scripts from a static theme template. + /// + /// The absolute base URL with a trailing slash, or an empty string when the current HTTP context is unavailable. + private string GetAppBaseUrl() + { + HttpRequest? request = _httpContextAccessor.HttpContext?.Request; + if (request is null) + return string.Empty; + + return $"{request.Scheme}://{request.Host}{request.PathBase}/"; + } + + /// + /// Resolves a localized audio player string. + /// + /// The resource key of the string. + /// The localized string. + private string Localize(string key) + { + return _localizer[key].Value; + } +} diff --git a/src/Lumina.Presentation.Web/Core/Themes/ThemeAudioPlayerRenderer.cs b/src/Lumina.Presentation.Web/Core/Themes/ThemeAudioPlayerRenderer.cs new file mode 100644 index 00000000..f7b71542 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Themes/ThemeAudioPlayerRenderer.cs @@ -0,0 +1,102 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.Themes; +using Lumina.Presentation.Web.Common.Primitives; +using System; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Themes; + +/// +/// Renders the audio player bar with a theme, inlining the sub templates of its dynamic content so that the client script can render queue items and playlist items from theme markup. +/// +public class ThemeAudioPlayerRenderer +{ + // The page keys mirror the template files of the theme packs, pinned in each theme manifest so that a missing sub template does not resolve to the component shell template. + private const string SHELL_PAGE_KEY = "shared/audio-player"; + private const string QUEUE_ITEM_PAGE_KEY = "shared/audio-player/queue-item"; + private const string PLAYLIST_ITEM_PAGE_KEY = "shared/audio-player/playlist-item"; + + private readonly ThemeService _themeService; + private readonly ThemeTemplateEngine _templateEngine; + private readonly ThemeAudioPlayerBuilder _builder; + + /// + /// Initializes a new instance of the class. + /// + /// The service that resolves the render documents. + /// The template engine used to render the component shell template. + /// The builder used to produce the component model. + public ThemeAudioPlayerRenderer(ThemeService themeService, ThemeTemplateEngine templateEngine, ThemeAudioPlayerBuilder builder) + { + _themeService = themeService; + _templateEngine = templateEngine; + _builder = builder; + } + + /// + /// Renders the themed audio player bar with the specified theme. + /// + /// The manifest id of the theme to render the bar with, normally the theme the layout was resolved with. + /// Cancellation token that can be used to stop the execution. + /// An containing either the component HTML, or an error. + public virtual async Task> RenderAsync(string themeId, CancellationToken cancellationToken) + { + try + { + ThemeRenderDocumentDto shellDocument = await _themeService.GetRenderDocumentAsync(SHELL_PAGE_KEY, themeId, cancellationToken).ConfigureAwait(false); + string assetBase = $"/theme-assets/{themeId}/assets"; + + string queueItemTemplate = await GetSubTemplateAsync(themeId, shellDocument.Template, QUEUE_ITEM_PAGE_KEY, cancellationToken).ConfigureAwait(false); + string playlistItemTemplate = await GetSubTemplateAsync(themeId, shellDocument.Template, PLAYLIST_ITEM_PAGE_KEY, cancellationToken).ConfigureAwait(false); + + ThemeAudioPlayerDto model = _builder.Build(assetBase, queueItemTemplate, playlistItemTemplate); + Result renderResult = _templateEngine.RenderPage(shellDocument.Template, model); + if (renderResult.IsFailure) + return renderResult.Errors; + + return renderResult.Value.Content + renderResult.Value.Script; + } + catch (OperationCanceledException) + { + throw; + } + catch (Exception) + { + // The audio player bar is best effort: when the component template of the active theme cannot be loaded or rendered, the application Razor fallback is rendered instead. + return Error.NotFound(code: "Theme.Template.Unavailable", description: "The audio player theme template could not be loaded."); + } + } + + /// + /// Gets the raw template source of an audio player sub template, degrading to an empty string when the theme does not provide one. + /// + /// The manifest id of the active theme. + /// The raw template source of the component shell, used to detect the mirrored resolution falling back to the shell when a sub template is missing. + /// The page key of the sub template. + /// Cancellation token that can be used to stop the execution. + /// The raw template source, or an empty string when the theme does not provide the template. + private async Task GetSubTemplateAsync(string themeId, string shellTemplate, string pageKey, CancellationToken cancellationToken) + { + try + { + ThemeRenderDocumentDto document = await _themeService.GetRenderDocumentAsync(pageKey, themeId, cancellationToken).ConfigureAwait(false); + // When the theme does not ship the sub template, the mirrored template resolution walks up the path scopes + // and returns the component shell template instead, which the client script must not render as dynamic content. + if (string.Equals(document.Template, shellTemplate, StringComparison.Ordinal)) + return string.Empty; + + return document.Template; + } + catch (OperationCanceledException) + { + throw; + } + catch (Exception) + { + // Each sub template is best effort: when the theme omits one, the client script renders that part with its built-in markup instead. + return string.Empty; + } + } +} diff --git a/src/Lumina.Presentation.Web/Core/Themes/ThemeLayoutRenderer.cs b/src/Lumina.Presentation.Web/Core/Themes/ThemeLayoutRenderer.cs index ecb86226..119d6a21 100644 --- a/src/Lumina.Presentation.Web/Core/Themes/ThemeLayoutRenderer.cs +++ b/src/Lumina.Presentation.Web/Core/Themes/ThemeLayoutRenderer.cs @@ -22,6 +22,7 @@ public class ThemeLayoutRenderer private readonly ThemeTemplateEngine _templateEngine; private readonly RazorViewToStringRenderer _viewRenderer; private readonly ThemeNavBuilder _navBuilder; + private readonly ThemeAudioPlayerRenderer _audioPlayerRenderer; private readonly IHttpContextAccessor _httpContextAccessor; /// @@ -31,13 +32,15 @@ public class ThemeLayoutRenderer /// The template engine used to render the documents. /// The renderer used to produce the application chrome fragments. /// The builder used to produce the navigation menu model. + /// The renderer used to produce the themed audio player bar. /// Injected accessor for the current HTTP context. - public ThemeLayoutRenderer(ThemeService themeService, ThemeTemplateEngine templateEngine, RazorViewToStringRenderer viewRenderer, ThemeNavBuilder navBuilder, IHttpContextAccessor httpContextAccessor) + public ThemeLayoutRenderer(ThemeService themeService, ThemeTemplateEngine templateEngine, RazorViewToStringRenderer viewRenderer, ThemeNavBuilder navBuilder, ThemeAudioPlayerRenderer audioPlayerRenderer, IHttpContextAccessor httpContextAccessor) { _themeService = themeService; _templateEngine = templateEngine; _viewRenderer = viewRenderer; _navBuilder = navBuilder; + _audioPlayerRenderer = audioPlayerRenderer; _httpContextAccessor = httpContextAccessor; } @@ -58,7 +61,7 @@ public class ThemeLayoutRenderer string appHead = await _viewRenderer.RenderPartialAsync("_ThemeLayoutHead", cancellationToken); string nav = await RenderNavAsync(themeId, cancellationToken); - string audioPlayer = isAuthenticated ? await _viewRenderer.RenderPartialAsync("_AudioPlayer", cancellationToken) : string.Empty; + string audioPlayer = isAuthenticated ? await RenderAudioPlayerAsync(themeId, cancellationToken) : string.Empty; string appScripts = await _viewRenderer.RenderPartialAsync("_ThemeLayoutScripts", cancellationToken); ThemeLayoutModelDto layoutModel = new( @@ -119,4 +122,21 @@ public class ThemeLayoutRenderer return await _viewRenderer.RenderPartialAsync("_NavMenu", cancellationToken); } + + /// + /// Renders the audio player bar with the theme the layout was resolved with, falling back to the application Razor markup when the theme does not provide a bar template. + /// + /// The manifest id of the theme the layout was rendered with, so that the bar always matches the shell, including a preview of another theme. + /// Cancellation token that can be used to stop the execution. + /// The rendered audio player bar HTML. + private async Task RenderAudioPlayerAsync(string themeId, CancellationToken cancellationToken) + { + // The audio player renderer already degrades to an error when the theme template is missing or cannot be + // rendered, so a failure here only means the application fallback markup is rendered instead. + Result audioPlayerResult = await _audioPlayerRenderer.RenderAsync(themeId, cancellationToken); + if (audioPlayerResult.IsSuccess) + return audioPlayerResult.Value; + + return await _viewRenderer.RenderPartialAsync("_AudioPlayer", cancellationToken); + } } diff --git a/src/Lumina.Presentation.Web/Core/Themes/ThemeNavBuilder.cs b/src/Lumina.Presentation.Web/Core/Themes/ThemeNavBuilder.cs index 63cfb3ce..c731f703 100644 --- a/src/Lumina.Presentation.Web/Core/Themes/ThemeNavBuilder.cs +++ b/src/Lumina.Presentation.Web/Core/Themes/ThemeNavBuilder.cs @@ -152,6 +152,8 @@ public sealed class ThemeNavBuilder ]; if (canCreateLibraries) items.Add(new ThemeNavEntryDto(Localize("AddNewLibrary"), _urlService.GetAbsoluteUrl(WebRoutes.LibraryManagement.ADD_LIBRARY), "nav-link", [])); + items.Add(new ThemeNavEntryDto(Localize("Favorites"), _urlService.GetAbsoluteUrl(WebRoutes.Favorites.INDEX), "nav-link", [])); + items.Add(new ThemeNavEntryDto(Localize("Statistics"), _urlService.GetAbsoluteUrl(WebRoutes.LibraryStatistics.INDEX), "nav-link", [])); // The written content and audio entries open the home page filtered to the libraries of their category, so that browsing starts // from the libraries the user owns (or from every library, for administrators), instead of from a single library picked upfront. string librariesCatalogUrl = _urlService.GetAbsoluteUrl(WebRoutes.Home.INDEX_CULTURED) ?? string.Empty; @@ -163,6 +165,7 @@ public sealed class ThemeNavBuilder items.Add(new ThemeNavEntryDto(Localize("Audio"), Url: null, CssClass: null, [ new ThemeNavEntryDto(Localize("Music"), $"{librariesCatalogUrl}?category=music", "nav-link", []), + new ThemeNavEntryDto(Localize("Playlists"), _urlService.GetAbsoluteUrl(WebRoutes.Playlists.INDEX), "nav-link", []), new ThemeNavEntryDto(Localize("Interviews"), "library/audio/interviews", "nav-link", []) ])); items.Add(new ThemeNavEntryDto(Localize("Video"), Url: null, CssClass: null, diff --git a/src/Lumina.Presentation.Web/Core/Views/Favorites/Index.cshtml b/src/Lumina.Presentation.Web/Core/Views/Favorites/Index.cshtml new file mode 100644 index 00000000..c1ed1828 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Views/Favorites/Index.cshtml @@ -0,0 +1,534 @@ +@* + FALLBACK FAVORITES PAGE - READ BEFORE EDITING + + This view is the application fallback of the favorites page, rendered only when the theme template of the page cannot be + loaded. The bundled themes ship no template for it, so this view is what the user sees on a healthy site as well. It keeps + the DOM contract and the client script a theme template would mirror, so that listing, filtering and removing favorites + keep working with any theme. + + The page lists the favorites of the current user across every media kind, from the most recently favorited, in pages of + 50 items, and the kind filter restricts the list to one kind. Every card links to the page of its item, and carries a + favorite heart (a card-favorite-toggle button, always visible, in the place the actions trigger has on the library cards) + that the global favorites script drives, so a favorite is removed from the card itself. The page listens to + the lumina:favorite-changed event the script dispatches and removes the card of an item that is no longer a favorite, so + the counter and the empty state follow without another request. A favorite whose item was deleted, or whose library the + user can no longer access, is kept as an unavailable card without a link, so the owner can still remove it. + + The element hooks the script needs are favorites-container, no-favorites, favorite-count, favorites-kind-filter, + load-more-favorites-button and retry-favorites-button, and the classes of the cards are media-card, media-panel and + card-favorite-toggle. A failed reload clears the rendered window and shows the retry button, so the page never keeps the cards + of a filter the combo no longer shows. + + To restyle the page, edit the theme files. This fallback is intentionally plain, so that a broken theme is obvious to the user while the page still functions. + + /favorites +*@ + +@using Lumina.Presentation.Web.Common.Services +@using Microsoft.AspNetCore.Mvc.Localization +@using System +@using System.Collections.Generic +@using System.Text.Json +@using System.Text.Json.Serialization + +@inject IViewLocalizer _localizer +@inject IUrlService _urlService + +@{ + // Generate a unique id for the scripts section of this view, so it can be dynamically loaded/unloaded by the global AJAX navigator handler. + var scriptId = ScriptIdentifierHelper.GenerateScriptId(); + var strings = new Dictionary + { + ["title"] = _localizer["Title"].Value, + ["noFavorites"] = _localizer["NoFavorites"].Value, + ["noFavoritesInKind"] = _localizer["NoFavoritesInKind"].Value, + ["unavailable"] = _localizer["Unavailable"].Value, + ["itemsCount"] = _localizer["ItemsCount"].Value, + ["loadFailed"] = _localizer["LoadFailed"].Value, + ["kindMusicArtist"] = _localizer["KindArtist"].Value, + ["kindMusicAlbum"] = _localizer["KindAlbum"].Value, + ["kindMusicTrack"] = _localizer["KindTrack"].Value, + ["kindBook"] = _localizer["KindBook"].Value + }; + var jsonOptions = new JsonSerializerOptions + { + PropertyNamingPolicy = JsonNamingPolicy.CamelCase, + Converters = { new JsonStringEnumConverter() } + }; +} + +@Html.AntiForgeryToken() + +
+
+
+
+
+

@_localizer["Title"]

+
+ +
+
+
+ + +
+
+
@_localizer["FilterAll"]
+
@_localizer["FilterArtists"]
+
@_localizer["FilterAlbums"]
+
@_localizer["FilterTracks"]
+
@_localizer["FilterBooks"]
+
+
+
+
+ +
+
+ +
+ + +
+
+
+
+ +@section Scripts { + + +} diff --git a/src/Lumina.Presentation.Web/Core/Views/Home/Index.cshtml b/src/Lumina.Presentation.Web/Core/Views/Home/Index.cshtml index 25a7aee3..32c73678 100644 --- a/src/Lumina.Presentation.Web/Core/Views/Home/Index.cshtml +++ b/src/Lumina.Presentation.Web/Core/Views/Home/Index.cshtml @@ -59,6 +59,138 @@ const librariesContainer = document.getElementById('libraries-container'); const noLibrariesMessage = document.getElementById('no-libraries'); + const jsLocalizedStrings = { + actions: @Json.Serialize(_localizer["Actions"].Value), + play: @Json.Serialize(_localizer["Play"].Value), + shuffle: @Json.Serialize(_localizer["Shuffle"].Value), + addToPlaylist: @Json.Serialize(_localizer["AddToPlaylist"].Value) + }; + + // Closes the actions menus of all the music library cards. + function closeCardMenus() { + librariesContainer.querySelectorAll('.media-card.open').forEach(card => { + card.classList.remove('open'); + const menu = card.querySelector('.card-actions-menu'); + if (menu) + menu.classList.remove('open'); + }); + } + + // Toggles the actions menu of a music library card, opening it with its top left corner at the given viewport position. + function toggleCardMenu(card, anchor) { + const wasOpen = card.classList.contains('open'); + closeCardMenus(); + if (wasOpen) + return; + card.classList.add('open'); + const menu = card.querySelector('.card-actions-menu'); + if (menu) { + menu.classList.add('open'); + positionActionsMenu(menu, anchor); + } + } + + // Resolves the viewport point where the card actions menu opens. + function resolveMenuAnchor(event) { + if (event.clientX !== 0 || event.clientY !== 0) + return { x: event.clientX, y: event.clientY }; + const triggerRect = event.currentTarget.getBoundingClientRect(); + return { x: triggerRect.left, y: triggerRect.bottom }; + } + + // Places the card actions menu with its top left corner at the requested viewport point. + function positionActionsMenu(menu, anchor) { + const margin = 4; + const maxLeft = Math.max(margin, window.innerWidth - menu.offsetWidth - margin); + const maxTop = Math.max(margin, window.innerHeight - menu.offsetHeight - margin); + menu.style.position = 'fixed'; + menu.style.left = `${Math.min(Math.max(margin, anchor.x), maxLeft)}px`; + menu.style.top = `${Math.min(Math.max(margin, anchor.y), maxTop)}px`; + } + + // Closes the actions menus when clicking or pressing a key outside them. + function handleCardMenuDismiss(event) { + if (event.type === 'keydown' && event.key !== 'Escape') + return; + if (event.type === 'click' && event.target.closest('.card-actions-menu, .card-actions-trigger')) + return; + closeCardMenus(); + } + + // Adds the actions menu of a music library card, with the play and shuffle actions that start the whole library. + function createMusicLibraryMenu(card, library) { + const libraryCoverPath = library.coverImage + ? `/media/libraries/${library.id}/${library.coverImage.substring(library.coverImage.lastIndexOf('cover.'))}` + : ''; + const trigger = document.createElement('button'); + trigger.type = 'button'; + trigger.className = 'card-actions-trigger'; + trigger.setAttribute('aria-haspopup', 'menu'); + trigger.setAttribute('aria-label', jsLocalizedStrings.actions); + trigger.addEventListener('click', event => { + event.preventDefault(); + event.stopImmediatePropagation(); + toggleCardMenu(card, resolveMenuAnchor(event)); + }); + + const menu = document.createElement('nav'); + menu.className = 'card-actions-menu'; + menu.setAttribute('role', 'menu'); + + const playAction = document.createElement('a'); + playAction.setAttribute('role', 'menuitem'); + playAction.href = '#'; + playAction.className = 'card-action-play'; + playAction.textContent = jsLocalizedStrings.play; + playAction.setAttribute('data-audio-player-play-library', ''); + playAction.dataset.libraryId = library.id; + playAction.dataset.title = library.title || ''; + if (libraryCoverPath) + playAction.dataset.coverArtPath = libraryCoverPath; + menu.appendChild(playAction); + + const shuffleAction = document.createElement('a'); + shuffleAction.setAttribute('role', 'menuitem'); + shuffleAction.href = '#'; + shuffleAction.className = 'card-action-shuffle'; + shuffleAction.textContent = jsLocalizedStrings.shuffle; + shuffleAction.setAttribute('data-audio-player-play-library-shuffled', ''); + shuffleAction.dataset.libraryId = library.id; + menu.appendChild(shuffleAction); + + const addToPlaylistAction = document.createElement('a'); + addToPlaylistAction.setAttribute('role', 'menuitem'); + addToPlaylistAction.href = '#'; + addToPlaylistAction.className = 'card-action-add-to-playlist'; + addToPlaylistAction.textContent = jsLocalizedStrings.addToPlaylist; + addToPlaylistAction.addEventListener('click', async event => { + event.preventDefault(); + event.stopImmediatePropagation(); + closeCardMenus(); + if (window.LuminaPlaylists) + await window.LuminaPlaylists.showAddScopeDialogAsync({ libraryId: library.id, title: library.title || '', addToPlaylistLabel: jsLocalizedStrings.addToPlaylist, returnFocus: trigger }); + }); + menu.appendChild(addToPlaylistAction); + + menu.addEventListener('click', event => { + // The global audio player delegation handles the play and shuffle actions; the menu only closes here. + if (event.target.closest('.card-action-play, .card-action-shuffle')) + closeCardMenus(); + }); + + card.appendChild(trigger); + card.appendChild(menu); + card.addEventListener('contextmenu', event => { + event.preventDefault(); + event.stopImmediatePropagation(); + toggleCardMenu(card, resolveMenuAnchor(event)); + }); + card.addEventListener('click', event => { + if (card.classList.contains('open') && !event.target.closest('.card-actions-menu')) + closeCardMenus(); + }); + } + async function InitializeAsync() { if (isInitialized) return; @@ -95,7 +227,15 @@ ${library.title} `; - librariesContainer.appendChild(libraryElement); + // A music library gets a card actions menu with the play and shuffle actions for the whole library. + if (library.libraryType === 'Music') { + const card = document.createElement('div'); + card.className = 'media-card'; + card.appendChild(libraryElement); + createMusicLibraryMenu(card, library); + librariesContainer.appendChild(card); + } else + librariesContainer.appendChild(libraryElement); }); // Bind the AJAX navigation behavior to the library links, which were created after the initial navigation binding. bindNavigationLinks(); @@ -107,10 +247,14 @@ } // Add listeners. + document.addEventListener('click', handleCardMenuDismiss); + document.addEventListener('keydown', handleCardMenuDismiss); document.addEventListener('DOMContentLoaded', InitializeAsync); // Register cleanup for these listeners. cleanupFunctions.push(() => { + document.removeEventListener('click', handleCardMenuDismiss); + document.removeEventListener('keydown', handleCardMenuDismiss); document.removeEventListener('DOMContentLoaded', InitializeAsync); }); diff --git a/src/Lumina.Presentation.Web/Core/Views/Library/AudioLibrary/MusicLibrary/Albums/Item.cshtml b/src/Lumina.Presentation.Web/Core/Views/Library/AudioLibrary/MusicLibrary/Albums/Item.cshtml index 731f9935..f02da968 100644 --- a/src/Lumina.Presentation.Web/Core/Views/Library/AudioLibrary/MusicLibrary/Albums/Item.cshtml +++ b/src/Lumina.Presentation.Web/Core/Views/Library/AudioLibrary/MusicLibrary/Albums/Item.cshtml @@ -8,6 +8,10 @@ The tracks of the album are NOT edited inline: they are listed as cards that navigate to their own pages, and the update request never changes the tracks. + The album header and every track row the script renders expose a play trigger for the global audio player. The player + handles those triggers by event delegation, so this view binds no playback listener; the trigger attribute contract + lives in docs/technical/theming/Theming.md. + To change the behavior of the page, edit this script (and the theme template, when present). To restyle the page, edit the theme files. This fallback keeps every feature working without styling, so that a broken theme is obvious to the user while the page still functions. @@ -73,6 +77,13 @@ }) .ToList(); var artworkItemsJson = System.Text.Json.JsonSerializer.Serialize(artworkItems); + // The cover the play affordances hand to the player, resolved exactly like the cover this page displays: the stored cover, or the first stored artwork when the album has no cover. + var playCoverPath = Model.CoverPath; + if (string.IsNullOrWhiteSpace(playCoverPath)) + playCoverPath = (Model.Artwork ?? []).FirstOrDefault(artwork => !string.IsNullOrWhiteSpace(artwork.Path))?.Path ?? string.Empty; + // The play album trigger starts disabled when the album is already known to hold no tracks, so an empty release cannot be + // clicked before the track list request resolves. A failed request never changes this state. + var hasTracks = (Model.Tracks?.Count ?? 0) > 0; } @inject IViewLocalizer _localizer @@ -88,6 +99,16 @@
+ +

@_localizer["EditAlbum"]

@@ -112,9 +133,12 @@
+ + +
@@ -589,6 +613,7 @@ const artistId = '@artistId'; const albumId = '@albumId'; + const albumTitle = @Json.Serialize(metadata?.Title ?? string.Empty); const libraryId = '@libraryId'; const saveUrl = '@_urlService.GetAbsoluteUrl(WebRoutes.Music.SAVE_ALBUM, new { artistId = default(Guid), albumId = default(Guid) })'.replace('/@(default(Guid))', `/${artistId}`).replace('/@(default(Guid))', `/${albumId}`); const deleteUrl = '@_urlService.GetAbsoluteUrl(WebRoutes.Music.DELETE_ALBUM, new { artistId = default(Guid), albumId = default(Guid) })'.replace('/@(default(Guid))', `/${artistId}`).replace('/@(default(Guid))', `/${albumId}`); @@ -601,6 +626,7 @@ const btnBackToArtist = document.getElementById('btn-back-to-artist'); const btnSaveAlbum = document.getElementById('btn-save-album'); const btnDeleteAlbum = document.getElementById('btn-delete-album'); + const btnPlayAlbum = document.getElementById('btn-play-album'); const btnAddCatalogNumber = document.getElementById('btn-add-catalog-number'); const btnAddReleaseType = document.getElementById('btn-add-release-type'); const btnAddGenre = document.getElementById('btn-add-genre'); @@ -633,9 +659,42 @@ noCover: @Json.Serialize(_localizer["NoCover"].Value), coverSaved: @Json.Serialize(_localizer["CoverSaved"].Value), coverUploadFailed: @Json.Serialize(_localizer["CoverUploadFailed"].Value), + playTrack: @Json.Serialize(_localizer["PlayTrack"].Value), + actions: @Json.Serialize(_localizer["Actions"].Value), + addToPlaylist: @Json.Serialize(_localizer["AddToPlaylist"].Value), + addToPlayQueue: @Json.Serialize(_localizer["AddToPlayQueue"].Value), + playAllFromHere: @Json.Serialize(_localizer["PlayAllFromHere"].Value), remove: @Json.Serialize(_localizer["Remove"].Value) }; + // Normalizes a cover path with the same rule the server uses: a missing or whitespace only path means no artwork. + function normalizeCoverPath(coverPath) { + return typeof coverPath === 'string' ? coverPath.trim() : ''; + } + + // The cover path the play affordances hand to the player, kept in step with the artwork the page currently displays. + let currentCoverPath = normalizeCoverPath(@Json.Serialize(playCoverPath ?? string.Empty)); + // The ordered tracks of the album, kept for the "play all from here" action of the track menu. + let albumTracks = []; + // The track actions menu that is currently open, so the page opens one menu at a time and closes it on dismissal. + let openTrackActionsMenu = null; + + // Writes the cover of a play descriptor onto a trigger, dropping the attribute when the context has no artwork. + function applyDescriptorCover(trigger, coverPath) { + const normalizedCoverPath = normalizeCoverPath(coverPath); + if (normalizedCoverPath) + trigger.dataset.coverArtPath = normalizedCoverPath; + else + delete trigger.dataset.coverArtPath; + } + + // Hands every play trigger the cover the page currently displays, so a play started after choosing or uploading an artwork shows that artwork in the player bar. + function applyPlayAffordanceCover(coverPath) { + currentCoverPath = normalizeCoverPath(coverPath); + applyDescriptorCover(btnPlayAlbum, currentCoverPath); + tracksBody.querySelectorAll('[data-audio-player-play]').forEach(trigger => applyDescriptorCover(trigger, currentCoverPath)); + } + // Reads the trimmed value of the element with the provided id. function readValue(id) { const element = document.getElementById(id); @@ -898,20 +957,54 @@ return `${minutes}:${paddedSeconds}`; } - // Renders a row of the tracks table per track, or shows the empty message when the album has no tracks. + // Renders a row of the tracks table per track, or shows the empty message when the album has no tracks. A failed + // request returns undefined, which is not an empty album: it leaves the existing rows and the play album state intact. function renderTracks(response) { + if (!response || !Array.isArray(response.data)) + return; tracksBody.innerHTML = ''; - const tracks = response && response.data ? response.data : []; + const tracks = response.data; + albumTracks = tracks; noTracksMessage.classList.toggle('hidden', tracks.length !== 0); + // Only a successful empty list disables the play album trigger. The player can still build the queue itself when + // the track list could not be loaded. + btnPlayAlbum.disabled = tracks.length === 0; tracks.forEach(track => tracksBody.appendChild(createTrackRow(track))); bindNavigationLinks(); } - // Creates a row of the tracks table, with the name of the track linking to its own page. + // Creates the play trigger of a track row. It describes a track context, so the player plays exactly this track. + function createTrackPlayButton(track) { + const button = document.createElement('button'); + button.type = 'button'; + button.className = 'confirm-button track-play-button'; + button.setAttribute('data-audio-player-play', ''); + button.dataset.libraryId = libraryId; + button.dataset.trackId = track.id; + button.dataset.albumId = albumId; + button.dataset.artistId = artistId; + button.dataset.title = track.title || ''; + button.dataset.albumTitle = albumTitle; + button.dataset.duration = String(track.durationInSeconds || ''); + applyDescriptorCover(button, currentCoverPath); + // The button carries no visible text, so its accessible name names both the action and the track it plays. + const label = `${jsLocalizedStrings.playTrack}: ${track.title || ''}`; + button.setAttribute('aria-label', label); + button.title = label; + button.textContent = '\u25B6'; + return button; + } + + // Creates a row of the tracks table, with the play trigger, the number, the name of the track linking to its own page, + // the duration, the favorite heart and the actions menu of the track. function createTrackRow(track) { const row = document.createElement('tr'); row.className = 'track-row'; + const playCell = document.createElement('td'); + playCell.className = 'track-play-cell'; + playCell.appendChild(createTrackPlayButton(track)); + const numberCell = document.createElement('td'); numberCell.textContent = track.trackNumber; @@ -925,12 +1018,190 @@ const durationCell = document.createElement('td'); durationCell.textContent = formatDuration(track.durationInSeconds); + row.appendChild(playCell); row.appendChild(numberCell); row.appendChild(nameCell); row.appendChild(durationCell); + row.appendChild(createTrackFavoriteCell(track)); + row.appendChild(createTrackActionsCell(track)); return row; } + // Creates the favorite cell of a track row, right after the duration. The heart is a plain button: the global favorites + // script finds it by its data attributes, hydrates its state and handles its click. + function createTrackFavoriteCell(track) { + const cell = document.createElement('td'); + cell.className = 'track-favorite-cell'; + const favoriteToggle = document.createElement('button'); + favoriteToggle.type = 'button'; + favoriteToggle.className = 'card-favorite-toggle track-favorite-toggle'; + favoriteToggle.setAttribute('data-favorite-toggle', ''); + favoriteToggle.setAttribute('data-favorite-media-kind', 'MusicTrack'); + favoriteToggle.setAttribute('data-favorite-media-item-id', track.id); + cell.appendChild(favoriteToggle); + return cell; + } + + // Gets the singleton audio player, or null when the layout did not render it. + function getAudioPlayer() { + return window.LuminaAudioPlayer && window.LuminaAudioPlayer.instance + ? window.LuminaAudioPlayer.instance + : null; + } + + // Builds the play descriptor of a track of this album, with the cover the page currently displays. + function buildTrackDescriptor(track) { + return { + libraryId: libraryId, + trackId: track.id, + albumId: albumId, + artistId: artistId, + title: track.title || '', + albumTitle: albumTitle, + durationInSeconds: Number(track.durationInSeconds) || 0, + coverArtPath: currentCoverPath + }; + } + + // Closes the open track actions menu, optionally returning the focus to its trigger. + function closeTrackActionsMenu(shouldRestoreFocus) { + if (!openTrackActionsMenu) + return; + const menu = openTrackActionsMenu.menu; + const trigger = openTrackActionsMenu.trigger; + openTrackActionsMenu = null; + menu.remove(); + trigger.setAttribute('aria-expanded', 'false'); + if (shouldRestoreFocus && trigger.isConnected) + trigger.focus(); + } + + // Places the track actions menu next to its trigger, right aligned and below it when there is room. + function positionTrackActionsMenu(menu, trigger) { + const margin = 4; + const triggerRect = trigger.getBoundingClientRect(); + const width = menu.offsetWidth; + const height = menu.offsetHeight; + const left = Math.min(Math.max(margin, triggerRect.right - width), Math.max(margin, window.innerWidth - width - margin)); + const below = triggerRect.bottom + margin; + const top = below + height <= window.innerHeight - margin + ? below + : Math.max(margin, triggerRect.top - height - margin); + menu.style.left = `${left}px`; + menu.style.top = `${top}px`; + } + + // Creates one entry of the track actions menu, using the same menu item markup as the card actions menus. + function createTrackMenuAction(label, className, handler) { + const link = document.createElement('a'); + link.href = '#'; + link.className = className; + link.setAttribute('role', 'menuitem'); + link.textContent = label; + link.addEventListener('click', event => { + event.preventDefault(); + event.stopPropagation(); + closeTrackActionsMenu(false); + handler(); + }); + return link; + } + + // Opens the actions menu of a track, or closes it when the same trigger is clicked again. + function openTrackActionsMenuFor(trigger, track) { + const wasOpen = openTrackActionsMenu && openTrackActionsMenu.trigger === trigger; + closeTrackActionsMenu(false); + if (wasOpen) + return; + const menu = document.createElement('nav'); + menu.className = 'card-actions-menu'; + menu.setAttribute('role', 'menu'); + menu.appendChild(createTrackMenuAction(jsLocalizedStrings.addToPlaylist, 'card-action-add-to-playlist', () => addTrackToPlaylist(track, trigger))); + menu.appendChild(createTrackMenuAction(jsLocalizedStrings.addToPlayQueue, 'card-action-add-to-queue', () => addTrackToQueueAsync(track))); + menu.appendChild(createTrackMenuAction(jsLocalizedStrings.playAllFromHere, 'card-action-play-all-from-here', () => playAllFromHereAsync(track))); + document.body.appendChild(menu); + menu.classList.add('open'); + positionTrackActionsMenu(menu, trigger); + trigger.setAttribute('aria-expanded', 'true'); + openTrackActionsMenu = { trigger, menu }; + const firstAction = menu.querySelector('a[role="menuitem"]'); + if (firstAction) + firstAction.focus(); + } + + // Creates the actions cell of a track row, using the same trigger and dots as the card actions menus. + function createTrackActionsCell(track) { + const cell = document.createElement('td'); + cell.className = 'track-actions-cell'; + const trigger = document.createElement('button'); + trigger.type = 'button'; + trigger.className = 'card-actions-trigger track-actions-trigger'; + trigger.setAttribute('aria-haspopup', 'menu'); + trigger.setAttribute('aria-expanded', 'false'); + trigger.setAttribute('aria-label', jsLocalizedStrings.actions); + trigger.title = jsLocalizedStrings.actions; + trigger.addEventListener('click', event => { + event.preventDefault(); + event.stopPropagation(); + openTrackActionsMenuFor(trigger, track); + }); + cell.appendChild(trigger); + return cell; + } + + // Closes the track actions menu when the user clicks elsewhere, presses Escape, scrolls or resizes the window. + function handleTrackActionsMenuDismiss(event) { + if (!openTrackActionsMenu) + return; + if (event.type === 'keydown') { + if (event.key === 'Escape') { + event.preventDefault(); + closeTrackActionsMenu(true); + } + return; + } + if (event.type === 'click' && event.target.closest('.card-actions-menu, .track-actions-trigger')) + return; + closeTrackActionsMenu(false); + } + + // Appends one track to the play queue, or starts it when the queue is empty. + async function addTrackToQueueAsync(track) { + const player = getAudioPlayer(); + if (!player || typeof player.appendToQueueAsync !== 'function') + return; + await player.appendToQueueAsync(buildTrackDescriptor(track)); + } + + // Starts a new queue with the clicked track and every track that follows it in the album track list. + async function playAllFromHereAsync(track) { + const player = getAudioPlayer(); + if (!player) + return; + const index = albumTracks.findIndex(candidate => candidate.id === track.id); + if (index < 0) + return; + const descriptors = albumTracks.slice(index).map(buildTrackDescriptor); + if (descriptors.length === 0) + return; + await player.playAsync({ ...descriptors[0], queue: descriptors }); + } + + // Opens the shared add-to-playlist dialog for this single track. + function addTrackToPlaylist(track, trigger) { + if (!window.LuminaPlaylists || typeof window.LuminaPlaylists.showAddScopeDialogAsync !== 'function') + return; + window.LuminaPlaylists.showAddScopeDialogAsync({ + libraryId: libraryId, + artistId: artistId, + albumId: albumId, + trackId: track.id, + title: track.title || '', + addToPlaylistLabel: jsLocalizedStrings.addToPlaylist, + returnFocus: trigger + }); + } + // Sends the edited album data to the server. async function handleSaveAsync() { const result = await callApiPutAsync(`${saveUrl}?libraryId=${encodeURIComponent(libraryId)}`, buildPayload()); @@ -1007,6 +1278,8 @@ coverImage.dataset.coverPath = storedPath; coverPathLabel.textContent = storedPath ? storedPath : jsLocalizedStrings.noCover; coverPathLabel.title = storedPath; + // The player shows the cover the page displays, so the uploaded cover is handed to the play triggers too. + applyPlayAffordanceCover(storedPath); }; reader.readAsDataURL(file); notificationService.show(jsLocalizedStrings.coverSaved, NotificationType.SUCCESS); @@ -1042,12 +1315,14 @@ artworkCarousel.querySelectorAll('.artwork-carousel-item').forEach(item => { item.classList.toggle('selected', item.dataset.artworkPath === artworkPath); }); + // The play affordances hand the player the cover the page currently displays, so a play started after choosing an artwork shows that artwork in the player bar. + applyPlayAffordanceCover(artworkPath); } // Shows the cover image of the album, or the first stored artwork when there is no cover, or a placeholder when the album has neither. function showCover() { - const coverPath = coverImage.dataset.coverPath || ''; - const artworkPath = coverPath || (artworkItems.length > 0 ? artworkItems[0].path : ''); + const coverPath = normalizeCoverPath(coverImage.dataset.coverPath); + const artworkPath = coverPath || (artworkItems.length > 0 ? normalizeCoverPath(artworkItems[0].path) : ''); if (artworkPath) { selectArtwork(artworkPath); } else { @@ -1075,6 +1350,10 @@ ratingsBody.addEventListener('click', handleRowRemoval); btnChangeCover.addEventListener('click', handleChangeCoverClick); coverInput.addEventListener('change', handleCoverChangeAsync); + document.addEventListener('click', handleTrackActionsMenuDismiss); + document.addEventListener('keydown', handleTrackActionsMenuDismiss); + window.addEventListener('scroll', handleTrackActionsMenuDismiss, true); + window.addEventListener('resize', handleTrackActionsMenuDismiss); document.addEventListener('DOMContentLoaded', InitializeAsync); // Register cleanup for these listeners. @@ -1096,6 +1375,11 @@ ratingsBody.removeEventListener('click', handleRowRemoval); btnChangeCover.removeEventListener('click', handleChangeCoverClick); coverInput.removeEventListener('change', handleCoverChangeAsync); + closeTrackActionsMenu(false); + document.removeEventListener('click', handleTrackActionsMenuDismiss); + document.removeEventListener('keydown', handleTrackActionsMenuDismiss); + window.removeEventListener('scroll', handleTrackActionsMenuDismiss, true); + window.removeEventListener('resize', handleTrackActionsMenuDismiss); document.removeEventListener('DOMContentLoaded', InitializeAsync); }); diff --git a/src/Lumina.Presentation.Web/Core/Views/Library/AudioLibrary/MusicLibrary/Artists/Index.cshtml b/src/Lumina.Presentation.Web/Core/Views/Library/AudioLibrary/MusicLibrary/Artists/Index.cshtml index 968984d8..cc63e49b 100644 --- a/src/Lumina.Presentation.Web/Core/Views/Library/AudioLibrary/MusicLibrary/Artists/Index.cshtml +++ b/src/Lumina.Presentation.Web/Core/Views/Library/AudioLibrary/MusicLibrary/Artists/Index.cshtml @@ -110,9 +110,13 @@ sortAscending: '@_localizer["SortAscending"]', sortDescending: '@_localizer["SortDescending"]', viewDetails: '@_localizer["ViewDetails"]', + actions: '@_localizer["Actions"]', + play: '@_localizer["Play"]', + shuffle: '@_localizer["Shuffle"]', deleteItem: '@_localizer["Delete"]', deleteConfirm: '@_localizer["DeleteConfirm"]', - deleteFailed: '@_localizer["DeleteFailed"]' + deleteFailed: '@_localizer["DeleteFailed"]', + addToPlaylist: '@_localizer["AddToPlaylist"]' }; function buildItemsUrl() { @@ -208,7 +212,7 @@ trigger.type = 'button'; trigger.className = 'card-actions-trigger'; trigger.setAttribute('aria-haspopup', 'menu'); - trigger.setAttribute('aria-label', jsLocalizedStrings.viewDetails); + trigger.setAttribute('aria-label', jsLocalizedStrings.actions); trigger.addEventListener('click', event => { event.preventDefault(); event.stopImmediatePropagation(); @@ -218,11 +222,68 @@ const menu = document.createElement('nav'); menu.className = 'card-actions-menu'; menu.setAttribute('role', 'menu'); - menu.innerHTML = ` - ${jsLocalizedStrings.viewDetails} - ${jsLocalizedStrings.deleteItem}`; + + const detailsAction = document.createElement('a'); + detailsAction.setAttribute('role', 'menuitem'); + detailsAction.href = artistUrl; + detailsAction.textContent = jsLocalizedStrings.viewDetails; + + const playAction = document.createElement('a'); + playAction.setAttribute('role', 'menuitem'); + playAction.href = '#'; + playAction.className = 'card-action-play'; + playAction.textContent = jsLocalizedStrings.play; + playAction.setAttribute('data-audio-player-play', ''); + playAction.dataset.libraryId = libraryId; + playAction.dataset.artistId = artist.id; + playAction.dataset.title = artist.name || ''; + if (artist.coverPath) + playAction.dataset.coverArtPath = artist.coverPath; + + const shuffleAction = document.createElement('a'); + shuffleAction.setAttribute('role', 'menuitem'); + shuffleAction.href = '#'; + shuffleAction.className = 'card-action-shuffle'; + shuffleAction.textContent = jsLocalizedStrings.shuffle; + shuffleAction.setAttribute('data-audio-player-play-shuffled', ''); + shuffleAction.setAttribute('data-audio-player-shuffle-scope', 'artist'); + shuffleAction.dataset.libraryId = libraryId; + shuffleAction.dataset.artistId = artist.id; + shuffleAction.dataset.title = artist.name || ''; + if (artist.coverPath) + shuffleAction.dataset.coverArtPath = artist.coverPath; + + const addToPlaylistAction = document.createElement('a'); + addToPlaylistAction.setAttribute('role', 'menuitem'); + addToPlaylistAction.href = '#'; + addToPlaylistAction.className = 'card-action-add-to-playlist'; + addToPlaylistAction.textContent = jsLocalizedStrings.addToPlaylist; + addToPlaylistAction.addEventListener('click', async event => { + event.preventDefault(); + event.stopImmediatePropagation(); + closeCardMenus(); + if (window.LuminaPlaylists) + await window.LuminaPlaylists.showAddScopeDialogAsync({ libraryId: libraryId, artistId: artist.id, title: artist.name || '', addToPlaylistLabel: jsLocalizedStrings.addToPlaylist, returnFocus: trigger }); + }); + + const deleteAction = document.createElement('a'); + deleteAction.setAttribute('role', 'menuitem'); + deleteAction.href = '#'; + deleteAction.className = 'card-action-delete'; + deleteAction.textContent = jsLocalizedStrings.deleteItem; + + menu.appendChild(detailsAction); + menu.appendChild(playAction); + menu.appendChild(shuffleAction); + menu.appendChild(addToPlaylistAction); + menu.appendChild(deleteAction); menu.addEventListener('click', async event => { + // The global audio player delegation handles the play and shuffle actions; the menu only closes here. + if (event.target.closest('.card-action-play, .card-action-shuffle')) { + closeCardMenus(); + return; + } const deleteItem = event.target.closest('.card-action-delete'); const menuItem = event.target.closest('a[role="menuitem"]'); if (!menuItem) @@ -237,7 +298,16 @@ await updateContentAsync(menuItem.href, true); }); + // The favorite heart is a plain button: the global favorites script finds it by its data attributes, hydrates its state and handles its click. + const favoriteToggle = document.createElement('button'); + favoriteToggle.type = 'button'; + favoriteToggle.className = 'card-favorite-toggle'; + favoriteToggle.setAttribute('data-favorite-toggle', ''); + favoriteToggle.setAttribute('data-favorite-media-kind', 'MusicArtist'); + favoriteToggle.setAttribute('data-favorite-media-item-id', artist.id); + card.appendChild(cardLink); + card.appendChild(favoriteToggle); card.appendChild(trigger); card.appendChild(menu); diff --git a/src/Lumina.Presentation.Web/Core/Views/Library/AudioLibrary/MusicLibrary/Artists/Item.cshtml b/src/Lumina.Presentation.Web/Core/Views/Library/AudioLibrary/MusicLibrary/Artists/Item.cshtml index 10142b94..378344c2 100644 --- a/src/Lumina.Presentation.Web/Core/Views/Library/AudioLibrary/MusicLibrary/Artists/Item.cshtml +++ b/src/Lumina.Presentation.Web/Core/Views/Library/AudioLibrary/MusicLibrary/Artists/Item.cshtml @@ -9,6 +9,9 @@ The albums of the artist are NOT edited inline: they are listed as cards that navigate to their own pages, and the update request only round-trips the albums unchanged, so that updating the artist never drops them. + The artist header exposes a play all trigger for the global audio player. The player handles the trigger by event + delegation, so this view binds no playback listener; the trigger attribute contract lives in docs/technical/theming/Theming.md. + To change the behavior of the page, edit this script (and the theme template, when present). To restyle the page, edit the theme files. This fallback keeps every feature working without styling, so that a broken theme is obvious to the user while the page still functions. @@ -36,6 +39,9 @@ var aliases = metadata?.Aliases ?? []; var contributors = Model.Contributors ?? []; var ratings = Model.Ratings ?? []; + // The play all trigger starts disabled when the artist is already known to hold no releases, so an empty discography + // cannot be clicked before the release list request resolves. A failed request never changes this state. + var hasReleases = (Model.Albums?.Count ?? 0) > 0; var genres = metadata?.Genres ?? []; var tags = metadata?.Tags ?? []; var area = metadata?.Area; @@ -110,6 +116,15 @@
+ +

@_localizer["EditArtist"]

@@ -624,6 +639,7 @@ const btnBackToArtists = document.getElementById('btn-back-to-artists'); const btnSaveArtist = document.getElementById('btn-save-artist'); const btnDeleteArtist = document.getElementById('btn-delete-artist'); + const btnPlayArtist = document.getElementById('btn-play-artist'); const btnAddAlias = document.getElementById('btn-add-alias'); const btnAddIpi = document.getElementById('btn-add-ipi'); const btnAddIsni = document.getElementById('btn-add-isni'); @@ -656,7 +672,10 @@ noCover: @Json.Serialize(_localizer["NoCover"].Value), coverSaved: @Json.Serialize(_localizer["CoverSaved"].Value), coverUploadFailed: @Json.Serialize(_localizer["CoverUploadFailed"].Value), - remove: @Json.Serialize(_localizer["Remove"].Value) + play: @Json.Serialize(_localizer["Play"].Value), + shuffle: @Json.Serialize(_localizer["Shuffle"].Value), + remove: @Json.Serialize(_localizer["Remove"].Value), + addToPlaylist: @Json.Serialize(_localizer["AddToPlaylist"].Value) }; // Reads the trimmed value of the element with the provided id. @@ -932,6 +951,28 @@ return deleteAlbumUrlTemplate.replace('/@(default(Guid))', `/${artistId}`).replace('/@(default(Guid))', `/${albumId}`) + `?libraryId=${libraryId}`; } + // Writes the play descriptor of an album onto an album card menu action. + function applyAlbumPlayDescriptor(trigger, album) { + trigger.dataset.libraryId = libraryId; + trigger.dataset.artistId = artistId; + trigger.dataset.albumId = album.id; + trigger.dataset.title = album.title || ''; + if (album.coverPath) + trigger.dataset.coverArtPath = album.coverPath; + else + delete trigger.dataset.coverArtPath; + } + + // Creates an action of the album card actions menu. + function createAlbumMenuAction(label, className) { + const action = document.createElement('a'); + action.setAttribute('role', 'menuitem'); + action.href = '#'; + action.className = className; + action.textContent = label; + return action; + } + // The localized labels of the release types, keyed by their canonical enum name. const releaseTypeLabels = { 'Album': '@_localizer["Album"].Value', @@ -962,11 +1003,16 @@ renderReleases(response); } - // Renders the releases of the artist, grouped by their primary release type, each group ordered by release year. + // Renders the releases of the artist, grouped by their primary release type, each group ordered by release year. A + // failed request returns undefined, which is not an empty discography: it leaves the existing list and play state intact. function renderReleases(response) { + if (!response || !Array.isArray(response.data)) + return; albumsContainer.querySelectorAll('.release-group').forEach(group => group.remove()); - const releases = response && response.data ? response.data : []; + const releases = response.data; noAlbumsMessage.classList.toggle('hidden', releases.length !== 0); + // Only a successful empty list disables the play all trigger. The player can still build the queue itself when the release list could not be loaded. + btnPlayArtist.disabled = releases.length === 0; // The releases are grouped by their first release type, falling back to "Other" when the type is not known. const groups = new Map(); @@ -1072,8 +1118,38 @@ const menu = document.createElement('nav'); menu.className = 'card-actions-menu'; menu.setAttribute('role', 'menu'); - menu.innerHTML = `${jsLocalizedStrings.remove}`; + + const playAction = createAlbumMenuAction(jsLocalizedStrings.play, 'card-action-play'); + playAction.setAttribute('data-audio-player-play', ''); + applyAlbumPlayDescriptor(playAction, album); + + const shuffleAction = createAlbumMenuAction(jsLocalizedStrings.shuffle, 'card-action-shuffle'); + shuffleAction.setAttribute('data-audio-player-play-shuffled', ''); + shuffleAction.setAttribute('data-audio-player-shuffle-scope', 'release'); + applyAlbumPlayDescriptor(shuffleAction, album); + + const addToPlaylistAction = createAlbumMenuAction(jsLocalizedStrings.addToPlaylist, 'card-action-add-to-playlist'); + addToPlaylistAction.addEventListener('click', async event => { + event.preventDefault(); + event.stopImmediatePropagation(); + closeCardMenus(); + if (window.LuminaPlaylists) + await window.LuminaPlaylists.showAddScopeDialogAsync({ libraryId: libraryId, artistId: artistId, albumId: album.id, title: album.title || '', addToPlaylistLabel: jsLocalizedStrings.addToPlaylist, returnFocus: trigger }); + }); + + const deleteAction = createAlbumMenuAction(jsLocalizedStrings.remove, 'card-action-delete'); + + menu.appendChild(playAction); + menu.appendChild(shuffleAction); + menu.appendChild(addToPlaylistAction); + menu.appendChild(deleteAction); + menu.addEventListener('click', async event => { + // Play and shuffle are handled by the global audio player delegation, so the menu only closes here. + if (event.target.closest('.card-action-play, .card-action-shuffle')) { + closeCardMenus(); + return; + } const deleteItem = event.target.closest('.card-action-delete'); if (!deleteItem) return; @@ -1083,7 +1159,16 @@ await deleteAlbumAsync(card.dataset.albumId); }); + // The favorite heart is a plain button: the global favorites script finds it by its data attributes, hydrates its state and handles its click. + const favoriteToggle = document.createElement('button'); + favoriteToggle.type = 'button'; + favoriteToggle.className = 'card-favorite-toggle'; + favoriteToggle.setAttribute('data-favorite-toggle', ''); + favoriteToggle.setAttribute('data-favorite-media-kind', 'MusicAlbum'); + favoriteToggle.setAttribute('data-favorite-media-item-id', album.id); + card.appendChild(cardLink); + card.appendChild(favoriteToggle); card.appendChild(trigger); card.appendChild(menu); @@ -1237,6 +1322,11 @@ coverImage.dataset.coverPath = storedPath; coverPathLabel.textContent = storedPath ? storedPath : jsLocalizedStrings.noCover; coverPathLabel.title = storedPath; + // The player shows the cover the page displays, so the uploaded cover is handed to the play trigger too. + if (storedPath) + btnPlayArtist.dataset.coverArtPath = storedPath; + else + delete btnPlayArtist.dataset.coverArtPath; }; reader.readAsDataURL(file); notificationService.show(jsLocalizedStrings.coverSaved, NotificationType.SUCCESS); diff --git a/src/Lumina.Presentation.Web/Core/Views/Library/AudioLibrary/MusicLibrary/Tracks/Item.cshtml b/src/Lumina.Presentation.Web/Core/Views/Library/AudioLibrary/MusicLibrary/Tracks/Item.cshtml index 133310d4..5ef63c9f 100644 --- a/src/Lumina.Presentation.Web/Core/Views/Library/AudioLibrary/MusicLibrary/Tracks/Item.cshtml +++ b/src/Lumina.Presentation.Web/Core/Views/Library/AudioLibrary/MusicLibrary/Tracks/Item.cshtml @@ -10,6 +10,9 @@ The audio properties, the release information, the language and original language, the work, the contributors, the ratings, the moods and the ISRCs are all editable, and they are all round-tripped on save. + The track header exposes a play trigger for the global audio player. The player handles the trigger by event + delegation, so this view binds no playback listener; the trigger attribute contract lives in docs/technical/theming/Theming.md. + To change the behavior of the page, edit this script (and the theme template, when present). To restyle the page, edit the theme files. This fallback keeps every feature working without styling, so that a broken theme is obvious to the user while the page still functions. @@ -35,8 +38,10 @@ var libraryId = Model.LibraryId.ToString(); // The cover shown on the left is the cover of the album the track belongs to, passed in by the endpoint. var albumCoverPath = ViewData["AlbumCoverPath"]?.ToString() ?? string.Empty; - // The track DTO does not carry the Id of its artist, so it is taken from the route that rendered the view. - var artistId = Context.Request.RouteValues["artistId"]?.ToString() ?? string.Empty; + var albumTitle = ViewData["AlbumTitle"]?.ToString() ?? string.Empty; + // The track DTO does not carry the Id of its artist, so the endpoint passes the normalized route value it used to load + // the track and its album. Both render paths therefore hand the player the same artist Id. + var artistId = ViewData["ArtistId"]?.ToString() ?? string.Empty; var metadata = Model.Metadata; var work = Model.Work; var releaseInfo = metadata?.ReleaseInfo; @@ -82,6 +87,19 @@
+ +

@_localizer["EditTrack"]

@@ -95,10 +113,10 @@

@_localizer["GeneralInformation"]

- +
-
:
-
+
@_localizer["TrackPath"]:
+
@(Model.Path ?? string.Empty)
@_localizer["TrackPathDescription"]
@@ -793,9 +811,9 @@ } // Builds the payload of the edited track, matching the update request of the API. + // The file system path is not included: a track path is set only by the scanner and can never be edited. function buildPayload() { return { - Path: readValue('track-path') || null, Metadata: { Title: readValue('track-title'), OriginalTitle: readValue('track-original-title') || null, diff --git a/src/Lumina.Presentation.Web/Core/Views/Library/Management/Item.cshtml b/src/Lumina.Presentation.Web/Core/Views/Library/Management/Item.cshtml index e6fd2a7f..32908860 100644 --- a/src/Lumina.Presentation.Web/Core/Views/Library/Management/Item.cshtml +++ b/src/Lumina.Presentation.Web/Core/Views/Library/Management/Item.cshtml @@ -8,6 +8,7 @@ @{ var id = Context.Request.RouteValues["id"] as string; + var shouldTrackConsumptionProgress = Model.ShouldTrackConsumptionProgress ?? false; // Generate a unique id for the scripts section of this view, so it can be dynamically loaded/unloaded by the global AJAX navigator handler. var scriptId = ScriptIdentifierHelper.GenerateScriptId(); } @@ -23,7 +24,7 @@
-
+ @Html.AntiForgeryToken() @@ -204,6 +205,28 @@
@_localizer["DescriptionShouldSkipUnchangedDirectoriesDuringScan"]
+
+
+ : +
+
+ +
+ @_localizer["DescriptionShouldTrackConsumptionProgress"] +
+
+
+ : +
+
+ + +
+ @_localizer["DescriptionCompletionThresholdPercentage"] +