From e56712731fbb56691cf268a2c315d3739b84ad68 Mon Sep 17 00:00:00 2001 From: Binary Alley Date: Mon, 26 Oct 2026 21:10:34 +0200 Subject: [PATCH] Adds documentation for media consumption history, resume points, and statistics --- docs/manual/index.md | 2 + docs/manual/managing-libraries/index.md | 39 +- docs/manual/using-lumina/index.md | 24 + .../music-library/Api.PlayHistory.md | 181 ------ .../statistics/Api.LibraryStatistics.md | 594 ++++++++++++++++++ .../media-consumption/Api.MediaConsumption.md | 10 +- .../architecture-decision-record-0018.md | 125 ++++ docs/technical/domain/UbiquitousLanguage.md | 28 + .../play-history/CompletePlay.http | 8 - .../play-history/GetPlayRecord.http | 2 - .../play-history/ReportPlayProgress.http | 8 - .../music-library/play-history/StartPlay.http | 2 - .../music-library/play-history/StopPlay.http | 8 - .../statistics/ClearConsumptionHistory.http | 7 + .../library/statistics/ClearResumePoints.http | 11 + .../DeleteConsumptionItemHistory.http | 7 + .../statistics/DeleteConsumptionRecord.http | 7 + .../GetAllUsersConsumptionStatistics.http | 3 + .../statistics/GetConsumptionStatistics.http | 7 + .../statistics/GetGenreConsumption.http | 7 + .../library/statistics/GetMostConsumed.http | 7 + .../statistics/GetRecentlyConsumed.http | 7 + .../library/statistics/GetTagConsumption.http | 7 + docs/technical/theming/Theming.md | 34 + src/Lumina.sln | 33 +- 25 files changed, 943 insertions(+), 225 deletions(-) delete mode 100644 docs/technical/api/library/audio-library/music-library/Api.PlayHistory.md create mode 100644 docs/technical/api/library/statistics/Api.LibraryStatistics.md create mode 100644 docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0018.md delete mode 100644 docs/technical/requests/library/audio-library/music-library/play-history/CompletePlay.http delete mode 100644 docs/technical/requests/library/audio-library/music-library/play-history/GetPlayRecord.http delete mode 100644 docs/technical/requests/library/audio-library/music-library/play-history/ReportPlayProgress.http delete mode 100644 docs/technical/requests/library/audio-library/music-library/play-history/StartPlay.http delete mode 100644 docs/technical/requests/library/audio-library/music-library/play-history/StopPlay.http create mode 100644 docs/technical/requests/library/statistics/ClearConsumptionHistory.http create mode 100644 docs/technical/requests/library/statistics/ClearResumePoints.http create mode 100644 docs/technical/requests/library/statistics/DeleteConsumptionItemHistory.http create mode 100644 docs/technical/requests/library/statistics/DeleteConsumptionRecord.http create mode 100644 docs/technical/requests/library/statistics/GetAllUsersConsumptionStatistics.http create mode 100644 docs/technical/requests/library/statistics/GetConsumptionStatistics.http create mode 100644 docs/technical/requests/library/statistics/GetGenreConsumption.http create mode 100644 docs/technical/requests/library/statistics/GetMostConsumed.http create mode 100644 docs/technical/requests/library/statistics/GetRecentlyConsumed.http create mode 100644 docs/technical/requests/library/statistics/GetTagConsumption.http diff --git a/docs/manual/index.md b/docs/manual/index.md index 4da0a1a7..c749cb1b 100644 --- a/docs/manual/index.md +++ b/docs/manual/index.md @@ -38,6 +38,8 @@ Lumina is growing, and this is what works right now: - **Written content.** Add a written content library and Lumina scans it, cataloguing the books and e-books it contains and dressing them up with metadata for browsing in the client. Open one and it renders in the browser through a reader plugin; the EPUB and PDF readers are bundled and can be enabled per library. - **Music.** Add a music library and Lumina indexes the artists, albums and tracks it contains, reading metadata from the tags inside the audio files. If you want more, enable a metadata provider and Lumina fills in the gaps from online sources, and artwork can come from your folders or from remote sources. You can also build your own playlists, order them the way you want and play them in the browser. - **Favorites.** Mark the artists, albums, tracks and books you love as favorites, 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/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 ad6781f5..d47bd33a 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. @@ -75,6 +77,8 @@ The artist page is also where you edit the artist. It lists the artist's albums 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. @@ -105,6 +109,26 @@ The **Favorites** page in the library section lists everything you marked, most 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. 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 applies the changes to Lumina's catalogue. diff --git a/docs/technical/api/library/audio-library/music-library/Api.PlayHistory.md b/docs/technical/api/library/audio-library/music-library/Api.PlayHistory.md deleted file mode 100644 index 7f6c0a3f..00000000 --- a/docs/technical/api/library/audio-library/music-library/Api.PlayHistory.md +++ /dev/null @@ -1,181 +0,0 @@ -# Lumina API - -- [Lumina API](#lumina-api) - - [Play History](#play-history) - - [Start Play](#start-play) - - [Start Play Request](#start-play-request) - - [Start Play Response](#start-play-response) - - [Get Play Record](#get-play-record) - - [Get Play Record Request](#get-play-record-request) - - [Get Play Record Response](#get-play-record-response) - - [Report Play Progress](#report-play-progress) - - [Report Play Progress Request](#report-play-progress-request) - - [Report Play Progress Response](#report-play-progress-response) - - [Complete Play](#complete-play) - - [Complete Play Request](#complete-play-request) - - [Complete Play Response](#complete-play-response) - - [Stop Play](#stop-play) - - [Stop Play Request](#stop-play-request) - - [Stop Play Response](#stop-play-response) - - [Concurrent Reports](#concurrent-reports) - -## Play History - -The play history records what the player played, how far it reached, how long the user listened, and whether the play completed or stopped. It is not a playback session: it stores no queue, current index, repeat or shuffle state, and it never restores playback. A play record belongs to the user that started it, and only that user can read it or report its progress, completion or stop. - -### Start Play - -#### Start Play Request - -```js -POST 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/plays -Authorization: Bearer -``` - -Records the start of a play of the track identified by the route. The library, artist, album and track Ids are taken from the route, so a request cannot substitute them with values from a body. The album and track are checked against the route scope, and the library ownership policy is evaluated, so a play is only recorded for a track of a library the current user can access. The request has no body. - -#### Start Play Response - -```js -200 Ok -``` - -```json -{ - "id": "2c1b0a9f-8e7d-4c6b-5a4f-3e2d1c0b9a8f", - "trackId": "9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f", - "libraryId": "3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a", - "albumId": "e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f", - "artistId": "d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a", - "status": "InProgress", - "lastPositionInSeconds": 0, - "listenedDurationInSeconds": 0, - "startedOnUtc": "2026-10-19T12:00:00.0000000Z", - "endedOnUtc": null, - "updatedOnUtc": null -} -``` - -The returned `id` identifies the play record in the progress, complete, stop and read routes. A track that does not exist, or that does not belong to the route's library, artist and album, is reported as not found with `AlbumNotFound` or `TrackNotFound`. - -### Get Play Record - -#### Get Play Record Request - -```js -GET api/v1/users/me/music-play-history/plays/2c1b0a9f-8e7d-4c6b-5a4f-3e2d1c0b9a8f -Authorization: Bearer -``` - -Returns the play 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 play. - -#### Get Play Record Response - -```js -200 Ok -``` - -```json -{ - "id": "2c1b0a9f-8e7d-4c6b-5a4f-3e2d1c0b9a8f", - "trackId": "9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f", - "libraryId": "3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a", - "albumId": "e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f", - "artistId": "d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a", - "status": "Stopped", - "lastPositionInSeconds": 92.5, - "listenedDurationInSeconds": 92.5, - "startedOnUtc": "2026-10-19T12:00:00.0000000Z", - "endedOnUtc": "2026-10-19T12:01:32.5000000Z", - "updatedOnUtc": "2026-10-19T12:01:32.5000000Z" -} -``` - -The response is private to the authenticated user: it carries `Cache-Control: private, no-store` and `Vary: Authorization`. - -### Report Play Progress - -#### Report Play Progress Request - -```js -PUT api/v1/users/me/music-play-history/plays/2c1b0a9f-8e7d-4c6b-5a4f-3e2d1c0b9a8f/progress -Authorization: Bearer -Content-Type: application/json -``` - -```json -{ - "positionInSeconds": 92.5, - "listenedDurationInSeconds": 92.5 -} -``` - -Reports the last position and the listened duration of an in-progress play of the current user. The listened duration can never decrease. A record of another user, or a record that does not exist, is reported as not found. - -#### Report Play Progress Response - -```js -200 Ok -``` - -The response body is an empty JSON object. - -A play that is no longer in progress is reported as a conflict (`409`) with `PlayIsNotInProgress`. A report that read the play before another report completed or stopped it is also reported as a conflict (`409`), with `ConcurrencyConflict`, instead of reverting the stored state. - -### Complete Play - -#### Complete Play Request - -```js -PUT api/v1/users/me/music-play-history/plays/2c1b0a9f-8e7d-4c6b-5a4f-3e2d1c0b9a8f/complete -Authorization: Bearer -Content-Type: application/json -``` - -```json -{ - "positionInSeconds": 354, - "listenedDurationInSeconds": 354 -} -``` - -Marks an in-progress play of the current user as completed, with the last position and the listened duration of the track. - -#### Complete Play Response - -```js -200 Ok -``` - -The response body is an empty JSON object. A play that is no longer in progress, or that another report changed after this one read it, is reported as a conflict (`409`) with `PlayIsNotInProgress` or `ConcurrencyConflict`. - -### Stop Play - -#### Stop Play Request - -```js -PUT api/v1/users/me/music-play-history/plays/2c1b0a9f-8e7d-4c6b-5a4f-3e2d1c0b9a8f/stop -Authorization: Bearer -Content-Type: application/json -``` - -```json -{ - "positionInSeconds": 92.5, - "listenedDurationInSeconds": 92.5 -} -``` - -Marks an in-progress play of the current user as stopped before the track completed, with the last position and the listened duration the user reached. - -#### Stop Play Response - -```js -200 Ok -``` - -The response body is an empty JSON object. A play that is no longer in progress, or that another report changed after this one read it, is reported as a conflict (`409`) with `PlayIsNotInProgress` or `ConcurrencyConflict`. - -### Concurrent Reports - -Every play record carries an optimistic concurrency version. A progress, complete or stop report reads the stored version, and the update is applied only when the stored version still matches. If another report ended or changed the play 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 play, never clears its end time, and never lowers its listened duration. A busy or locked SQLite write is reported the same way. 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..9158e421 --- /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. A media kind to restrict the history to. `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. | +| `toUtc` | Optional. The inclusive end of the history date range. 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. A media kind to restrict the statistics to. `None` is rejected. | +| `fromUtc` | Optional. The inclusive start of the date range. | +| `toUtc` | Optional. The inclusive end of the date range. 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. 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. + +### 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. + +### 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 | `fromUtc` is after `toUtc`. | + +A value that cannot be bound to the request type, such as a malformed route Id on delete item history or an unknown media kind name on a query filter, is rejected by the framework before these validators run. + +### 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 index 19d690e3..33687bc2 100644 --- a/docs/technical/api/media-consumption/Api.MediaConsumption.md +++ b/docs/technical/api/media-consumption/Api.MediaConsumption.md @@ -33,7 +33,7 @@ ## 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 future catalogues use the same routes without a per-kind endpoint. +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. @@ -64,7 +64,7 @@ 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` today. Numeric values such as `1`, `6` or `0` are rejected, even when they are defined enumeration values. | +| `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. @@ -243,6 +243,8 @@ A session of a non-page-based kind cannot report consecutive pages above zero. A 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 spine sections as pages, because the reader exposes no pagination finer than a section. A PDF page is a section of its own, but a reflowable book can put a whole chapter, or several pages, in one section, so the reported page count approximates the pages a reader saw and the threshold counts sections rather than printed or viewport pages. + #### Report Consumption Progress Response ```js @@ -513,7 +515,7 @@ A missing resume point returns `MediaResumePointNotFound`. A deleted item, or an | `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 today. 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. +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 @@ -562,6 +564,8 @@ A resume point is separate from the history. It is created or updated by progres 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: 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..e43c85c3 --- /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. +- **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 and deletes any user's history, statistics and resume points. 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 through the per-user routes. + +## 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/UbiquitousLanguage.md b/docs/technical/domain/UbiquitousLanguage.md index 35b68173..f3f249c4 100644 --- a/docs/technical/domain/UbiquitousLanguage.md +++ b/docs/technical/domain/UbiquitousLanguage.md @@ -18,6 +18,13 @@ - _**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 @@ -95,6 +102,8 @@ - SheetMusic - Photo - PhotoAlbum +- MediaConsumptionRecord +- MediaResumePoint - User - Playlist - Favorite @@ -118,6 +127,7 @@ - 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) @@ -170,6 +180,14 @@ - StreamInfo - StreamingQuality - UserPreferences +- LibraryConsumptionSettings +- MediaConsumptionRecordId +- MediaResumePointId +- MediaPosition +- MediaConsumptionRule (abstract) +- DurationThresholdConsumptionRule (abstract) +- PageThresholdConsumptionRule (abstract) +- EverySessionConsumptionRule (abstract) - Rating (abstract) - AudioRating - Genre @@ -219,6 +237,10 @@ - PlaylistDeleted - FavoriteAdded - FavoriteRemoved +- MediaConsumptionStarted +- MediaConsumptionProgressed +- MediaConsumptionCompleted +- MediaConsumptionStopped - UserPreferencesChanged - MetadataUpdated - FileTranscoded @@ -237,6 +259,9 @@ - Aggregates: Playlist - Favorites - Aggregates: Favorite +- MediaConsumption + - Aggregates: MediaConsumptionRecord, MediaResumePoint + - Read models: ConsumptionStatistics - ContentDelivery - Aggregates: FileSystemManagement - Services: StreamingService, ContentSynchronizationService @@ -253,6 +278,9 @@ - UserRepository - PlaylistRepository - FavoriteRepository +- MediaConsumptionRecordRepository +- MediaResumePointRepository +- ConsumptionStatisticsRepository - CollectionRepository - FileRepository - StreamRepository diff --git a/docs/technical/requests/library/audio-library/music-library/play-history/CompletePlay.http b/docs/technical/requests/library/audio-library/music-library/play-history/CompletePlay.http deleted file mode 100644 index f79d3634..00000000 --- a/docs/technical/requests/library/audio-library/music-library/play-history/CompletePlay.http +++ /dev/null @@ -1,8 +0,0 @@ -PUT {{host}}/api/v1/users/me/music-play-history/plays/2c1b0a9f-8e7d-4c6b-5a4f-3e2d1c0b9a8f/complete -Authorization: Bearer {{ACCESS_TOKEN}} -Content-Type: application/json - -{ - "positionInSeconds": 354, - "listenedDurationInSeconds": 354 -} diff --git a/docs/technical/requests/library/audio-library/music-library/play-history/GetPlayRecord.http b/docs/technical/requests/library/audio-library/music-library/play-history/GetPlayRecord.http deleted file mode 100644 index b727c700..00000000 --- a/docs/technical/requests/library/audio-library/music-library/play-history/GetPlayRecord.http +++ /dev/null @@ -1,2 +0,0 @@ -GET {{host}}/api/v1/users/me/music-play-history/plays/2c1b0a9f-8e7d-4c6b-5a4f-3e2d1c0b9a8f -Authorization: Bearer {{ACCESS_TOKEN}} diff --git a/docs/technical/requests/library/audio-library/music-library/play-history/ReportPlayProgress.http b/docs/technical/requests/library/audio-library/music-library/play-history/ReportPlayProgress.http deleted file mode 100644 index 0e5ebedc..00000000 --- a/docs/technical/requests/library/audio-library/music-library/play-history/ReportPlayProgress.http +++ /dev/null @@ -1,8 +0,0 @@ -PUT {{host}}/api/v1/users/me/music-play-history/plays/2c1b0a9f-8e7d-4c6b-5a4f-3e2d1c0b9a8f/progress -Authorization: Bearer {{ACCESS_TOKEN}} -Content-Type: application/json - -{ - "positionInSeconds": 92.5, - "listenedDurationInSeconds": 92.5 -} diff --git a/docs/technical/requests/library/audio-library/music-library/play-history/StartPlay.http b/docs/technical/requests/library/audio-library/music-library/play-history/StartPlay.http deleted file mode 100644 index d155969d..00000000 --- a/docs/technical/requests/library/audio-library/music-library/play-history/StartPlay.http +++ /dev/null @@ -1,2 +0,0 @@ -POST {{host}}/api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/albums/e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f/tracks/9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f/plays -Authorization: Bearer {{ACCESS_TOKEN}} diff --git a/docs/technical/requests/library/audio-library/music-library/play-history/StopPlay.http b/docs/technical/requests/library/audio-library/music-library/play-history/StopPlay.http deleted file mode 100644 index 2131b728..00000000 --- a/docs/technical/requests/library/audio-library/music-library/play-history/StopPlay.http +++ /dev/null @@ -1,8 +0,0 @@ -PUT {{host}}/api/v1/users/me/music-play-history/plays/2c1b0a9f-8e7d-4c6b-5a4f-3e2d1c0b9a8f/stop -Authorization: Bearer {{ACCESS_TOKEN}} -Content-Type: application/json - -{ - "positionInSeconds": 92.5, - "listenedDurationInSeconds": 92.5 -} 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/theming/Theming.md b/docs/technical/theming/Theming.md index 46bf2018..1401a625 100644 --- a/docs/technical/theming/Theming.md +++ b/docs/technical/theming/Theming.md @@ -23,6 +23,7 @@ The web client of Lumina is a themed shell: every page is rendered inside the te - [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) @@ -177,6 +178,7 @@ Known page keys: | `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. | @@ -612,6 +614,38 @@ The fallback view keeps these element hooks, which the application script drives 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. diff --git a/src/Lumina.sln b/src/Lumina.sln index c2b55fd7..a43c8b01 100644 --- a/src/Lumina.sln +++ b/src/Lumina.sln @@ -106,7 +106,6 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "music-library", "music-libr ProjectSection(SolutionItems) = preProject ..\docs\technical\api\library\audio-library\music-library\Api.Albums.md = ..\docs\technical\api\library\audio-library\music-library\Api.Albums.md ..\docs\technical\api\library\audio-library\music-library\Api.Artists.md = ..\docs\technical\api\library\audio-library\music-library\Api.Artists.md - ..\docs\technical\api\library\audio-library\music-library\Api.PlayHistory.md = ..\docs\technical\api\library\audio-library\music-library\Api.PlayHistory.md ..\docs\technical\api\library\audio-library\music-library\Api.Tracks.md = ..\docs\technical\api\library\audio-library\music-library\Api.Tracks.md EndProjectSection EndProject @@ -115,6 +114,11 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "management", "management", ..\docs\technical\api\library\management\Api.Libraries.md = ..\docs\technical\api\library\management\Api.Libraries.md EndProjectSection EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "statistics", "statistics", "{57C34ED6-E399-4442-ACBE-DBB5E06174D4}" + ProjectSection(SolutionItems) = preProject + ..\docs\technical\api\library\statistics\Api.LibraryStatistics.md = ..\docs\technical\api\library\statistics\Api.LibraryStatistics.md + EndProjectSection +EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "written-content-library", "written-content-library", "{2293B76C-F1EB-46A9-8F67-E88BAEA4FC0C}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "book-library", "book-library", "{52264424-9A8F-4E12-9A14-87F306C595C7}" @@ -189,6 +193,7 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "architecture-decision-log", ..\docs\technical\architecture\architecture-knowledge-management\architecture-decision-log\architecture-decision-record-0015.md = ..\docs\technical\architecture\architecture-knowledge-management\architecture-decision-log\architecture-decision-record-0015.md ..\docs\technical\architecture\architecture-knowledge-management\architecture-decision-log\architecture-decision-record-0016.md = ..\docs\technical\architecture\architecture-knowledge-management\architecture-decision-log\architecture-decision-record-0016.md ..\docs\technical\architecture\architecture-knowledge-management\architecture-decision-log\architecture-decision-record-0017.md = ..\docs\technical\architecture\architecture-knowledge-management\architecture-decision-log\architecture-decision-record-0017.md + ..\docs\technical\architecture\architecture-knowledge-management\architecture-decision-log\architecture-decision-record-0018.md = ..\docs\technical\architecture\architecture-knowledge-management\architecture-decision-log\architecture-decision-record-0018.md EndProjectSection EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "domain", "domain", "{3EE8EFDF-4D55-4EA3-BEE2-74D00CB50570}" @@ -324,15 +329,6 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "tracks", "tracks", "{B1B657 ..\docs\technical\requests\library\audio-library\music-library\tracks\UpdateTrack.http = ..\docs\technical\requests\library\audio-library\music-library\tracks\UpdateTrack.http EndProjectSection EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "play-history", "play-history", "{9402C854-E845-4F86-BECB-F708E0C7CB2E}" - ProjectSection(SolutionItems) = preProject - ..\docs\technical\requests\library\audio-library\music-library\play-history\CompletePlay.http = ..\docs\technical\requests\library\audio-library\music-library\play-history\CompletePlay.http - ..\docs\technical\requests\library\audio-library\music-library\play-history\GetPlayRecord.http = ..\docs\technical\requests\library\audio-library\music-library\play-history\GetPlayRecord.http - ..\docs\technical\requests\library\audio-library\music-library\play-history\ReportPlayProgress.http = ..\docs\technical\requests\library\audio-library\music-library\play-history\ReportPlayProgress.http - ..\docs\technical\requests\library\audio-library\music-library\play-history\StartPlay.http = ..\docs\technical\requests\library\audio-library\music-library\play-history\StartPlay.http - ..\docs\technical\requests\library\audio-library\music-library\play-history\StopPlay.http = ..\docs\technical\requests\library\audio-library\music-library\play-history\StopPlay.http - EndProjectSection -EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "management", "management", "{FDED0D4B-3FB6-42CA-AC73-76038F9DDF5E}" ProjectSection(SolutionItems) = preProject ..\docs\technical\requests\library\management\AddLibrary.http = ..\docs\technical\requests\library\management\AddLibrary.http @@ -350,6 +346,20 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "management", "management", ..\docs\technical\requests\library\management\UpdateLibrary.http = ..\docs\technical\requests\library\management\UpdateLibrary.http EndProjectSection EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "statistics", "statistics", "{B715DF5A-2F47-4CAA-94F9-DB7B9F2F1D99}" + ProjectSection(SolutionItems) = preProject + ..\docs\technical\requests\library\statistics\ClearConsumptionHistory.http = ..\docs\technical\requests\library\statistics\ClearConsumptionHistory.http + ..\docs\technical\requests\library\statistics\ClearResumePoints.http = ..\docs\technical\requests\library\statistics\ClearResumePoints.http + ..\docs\technical\requests\library\statistics\DeleteConsumptionItemHistory.http = ..\docs\technical\requests\library\statistics\DeleteConsumptionItemHistory.http + ..\docs\technical\requests\library\statistics\DeleteConsumptionRecord.http = ..\docs\technical\requests\library\statistics\DeleteConsumptionRecord.http + ..\docs\technical\requests\library\statistics\GetAllUsersConsumptionStatistics.http = ..\docs\technical\requests\library\statistics\GetAllUsersConsumptionStatistics.http + ..\docs\technical\requests\library\statistics\GetConsumptionStatistics.http = ..\docs\technical\requests\library\statistics\GetConsumptionStatistics.http + ..\docs\technical\requests\library\statistics\GetGenreConsumption.http = ..\docs\technical\requests\library\statistics\GetGenreConsumption.http + ..\docs\technical\requests\library\statistics\GetMostConsumed.http = ..\docs\technical\requests\library\statistics\GetMostConsumed.http + ..\docs\technical\requests\library\statistics\GetRecentlyConsumed.http = ..\docs\technical\requests\library\statistics\GetRecentlyConsumed.http + ..\docs\technical\requests\library\statistics\GetTagConsumption.http = ..\docs\technical\requests\library\statistics\GetTagConsumption.http + EndProjectSection +EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "written-content-library", "written-content-library", "{61824D19-B08C-45C6-95F8-716B5FDA183C}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "book-library", "book-library", "{0C975F46-8A47-48EC-91A0-2B222032C043}" @@ -1456,8 +1466,9 @@ Global {B4DF8E8D-C245-4E7C-B85B-B52935EDA93B} = {A65199DD-543E-4C18-A16A-215BD34962A5} {F3818697-E304-491D-8BF3-4DAA1733B5F5} = {A65199DD-543E-4C18-A16A-215BD34962A5} {B1B657B1-60DC-4E22-89D2-6212154D6BA8} = {A65199DD-543E-4C18-A16A-215BD34962A5} - {9402C854-E845-4F86-BECB-F708E0C7CB2E} = {A65199DD-543E-4C18-A16A-215BD34962A5} {FDED0D4B-3FB6-42CA-AC73-76038F9DDF5E} = {38048ADA-6830-4575-BDA6-C6D77E6D3E09} + {57C34ED6-E399-4442-ACBE-DBB5E06174D4} = {6A5D3BED-AE4A-4D26-B12A-5DE996152A64} + {B715DF5A-2F47-4CAA-94F9-DB7B9F2F1D99} = {38048ADA-6830-4575-BDA6-C6D77E6D3E09} {61824D19-B08C-45C6-95F8-716B5FDA183C} = {38048ADA-6830-4575-BDA6-C6D77E6D3E09} {0C975F46-8A47-48EC-91A0-2B222032C043} = {61824D19-B08C-45C6-95F8-716B5FDA183C} {299D6BD8-A7AC-4913-AA0C-EE0A7AAF5B9A} = {0C975F46-8A47-48EC-91A0-2B222032C043}