Fixes media consumption tracking, statistics, and reader page counting

This commit is contained in:
BinaryAlley committed 2026-10-26 22:04:28 +02:00
1 parent e56712731f
commit 02bcf91661
40 files changed
+298 -168

No files matched your search

@@ -128,7 +128,7 @@ public class GetGenreConsumptionQueryHandler : IQueryHandler<GetGenreConsumption
Dictionary<(MediaKind MediaKind, Guid MediaItemId, Guid LibraryId), List<string>> genreNamesByItem = [];
foreach (TrackEntity track in tracks)
{
List<string> itemGenres = [.. track.Genres.Select(genre => genre.Name).OfType<string>()];
List<string> itemGenres = GetTrackGenreNames(track);
if (itemGenres.Count > 0)
genreNamesByItem[(MediaKind.MusicTrack, track.Id, track.LibraryId)] = itemGenres;
}
@@ -181,6 +181,21 @@ public class GetGenreConsumptionQueryHandler : IQueryHandler<GetGenreConsumption
return Result.From(genreConsumptions.ToResponses());
}
/// <summary>
/// Gets the genre names of <paramref name="track"/>, falling back to the genres of its album and then its artist.
/// </summary>
/// <param name="track">The track whose genres are resolved.</param>
/// <returns>The genre names of the track, its album, or its artist, in the first level that has any.</returns>
private static List<string> GetTrackGenreNames(TrackEntity track)
{
List<string> genreNames = [.. track.Genres.Select(genre => genre.Name).OfType<string>()];
if (genreNames.Count == 0 && track.Album is not null)
genreNames = [.. track.Album.Genres.Select(genre => genre.Name).OfType<string>()];
if (genreNames.Count == 0 && track.Album is not null && track.Album.Artist is not null)
genreNames = [.. track.Album.Artist.Genres.Select(genre => genre.Name).OfType<string>()];
return genreNames;
}
/// <summary>
/// Adds the lowercase <paramref name="names"/> of one item to the accumulated <paramref name="genres"/>.
/// </summary>
@@ -2,6 +2,7 @@
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.DataAccess.Entities.MediaConsumption;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Infrastructure.Authentication;
@@ -89,6 +90,25 @@ public class GetResumePointQueryHandler : IQueryHandler<GetResumePointQuery, Res
if (getResumePointResult.Value is null)
return DomainErrors.MediaConsumption.MediaResumePointNotFound;
// A resume point stored before progress tracking was turned off must not be served, because the library no longer remembers positions.
// It is deleted as stale data, so turning tracking on again starts from a fresh position instead of an old one.
Result<LibraryEntity?> getLibraryResult = await _unitOfWork.LibraryRepository
.GetByIdAsync(getResumePointResult.Value.LibraryId, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false);
if (getLibraryResult.IsFailure)
return getLibraryResult.Errors;
if (getLibraryResult.Value is not null && !getLibraryResult.Value.ShouldTrackConsumptionProgress)
{
Result<Deleted> deleteStaleResumePointResult = await _unitOfWork.MediaResumePointRepository.DeleteForUserAndMediaItemAsync(userId, mediaKind, mediaItemId, cancellationToken).ConfigureAwait(false);
if (deleteStaleResumePointResult.IsFailure)
return deleteStaleResumePointResult.Errors;
Result<Success> saveStaleResumePointDeletionResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
// A concurrent deletion of the same stale resume point is the desired outcome, so only other persistence failures are returned.
if (saveStaleResumePointDeletionResult.IsFailure &&
!saveStaleResumePointDeletionResult.Errors.Any(error => error == ApplicationErrors.Persistence.ConcurrencyConflict))
return saveStaleResumePointDeletionResult.Errors;
return DomainErrors.MediaConsumption.MediaResumePointNotFound;
}
// The media item must still exist in the library the resume point was recorded in. A resume point whose item was deleted, or whose item no
// longer belongs to that library, is an orphan, so it is removed before the same not-found result as a missing item is returned.
if (mediaKind == MediaKind.MusicTrack)
@@ -128,7 +128,7 @@ public class GetTagConsumptionQueryHandler : IQueryHandler<GetTagConsumptionQuer
Dictionary<(MediaKind MediaKind, Guid MediaItemId, Guid LibraryId), List<string>> tagNamesByItem = [];
foreach (TrackEntity track in tracks)
{
List<string> itemTags = [.. track.Tags.Select(tag => tag.Name).OfType<string>()];
List<string> itemTags = GetTrackTagNames(track);
if (itemTags.Count > 0)
tagNamesByItem[(MediaKind.MusicTrack, track.Id, track.LibraryId)] = itemTags;
}
@@ -181,6 +181,21 @@ public class GetTagConsumptionQueryHandler : IQueryHandler<GetTagConsumptionQuer
return Result.From(tagConsumptions.ToResponses());
}
/// <summary>
/// Gets the tag names of <paramref name="track"/>, falling back to the tags of its album and then its artist.
/// </summary>
/// <param name="track">The track whose tags are resolved.</param>
/// <returns>The tag names of the track, its album, or its artist, in the first level that has any.</returns>
private static List<string> GetTrackTagNames(TrackEntity track)
{
List<string> tagNames = [.. track.Tags.Select(tag => tag.Name).OfType<string>()];
if (tagNames.Count == 0 && track.Album is not null)
tagNames = [.. track.Album.Tags.Select(tag => tag.Name).OfType<string>()];
if (tagNames.Count == 0 && track.Album is not null && track.Album.Artist is not null)
tagNames = [.. track.Album.Artist.Tags.Select(tag => tag.Name).OfType<string>()];
return tagNames;
}
/// <summary>
/// Adds the lowercase <paramref name="names"/> of one item to the accumulated <paramref name="tags"/>.
/// </summary>
@@ -578,7 +578,15 @@ internal sealed class TrackRepository : ITrackRepository
{
query = query
.Include(track => track.Album)
.ThenInclude(album => album!.Artist)
.ThenInclude(album => album!.Tags)
.Include(track => track.Album)
.ThenInclude(album => album!.Genres)
.Include(track => track.Album)
.ThenInclude(album => album!.Artist)
.ThenInclude(artist => artist!.Tags)
.Include(track => track.Album)
.ThenInclude(album => album!.Artist)
.ThenInclude(artist => artist!.Genres)
.Include(track => track.Ratings)
.Include(track => track.Tags)
.Include(track => track.Genres)
@@ -1111,7 +1111,7 @@
<value>تنسيق معرف MusicBrainz غير صالح!</value>
</data>
<data name="NoReaderAvailable" xml:space="preserve">
<value>لا يوجد قارئ متاح لهذا الكتاب!</value>
<value>لا يوجد قارئ كتب متاح لهذا الكتاب!</value>
</data>
<data name="NoSupportedPlaybackFormat" xml:space="preserve">
<value>لم يتم العثور على تنسيق تشغيل مدعوم!</value>
@@ -1198,7 +1198,7 @@
<value>نوع قائمة التشغيل غير صالح!</value>
</data>
<data name="ReaderDisabled" xml:space="preserve">
<value>تم تعطيل القارئ لهذه المكتبة!</value>
<value>قارئ الكتب معطل لهذه المكتبة!</value>
</data>
<data name="ResourceKeyCannotBeEmpty" xml:space="preserve">
<value>لا يمكن أن يكون مفتاح المورد فارغًا!</value>
@@ -1111,7 +1111,7 @@
<value>Das MusicBrainz-Id-Format ist ungültig!</value>
</data>
<data name="NoReaderAvailable" xml:space="preserve">
<value>Für dieses Buch ist kein Reader verfügbar!</value>
<value>Für dieses Buch ist kein Buchleser verfügbar!</value>
</data>
<data name="NoSupportedPlaybackFormat" xml:space="preserve">
<value>Es wurde kein unterstütztes Wiedergabeformat gefunden!</value>
@@ -1198,7 +1198,7 @@
<value>Der Wiedergabelistentyp ist ungültig!</value>
</data>
<data name="ReaderDisabled" xml:space="preserve">
<value>Der Reader ist für diese Bibliothek deaktiviert!</value>
<value>Der Buchleser, der dieses Buch öffnet, ist für diese Bibliothek deaktiviert!</value>
</data>
<data name="ResourceKeyCannotBeEmpty" xml:space="preserve">
<value>Der Ressourcenschlüssel darf nicht leer sein!</value>
@@ -1111,7 +1111,7 @@
<value>¡El formato de ID de MusicBrainz no es válido!</value>
</data>
<data name="NoReaderAvailable" xml:space="preserve">
<value>¡No hay lectores disponibles para este libro!</value>
<value>¡No hay ningún lector de libros disponible para este libro!</value>
</data>
<data name="NoSupportedPlaybackFormat" xml:space="preserve">
<value>¡No se encontró ningún formato de reproducción compatible!</value>
@@ -1198,7 +1198,7 @@
<value>¡El tipo de lista de reproducción no es válido!</value>
</data>
<data name="ReaderDisabled" xml:space="preserve">
<value>¡El lector está deshabilitado para esta biblioteca!</value>
<value>¡El lector de libros está deshabilitado para esta biblioteca!</value>
</data>
<data name="ResourceKeyCannotBeEmpty" xml:space="preserve">
<value>¡La clave de recurso no puede estar vacía!</value>
@@ -1111,7 +1111,7 @@
<value>Le format MusicBrainz Id n’est pas valide !</value>
</data>
<data name="NoReaderAvailable" xml:space="preserve">
<value>Aucun lecteur n'est disponible pour ce livre !</value>
<value>Aucun lecteur de livres n'est disponible pour ce livre !</value>
</data>
<data name="NoSupportedPlaybackFormat" xml:space="preserve">
<value>Aucun format de lecture pris en charge n'a été trouvé !</value>
@@ -1150,7 +1150,7 @@
<value>Une partie valeur du modèle de chemin doit contenir exactement un espace réservé !</value>
</data>
<data name="PermissionNotFound" xml:space="preserve">
<value>L'autorisation n'a pas été trouvée !</value>
<value>La permission n'a pas été trouvée !</value>
</data>
<data name="PlaybackDeliveryChanged" xml:space="preserve">
<value>La diffusion de la lecture a changé !</value>
@@ -1198,7 +1198,7 @@
<value>Le type de liste de lecture est invalide !</value>
</data>
<data name="ReaderDisabled" xml:space="preserve">
<value>Le lecteur est désactivé pour cette bibliothèque !</value>
<value>Le lecteur de livres est désactivé pour cette bibliothèque !</value>
</data>
<data name="ResourceKeyCannotBeEmpty" xml:space="preserve">
<value>La clé de ressource ne peut pas être vide !</value>
@@ -1111,7 +1111,7 @@
<value>Il formato dell'ID MusicBrainz non è valido!</value>
</data>
<data name="NoReaderAvailable" xml:space="preserve">
<value>Nessun lettore disponibile per questo libro!</value>
<value>Nessun lettore di libri disponibile per questo libro!</value>
</data>
<data name="NoSupportedPlaybackFormat" xml:space="preserve">
<value>Non è stato trovato alcun formato di riproduzione supportato!</value>
@@ -1198,7 +1198,7 @@
<value>Il tipo di playlist non è valido!</value>
</data>
<data name="ReaderDisabled" xml:space="preserve">
<value>Il lettore è disabilitato per questa libreria!</value>
<value>Il lettore di libri è disabilitato per questa libreria!</value>
</data>
<data name="ResourceKeyCannotBeEmpty" xml:space="preserve">
<value>La chiave della risorsa non può essere vuota!</value>
@@ -217,22 +217,22 @@
<value>完了したスキャンジョブ数は正の値でなければなりません!</value>
</data>
<data name="ContributorDisplayNameCannotBeEmpty" xml:space="preserve">
<value>出演者の表示名を空にすることはできません!</value>
<value>寄稿者の表示名を空にすることはできません。</value>
</data>
<data name="ContributorDisplayNameMustBeMaximum100CharactersLong" xml:space="preserve">
<value>出演者の表示名は最大100文字までです!</value>
<value>寄稿者の表示名は最大100文字までです!</value>
</data>
<data name="ContributorLegalNameMustBeMaximum100CharactersLong" xml:space="preserve">
<value>出演者の本名は最大100文字までです!</value>
<value>寄稿者の本名は最大100文字までです!</value>
</data>
<data name="ContributorNameCannotBeEmpty" xml:space="preserve">
<value>出演者名を空にすることはできません!</value>
<value>寄稿者名を空にすることはできません。</value>
</data>
<data name="ContributorRoleCannotBeNull" xml:space="preserve">
<value>出演者の役割をnullにすることはできません!</value>
<value>寄稿者の役割をnullにすることはできません。</value>
</data>
<data name="ContributorsListCannotBeNull" xml:space="preserve">
<value>出演者リストをnullにすることはできません!</value>
<value>寄稿者リストをnullにすることはできません。</value>
</data>
<data name="CorsOriginIsInvalid" xml:space="preserve">
<value>CORSオリジンが無効です!</value>
@@ -1090,7 +1090,7 @@
<value>メディア寄稿者名を空にすることはできません。</value>
</data>
<data name="MediaContributorRoleNameCannotBeEmpty" xml:space="preserve">
<value>メディア投稿者のロール名を空にすることはできません。</value>
<value>メディア寄稿者のロール名を空にすることはできません。</value>
</data>
<data name="MediaItemIdCannotBeEmpty" xml:space="preserve">
<value>メディア項目 Idは空にできません。</value>
@@ -1111,7 +1111,7 @@
<value>MusicBrainz ID の形式が無効です。</value>
</data>
<data name="NoReaderAvailable" xml:space="preserve">
<value>この本にはリーダーがいません!</value>
<value>この本の形式を開けるブックリーダーがありません。</value>
</data>
<data name="NoSupportedPlaybackFormat" xml:space="preserve">
<value>サポートされている再生フォーマットが見つかりませんでした。</value>
@@ -1123,7 +1123,7 @@
<value>トラックの正規化に失敗しました!</value>
</data>
<data name="NormalizationIsNotRequiredForDirectPlay" xml:space="preserve">
<value>直接再生する場合はノーマライズは必要ありません。</value>
<value>直接再生する場合は正規化は必要ありません。</value>
</data>
<data name="NormalizationTimedOut" xml:space="preserve">
<value>トラックの正規化がタイムアウトになりました。</value>
@@ -1150,7 +1150,7 @@
<value>パス テンプレートの値部分には、プレースホルダーを 1 つだけ含める必要があります。</value>
</data>
<data name="PermissionNotFound" xml:space="preserve">
<value>許可が見つかりませんでした!</value>
<value>権限が見つかりませんでした。</value>
</data>
<data name="PlaybackDeliveryChanged" xml:space="preserve">
<value>再生配信が変わりました!</value>
@@ -1198,7 +1198,7 @@
<value>プレイリストのタイプが無効です。</value>
</data>
<data name="ReaderDisabled" xml:space="preserve">
<value>このライブラリではリーダーが無効になっています。</value>
<value>この本を開くブックリーダーは、このライブラリで無効になっています。ライブラリ設定で有効にすると本を読めます。</value>
</data>
<data name="ResourceKeyCannotBeEmpty" xml:space="preserve">
<value>リソース キーを空にすることはできません。</value>
@@ -844,10 +844,10 @@
<value>Calitatea fluxului nu poate fi nulă!</value>
</data>
<data name="ShuffleTrackCountMustBeGreaterThanZero" xml:space="preserve">
<value>Numărul de piste pentru redare aleatorie trebuie să fie mai mare decât zero!</value>
<value>Numărul de piese pentru redare aleatorie trebuie să fie mai mare decât zero!</value>
</data>
<data name="ShuffleTrackCountMustBeAtMost500" xml:space="preserve">
<value>Numărul de piste pentru redare aleatorie nu poate depăși 500!</value>
<value>Numărul de piese pentru redare aleatorie nu poate depăși 500!</value>
</data>
<data name="VuMeterReleasePerSecondCannotBeNull" xml:space="preserve">
<value>Scăderea vumetrului nu poate fi nulă!</value>
@@ -1111,7 +1111,7 @@
<value>Formatul MusicBrainz Id este nevalid!</value>
</data>
<data name="NoReaderAvailable" xml:space="preserve">
<value>Niciun cititor nu este disponibil pentru această carte!</value>
<value>Niciun cititor de cărți nu este disponibil pentru această carte!</value>
</data>
<data name="NoSupportedPlaybackFormat" xml:space="preserve">
<value>Nu a fost găsit niciun format de redare acceptat!</value>
@@ -1120,13 +1120,13 @@
<value>Limita cache-ului de normalizare a fost depășită!</value>
</data>
<data name="NormalizationFailed" xml:space="preserve">
<value>Normalizarea pistei a eșuat!</value>
<value>Normalizarea piesei a eșuat!</value>
</data>
<data name="NormalizationIsNotRequiredForDirectPlay" xml:space="preserve">
<value>Normalizarea nu este necesară pentru redarea directă!</value>
</data>
<data name="NormalizationTimedOut" xml:space="preserve">
<value>Normalizarea pistei a expirat!</value>
<value>Normalizarea piesei a expirat!</value>
</data>
<data name="NormalizationUnavailable" xml:space="preserve">
<value>Normalizarea piesei este indisponibilă momentan!</value>
@@ -1198,7 +1198,7 @@
<value>Tipul playlistului este nevalid!</value>
</data>
<data name="ReaderDisabled" xml:space="preserve">
<value>Cititorul este dezactivat pentru această bibliotecă!</value>
<value>Cititorul de cărți este dezactivat pentru această bibliotecă!</value>
</data>
<data name="ResourceKeyCannotBeEmpty" xml:space="preserve">
<value>Cheia de resurse nu poate fi goală!</value>
@@ -1249,7 +1249,7 @@
<value>Piesa există deja!</value>
</data>
<data name="TrackDurationMustBePositive" xml:space="preserve">
<value>Durata pistei trebuie să fie pozitivă!</value>
<value>Durata piesei trebuie să fie pozitivă!</value>
</data>
<data name="TrackFileNotFound" xml:space="preserve">
<value>Fișierul piesei nu a fost găsit!</value>
@@ -1264,13 +1264,13 @@
<value>Numărul piesei trebuie să fie mai mare decât zero!</value>
</data>
<data name="TrackPathCannotBeEmpty" xml:space="preserve">
<value>Calea pistei nu poate fi goală!</value>
<value>Calea piesei nu poate fi goală!</value>
</data>
<data name="TrackPathMustBeMaximum2048CharactersLong" xml:space="preserve">
<value>Calea pistei trebuie să aibă maximum 2048 de caractere!</value>
<value>Calea piesei trebuie să aibă maximum 2048 de caractere!</value>
</data>
<data name="TrackPathMustBeWithinLibraryContentLocations" xml:space="preserve">
<value>Calea pistei trebuie să fie în interiorul uneia dintre locațiile conținutului bibliotecii!</value>
<value>Calea piesei trebuie să fie în interiorul uneia dintre locațiile conținutului bibliotecii!</value>
</data>
<data name="TracksListCannotBeNull" xml:space="preserve">
<value>Lista de piese nu poate fi nulă!</value>
@@ -934,7 +934,7 @@
<value>Псевдонім виконавця має містити максимум 255 символів!</value>
</data>
<data name="ArtistAlreadyExists" xml:space="preserve">
<value>Артист вже є!</value>
<value>Виконавець уже існує!</value>
</data>
<data name="ArtistIdCannotBeEmpty" xml:space="preserve">
<value>Ідентифікатор виконавця не може бути порожнім!</value>
@@ -949,7 +949,7 @@
<value>Ім'я виконавця має містити максимум 255 символів!</value>
</data>
<data name="ArtistNotFound" xml:space="preserve">
<value>Художника не знайшли!</value>
<value>Виконавця не знайдено!</value>
</data>
<data name="ArtistWebsiteMustBeMaximum2048CharactersLong" xml:space="preserve">
<value>Веб-сайт виконавця має містити максимум 2048 символів!</value>
@@ -1111,7 +1111,7 @@
<value>Формат ідентифікатора MusicBrainz недійсний!</value>
</data>
<data name="NoReaderAvailable" xml:space="preserve">
<value>Немає читача для цієї книги!</value>
<value>Немає читача книг для цієї книги!</value>
</data>
<data name="NoSupportedPlaybackFormat" xml:space="preserve">
<value>Не знайдено жодного підтримуваного формату відтворення!</value>
@@ -1198,7 +1198,7 @@
<value>Тип списку відтворення недійсний!</value>
</data>
<data name="ReaderDisabled" xml:space="preserve">
<value>Читач вимкнено для цієї бібліотеки!</value>
<value>Читач книг вимкнено для цієї бібліотеки!</value>
</data>
<data name="ResourceKeyCannotBeEmpty" xml:space="preserve">
<value>Ключ ресурсу не може бути порожнім!</value>
@@ -217,22 +217,22 @@
<value>已完成扫描任务数量必须为正数!</value>
</data>
<data name="ContributorDisplayNameCannotBeEmpty" xml:space="preserve">
<value>参与者显示名称不能为空!</value>
<value>贡献者显示名称不能为空!</value>
</data>
<data name="ContributorDisplayNameMustBeMaximum100CharactersLong" xml:space="preserve">
<value>参与者显示名称最多只能有100个字符!</value>
<value>贡献者显示名称最多只能有100个字符!</value>
</data>
<data name="ContributorLegalNameMustBeMaximum100CharactersLong" xml:space="preserve">
<value>参与者法定姓名最多只能有100个字符!</value>
<value>贡献者法定姓名最多只能有100个字符!</value>
</data>
<data name="ContributorNameCannotBeEmpty" xml:space="preserve">
<value>参与者姓名不能为空!</value>
<value>贡献者姓名不能为空!</value>
</data>
<data name="ContributorRoleCannotBeNull" xml:space="preserve">
<value>参与者角色不能为空!</value>
<value>贡献者角色不能为空!</value>
</data>
<data name="ContributorsListCannotBeNull" xml:space="preserve">
<value>参与者列表不能为空!</value>
<value>贡献者列表不能为空!</value>
</data>
<data name="CorsOriginIsInvalid" xml:space="preserve">
<value>CORS来源无效!</value>
@@ -907,7 +907,7 @@
<value>该专辑已经存在!</value>
</data>
<data name="AlbumIdCannotBeEmpty" xml:space="preserve">
<value>相册ID不能为空!</value>
<value>专辑ID不能为空!</value>
</data>
<data name="AlbumNotFound" xml:space="preserve">
<value>找不到专辑!</value>
@@ -1024,25 +1024,25 @@
<value>已结束的消费必须有结束时间!</value>
</data>
<data name="FavoriteAlreadyExists" xml:space="preserve">
<value>最喜欢的已经存在了!</value>
<value>收藏已存在!</value>
</data>
<data name="FavoriteMediaItemIdCannotBeEmpty" xml:space="preserve">
<value>收藏的媒体项 ID 不能为空!</value>
</data>
<data name="FavoriteMediaItemIdsCannotBeEmpty" xml:space="preserve">
<value>最喜欢的媒体项目 ID 列表不能为空!</value>
<value>收藏的媒体项 ID 列表不能为空!</value>
</data>
<data name="FavoriteMediaItemIdsExceedMaximumCount" xml:space="preserve">
<value>最喜欢的媒体项目 ID 列表超出了最大计数!</value>
<value>收藏的媒体项 ID 列表超出最大数量!</value>
</data>
<data name="FavoriteMediaKindIsInvalid" xml:space="preserve">
<value>最喜欢的媒体类型无效!</value>
<value>收藏的媒体类型无效!</value>
</data>
<data name="FavoriteMediaKindIsNotSupported" xml:space="preserve">
<value>不支持最喜欢的媒体类型!</value>
<value>不支持收藏的媒体类型!</value>
</data>
<data name="FavoriteNotFound" xml:space="preserve">
<value>没有找到最喜欢的!</value>
<value>找不到收藏!</value>
</data>
<data name="FileTooLarge" xml:space="preserve">
<value>文件太大!</value>
@@ -1084,13 +1084,13 @@
<value>位置参考不能为空!</value>
</data>
<data name="MediaContributorAlreadyExists" xml:space="preserve">
<value>媒体投稿人已经存在!</value>
<value>媒体贡献者已存在!</value>
</data>
<data name="MediaContributorNameCannotBeEmpty" xml:space="preserve">
<value>媒体投稿人姓名不能为空!</value>
<value>媒体贡献者名称不能为空!</value>
</data>
<data name="MediaContributorRoleNameCannotBeEmpty" xml:space="preserve">
<value>媒体投稿人角色名称不能为空!</value>
<value>媒体贡献者角色名称不能为空!</value>
</data>
<data name="MediaItemIdCannotBeEmpty" xml:space="preserve">
<value>媒体项 Id不能为空!</value>
@@ -1111,7 +1111,7 @@
<value>MusicBrainz Id 格式无效!</value>
</data>
<data name="NoReaderAvailable" xml:space="preserve">
<value>没有读者可以阅读这本书!</value>
<value>没有可用的图书阅读器能够打开此图书。</value>
</data>
<data name="NoSupportedPlaybackFormat" xml:space="preserve">
<value>未找到支持的播放格式!</value>
@@ -1123,7 +1123,7 @@
<value>曲目规范化失败!</value>
</data>
<data name="NormalizationIsNotRequiredForDirectPlay" xml:space="preserve">
<value>直接播放不需要标准化!</value>
<value>直接播放不需要规范化!</value>
</data>
<data name="NormalizationTimedOut" xml:space="preserve">
<value>曲目规范化超时!</value>
@@ -1198,7 +1198,7 @@
<value>播放列表类型无效!</value>
</data>
<data name="ReaderDisabled" xml:space="preserve">
<value>该库的读者已被禁用!</value>
<value>打开此图书的图书阅读器已在此媒体库中禁用。在媒体库设置中启用它即可阅读该图书。</value>
</data>
<data name="ResourceKeyCannotBeEmpty" xml:space="preserve">
<value>资源键不能为空!</value>
@@ -294,9 +294,6 @@
<data name="Yes" xml:space="preserve">
<value>نعم</value>
</data>
<data name="YouTube" xml:space="preserve">
<value>يوتيوب</value>
</data>
<data name="Youtube" xml:space="preserve">
<value>YouTube</value>
</data>
@@ -294,9 +294,6 @@
<data name="Yes" xml:space="preserve">
<value>Ja</value>
</data>
<data name="YouTube" xml:space="preserve">
<value>YouTube</value>
</data>
<data name="Youtube" xml:space="preserve">
<value>YouTube</value>
</data>
@@ -294,9 +294,6 @@
<data name="Yes" xml:space="preserve">
<value>Yes</value>
</data>
<data name="YouTube" xml:space="preserve">
<value>YouTube</value>
</data>
<data name="Youtube" xml:space="preserve">
<value>YouTube</value>
</data>
@@ -294,9 +294,6 @@
<data name="Yes" xml:space="preserve">
<value>Sí</value>
</data>
<data name="YouTube" xml:space="preserve">
<value>YouTube</value>
</data>
<data name="Youtube" xml:space="preserve">
<value>YouTube</value>
</data>
@@ -294,9 +294,6 @@
<data name="Yes" xml:space="preserve">
<value>Oui</value>
</data>
<data name="YouTube" xml:space="preserve">
<value>YouTube</value>
</data>
<data name="Youtube" xml:space="preserve">
<value>YouTube</value>
</data>
@@ -294,9 +294,6 @@
<data name="Yes" xml:space="preserve">
<value>Sì</value>
</data>
<data name="YouTube" xml:space="preserve">
<value>YouTube</value>
</data>
<data name="Youtube" xml:space="preserve">
<value>YouTube</value>
</data>
@@ -294,9 +294,6 @@
<data name="Yes" xml:space="preserve">
<value>はい</value>
</data>
<data name="YouTube" xml:space="preserve">
<value>ユーチューブ</value>
</data>
<data name="Youtube" xml:space="preserve">
<value>YouTube</value>
</data>
@@ -294,9 +294,6 @@
<data name="Yes" xml:space="preserve">
<value>Yes</value>
</data>
<data name="YouTube" xml:space="preserve">
<value>YouTube</value>
</data>
<data name="Youtube" xml:space="preserve">
<value>YouTube</value>
</data>
@@ -294,9 +294,6 @@
<data name="Yes" xml:space="preserve">
<value>Da</value>
</data>
<data name="YouTube" xml:space="preserve">
<value>YouTube</value>
</data>
<data name="Youtube" xml:space="preserve">
<value>YouTube</value>
</data>
@@ -294,9 +294,6 @@
<data name="Yes" xml:space="preserve">
<value>Так</value>
</data>
<data name="YouTube" xml:space="preserve">
<value>Ютуб</value>
</data>
<data name="Youtube" xml:space="preserve">
<value>YouTube</value>
</data>
@@ -294,9 +294,6 @@
<data name="Yes" xml:space="preserve">
<value>是</value>
</data>
<data name="YouTube" xml:space="preserve">
<value>油管</value>
</data>
<data name="Youtube" xml:space="preserve">
<value>YouTube</value>
</data>
@@ -312,9 +312,6 @@
<data name="WrittenContent" xml:space="preserve">
<value>محتوى مكتوب</value>
</data>
<data name="YouTube" xml:space="preserve">
<value>YouTube</value>
</data>
<data name="Name" xml:space="preserve">
<value>الاسم</value>
</data>
@@ -312,9 +312,6 @@
<data name="WrittenContent" xml:space="preserve">
<value>Schriftliche Inhalte</value>
</data>
<data name="YouTube" xml:space="preserve">
<value>YouTube</value>
</data>
<data name="Name" xml:space="preserve">
<value>Name</value>
</data>
@@ -312,9 +312,6 @@
<data name="WrittenContent" xml:space="preserve">
<value>Written Content</value>
</data>
<data name="YouTube" xml:space="preserve">
<value>YouTube</value>
</data>
<data name="Name" xml:space="preserve">
<value>Name</value>
</data>
@@ -312,9 +312,6 @@
<data name="WrittenContent" xml:space="preserve">
<value>Contenido Escrito</value>
</data>
<data name="YouTube" xml:space="preserve">
<value>YouTube</value>
</data>
<data name="Name" xml:space="preserve">
<value>Nombre</value>
</data>
@@ -312,9 +312,6 @@
<data name="WrittenContent" xml:space="preserve">
<value>Contenu Écrit</value>
</data>
<data name="YouTube" xml:space="preserve">
<value>YouTube</value>
</data>
<data name="Name" xml:space="preserve">
<value>Nom</value>
</data>
@@ -312,9 +312,6 @@
<data name="WrittenContent" xml:space="preserve">
<value>Contenuto Scritto</value>
</data>
<data name="YouTube" xml:space="preserve">
<value>YouTube</value>
</data>
<data name="Name" xml:space="preserve">
<value>Nome</value>
</data>
@@ -312,9 +312,6 @@
<data name="WrittenContent" xml:space="preserve">
<value>文字コンテンツ</value>
</data>
<data name="YouTube" xml:space="preserve">
<value>ユーチューブ</value>
</data>
<data name="Name" xml:space="preserve">
<value>名前</value>
</data>
@@ -312,9 +312,6 @@
<data name="WrittenContent" xml:space="preserve">
<value>Written Content</value>
</data>
<data name="YouTube" xml:space="preserve">
<value>YouTube</value>
</data>
<data name="Name" xml:space="preserve">
<value>Name</value>
</data>
@@ -312,9 +312,6 @@
<data name="WrittenContent" xml:space="preserve">
<value>Conținut Scris</value>
</data>
<data name="YouTube" xml:space="preserve">
<value>YouTube</value>
</data>
<data name="Name" xml:space="preserve">
<value>Nume</value>
</data>
@@ -312,9 +312,6 @@
<data name="WrittenContent" xml:space="preserve">
<value>Письмовий контент</value>
</data>
<data name="YouTube" xml:space="preserve">
<value>Ютуб</value>
</data>
<data name="Name" xml:space="preserve">
<value>Ім'я</value>
</data>
@@ -312,9 +312,6 @@
<data name="WrittenContent" xml:space="preserve">
<value>文字内容</value>
</data>
<data name="YouTube" xml:space="preserve">
<value>油管</value>
</data>
<data name="Name" xml:space="preserve">
<value>名称</value>
</data>
@@ -35,7 +35,7 @@
<div id="reader-content" class="reader-content"></div>
</div>
@section Scripts {
<!-- The "text/plain" type is a design choice, not a mistake: it keeps the browser from executing this view script during HTML parsing, before site.js defines the API helpers it calls (callApiGetAsync, callApiPutAsync, ...). site.js (which loads deferred) executes these scripts once it is loaded, both on the initial page load and during AJAX navigation. -->
<!-- The "text/plain" type is a design choice, not a mistake: it keeps the browser from executing this view script during HTML parsing, before the deferred global scripts define the helpers it calls (notificationService, updateContentAsync, ...). Those scripts execute these view scripts once they are loaded, both on the initial page load and during AJAX navigation. -->
<script type="text/plain" data-form="@scriptId">
// Create cleanup registry for this view.
const cleanupFunctions = [];
@@ -46,6 +46,9 @@
const manifestUrl = '@_urlService.GetAbsoluteUrl(WebRoutes.Books.GET_READING_MANIFEST, new { bookId = default(Guid) })'.replace('/@(default(Guid))', `/${bookId}`) + `?libraryId=${libraryId}`;
const availabilityUrl = '@_urlService.GetAbsoluteUrl(WebRoutes.Books.GET_READING_AVAILABILITY, new { bookId = default(Guid) })'.replace('/@(default(Guid))', `/${bookId}`) + `?libraryId=${libraryId}`;
const libraryIndexUrl = '@_urlService.GetAbsoluteUrl(WebRoutes.Books.INDEX)';
// The login route takes the page to return to as an optional route value. The template is kept, so the reader can append
// the current page to it when a JSON request discovers that the session ended.
const signInUrlTemplate = '@_urlService.GetAbsoluteUrl(WebRoutes.Authentication.LOGIN_VIEW)';
const sectionUrlTemplate = '@_urlService.GetAbsoluteUrl(WebRoutes.Books.GET_READING_SECTION, new { bookId = default(Guid) })'.replace('/@(default(Guid))', `/${bookId}`) + `?libraryId=${libraryId}&locationRef=`;
const resourceUrlTemplate = '@_urlService.GetAbsoluteUrl(WebRoutes.Books.GET_READING_RESOURCE, new { bookId = default(Guid) })'.replace('/@(default(Guid))', `/${bookId}`) + `?libraryId=${libraryId}&resourceKey=`;
const startConsumptionUrl = '@_urlService.GetAbsoluteUrl(WebRoutes.MediaConsumption.START_CONSUMPTION, new { libraryId = Model.LibraryId, mediaKind = "Book", mediaItemId = Model.BookId })';
@@ -70,7 +73,8 @@
// first section, because its result chooses that section, so this bounds the wait. The manifest fetch itself is bounded only
// by the browser and the server, not by the reader.
const RESUME_POINT_REQUEST_TIMEOUT_MS = 5000;
// Marks a section request that was redirected to the sign in page, so its caller navigates instead of reporting a failure.
// Marks a request that ended the reading session and is navigating to the sign in page, so its caller does not report a
// failure. It is used by the resume point lookup and by the section request.
const REDIRECTED = Symbol('redirected');
// Marks a start request that did not settle within the bounded recovery wait, so the reader shows its failure state instead
// of opening a provisional first section that could overwrite the saved place.
@@ -124,9 +128,12 @@
let pendingConsumptionSession = null;
let isConsumptionSessionFinished = false;
let isConsumptionSessionCompleted = false;
// The number of pages read consecutively in the current forward run, including the page the run starts on. The reader
// paginates by spine section: a PDF page is a section of its own, and a reflowable book advances one section at a time.
// The number of pages read consecutively in the current forward run, including the page the run starts on. A page is one
// visible reader viewport: a PDF page is a section of its own, while a reflowable section can hold several viewport pages.
// Scrolling forward through a section adds one page per viewport crossed, and scrolling back starts a new run.
let consecutivePagesRead = 0;
// The zero based viewport page of the current section that is visible. It is reset at the top of each newly opened section.
let currentReaderPageIndex = 0;
// The active reading clock. Only the time during which the reader is visible is accumulated.
let activeReadingMilliseconds = 0;
let readingClockStartedOnMs = null;
@@ -143,22 +150,79 @@
return Number.isFinite(number) ? Math.round(number * 1000) / 1000 : 0;
}
// Gets the position of the section the reader currently shows, as the opaque location the consumption API stores for books.
function buildReadingPosition() {
if (!manifest || !manifest.spine || currentIndex < 0 || currentIndex >= manifest.spine.length)
// Gets the position and fraction a consumption record was recovered with before any section of the book was displayed.
// The record starts before the first section on the recovery path, so the reader can be left while that section is still
// loading. Reporting the recovered values in that window keeps the position and the fraction describing the same place,
// instead of resetting the fraction to zero while the position stays at the recovered one.
function getRecoveredReadingState(session) {
if (session === null || session.recoveredPosition === null || !session.recoveredPosition.location)
return null;
return {
kind: LOCATION_POSITION_KIND,
timeOffsetSeconds: null,
location: manifest.spine[currentIndex].locationRef
// The recovered position is rebuilt as the opaque location the reader reports for its sections, so the terminal
// report does not depend on how the start response represented the kind of the stored position.
position: {
kind: LOCATION_POSITION_KIND,
timeOffsetSeconds: null,
location: session.recoveredPosition.location
},
progressFraction: session.recoveredProgressFraction
};
}
// Gets the position of the section the reader currently shows, as the opaque location the consumption API stores for books.
function buildReadingPosition() {
if (manifest && manifest.spine && currentIndex >= 0 && currentIndex < manifest.spine.length) {
return {
kind: LOCATION_POSITION_KIND,
timeOffsetSeconds: null,
location: manifest.spine[currentIndex].locationRef
};
}
const recoveredState = getRecoveredReadingState(consumptionSession);
return recoveredState === null ? null : recoveredState.position;
}
// Gets the fraction of the book read so far. The current section counts as read, so the last section is the whole book.
function getReadingProgressFraction() {
if (!manifest || !manifest.spine || manifest.spine.length === 0 || currentIndex < 0)
return 0;
return Math.min(1, (currentIndex + 1) / manifest.spine.length);
if (manifest && manifest.spine && manifest.spine.length > 0 && currentIndex >= 0)
return Math.min(1, (currentIndex + 1) / manifest.spine.length);
const recoveredState = getRecoveredReadingState(consumptionSession);
return recoveredState === null ? 0 : recoveredState.progressFraction;
}
// Gets the number of viewport pages of the current section, at least one, and the zero based page the reader shows.
function getReaderPageMetrics() {
const viewportHeight = readerContent.clientHeight;
if (viewportHeight <= 0)
return { pageIndex: 0, pageCount: 1 };
const pageCount = Math.max(1, Math.ceil(readerContent.scrollHeight / viewportHeight));
const maximumScrollTop = Math.max(0, readerContent.scrollHeight - viewportHeight);
const scrollTop = Math.min(Math.max(0, readerContent.scrollTop), maximumScrollTop);
return {
pageIndex: Math.min(pageCount - 1, Math.floor((scrollTop + viewportHeight / 2) / viewportHeight)),
pageCount: pageCount
};
}
// Follows the visible page of the current section. A forward page movement counts as the next consecutive page, while a
// backward movement starts a new run at the page the reader landed on.
function syncReaderPageIndex() {
const pageIndex = getReaderPageMetrics().pageIndex;
if (pageIndex === currentReaderPageIndex)
return;
if (pageIndex > currentReaderPageIndex)
consecutivePagesRead += 1;
else
consecutivePagesRead = 1;
currentReaderPageIndex = pageIndex;
reportReadingProgressAsync().catch((error) => {
console.debug('Book reader: the reading page could not be reported.', error);
});
}
// Resets the visible page baseline after a layout change that is not a page read, such as a font size change.
function resetReaderPageIndex() {
currentReaderPageIndex = getReaderPageMetrics().pageIndex;
}
// Starts the active reading clock, unless it is already running.
@@ -218,6 +282,27 @@
pauseReadingClock();
}
// Follows the navigation of a response that ended the session, and returns true when the caller must stop handling it. A
// page navigation is redirected by the server to the sign in page, but these requests ask for JSON, so an expired session
// is answered with a JSON 401 after the authentication cookie has been cleared. The explicit navigation is what shows the
// sign in prompt in that case, with the reading page as the return URL. The return URL is passed as a query value, like the
// redirects of the authentication middleware do, so the reader page is not encoded into the path of the login route.
function redirectIfSessionEnded(response) {
if (response.status === 401) {
if (!signInUrlTemplate)
return true;
const returnUrl = encodeURIComponent(window.location.pathname + window.location.search + window.location.hash);
const signInUrl = signInUrlTemplate.replace('/{returnUrl?}', '');
window.location.href = `${signInUrl}?returnUrl=${returnUrl}`;
return true;
}
if (response.redirected) {
window.location.href = response.url;
return true;
}
return false;
}
// Sends a consumption request in the background, with the anti-forgery token the page rendered. Reporting is a background
// concern, so a failed request is only logged and never interrupts or fails the reading itself.
async function sendConsumptionRequestAsync(url, payload, options = {}) {
@@ -247,12 +332,8 @@
signal: abortController === null ? undefined : abortController.signal,
keepalive: options.keepalive === true
});
// An expired session is redirected to the sign in page. Following it in the background would parse an HTML page as
// JSON and silently drop the rest of the history, so the reader navigates to the sign in page instead.
if (response.redirected) {
window.location.href = response.url;
if (redirectIfSessionEnded(response))
return null;
}
if (!response.ok)
return null;
const jsonResponse = await response.json();
@@ -266,9 +347,10 @@
}
}
// Fetches the resume point of the current user for the book. It returns the resume point, null when the user has none, or
// undefined when the optional lookup failed. A failed lookup must not be treated as an absent one, because opening the first
// section and reporting it would overwrite the saved place with the start of the book.
// Fetches the resume point of the current user for the book. It returns the resume point, null when the user has none,
// undefined when the optional lookup failed, or REDIRECTED when the session ended and the sign in page is being opened.
// A failed lookup must not be treated as an absent one, because opening the first section and reporting it would overwrite
// the saved place with the start of the book.
async function fetchResumePointAsync() {
if (!resumePointUrl)
return undefined;
@@ -282,10 +364,8 @@
},
signal: abortController.signal
});
if (response.redirected) {
window.location.href = response.url;
return undefined;
}
if (redirectIfSessionEnded(response))
return REDIRECTED;
if (!response.ok)
return undefined;
const jsonResponse = await response.json();
@@ -319,6 +399,10 @@
function createConsumptionSession() {
return {
recordId: null,
// The position and fraction the start response recovered from the stored resume point. They stand in for the
// displayed section until the first section of the book is really shown.
recoveredPosition: null,
recoveredProgressFraction: 0,
startPromise: null,
startSettled: false,
pendingEndPayload: null,
@@ -353,12 +437,26 @@
if (!recordId)
return null;
session.recordId = recordId;
// A record that was started before the first section is displayed carries the stored position and fraction that the
// start recovered. They are the position and fraction of the session until a section is shown.
session.recoveredPosition = record.lastPosition || null;
const recoveredProgressFraction = Number(record.lastProgressFraction);
session.recoveredProgressFraction = Number.isFinite(recoveredProgressFraction) ? recoveredProgressFraction : 0;
// The session was ended and detached while the start request was in flight, so it still has a terminal payload to send.
// The record this request created is closed here with that payload, so it never stays in progress.
if (session.pendingEndPayload !== null)
if (session.pendingEndPayload !== null) {
// The payload was captured before this response supplied the recovered values, and before any section could be
// displayed. A terminal report without a position therefore takes the recovered position and fraction, so the
// stop cannot keep the recovered position while resetting its fraction to zero.
const recoveredState = getRecoveredReadingState(session);
if (session.pendingEndPayload.position === null && recoveredState !== null) {
session.pendingEndPayload.position = recoveredState.position;
session.pendingEndPayload.progressFraction = recoveredState.progressFraction;
}
finishEndedConsumptionSessionAsync(session).catch((error) => {
console.debug('Book reader: the consumption record of the replaced session could not be ended.', error);
});
}
return record;
}
@@ -427,6 +525,11 @@
// detached, so a restored page can reset the reading clock and the page count without changing what this session reports.
// When the start request is still in flight, its continuation either sends the captured terminal payload once the record
// identifier is known, or continues the revived session if the page is restored before that.
//
// Closing the record is best effort. A full page unload can destroy this page while the start request is still in flight,
// and the browser may finish that start after the page is gone. The record it creates is then never closed, because the
// pending session exists only in this page's memory. The server does not expire or reuse such a record, so it can remain
// InProgress indefinitely.
function finishConsumptionSession(outcome) {
if (isConsumptionSessionFinished)
return;
@@ -543,8 +646,9 @@
});
}
// Updates the page count and reports the section the reader just opened. The first section opens the reader session, a
// forward page advance into the last section completes it, and every other section reports its progress.
// Updates the page count and reports the section the reader just opened. The first displayed page starts a run at one, a
// backward navigation starts a new run at the page it lands on, and a forward section advance adds its first page. Scrolling
// within a section adds the viewport pages crossed, and a forward advance into the last section completes the session.
async function handleSectionOpenedAsync(previousIndex, index) {
// A section that finishes loading after the reader was left belongs to a finished session and must not open a new one.
if (isConsumptionSessionFinished)
@@ -556,6 +660,7 @@
consecutivePagesRead = 1;
else if (index > previousIndex)
consecutivePagesRead += 1;
currentReaderPageIndex = 0;
if (readingHeartbeatTimer === null)
startReadingHeartbeat();
// Only a forward page advance into the last section proves that the reading reached the end of the book. Opening
@@ -582,10 +687,8 @@
'X-Requested-With': 'XMLHttpRequest'
}
});
if (response.redirected) {
window.location.href = response.url;
if (redirectIfSessionEnded(response))
return;
}
if (!response.ok) {
readerStatus.textContent = jsLocalizedStrings.readFailed;
return;
@@ -620,6 +723,9 @@
let initialSectionRecord = null;
if (manifestResponse.spine && manifestResponse.spine.length > 0) {
resumePointResult = await resumePointPromise;
// The lookup already navigated to the sign in page, so no section and no record is started for a session that ended.
if (resumePointResult === REDIRECTED)
return;
if (resumePointResult === undefined) {
// The optional lookup failed, so the saved position is only available from the start response. The wait for it is
// bounded, so a slow or hung start cannot hold the reader on the loading state. The start continues in the
@@ -661,7 +767,33 @@
// render-as-images setting is off, since enabling that setting is the way to make such a book readable, and navigates back
// to the library page, because the reading page cannot display anything for such a book.
async function notifyIfPdfImageOnlyAsync() {
const settings = await callApiGetAsync('@_urlService.GetAbsoluteUrl(WebRoutes.Settings.GET_USER_SETTINGS)');
// The shared callApiGetAsync helper answers a JSON 401 with an error notification, but a reader whose session ended must
// be taken to the sign in prompt like the other reader requests, so this lookup is made here and checks the status first.
let response;
try {
response = await fetch('@_urlService.GetAbsoluteUrl(WebRoutes.Settings.GET_USER_SETTINGS)', {
headers: {
'Accept': 'application/json',
'X-Requested-With': 'XMLHttpRequest'
}
});
} catch (error) {
console.debug('Book reader: the user settings could not be fetched.', error);
notificationService.show(jsLocalizedStrings.readFailed, NotificationType.ERROR);
return;
}
if (redirectIfSessionEnded(response))
return;
if (!response.ok) {
notificationService.show(jsLocalizedStrings.readFailed, NotificationType.ERROR);
return;
}
const jsonResponse = await response.json();
if (!jsonResponse || jsonResponse.success !== true) {
notificationService.show(jsonResponse && jsonResponse.errorMessage ? jsonResponse.errorMessage : jsLocalizedStrings.readFailed, NotificationType.ERROR);
return;
}
const settings = jsonResponse.data;
if (settings && settings.shouldRenderPdfAsImages !== true) {
notificationService.show(jsLocalizedStrings.imageOnlyPdf, NotificationType.WARNING);
await redirectToLibraryPageAsync();
@@ -678,6 +810,8 @@
'X-Requested-With': 'XMLHttpRequest'
}
});
if (redirectIfSessionEnded(response))
return;
if (!response.ok)
return;
const jsonResponse = await response.json();
@@ -698,10 +832,8 @@
},
signal
});
if (response.redirected) {
window.location.href = response.url;
if (redirectIfSessionEnded(response))
return REDIRECTED;
}
if (!response.ok)
return null;
const jsonResponse = await response.json();
@@ -749,6 +881,7 @@
const previousIndex = currentIndex;
currentIndex = index;
readerContent.innerHTML = section.contentHtml || '';
currentReaderPageIndex = 0;
resolveResources();
updatePosition();
readerStatus.classList.add('hidden');
@@ -851,6 +984,7 @@
// Applies the current font size to the reading content.
function applyFontSize() {
readerContent.style.fontSize = `${fontSize}px`;
resetReaderPageIndex();
}
// On font size decrease button click, decreases the font size of the reading content.
@@ -873,6 +1007,7 @@
btnNext.addEventListener('click', handleNextClick);
btnFontDecrease.addEventListener('click', handleFontDecreaseClick);
btnFontIncrease.addEventListener('click', handleFontIncreaseClick);
readerContent.addEventListener('scroll', syncReaderPageIndex, { passive: true });
document.addEventListener('DOMContentLoaded', InitializeAsync);
document.addEventListener('visibilitychange', handleVisibilityChange);
// A full page unload does not run the view cleanups, so the last reading time and page are also stopped on pagehide.
@@ -888,6 +1023,7 @@
btnNext.removeEventListener('click', handleNextClick);
btnFontDecrease.removeEventListener('click', handleFontDecreaseClick);
btnFontIncrease.removeEventListener('click', handleFontIncreaseClick);
readerContent.removeEventListener('scroll', syncReaderPageIndex);
document.removeEventListener('DOMContentLoaded', InitializeAsync);
document.removeEventListener('visibilitychange', handleVisibilityChange);
window.removeEventListener('pagehide', stopReadingSession);