From e9ec6671d5b90f496d7d29db826227e068672889 Mon Sep 17 00:00:00 2001 From: Joseph Milazzo Date: Tue, 10 Aug 2021 18:18:07 -0500 Subject: [PATCH] Bookmarking Pages within the Reader (#469) # Added - Added: Added the ability to bookmark certain pages within the manga (image) reader and later download them from the series context menu. # Fixed - Fixed: Fixed an issue where after adding a new folder to an existing library, a scan wouldn't be kicked off - Fixed: In some cases, after clicking the background of a modal, the modal would close, but state wouldn't be handled as if cancel was pushed # Changed - Changed: Admin contextual actions on cards will now be separated by a line to help differentiate. - Changed: Performance enhancement on an API used before reading # Dev - Bumped dependencies to latest versions ============================================= * Bumped versions of dependencies and refactored bookmark to progress. * Refactored method names in UI from bookmark to progress to prepare for new bookmark entity * Basic code is done, user can now bookmark a page (currently image reader only). * Comments and pipes * Some accessibility for new bookmark button * Fixed up the APIs to work correctly, added a new modal to quickly explore bookmarks (not implemented, not final). * Cleanup on the UI side to get the modal to look decent * Added dismissed handlers for modals where appropriate * Refactored UI to only show number of bookmarks across files to simplify delivery. Admin actionables are now separated by hr vs non-admin actions. * Basic API implemented, now to implement the ability to actually extract files. * Implemented the ability to download bookmarks. * Fixed a bug where adding a new folder to an existing library would not trigger a scan library task. * Fixed an issue that could cause bookmarked pages to get copied out of order. * Added handler from series-card component --- API.Tests/API.Tests.csproj | 6 +- API/API.csproj | 46 +- API/Controllers/DownloadController.cs | 71 +- API/Controllers/LibraryController.cs | 7 +- API/Controllers/ReaderController.cs | 225 ++++- API/DTOs/BookmarkDto.cs | 12 +- API/DTOs/Downloads/DownloadBookmarkDto.cs | 9 + API/DTOs/ProgressDto.cs | 15 + API/Data/BookmarkRepository.cs | 7 + API/Data/DataContext.cs | 17 +- .../20210809210326_BookmarkPages.Designer.cs | 913 ++++++++++++++++++ .../20210809210326_BookmarkPages.cs | 44 + .../Migrations/DataContextModelSnapshot.cs | 43 +- API/Data/UnitOfWork.cs | 4 +- API/Data/UserRepository.cs | 41 +- API/Data/VolumeRepository.cs | 22 +- API/Entities/AppUser.cs | 5 +- API/Entities/AppUserBookmark.cs | 22 + API/Helpers/AutoMapperProfiles.cs | 16 +- API/Interfaces/IUserRepository.cs | 5 +- API/Interfaces/IVolumeRepository.cs | 5 +- API/Interfaces/Services/ICacheService.cs | 1 + API/Interfaces/Services/IDirectoryService.cs | 2 +- API/Services/ArchiveService.cs | 5 +- API/Services/CacheService.cs | 92 +- API/Services/DirectoryService.cs | 78 +- Kavita.Common/Kavita.Common.csproj | 4 +- .../bookmarks-modal.component.html | 28 + .../bookmarks-modal.component.scss | 0 .../bookmarks-modal.component.ts | 70 ++ UI/Web/src/app/_models/page-bookmark.ts | 7 + .../{bookmark.ts => progress-bookmark.ts} | 2 +- .../app/_services/action-factory.service.ts | 62 +- UI/Web/src/app/_services/action.service.ts | 31 +- UI/Web/src/app/_services/image.service.ts | 4 + .../src/app/_services/message-hub.service.ts | 3 + UI/Web/src/app/_services/reader.service.ts | 39 +- UI/Web/src/app/app.module.ts | 4 +- .../book-reader/book-reader.component.ts | 29 +- .../manga-reader/manga-reader.component.html | 3 + .../manga-reader/manga-reader.component.ts | 48 +- .../app/series-card/series-card.component.ts | 7 +- .../series-detail.component.html | 5 +- .../series-detail/series-detail.component.ts | 3 + .../app/shared/_services/download.service.ts | 8 + .../card-actionables.component.html | 4 +- .../card-actionables.component.ts | 9 + UI/Web/src/app/shared/confirm.service.ts | 11 +- UI/Web/src/styles.scss | 7 +- 49 files changed, 1860 insertions(+), 241 deletions(-) create mode 100644 API/DTOs/Downloads/DownloadBookmarkDto.cs create mode 100644 API/DTOs/ProgressDto.cs create mode 100644 API/Data/BookmarkRepository.cs create mode 100644 API/Data/Migrations/20210809210326_BookmarkPages.Designer.cs create mode 100644 API/Data/Migrations/20210809210326_BookmarkPages.cs create mode 100644 API/Entities/AppUserBookmark.cs create mode 100644 UI/Web/src/app/_modals/bookmarks-modal/bookmarks-modal.component.html create mode 100644 UI/Web/src/app/_modals/bookmarks-modal/bookmarks-modal.component.scss create mode 100644 UI/Web/src/app/_modals/bookmarks-modal/bookmarks-modal.component.ts create mode 100644 UI/Web/src/app/_models/page-bookmark.ts rename UI/Web/src/app/_models/{bookmark.ts => progress-bookmark.ts} (66%) diff --git a/API.Tests/API.Tests.csproj b/API.Tests/API.Tests.csproj index d486d9877..73a19fd5d 100644 --- a/API.Tests/API.Tests.csproj +++ b/API.Tests/API.Tests.csproj @@ -7,15 +7,15 @@ - - + + runtime; build; native; contentfiles; analyzers; buildtransitive all - + runtime; build; native; contentfiles; analyzers; buildtransitive all diff --git a/API/API.csproj b/API/API.csproj index 504cf7271..d824795e5 100644 --- a/API/API.csproj +++ b/API/API.csproj @@ -35,35 +35,35 @@ - - + + - + - - - + + + - + all runtime; build; native; contentfiles; analyzers; buildtransitive - - - + + + - - + + - + all runtime; build; native; contentfiles; analyzers; buildtransitive - + - + @@ -77,22 +77,38 @@ + + + + + + + + + + + + + + + + diff --git a/API/Controllers/DownloadController.cs b/API/Controllers/DownloadController.cs index 3e89c98ef..cc4fd0214 100644 --- a/API/Controllers/DownloadController.cs +++ b/API/Controllers/DownloadController.cs @@ -3,7 +3,11 @@ using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; +using API.Comparators; +using API.DTOs; +using API.DTOs.Downloads; using API.Entities; +using API.Entities.Enums; using API.Extensions; using API.Interfaces; using API.Interfaces.Services; @@ -21,12 +25,16 @@ namespace API.Controllers private readonly IUnitOfWork _unitOfWork; private readonly IArchiveService _archiveService; private readonly IDirectoryService _directoryService; + private readonly ICacheService _cacheService; + private readonly NumericComparer _numericComparer; - public DownloadController(IUnitOfWork unitOfWork, IArchiveService archiveService, IDirectoryService directoryService) + public DownloadController(IUnitOfWork unitOfWork, IArchiveService archiveService, IDirectoryService directoryService, ICacheService cacheService) { _unitOfWork = unitOfWork; _archiveService = archiveService; _directoryService = directoryService; + _cacheService = cacheService; + _numericComparer = new NumericComparer(); } [HttpGet("volume-size")] @@ -39,7 +47,7 @@ namespace API.Controllers [HttpGet("chapter-size")] public async Task> GetChapterSize(int chapterId) { - var files = await _unitOfWork.VolumeRepository.GetFilesForChapter(chapterId); + var files = await _unitOfWork.VolumeRepository.GetFilesForChapterAsync(chapterId); return Ok(DirectoryService.GetTotalSize(files.Select(c => c.FilePath))); } @@ -96,7 +104,7 @@ namespace API.Controllers [HttpGet("chapter")] public async Task DownloadChapter(int chapterId) { - var files = await _unitOfWork.VolumeRepository.GetFilesForChapter(chapterId); + var files = await _unitOfWork.VolumeRepository.GetFilesForChapterAsync(chapterId); try { if (files.Count == 1) @@ -132,5 +140,62 @@ namespace API.Controllers return BadRequest(ex.Message); } } + + [HttpPost("bookmarks")] + public async Task DownloadBookmarkPages(DownloadBookmarkDto downloadBookmarkDto) + { + // We know that all bookmarks will be for one single seriesId + var series = await _unitOfWork.SeriesRepository.GetSeriesByIdAsync(downloadBookmarkDto.Bookmarks.First().SeriesId); + var totalFilePaths = new List(); + + var tempFolder = $"download_{series.Id}_bookmarks"; + var fullExtractPath = Path.Join(DirectoryService.TempDirectory, tempFolder); + if (new DirectoryInfo(fullExtractPath).Exists) + { + return BadRequest( + "Server is currently processing this exact download. Please try again in a few minutes."); + } + DirectoryService.ExistOrCreate(fullExtractPath); + + var uniqueChapterIds = downloadBookmarkDto.Bookmarks.Select(b => b.ChapterId).Distinct().ToList(); + + foreach (var chapterId in uniqueChapterIds) + { + var chapterExtractPath = Path.Join(fullExtractPath, $"{series.Id}_bookmark_{chapterId}"); + var chapterPages = downloadBookmarkDto.Bookmarks.Where(b => b.ChapterId == chapterId) + .Select(b => b.Page).ToList(); + var mangaFiles = await _unitOfWork.VolumeRepository.GetFilesForChapterAsync(chapterId); + switch (series.Format) + { + case MangaFormat.Image: + DirectoryService.ExistOrCreate(chapterExtractPath); + _directoryService.CopyFilesToDirectory(mangaFiles.Select(f => f.FilePath), chapterExtractPath, $"{chapterId}_"); + break; + case MangaFormat.Archive: + case MangaFormat.Pdf: + _cacheService.ExtractChapterFiles(chapterExtractPath, mangaFiles.ToList()); + var originalFiles = _directoryService.GetFilesWithExtension(chapterExtractPath, + Parser.Parser.ImageFileExtensions); + _directoryService.CopyFilesToDirectory(originalFiles, chapterExtractPath, $"{chapterId}_"); + DirectoryService.DeleteFiles(originalFiles); + break; + case MangaFormat.Epub: + return BadRequest("Series is not in a valid format."); + default: + return BadRequest("Series is not in a valid format. Please rescan series and try again."); + } + + var files = _directoryService.GetFilesWithExtension(chapterExtractPath, Parser.Parser.ImageFileExtensions); + // Filter out images that aren't in bookmarks + Array.Sort(files, _numericComparer); + totalFilePaths.AddRange(files.Where((t, i) => chapterPages.Contains(i))); + } + + + var (fileBytes, zipPath) = await _archiveService.CreateZipForDownload(totalFilePaths, + tempFolder); + DirectoryService.ClearAndDeleteDirectory(fullExtractPath); + return File(fileBytes, "application/zip", $"{series.Name} - Bookmarks.zip"); + } } } diff --git a/API/Controllers/LibraryController.cs b/API/Controllers/LibraryController.cs index 4d47e3f06..dda5543c3 100644 --- a/API/Controllers/LibraryController.cs +++ b/API/Controllers/LibraryController.cs @@ -203,8 +203,7 @@ namespace API.Controllers { var library = await _unitOfWork.LibraryRepository.GetLibraryForIdAsync(libraryForUserDto.Id); - var originalFolders = library.Folders.Select(x => x.Path); - var differenceBetweenFolders = originalFolders.Except(libraryForUserDto.Folders); + var originalFolders = library.Folders.Select(x => x.Path).ToList(); library.Name = libraryForUserDto.Name; library.Folders = libraryForUserDto.Folders.Select(s => new FolderPath() {Path = s}).ToList(); @@ -212,9 +211,9 @@ namespace API.Controllers _unitOfWork.LibraryRepository.Update(library); if (!await _unitOfWork.CommitAsync()) return BadRequest("There was a critical issue updating the library."); - if (differenceBetweenFolders.Any()) + if (originalFolders.Count != libraryForUserDto.Folders.Count()) { - _taskScheduler.ScanLibrary(library.Id, true); + _taskScheduler.ScanLibrary(library.Id); } return Ok(); diff --git a/API/Controllers/ReaderController.cs b/API/Controllers/ReaderController.cs index 5a10676d1..b1d42b6cb 100644 --- a/API/Controllers/ReaderController.cs +++ b/API/Controllers/ReaderController.cs @@ -50,15 +50,16 @@ namespace API.Controllers } [HttpGet("chapter-info")] - public async Task> GetChapterInfo(int chapterId) + public async Task> GetChapterInfo(int seriesId, int chapterId) { // PERF: Write this in one DB call var chapter = await _cacheService.Ensure(chapterId); if (chapter == null) return BadRequest("Could not find Chapter"); - var volume = await _unitOfWork.SeriesRepository.GetVolumeAsync(chapter.VolumeId); + + var volume = await _unitOfWork.SeriesRepository.GetVolumeDtoAsync(chapter.VolumeId); if (volume == null) return BadRequest("Could not find Volume"); - var (_, mangaFile) = await _cacheService.GetCachedPagePath(chapter, 0); - var series = await _unitOfWork.SeriesRepository.GetSeriesByIdAsync(volume.SeriesId); + var mangaFile = (await _unitOfWork.VolumeRepository.GetFilesForChapterAsync(chapterId)).First(); + var series = await _unitOfWork.SeriesRepository.GetSeriesByIdAsync(seriesId); return Ok(new ChapterInfoDto() { @@ -72,29 +73,6 @@ namespace API.Controllers }); } - [HttpGet("get-bookmark")] - public async Task> GetBookmark(int chapterId) - { - var user = await _unitOfWork.UserRepository.GetUserByUsernameAsync(User.GetUsername()); - var bookmark = new BookmarkDto() - { - PageNum = 0, - ChapterId = chapterId, - VolumeId = 0, - SeriesId = 0 - }; - if (user.Progresses == null) return Ok(bookmark); - var progress = user.Progresses.SingleOrDefault(x => x.AppUserId == user.Id && x.ChapterId == chapterId); - - if (progress != null) - { - bookmark.SeriesId = progress.SeriesId; - bookmark.VolumeId = progress.VolumeId; - bookmark.PageNum = progress.PagesRead; - bookmark.BookScrollId = progress.BookScrollId; - } - return Ok(bookmark); - } [HttpPost("mark-read")] public async Task MarkRead(MarkReadDto markReadDto) @@ -232,21 +210,45 @@ namespace API.Controllers return BadRequest("Could not save progress"); } - [HttpPost("bookmark")] - public async Task Bookmark(BookmarkDto bookmarkDto) + [HttpGet("get-progress")] + public async Task> GetProgress(int chapterId) + { + var user = await _unitOfWork.UserRepository.GetUserByUsernameAsync(User.GetUsername()); + var progressBookmark = new ProgressDto() + { + PageNum = 0, + ChapterId = chapterId, + VolumeId = 0, + SeriesId = 0 + }; + if (user.Progresses == null) return Ok(progressBookmark); + var progress = user.Progresses.SingleOrDefault(x => x.AppUserId == user.Id && x.ChapterId == chapterId); + + if (progress != null) + { + progressBookmark.SeriesId = progress.SeriesId; + progressBookmark.VolumeId = progress.VolumeId; + progressBookmark.PageNum = progress.PagesRead; + progressBookmark.BookScrollId = progress.BookScrollId; + } + return Ok(progressBookmark); + } + + [HttpPost("progress")] + public async Task BookmarkProgress(ProgressDto progressDto) { var user = await _unitOfWork.UserRepository.GetUserByUsernameAsync(User.GetUsername()); - // Don't let user bookmark past total pages. - var chapter = await _unitOfWork.VolumeRepository.GetChapterAsync(bookmarkDto.ChapterId); - if (bookmarkDto.PageNum > chapter.Pages) + // Don't let user save past total pages. + var chapter = await _unitOfWork.VolumeRepository.GetChapterAsync(progressDto.ChapterId); + if (progressDto.PageNum > chapter.Pages) { - bookmarkDto.PageNum = chapter.Pages; + progressDto.PageNum = chapter.Pages; } - if (bookmarkDto.PageNum < 0) + if (progressDto.PageNum < 0) { - bookmarkDto.PageNum = 0; + progressDto.PageNum = 0; } @@ -255,26 +257,26 @@ namespace API.Controllers // TODO: Look into creating a progress entry when a new item is added to the DB so we can just look it up and modify it user.Progresses ??= new List(); var userProgress = - user.Progresses.SingleOrDefault(x => x.ChapterId == bookmarkDto.ChapterId && x.AppUserId == user.Id); + user.Progresses.SingleOrDefault(x => x.ChapterId == progressDto.ChapterId && x.AppUserId == user.Id); if (userProgress == null) { user.Progresses.Add(new AppUserProgress { - PagesRead = bookmarkDto.PageNum, - VolumeId = bookmarkDto.VolumeId, - SeriesId = bookmarkDto.SeriesId, - ChapterId = bookmarkDto.ChapterId, - BookScrollId = bookmarkDto.BookScrollId, + PagesRead = progressDto.PageNum, + VolumeId = progressDto.VolumeId, + SeriesId = progressDto.SeriesId, + ChapterId = progressDto.ChapterId, + BookScrollId = progressDto.BookScrollId, LastModified = DateTime.Now }); } else { - userProgress.PagesRead = bookmarkDto.PageNum; - userProgress.SeriesId = bookmarkDto.SeriesId; - userProgress.VolumeId = bookmarkDto.VolumeId; - userProgress.BookScrollId = bookmarkDto.BookScrollId; + userProgress.PagesRead = progressDto.PageNum; + userProgress.SeriesId = progressDto.SeriesId; + userProgress.VolumeId = progressDto.VolumeId; + userProgress.BookScrollId = progressDto.BookScrollId; userProgress.LastModified = DateTime.Now; } @@ -293,6 +295,139 @@ namespace API.Controllers return BadRequest("Could not save progress"); } + [HttpGet("get-bookmarks")] + public async Task>> GetBookmarks(int chapterId) + { + var user = await _unitOfWork.UserRepository.GetUserByUsernameAsync(User.GetUsername()); + if (user.Bookmarks == null) return Ok(Array.Empty()); + return Ok(await _unitOfWork.UserRepository.GetBookmarkDtosForChapter(user.Id, chapterId)); + } + + [HttpPost("remove-bookmarks")] + public async Task RemoveBookmarks(int seriesId) + { + var user = await _unitOfWork.UserRepository.GetUserByUsernameAsync(User.GetUsername()); + if (user.Bookmarks == null) return Ok("Nothing to remove"); + try + { + user.Bookmarks = user.Bookmarks.Where(bmk => bmk.SeriesId == seriesId).ToList(); + _unitOfWork.UserRepository.Update(user); + + if (await _unitOfWork.CommitAsync()) + { + return Ok(); + } + } + catch (Exception) + { + await _unitOfWork.RollbackAsync(); + } + + return BadRequest("Could not clear bookmarks"); + + } + + [HttpGet("get-volume-bookmarks")] + public async Task>> GetBookmarksForVolume(int volumeId) + { + var user = await _unitOfWork.UserRepository.GetUserByUsernameAsync(User.GetUsername()); + if (user.Bookmarks == null) return Ok(Array.Empty()); + return Ok(await _unitOfWork.UserRepository.GetBookmarkDtosForVolume(user.Id, volumeId)); + } + + [HttpGet("get-series-bookmarks")] + public async Task>> GetBookmarksForSeries(int seriesId) + { + var user = await _unitOfWork.UserRepository.GetUserByUsernameAsync(User.GetUsername()); + if (user.Bookmarks == null) return Ok(Array.Empty()); + + return Ok(await _unitOfWork.UserRepository.GetBookmarkDtosForSeries(user.Id, seriesId)); + } + + [HttpPost("bookmark")] + public async Task BookmarkPage(BookmarkDto bookmarkDto) + { + var user = await _unitOfWork.UserRepository.GetUserByUsernameAsync(User.GetUsername()); + + // Don't let user save past total pages. + var chapter = await _unitOfWork.VolumeRepository.GetChapterAsync(bookmarkDto.ChapterId); + if (bookmarkDto.Page > chapter.Pages) + { + bookmarkDto.Page = chapter.Pages; + } + + if (bookmarkDto.Page < 0) + { + bookmarkDto.Page = 0; + } + + + try + { + user.Bookmarks ??= new List(); + var userBookmark = + user.Bookmarks.SingleOrDefault(x => x.ChapterId == bookmarkDto.ChapterId && x.AppUserId == user.Id && x.Page == bookmarkDto.Page); + + if (userBookmark == null) + { + user.Bookmarks.Add(new AppUserBookmark() + { + Page = bookmarkDto.Page, + VolumeId = bookmarkDto.VolumeId, + SeriesId = bookmarkDto.SeriesId, + ChapterId = bookmarkDto.ChapterId, + }); + } + else + { + userBookmark.Page = bookmarkDto.Page; + userBookmark.SeriesId = bookmarkDto.SeriesId; + userBookmark.VolumeId = bookmarkDto.VolumeId; + } + + _unitOfWork.UserRepository.Update(user); + + if (await _unitOfWork.CommitAsync()) + { + return Ok(); + } + } + catch (Exception) + { + await _unitOfWork.RollbackAsync(); + } + + return BadRequest("Could not save bookmark"); + } + + [HttpPost("unbookmark")] + public async Task UnBookmarkPage(BookmarkDto bookmarkDto) + { + var user = await _unitOfWork.UserRepository.GetUserByUsernameAsync(User.GetUsername()); + + if (user.Bookmarks == null) return Ok(); + try { + user.Bookmarks = user.Bookmarks.Where(x => + x.ChapterId == bookmarkDto.ChapterId + && x.AppUserId == user.Id + && x.Page != bookmarkDto.Page).ToList(); + + + _unitOfWork.UserRepository.Update(user); + + if (await _unitOfWork.CommitAsync()) + { + return Ok(); + } + } + catch (Exception) + { + await _unitOfWork.RollbackAsync(); + } + + return BadRequest("Could not remove bookmark"); + } + /// /// Returns the next logical chapter from the series. /// diff --git a/API/DTOs/BookmarkDto.cs b/API/DTOs/BookmarkDto.cs index c06f6d30a..c45a183c3 100644 --- a/API/DTOs/BookmarkDto.cs +++ b/API/DTOs/BookmarkDto.cs @@ -2,14 +2,10 @@ { public class BookmarkDto { + public int Id { get; set; } + public int Page { get; set; } public int VolumeId { get; set; } - public int ChapterId { get; set; } - public int PageNum { get; set; } public int SeriesId { get; set; } - /// - /// For Book reader, this can be an optional string of the id of a part marker, to help resume reading position - /// on pages that combine multiple "chapters". - /// - public string BookScrollId { get; set; } + public int ChapterId { get; set; } } -} \ No newline at end of file +} diff --git a/API/DTOs/Downloads/DownloadBookmarkDto.cs b/API/DTOs/Downloads/DownloadBookmarkDto.cs new file mode 100644 index 000000000..5239b4aae --- /dev/null +++ b/API/DTOs/Downloads/DownloadBookmarkDto.cs @@ -0,0 +1,9 @@ +using System.Collections.Generic; + +namespace API.DTOs.Downloads +{ + public class DownloadBookmarkDto + { + public IEnumerable Bookmarks { get; set; } + } +} diff --git a/API/DTOs/ProgressDto.cs b/API/DTOs/ProgressDto.cs new file mode 100644 index 000000000..4810a40a9 --- /dev/null +++ b/API/DTOs/ProgressDto.cs @@ -0,0 +1,15 @@ +namespace API.DTOs +{ + public class ProgressDto + { + public int VolumeId { get; set; } + public int ChapterId { get; set; } + public int PageNum { get; set; } + public int SeriesId { get; set; } + /// + /// For Book reader, this can be an optional string of the id of a part marker, to help resume reading position + /// on pages that combine multiple "chapters". + /// + public string BookScrollId { get; set; } + } +} diff --git a/API/Data/BookmarkRepository.cs b/API/Data/BookmarkRepository.cs new file mode 100644 index 000000000..af212bc72 --- /dev/null +++ b/API/Data/BookmarkRepository.cs @@ -0,0 +1,7 @@ +namespace API.Data +{ + public class BookmarkRepository + { + + } +} diff --git a/API/Data/DataContext.cs b/API/Data/DataContext.cs index 008d96ed2..98e0cb8cd 100644 --- a/API/Data/DataContext.cs +++ b/API/Data/DataContext.cs @@ -8,7 +8,7 @@ using Microsoft.EntityFrameworkCore.ChangeTracking; namespace API.Data { - public sealed class DataContext : IdentityDbContext, AppUserRole, IdentityUserLogin, IdentityRoleClaim, IdentityUserToken> { @@ -17,10 +17,10 @@ namespace API.Data ChangeTracker.Tracked += OnEntityTracked; ChangeTracker.StateChanged += OnEntityStateChanged; } - + public DbSet Library { get; set; } public DbSet Series { get; set; } - + public DbSet Chapter { get; set; } public DbSet Volume { get; set; } public DbSet AppUser { get; set; } @@ -31,18 +31,19 @@ namespace API.Data public DbSet AppUserPreferences { get; set; } public DbSet SeriesMetadata { get; set; } public DbSet CollectionTag { get; set; } + public DbSet AppUserBookmark { get; set; } protected override void OnModelCreating(ModelBuilder builder) { base.OnModelCreating(builder); - + builder.Entity() .HasMany(ur => ur.UserRoles) .WithOne(u => u.User) .HasForeignKey(ur => ur.UserId) .IsRequired(); - + builder.Entity() .HasMany(ur => ur.UserRoles) .WithOne(u => u.Role) @@ -50,7 +51,7 @@ namespace API.Data .IsRequired(); } - + void OnEntityTracked(object sender, EntityTrackedEventArgs e) { if (!e.FromQuery && e.Entry.State == EntityState.Added && e.Entry.Entity is IEntityDate entity) @@ -58,7 +59,7 @@ namespace API.Data entity.Created = DateTime.Now; entity.LastModified = DateTime.Now; } - + } void OnEntityStateChanged(object sender, EntityStateChangedEventArgs e) @@ -67,4 +68,4 @@ namespace API.Data entity.LastModified = DateTime.Now; } } -} \ No newline at end of file +} diff --git a/API/Data/Migrations/20210809210326_BookmarkPages.Designer.cs b/API/Data/Migrations/20210809210326_BookmarkPages.Designer.cs new file mode 100644 index 000000000..b339bbd99 --- /dev/null +++ b/API/Data/Migrations/20210809210326_BookmarkPages.Designer.cs @@ -0,0 +1,913 @@ +// +using System; +using API.Data; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +namespace API.Data.Migrations +{ + [DbContext(typeof(DataContext))] + [Migration("20210809210326_BookmarkPages")] + partial class BookmarkPages + { + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "5.0.8"); + + modelBuilder.Entity("API.Entities.AppRole", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("TEXT"); + + b.Property("Name") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("NormalizedName") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedName") + .IsUnique() + .HasDatabaseName("RoleNameIndex"); + + b.ToTable("AspNetRoles"); + }); + + modelBuilder.Entity("API.Entities.AppUser", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("AccessFailedCount") + .HasColumnType("INTEGER"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("TEXT"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Email") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("EmailConfirmed") + .HasColumnType("INTEGER"); + + b.Property("LastActive") + .HasColumnType("TEXT"); + + b.Property("LockoutEnabled") + .HasColumnType("INTEGER"); + + b.Property("LockoutEnd") + .HasColumnType("TEXT"); + + b.Property("NormalizedEmail") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("NormalizedUserName") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("PasswordHash") + .HasColumnType("TEXT"); + + b.Property("PhoneNumber") + .HasColumnType("TEXT"); + + b.Property("PhoneNumberConfirmed") + .HasColumnType("INTEGER"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .HasColumnType("INTEGER"); + + b.Property("SecurityStamp") + .HasColumnType("TEXT"); + + b.Property("TwoFactorEnabled") + .HasColumnType("INTEGER"); + + b.Property("UserName") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedEmail") + .HasDatabaseName("EmailIndex"); + + b.HasIndex("NormalizedUserName") + .IsUnique() + .HasDatabaseName("UserNameIndex"); + + b.ToTable("AspNetUsers"); + }); + + modelBuilder.Entity("API.Entities.AppUserBookmark", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("AppUserId") + .HasColumnType("INTEGER"); + + b.Property("ChapterId") + .HasColumnType("INTEGER"); + + b.Property("Page") + .HasColumnType("INTEGER"); + + b.Property("SeriesId") + .HasColumnType("INTEGER"); + + b.Property("VolumeId") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("AppUserId"); + + b.ToTable("AppUserBookmark"); + }); + + modelBuilder.Entity("API.Entities.AppUserPreferences", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("AppUserId") + .HasColumnType("INTEGER"); + + b.Property("AutoCloseMenu") + .HasColumnType("INTEGER"); + + b.Property("BookReaderDarkMode") + .HasColumnType("INTEGER"); + + b.Property("BookReaderFontFamily") + .HasColumnType("TEXT"); + + b.Property("BookReaderFontSize") + .HasColumnType("INTEGER"); + + b.Property("BookReaderLineSpacing") + .HasColumnType("INTEGER"); + + b.Property("BookReaderMargin") + .HasColumnType("INTEGER"); + + b.Property("BookReaderReadingDirection") + .HasColumnType("INTEGER"); + + b.Property("BookReaderTapToPaginate") + .HasColumnType("INTEGER"); + + b.Property("PageSplitOption") + .HasColumnType("INTEGER"); + + b.Property("ReaderMode") + .HasColumnType("INTEGER"); + + b.Property("ReadingDirection") + .HasColumnType("INTEGER"); + + b.Property("ScalingOption") + .HasColumnType("INTEGER"); + + b.Property("SiteDarkMode") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("AppUserId") + .IsUnique(); + + b.ToTable("AppUserPreferences"); + }); + + modelBuilder.Entity("API.Entities.AppUserProgress", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("AppUserId") + .HasColumnType("INTEGER"); + + b.Property("BookScrollId") + .HasColumnType("TEXT"); + + b.Property("ChapterId") + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("LastModified") + .HasColumnType("TEXT"); + + b.Property("PagesRead") + .HasColumnType("INTEGER"); + + b.Property("SeriesId") + .HasColumnType("INTEGER"); + + b.Property("VolumeId") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("AppUserId"); + + b.ToTable("AppUserProgresses"); + }); + + modelBuilder.Entity("API.Entities.AppUserRating", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("AppUserId") + .HasColumnType("INTEGER"); + + b.Property("Rating") + .HasColumnType("INTEGER"); + + b.Property("Review") + .HasColumnType("TEXT"); + + b.Property("SeriesId") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("AppUserId"); + + b.ToTable("AppUserRating"); + }); + + modelBuilder.Entity("API.Entities.AppUserRole", b => + { + b.Property("UserId") + .HasColumnType("INTEGER"); + + b.Property("RoleId") + .HasColumnType("INTEGER"); + + b.HasKey("UserId", "RoleId"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetUserRoles"); + }); + + modelBuilder.Entity("API.Entities.Chapter", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("CoverImage") + .HasColumnType("BLOB"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("IsSpecial") + .HasColumnType("INTEGER"); + + b.Property("LastModified") + .HasColumnType("TEXT"); + + b.Property("Number") + .HasColumnType("TEXT"); + + b.Property("Pages") + .HasColumnType("INTEGER"); + + b.Property("Range") + .HasColumnType("TEXT"); + + b.Property("Title") + .HasColumnType("TEXT"); + + b.Property("VolumeId") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("VolumeId"); + + b.ToTable("Chapter"); + }); + + modelBuilder.Entity("API.Entities.CollectionTag", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("CoverImage") + .HasColumnType("BLOB"); + + b.Property("NormalizedTitle") + .HasColumnType("TEXT"); + + b.Property("Promoted") + .HasColumnType("INTEGER"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .HasColumnType("INTEGER"); + + b.Property("Summary") + .HasColumnType("TEXT"); + + b.Property("Title") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("Id", "Promoted") + .IsUnique(); + + b.ToTable("CollectionTag"); + }); + + modelBuilder.Entity("API.Entities.FolderPath", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("LastScanned") + .HasColumnType("TEXT"); + + b.Property("LibraryId") + .HasColumnType("INTEGER"); + + b.Property("Path") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("LibraryId"); + + b.ToTable("FolderPath"); + }); + + modelBuilder.Entity("API.Entities.Library", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("CoverImage") + .HasColumnType("TEXT"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("LastModified") + .HasColumnType("TEXT"); + + b.Property("Name") + .HasColumnType("TEXT"); + + b.Property("Type") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.ToTable("Library"); + }); + + modelBuilder.Entity("API.Entities.MangaFile", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("ChapterId") + .HasColumnType("INTEGER"); + + b.Property("FilePath") + .HasColumnType("TEXT"); + + b.Property("Format") + .HasColumnType("INTEGER"); + + b.Property("LastModified") + .HasColumnType("TEXT"); + + b.Property("Pages") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("ChapterId"); + + b.ToTable("MangaFile"); + }); + + modelBuilder.Entity("API.Entities.Series", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("CoverImage") + .HasColumnType("BLOB"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Format") + .HasColumnType("INTEGER"); + + b.Property("LastModified") + .HasColumnType("TEXT"); + + b.Property("LibraryId") + .HasColumnType("INTEGER"); + + b.Property("LocalizedName") + .HasColumnType("TEXT"); + + b.Property("Name") + .HasColumnType("TEXT"); + + b.Property("NormalizedName") + .HasColumnType("TEXT"); + + b.Property("OriginalName") + .HasColumnType("TEXT"); + + b.Property("Pages") + .HasColumnType("INTEGER"); + + b.Property("SortName") + .HasColumnType("TEXT"); + + b.Property("Summary") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("LibraryId"); + + b.HasIndex("Name", "NormalizedName", "LocalizedName", "LibraryId", "Format") + .IsUnique(); + + b.ToTable("Series"); + }); + + modelBuilder.Entity("API.Entities.SeriesMetadata", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .HasColumnType("INTEGER"); + + b.Property("SeriesId") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("SeriesId") + .IsUnique(); + + b.HasIndex("Id", "SeriesId") + .IsUnique(); + + b.ToTable("SeriesMetadata"); + }); + + modelBuilder.Entity("API.Entities.ServerSetting", b => + { + b.Property("Key") + .HasColumnType("INTEGER"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .HasColumnType("INTEGER"); + + b.Property("Value") + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.ToTable("ServerSetting"); + }); + + modelBuilder.Entity("API.Entities.Volume", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("CoverImage") + .HasColumnType("BLOB"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("LastModified") + .HasColumnType("TEXT"); + + b.Property("Name") + .HasColumnType("TEXT"); + + b.Property("Number") + .HasColumnType("INTEGER"); + + b.Property("Pages") + .HasColumnType("INTEGER"); + + b.Property("SeriesId") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("SeriesId"); + + b.ToTable("Volume"); + }); + + modelBuilder.Entity("AppUserLibrary", b => + { + b.Property("AppUsersId") + .HasColumnType("INTEGER"); + + b.Property("LibrariesId") + .HasColumnType("INTEGER"); + + b.HasKey("AppUsersId", "LibrariesId"); + + b.HasIndex("LibrariesId"); + + b.ToTable("AppUserLibrary"); + }); + + modelBuilder.Entity("CollectionTagSeriesMetadata", b => + { + b.Property("CollectionTagsId") + .HasColumnType("INTEGER"); + + b.Property("SeriesMetadatasId") + .HasColumnType("INTEGER"); + + b.HasKey("CollectionTagsId", "SeriesMetadatasId"); + + b.HasIndex("SeriesMetadatasId"); + + b.ToTable("CollectionTagSeriesMetadata"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("ClaimType") + .HasColumnType("TEXT"); + + b.Property("ClaimValue") + .HasColumnType("TEXT"); + + b.Property("RoleId") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetRoleClaims"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("ClaimType") + .HasColumnType("TEXT"); + + b.Property("ClaimValue") + .HasColumnType("TEXT"); + + b.Property("UserId") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserClaims"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.Property("LoginProvider") + .HasColumnType("TEXT"); + + b.Property("ProviderKey") + .HasColumnType("TEXT"); + + b.Property("ProviderDisplayName") + .HasColumnType("TEXT"); + + b.Property("UserId") + .HasColumnType("INTEGER"); + + b.HasKey("LoginProvider", "ProviderKey"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserLogins"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.Property("UserId") + .HasColumnType("INTEGER"); + + b.Property("LoginProvider") + .HasColumnType("TEXT"); + + b.Property("Name") + .HasColumnType("TEXT"); + + b.Property("Value") + .HasColumnType("TEXT"); + + b.HasKey("UserId", "LoginProvider", "Name"); + + b.ToTable("AspNetUserTokens"); + }); + + modelBuilder.Entity("API.Entities.AppUserBookmark", b => + { + b.HasOne("API.Entities.AppUser", "AppUser") + .WithMany("Bookmarks") + .HasForeignKey("AppUserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("AppUser"); + }); + + modelBuilder.Entity("API.Entities.AppUserPreferences", b => + { + b.HasOne("API.Entities.AppUser", "AppUser") + .WithOne("UserPreferences") + .HasForeignKey("API.Entities.AppUserPreferences", "AppUserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("AppUser"); + }); + + modelBuilder.Entity("API.Entities.AppUserProgress", b => + { + b.HasOne("API.Entities.AppUser", "AppUser") + .WithMany("Progresses") + .HasForeignKey("AppUserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("AppUser"); + }); + + modelBuilder.Entity("API.Entities.AppUserRating", b => + { + b.HasOne("API.Entities.AppUser", "AppUser") + .WithMany("Ratings") + .HasForeignKey("AppUserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("AppUser"); + }); + + modelBuilder.Entity("API.Entities.AppUserRole", b => + { + b.HasOne("API.Entities.AppRole", "Role") + .WithMany("UserRoles") + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("API.Entities.AppUser", "User") + .WithMany("UserRoles") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Role"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("API.Entities.Chapter", b => + { + b.HasOne("API.Entities.Volume", "Volume") + .WithMany("Chapters") + .HasForeignKey("VolumeId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Volume"); + }); + + modelBuilder.Entity("API.Entities.FolderPath", b => + { + b.HasOne("API.Entities.Library", "Library") + .WithMany("Folders") + .HasForeignKey("LibraryId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Library"); + }); + + modelBuilder.Entity("API.Entities.MangaFile", b => + { + b.HasOne("API.Entities.Chapter", "Chapter") + .WithMany("Files") + .HasForeignKey("ChapterId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Chapter"); + }); + + modelBuilder.Entity("API.Entities.Series", b => + { + b.HasOne("API.Entities.Library", "Library") + .WithMany("Series") + .HasForeignKey("LibraryId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Library"); + }); + + modelBuilder.Entity("API.Entities.SeriesMetadata", b => + { + b.HasOne("API.Entities.Series", "Series") + .WithOne("Metadata") + .HasForeignKey("API.Entities.SeriesMetadata", "SeriesId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Series"); + }); + + modelBuilder.Entity("API.Entities.Volume", b => + { + b.HasOne("API.Entities.Series", "Series") + .WithMany("Volumes") + .HasForeignKey("SeriesId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Series"); + }); + + modelBuilder.Entity("AppUserLibrary", b => + { + b.HasOne("API.Entities.AppUser", null) + .WithMany() + .HasForeignKey("AppUsersId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("API.Entities.Library", null) + .WithMany() + .HasForeignKey("LibrariesId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("CollectionTagSeriesMetadata", b => + { + b.HasOne("API.Entities.CollectionTag", null) + .WithMany() + .HasForeignKey("CollectionTagsId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("API.Entities.SeriesMetadata", null) + .WithMany() + .HasForeignKey("SeriesMetadatasId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.HasOne("API.Entities.AppRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.HasOne("API.Entities.AppUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.HasOne("API.Entities.AppUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.HasOne("API.Entities.AppUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("API.Entities.AppRole", b => + { + b.Navigation("UserRoles"); + }); + + modelBuilder.Entity("API.Entities.AppUser", b => + { + b.Navigation("Bookmarks"); + + b.Navigation("Progresses"); + + b.Navigation("Ratings"); + + b.Navigation("UserPreferences"); + + b.Navigation("UserRoles"); + }); + + modelBuilder.Entity("API.Entities.Chapter", b => + { + b.Navigation("Files"); + }); + + modelBuilder.Entity("API.Entities.Library", b => + { + b.Navigation("Folders"); + + b.Navigation("Series"); + }); + + modelBuilder.Entity("API.Entities.Series", b => + { + b.Navigation("Metadata"); + + b.Navigation("Volumes"); + }); + + modelBuilder.Entity("API.Entities.Volume", b => + { + b.Navigation("Chapters"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/API/Data/Migrations/20210809210326_BookmarkPages.cs b/API/Data/Migrations/20210809210326_BookmarkPages.cs new file mode 100644 index 000000000..0ae48eeed --- /dev/null +++ b/API/Data/Migrations/20210809210326_BookmarkPages.cs @@ -0,0 +1,44 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +namespace API.Data.Migrations +{ + public partial class BookmarkPages : Migration + { + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "AppUserBookmark", + columns: table => new + { + Id = table.Column(type: "INTEGER", nullable: false) + .Annotation("Sqlite:Autoincrement", true), + Page = table.Column(type: "INTEGER", nullable: false), + VolumeId = table.Column(type: "INTEGER", nullable: false), + SeriesId = table.Column(type: "INTEGER", nullable: false), + ChapterId = table.Column(type: "INTEGER", nullable: false), + AppUserId = table.Column(type: "INTEGER", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_AppUserBookmark", x => x.Id); + table.ForeignKey( + name: "FK_AppUserBookmark_AspNetUsers_AppUserId", + column: x => x.AppUserId, + principalTable: "AspNetUsers", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateIndex( + name: "IX_AppUserBookmark_AppUserId", + table: "AppUserBookmark", + column: "AppUserId"); + } + + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "AppUserBookmark"); + } + } +} diff --git a/API/Data/Migrations/DataContextModelSnapshot.cs b/API/Data/Migrations/DataContextModelSnapshot.cs index ebf940768..c6d708f16 100644 --- a/API/Data/Migrations/DataContextModelSnapshot.cs +++ b/API/Data/Migrations/DataContextModelSnapshot.cs @@ -14,7 +14,7 @@ namespace API.Data.Migrations { #pragma warning disable 612, 618 modelBuilder - .HasAnnotation("ProductVersion", "5.0.4"); + .HasAnnotation("ProductVersion", "5.0.8"); modelBuilder.Entity("API.Entities.AppRole", b => { @@ -118,6 +118,34 @@ namespace API.Data.Migrations b.ToTable("AspNetUsers"); }); + modelBuilder.Entity("API.Entities.AppUserBookmark", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("AppUserId") + .HasColumnType("INTEGER"); + + b.Property("ChapterId") + .HasColumnType("INTEGER"); + + b.Property("Page") + .HasColumnType("INTEGER"); + + b.Property("SeriesId") + .HasColumnType("INTEGER"); + + b.Property("VolumeId") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("AppUserId"); + + b.ToTable("AppUserBookmark"); + }); + modelBuilder.Entity("API.Entities.AppUserPreferences", b => { b.Property("Id") @@ -641,6 +669,17 @@ namespace API.Data.Migrations b.ToTable("AspNetUserTokens"); }); + modelBuilder.Entity("API.Entities.AppUserBookmark", b => + { + b.HasOne("API.Entities.AppUser", "AppUser") + .WithMany("Bookmarks") + .HasForeignKey("AppUserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("AppUser"); + }); + modelBuilder.Entity("API.Entities.AppUserPreferences", b => { b.HasOne("API.Entities.AppUser", "AppUser") @@ -832,6 +871,8 @@ namespace API.Data.Migrations modelBuilder.Entity("API.Entities.AppUser", b => { + b.Navigation("Bookmarks"); + b.Navigation("Progresses"); b.Navigation("Ratings"); diff --git a/API/Data/UnitOfWork.cs b/API/Data/UnitOfWork.cs index 394e6fed1..564043577 100644 --- a/API/Data/UnitOfWork.cs +++ b/API/Data/UnitOfWork.cs @@ -20,7 +20,7 @@ namespace API.Data } public ISeriesRepository SeriesRepository => new SeriesRepository(_context, _mapper); - public IUserRepository UserRepository => new UserRepository(_context, _userManager); + public IUserRepository UserRepository => new UserRepository(_context, _userManager, _mapper); public ILibraryRepository LibraryRepository => new LibraryRepository(_context, _mapper); public IVolumeRepository VolumeRepository => new VolumeRepository(_context, _mapper); @@ -56,4 +56,4 @@ namespace API.Data return true; } } -} \ No newline at end of file +} diff --git a/API/Data/UserRepository.cs b/API/Data/UserRepository.cs index 4f86ca5b5..d330b7954 100644 --- a/API/Data/UserRepository.cs +++ b/API/Data/UserRepository.cs @@ -5,6 +5,8 @@ using API.Constants; using API.DTOs; using API.Entities; using API.Interfaces; +using AutoMapper; +using AutoMapper.QueryableExtensions; using Microsoft.AspNetCore.Identity; using Microsoft.EntityFrameworkCore; @@ -14,18 +16,20 @@ namespace API.Data { private readonly DataContext _context; private readonly UserManager _userManager; + private readonly IMapper _mapper; - public UserRepository(DataContext context, UserManager userManager) + public UserRepository(DataContext context, UserManager userManager, IMapper mapper) { _context = context; _userManager = userManager; + _mapper = mapper; } public void Update(AppUser user) { _context.Entry(user).State = EntityState.Modified; } - + public void Update(AppUserPreferences preferences) { _context.Entry(preferences).State = EntityState.Modified; @@ -45,6 +49,7 @@ namespace API.Data { return await _context.Users .Include(u => u.Progresses) + .Include(u => u.Bookmarks) .SingleOrDefaultAsync(x => x.UserName == username); } @@ -71,6 +76,36 @@ namespace API.Data .SingleOrDefaultAsync(p => p.AppUser.UserName == username); } + public async Task> GetBookmarkDtosForSeries(int userId, int seriesId) + { + return await _context.AppUserBookmark + .Where(x => x.AppUserId == userId && x.SeriesId == seriesId) + .OrderBy(x => x.Page) + .AsNoTracking() + .ProjectTo(_mapper.ConfigurationProvider) + .ToListAsync(); + } + + public async Task> GetBookmarkDtosForVolume(int userId, int volumeId) + { + return await _context.AppUserBookmark + .Where(x => x.AppUserId == userId && x.VolumeId == volumeId) + .OrderBy(x => x.Page) + .AsNoTracking() + .ProjectTo(_mapper.ConfigurationProvider) + .ToListAsync(); + } + + public async Task> GetBookmarkDtosForChapter(int userId, int chapterId) + { + return await _context.AppUserBookmark + .Where(x => x.AppUserId == userId && x.ChapterId == chapterId) + .OrderBy(x => x.Page) + .AsNoTracking() + .ProjectTo(_mapper.ConfigurationProvider) + .ToListAsync(); + } + public async Task> GetMembersAsync() { return await _context.Users @@ -97,4 +132,4 @@ namespace API.Data .ToListAsync(); } } -} \ No newline at end of file +} diff --git a/API/Data/VolumeRepository.cs b/API/Data/VolumeRepository.cs index 3bcd092a9..bcab3d113 100644 --- a/API/Data/VolumeRepository.cs +++ b/API/Data/VolumeRepository.cs @@ -1,7 +1,9 @@ using System.Collections.Generic; +using System.IO; using System.Linq; using System.Threading.Tasks; using API.DTOs; +using API.DTOs.Reader; using API.Entities; using API.Interfaces; using AutoMapper; @@ -38,7 +40,6 @@ namespace API.Data .SingleOrDefaultAsync(c => c.Id == chapterId); } - /// /// Returns Chapters for a volume id. /// @@ -79,13 +80,30 @@ namespace API.Data return chapter; } - public async Task> GetFilesForChapter(int chapterId) + /// + /// Returns non-tracked files for a given chapterId + /// + /// + /// + public async Task> GetFilesForChapterAsync(int chapterId) { return await _context.MangaFile .Where(c => chapterId == c.ChapterId) .AsNoTracking() .ToListAsync(); } + /// + /// Returns non-tracked files for a set of chapterIds + /// + /// + /// + public async Task> GetFilesForChaptersAsync(IReadOnlyList chapterIds) + { + return await _context.MangaFile + .Where(c => chapterIds.Contains(c.ChapterId)) + .AsNoTracking() + .ToListAsync(); + } public async Task> GetFilesForVolume(int volumeId) { diff --git a/API/Entities/AppUser.cs b/API/Entities/AppUser.cs index 49df4d7af..b75c871f2 100644 --- a/API/Entities/AppUser.cs +++ b/API/Entities/AppUser.cs @@ -16,7 +16,8 @@ namespace API.Entities public ICollection Progresses { get; set; } public ICollection Ratings { get; set; } public AppUserPreferences UserPreferences { get; set; } - + public ICollection Bookmarks { get; set; } + [ConcurrencyCheck] public uint RowVersion { get; set; } @@ -26,4 +27,4 @@ namespace API.Entities } } -} \ No newline at end of file +} diff --git a/API/Entities/AppUserBookmark.cs b/API/Entities/AppUserBookmark.cs new file mode 100644 index 000000000..cfb9aa29a --- /dev/null +++ b/API/Entities/AppUserBookmark.cs @@ -0,0 +1,22 @@ +using System.Text.Json.Serialization; + +namespace API.Entities +{ + /// + /// Represents a saved page in a Chapter entity for a given user. + /// + public class AppUserBookmark + { + public int Id { get; set; } + public int Page { get; set; } + public int VolumeId { get; set; } + public int SeriesId { get; set; } + public int ChapterId { get; set; } + + + // Relationships + [JsonIgnore] + public AppUser AppUser { get; set; } + public int AppUserId { get; set; } + } +} diff --git a/API/Helpers/AutoMapperProfiles.cs b/API/Helpers/AutoMapperProfiles.cs index 33f2c2223..084a7d28c 100644 --- a/API/Helpers/AutoMapperProfiles.cs +++ b/API/Helpers/AutoMapperProfiles.cs @@ -16,11 +16,11 @@ namespace API.Helpers CreateMap(); CreateMap(); - + CreateMap(); CreateMap(); - + CreateMap(); CreateMap(); @@ -29,18 +29,20 @@ namespace API.Helpers CreateMap(); + CreateMap(); + CreateMap() .ForMember(dest => dest.SeriesId, opt => opt.MapFrom(src => src.Id)) .ForMember(dest => dest.LibraryName, opt => opt.MapFrom(src => src.Library.Name)); - - + + CreateMap() .ForMember(dest => dest.Folders, - opt => + opt => opt.MapFrom(src => src.Folders.Select(x => x.Path).ToList())); - + CreateMap() .AfterMap((ps, pst, context) => context.Mapper.Map(ps.Libraries, pst.Libraries)); @@ -50,4 +52,4 @@ namespace API.Helpers .ConvertUsing(); } } -} \ No newline at end of file +} diff --git a/API/Interfaces/IUserRepository.cs b/API/Interfaces/IUserRepository.cs index 6821da667..eb2062646 100644 --- a/API/Interfaces/IUserRepository.cs +++ b/API/Interfaces/IUserRepository.cs @@ -16,5 +16,8 @@ namespace API.Interfaces Task GetUserRating(int seriesId, int userId); void AddRatingTracking(AppUserRating userRating); Task GetPreferencesAsync(string username); + Task> GetBookmarkDtosForSeries(int userId, int seriesId); + Task> GetBookmarkDtosForVolume(int userId, int volumeId); + Task> GetBookmarkDtosForChapter(int userId, int chapterId); } -} \ No newline at end of file +} diff --git a/API/Interfaces/IVolumeRepository.cs b/API/Interfaces/IVolumeRepository.cs index b5ac06087..0cd703ee9 100644 --- a/API/Interfaces/IVolumeRepository.cs +++ b/API/Interfaces/IVolumeRepository.cs @@ -10,9 +10,10 @@ namespace API.Interfaces void Update(Volume volume); Task GetChapterAsync(int chapterId); Task GetChapterDtoAsync(int chapterId); - Task> GetFilesForChapter(int chapterId); + Task> GetFilesForChapterAsync(int chapterId); + Task> GetFilesForChaptersAsync(IReadOnlyList chapterIds); Task> GetChaptersAsync(int volumeId); Task GetChapterCoverImageAsync(int chapterId); Task> GetFilesForVolume(int volumeId); } -} \ No newline at end of file +} diff --git a/API/Interfaces/Services/ICacheService.cs b/API/Interfaces/Services/ICacheService.cs index 8499702b1..395898dc2 100644 --- a/API/Interfaces/Services/ICacheService.cs +++ b/API/Interfaces/Services/ICacheService.cs @@ -36,5 +36,6 @@ namespace API.Interfaces.Services void EnsureCacheDirectory(); string GetCachedEpubFile(int chapterId, Chapter chapter); + public void ExtractChapterFiles(string extractPath, IReadOnlyList files); } } diff --git a/API/Interfaces/Services/IDirectoryService.cs b/API/Interfaces/Services/IDirectoryService.cs index 4e6979bd5..43779774c 100644 --- a/API/Interfaces/Services/IDirectoryService.cs +++ b/API/Interfaces/Services/IDirectoryService.cs @@ -20,7 +20,7 @@ namespace API.Interfaces.Services /// string[] GetFilesWithExtension(string path, string searchPatternExpression = ""); Task ReadFileAsync(string path); - bool CopyFilesToDirectory(IEnumerable filePaths, string directoryPath); + bool CopyFilesToDirectory(IEnumerable filePaths, string directoryPath, string prepend = ""); bool Exists(string directory); IEnumerable GetFiles(string path, string searchPatternExpression = "", diff --git a/API/Services/ArchiveService.cs b/API/Services/ArchiveService.cs index 36eded36b..e0a6fa596 100644 --- a/API/Services/ArchiveService.cs +++ b/API/Services/ArchiveService.cs @@ -224,17 +224,16 @@ namespace API.Services public async Task> CreateZipForDownload(IEnumerable files, string tempFolder) { - var tempDirectory = Path.Join(Directory.GetCurrentDirectory(), "temp"); var dateString = DateTime.Now.ToShortDateString().Replace("/", "_"); - var tempLocation = Path.Join(tempDirectory, $"{tempFolder}_{dateString}"); + var tempLocation = Path.Join(DirectoryService.TempDirectory, $"{tempFolder}_{dateString}"); DirectoryService.ExistOrCreate(tempLocation); if (!_directoryService.CopyFilesToDirectory(files, tempLocation)) { throw new KavitaException("Unable to copy files to temp directory archive download."); } - var zipPath = Path.Join(tempDirectory, $"kavita_{tempFolder}_{dateString}.zip"); + var zipPath = Path.Join(DirectoryService.TempDirectory, $"kavita_{tempFolder}_{dateString}.zip"); try { ZipFile.CreateFromDirectory(tempLocation, zipPath); diff --git a/API/Services/CacheService.cs b/API/Services/CacheService.cs index 89d1cf395..05b8bd21b 100644 --- a/API/Services/CacheService.cs +++ b/API/Services/CacheService.cs @@ -37,7 +37,7 @@ namespace API.Services public void EnsureCacheDirectory() { - if (!DirectoryService.ExistOrCreate(CacheDirectory)) + if (!DirectoryService.ExistOrCreate(DirectoryService.CacheDirectory)) { _logger.LogError("Cache directory {CacheDirectory} is not accessible or does not exist. Creating...", CacheDirectory); } @@ -60,58 +60,77 @@ namespace API.Services return path; } + /// + /// Caches the files for the given chapter to CacheDirectory + /// + /// + /// This will always return the Chapter for the chpaterId public async Task Ensure(int chapterId) { EnsureCacheDirectory(); var chapter = await _unitOfWork.VolumeRepository.GetChapterAsync(chapterId); - var files = chapter.Files.ToList(); - var fileCount = files.Count; var extractPath = GetCachePath(chapterId); - var extraPath = ""; - var removeNonImages = true; - if (Directory.Exists(extractPath)) + if (!Directory.Exists(extractPath)) { - return chapter; + var files = chapter.Files.ToList(); + ExtractChapterFiles(extractPath, files); } + return chapter; + } + + /// + /// This is an internal method for cache service for extracting chapter files to disk. The code is structured + /// for cache service, but can be re-used (download bookmarks) + /// + /// + /// + /// + public void ExtractChapterFiles(string extractPath, IReadOnlyList files) + { + var removeNonImages = true; + var fileCount = files.Count; + var extraPath = ""; var extractDi = new DirectoryInfo(extractPath); if (files.Count > 0 && files[0].Format == MangaFormat.Image) { - DirectoryService.ExistOrCreate(extractPath); - if (files.Count == 1) - { - _directoryService.CopyFileToDirectory(files[0].FilePath, extractPath); - } - else - { - _directoryService.CopyDirectoryToDirectory(Path.GetDirectoryName(files[0].FilePath), extractPath, Parser.Parser.ImageFileExtensions); - } + DirectoryService.ExistOrCreate(extractPath); + if (files.Count == 1) + { + _directoryService.CopyFileToDirectory(files[0].FilePath, extractPath); + } + else + { + _directoryService.CopyDirectoryToDirectory(Path.GetDirectoryName(files[0].FilePath), extractPath, + Parser.Parser.ImageFileExtensions); + } - extractDi.Flatten(); - return chapter; + extractDi.Flatten(); } foreach (var file in files) { - if (fileCount > 1) - { - extraPath = file.Id + string.Empty; - } + if (fileCount > 1) + { + extraPath = file.Id + string.Empty; + } - if (file.Format == MangaFormat.Archive) - { - _archiveService.ExtractArchive(file.FilePath, Path.Join(extractPath, extraPath)); - } else if (file.Format == MangaFormat.Pdf) - { - _bookService.ExtractPdfImages(file.FilePath, Path.Join(extractPath, extraPath)); - } else if (file.Format == MangaFormat.Epub) - { - removeNonImages = false; - DirectoryService.ExistOrCreate(extractPath); - _directoryService.CopyFileToDirectory(files[0].FilePath, extractPath); - } + if (file.Format == MangaFormat.Archive) + { + _archiveService.ExtractArchive(file.FilePath, Path.Join(extractPath, extraPath)); + } + else if (file.Format == MangaFormat.Pdf) + { + _bookService.ExtractPdfImages(file.FilePath, Path.Join(extractPath, extraPath)); + } + else if (file.Format == MangaFormat.Epub) + { + removeNonImages = false; + DirectoryService.ExistOrCreate(extractPath); + _directoryService.CopyFileToDirectory(files[0].FilePath, extractPath); + } } extractDi.Flatten(); @@ -119,9 +138,6 @@ namespace API.Services { extractDi.RemoveNonImages(); } - - - return chapter; } @@ -173,7 +189,7 @@ namespace API.Services { // Calculate what chapter the page belongs to var pagesSoFar = 0; - var chapterFiles = chapter.Files ?? await _unitOfWork.VolumeRepository.GetFilesForChapter(chapter.Id); + var chapterFiles = chapter.Files ?? await _unitOfWork.VolumeRepository.GetFilesForChapterAsync(chapter.Id); foreach (var mangaFile in chapterFiles) { if (page <= (mangaFile.Pages + pagesSoFar)) diff --git a/API/Services/DirectoryService.cs b/API/Services/DirectoryService.cs index 80156bd2a..0451088e9 100644 --- a/API/Services/DirectoryService.cs +++ b/API/Services/DirectoryService.cs @@ -16,6 +16,9 @@ namespace API.Services private static readonly Regex ExcludeDirectories = new Regex( @"@eaDir|\.DS_Store", RegexOptions.Compiled | RegexOptions.IgnoreCase); + public static readonly string TempDirectory = Path.Join(Directory.GetCurrentDirectory(), "temp"); + public static readonly string LogDirectory = Path.Join(Directory.GetCurrentDirectory(), "logs"); + public static readonly string CacheDirectory = Path.Join(Directory.GetCurrentDirectory(), "cache"); public DirectoryService(ILogger logger) { @@ -247,33 +250,40 @@ namespace API.Services } } - public bool CopyFilesToDirectory(IEnumerable filePaths, string directoryPath) + /// + /// Copies files to a destination directory. If the destination directory doesn't exist, this will create it. + /// + /// + /// + /// An optional string to prepend to the target file's name + /// + public bool CopyFilesToDirectory(IEnumerable filePaths, string directoryPath, string prepend = "") { - string currentFile = null; - try - { - foreach (var file in filePaths) - { - currentFile = file; - var fileInfo = new FileInfo(file); - if (fileInfo.Exists) - { - fileInfo.CopyTo(Path.Join(directoryPath, fileInfo.Name)); - } - else - { - _logger.LogWarning("Tried to copy {File} but it doesn't exist", file); - } + ExistOrCreate(directoryPath); + string currentFile = null; + try + { + foreach (var file in filePaths) + { + currentFile = file; + var fileInfo = new FileInfo(file); + if (fileInfo.Exists) + { + fileInfo.CopyTo(Path.Join(directoryPath, prepend + fileInfo.Name)); + } + else + { + _logger.LogWarning("Tried to copy {File} but it doesn't exist", file); + } + } + } + catch (Exception ex) + { + _logger.LogError(ex, "Unable to copy {File} to {DirectoryPath}", currentFile, directoryPath); + return false; + } - } - } - catch (Exception ex) - { - _logger.LogError(ex, "Unable to copy {File} to {DirectoryPath}", currentFile, directoryPath); - return false; - } - - return true; + return true; } public IEnumerable ListDirectory(string rootPath) @@ -404,5 +414,23 @@ namespace API.Services return fileCount; } + /// + /// Attempts to delete the files passed to it. Swallows exceptions. + /// + /// Full path of files to delete + public static void DeleteFiles(IEnumerable files) + { + foreach (var file in files) + { + try + { + new FileInfo(file).Delete(); + } + catch (Exception) + { + /* Swallow exception */ + } + } + } } } diff --git a/Kavita.Common/Kavita.Common.csproj b/Kavita.Common/Kavita.Common.csproj index 96b0a3619..fd04df1ec 100644 --- a/Kavita.Common/Kavita.Common.csproj +++ b/Kavita.Common/Kavita.Common.csproj @@ -11,8 +11,8 @@ - - + + all runtime; build; native; contentfiles; analyzers; buildtransitive diff --git a/UI/Web/src/app/_modals/bookmarks-modal/bookmarks-modal.component.html b/UI/Web/src/app/_modals/bookmarks-modal/bookmarks-modal.component.html new file mode 100644 index 000000000..95e47a42d --- /dev/null +++ b/UI/Web/src/app/_modals/bookmarks-modal/bookmarks-modal.component.html @@ -0,0 +1,28 @@ + + + diff --git a/UI/Web/src/app/_modals/bookmarks-modal/bookmarks-modal.component.scss b/UI/Web/src/app/_modals/bookmarks-modal/bookmarks-modal.component.scss new file mode 100644 index 000000000..e69de29bb diff --git a/UI/Web/src/app/_modals/bookmarks-modal/bookmarks-modal.component.ts b/UI/Web/src/app/_modals/bookmarks-modal/bookmarks-modal.component.ts new file mode 100644 index 000000000..098f06bf4 --- /dev/null +++ b/UI/Web/src/app/_modals/bookmarks-modal/bookmarks-modal.component.ts @@ -0,0 +1,70 @@ +import { Component, Input, OnInit } from '@angular/core'; +import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap'; +import { ToastrService } from 'ngx-toastr'; +import { take } from 'rxjs/operators'; +import { DownloadService } from 'src/app/shared/_services/download.service'; +import { PageBookmark } from 'src/app/_models/page-bookmark'; +import { Series } from 'src/app/_models/series'; +import { ImageService } from 'src/app/_services/image.service'; +import { ReaderService } from 'src/app/_services/reader.service'; +import { SeriesService } from 'src/app/_services/series.service'; + +@Component({ + selector: 'app-bookmarks-modal', + templateUrl: './bookmarks-modal.component.html', + styleUrls: ['./bookmarks-modal.component.scss'] +}) +export class BookmarksModalComponent implements OnInit { + + @Input() series!: Series; + + bookmarks: Array = []; + title: string = ''; + subtitle: string = ''; + isDownloading: boolean = false; + isClearing: boolean = false; + + uniqueChapters: number = 0; + + constructor(public imageService: ImageService, private readerService: ReaderService, + public modal: NgbActiveModal, private downloadService: DownloadService, + private toastr: ToastrService, private seriesService: SeriesService) { } + + ngOnInit(): void { + this.init(); + } + + init() { + this.readerService.getBookmarksForSeries(this.series.id).pipe(take(1)).subscribe(bookmarks => { + this.bookmarks = bookmarks; + const chapters: {[id: number]: string} = {}; + this.bookmarks.forEach(bmk => { + if (!chapters.hasOwnProperty(bmk.chapterId)) { + chapters[bmk.chapterId] = ''; + } + }); + this.uniqueChapters = Object.keys(chapters).length; + }); + } + + close() { + this.modal.close(); + } + + downloadBookmarks() { + this.isDownloading = true; + this.downloadService.downloadBookmarks(this.bookmarks, this.series.name).pipe(take(1)).subscribe(() => { + this.isDownloading = false; + }); + } + + clearBookmarks() { + this.isClearing = true; + this.readerService.clearBookmarks(this.series.id).subscribe(() => { + this.isClearing = false; + this.init(); + this.toastr.success(this.series.name + '\'s bookmarks have been removed'); + }); + } + +} diff --git a/UI/Web/src/app/_models/page-bookmark.ts b/UI/Web/src/app/_models/page-bookmark.ts new file mode 100644 index 000000000..6d46bfe4d --- /dev/null +++ b/UI/Web/src/app/_models/page-bookmark.ts @@ -0,0 +1,7 @@ +export interface PageBookmark { + id: number; + page: number; + seriesId: number; + volumeId: number; + chapterId: number; +} \ No newline at end of file diff --git a/UI/Web/src/app/_models/bookmark.ts b/UI/Web/src/app/_models/progress-bookmark.ts similarity index 66% rename from UI/Web/src/app/_models/bookmark.ts rename to UI/Web/src/app/_models/progress-bookmark.ts index 801cc399a..e8d0c22bd 100644 --- a/UI/Web/src/app/_models/bookmark.ts +++ b/UI/Web/src/app/_models/progress-bookmark.ts @@ -1,4 +1,4 @@ -export interface Bookmark { +export interface ProgressBookmark { pageNum: number; chapterId: number; bookScrollId?: string; diff --git a/UI/Web/src/app/_services/action-factory.service.ts b/UI/Web/src/app/_services/action-factory.service.ts index 2e0db2452..5b1e9f849 100644 --- a/UI/Web/src/app/_services/action-factory.service.ts +++ b/UI/Web/src/app/_services/action-factory.service.ts @@ -14,14 +14,15 @@ export enum Action { Edit = 4, Info = 5, RefreshMetadata = 6, - Download = 7 + Download = 7, + Bookmarks = 8 } export interface ActionItem { title: string; action: Action; callback: (action: Action, data: T) => void; - + requiresAdmin: boolean; } @Injectable({ @@ -58,43 +59,50 @@ export class ActionFactoryService { this.collectionTagActions.push({ action: Action.Edit, title: 'Edit', - callback: this.dummyCallback + callback: this.dummyCallback, + requiresAdmin: true }); this.seriesActions.push({ action: Action.ScanLibrary, title: 'Scan Series', - callback: this.dummyCallback + callback: this.dummyCallback, + requiresAdmin: true }); this.seriesActions.push({ action: Action.RefreshMetadata, title: 'Refresh Metadata', - callback: this.dummyCallback + callback: this.dummyCallback, + requiresAdmin: true }); this.seriesActions.push({ action: Action.Delete, title: 'Delete', - callback: this.dummyCallback + callback: this.dummyCallback, + requiresAdmin: true }); this.seriesActions.push({ action: Action.Edit, title: 'Edit', - callback: this.dummyCallback + callback: this.dummyCallback, + requiresAdmin: true }); this.libraryActions.push({ action: Action.ScanLibrary, title: 'Scan Library', - callback: this.dummyCallback + callback: this.dummyCallback, + requiresAdmin: true }); this.libraryActions.push({ action: Action.RefreshMetadata, title: 'Refresh Metadata', - callback: this.dummyCallback + callback: this.dummyCallback, + requiresAdmin: true }); } @@ -102,13 +110,15 @@ export class ActionFactoryService { this.volumeActions.push({ action: Action.Download, title: 'Download', - callback: this.dummyCallback + callback: this.dummyCallback, + requiresAdmin: false }); this.chapterActions.push({ action: Action.Download, title: 'Download', - callback: this.dummyCallback + callback: this.dummyCallback, + requiresAdmin: false }); } }); @@ -150,12 +160,20 @@ export class ActionFactoryService { { action: Action.MarkAsRead, title: 'Mark as Read', - callback: this.dummyCallback + callback: this.dummyCallback, + requiresAdmin: false }, { action: Action.MarkAsUnread, title: 'Mark as Unread', - callback: this.dummyCallback + callback: this.dummyCallback, + requiresAdmin: false + }, + { + action: Action.Bookmarks, + title: 'Bookmarks', + callback: this.dummyCallback, + requiresAdmin: false } ]; @@ -163,12 +181,14 @@ export class ActionFactoryService { { action: Action.MarkAsRead, title: 'Mark as Read', - callback: this.dummyCallback + callback: this.dummyCallback, + requiresAdmin: false }, { action: Action.MarkAsUnread, title: 'Mark as Unread', - callback: this.dummyCallback + callback: this.dummyCallback, + requiresAdmin: false } ]; @@ -176,25 +196,29 @@ export class ActionFactoryService { { action: Action.MarkAsRead, title: 'Mark as Read', - callback: this.dummyCallback + callback: this.dummyCallback, + requiresAdmin: false }, { action: Action.MarkAsUnread, title: 'Mark as Unread', - callback: this.dummyCallback + callback: this.dummyCallback, + requiresAdmin: false } ]; this.volumeActions.push({ action: Action.Info, title: 'Info', - callback: this.dummyCallback + callback: this.dummyCallback, + requiresAdmin: false }); this.chapterActions.push({ action: Action.Info, title: 'Info', - callback: this.dummyCallback + callback: this.dummyCallback, + requiresAdmin: false }); diff --git a/UI/Web/src/app/_services/action.service.ts b/UI/Web/src/app/_services/action.service.ts index 78e5d9f83..814dd49b0 100644 --- a/UI/Web/src/app/_services/action.service.ts +++ b/UI/Web/src/app/_services/action.service.ts @@ -1,7 +1,9 @@ import { Injectable, OnDestroy } from '@angular/core'; +import { NgbModal, NgbModalRef } from '@ng-bootstrap/ng-bootstrap'; import { ToastrService } from 'ngx-toastr'; import { forkJoin, Subject } from 'rxjs'; import { take, takeUntil } from 'rxjs/operators'; +import { BookmarksModalComponent } from '../_modals/bookmarks-modal/bookmarks-modal.component'; import { Chapter } from '../_models/chapter'; import { Library } from '../_models/library'; import { Series } from '../_models/series'; @@ -24,9 +26,10 @@ export type ChapterActionCallback = (chapter: Chapter) => void; export class ActionService implements OnDestroy { private readonly onDestroy = new Subject(); + private bookmarkModalRef: NgbModalRef | null = null; constructor(private libraryService: LibraryService, private seriesService: SeriesService, - private readerService: ReaderService, private toastr: ToastrService) { } + private readerService: ReaderService, private toastr: ToastrService, private modalService: NgbModal) { } ngOnDestroy() { this.onDestroy.next(); @@ -153,7 +156,7 @@ export class ActionService implements OnDestroy { * @param callback Optional callback to perform actions after API completes */ markVolumeAsUnread(seriesId: number, volume: Volume, callback?: VolumeActionCallback) { - forkJoin(volume.chapters?.map(chapter => this.readerService.bookmark(seriesId, volume.id, chapter.id, 0))).pipe(takeUntil(this.onDestroy)).subscribe(results => { + forkJoin(volume.chapters?.map(chapter => this.readerService.saveProgress(seriesId, volume.id, chapter.id, 0))).pipe(takeUntil(this.onDestroy)).subscribe(results => { volume.pagesRead = 0; volume.chapters?.forEach(c => c.pagesRead = 0); this.toastr.success('Marked as Unread'); @@ -170,7 +173,7 @@ export class ActionService implements OnDestroy { * @param callback Optional callback to perform actions after API completes */ markChapterAsRead(seriesId: number, chapter: Chapter, callback?: ChapterActionCallback) { - this.readerService.bookmark(seriesId, chapter.volumeId, chapter.id, chapter.pages).pipe(take(1)).subscribe(results => { + this.readerService.saveProgress(seriesId, chapter.volumeId, chapter.id, chapter.pages).pipe(take(1)).subscribe(results => { chapter.pagesRead = chapter.pages; this.toastr.success('Marked as Read'); if (callback) { @@ -186,7 +189,7 @@ export class ActionService implements OnDestroy { * @param callback Optional callback to perform actions after API completes */ markChapterAsUnread(seriesId: number, chapter: Chapter, callback?: ChapterActionCallback) { - this.readerService.bookmark(seriesId, chapter.volumeId, chapter.id, chapter.pages).pipe(take(1)).subscribe(results => { + this.readerService.saveProgress(seriesId, chapter.volumeId, chapter.id, chapter.pages).pipe(take(1)).subscribe(results => { chapter.pagesRead = 0; this.toastr.success('Marked as unread'); if (callback) { @@ -195,5 +198,23 @@ export class ActionService implements OnDestroy { }); } - + + openBookmarkModal(series: Series, callback?: SeriesActionCallback) { + if (this.bookmarkModalRef != null) { return; } + this.bookmarkModalRef = this.modalService.open(BookmarksModalComponent, { scrollable: true, size: 'lg' }); + this.bookmarkModalRef.componentInstance.series = series; + this.bookmarkModalRef.closed.pipe(take(1)).subscribe(() => { + this.bookmarkModalRef = null; + if (callback) { + callback(series); + } + }); + this.bookmarkModalRef.dismissed.pipe(take(1)).subscribe(() => { + this.bookmarkModalRef = null; + if (callback) { + callback(series); + } + }); + } + } diff --git a/UI/Web/src/app/_services/image.service.ts b/UI/Web/src/app/_services/image.service.ts index 377c2b0d9..2e8d3f83b 100644 --- a/UI/Web/src/app/_services/image.service.ts +++ b/UI/Web/src/app/_services/image.service.ts @@ -39,6 +39,10 @@ export class ImageService { return this.baseUrl + 'image/chapter-cover?chapterId=' + chapterId; } + getBookmarkedImage(chapterId: number, pageNum: number) { + return this.baseUrl + 'image/chapter-cover?chapterId=' + chapterId + '&pageNum=' + pageNum; + } + updateErroredImage(event: any) { event.target.src = this.placeholderImage; } diff --git a/UI/Web/src/app/_services/message-hub.service.ts b/UI/Web/src/app/_services/message-hub.service.ts index 948761d53..8683164c2 100644 --- a/UI/Web/src/app/_services/message-hub.service.ts +++ b/UI/Web/src/app/_services/message-hub.service.ts @@ -43,6 +43,9 @@ export class MessageHubService { this.updateNotificationModalRef.closed.subscribe(() => { this.updateNotificationModalRef = null; }); + this.updateNotificationModalRef.dismissed.subscribe(() => { + this.updateNotificationModalRef = null; + }); }); } diff --git a/UI/Web/src/app/_services/reader.service.ts b/UI/Web/src/app/_services/reader.service.ts index 9e13c80a7..8b358a386 100644 --- a/UI/Web/src/app/_services/reader.service.ts +++ b/UI/Web/src/app/_services/reader.service.ts @@ -3,8 +3,9 @@ import { Injectable } from '@angular/core'; import { environment } from 'src/environments/environment'; import { ChapterInfo } from '../manga-reader/_models/chapter-info'; import { UtilityService } from '../shared/_services/utility.service'; -import { Bookmark } from '../_models/bookmark'; import { Chapter } from '../_models/chapter'; +import { PageBookmark } from '../_models/page-bookmark'; +import { ProgressBookmark } from '../_models/progress-bookmark'; import { Volume } from '../_models/volume'; @Injectable({ @@ -19,20 +20,44 @@ export class ReaderService { constructor(private httpClient: HttpClient, private utilityService: UtilityService) { } - getBookmark(chapterId: number) { - return this.httpClient.get(this.baseUrl + 'reader/get-bookmark?chapterId=' + chapterId); + bookmark(seriesId: number, volumeId: number, chapterId: number, page: number) { + return this.httpClient.post(this.baseUrl + 'reader/bookmark', {seriesId, volumeId, chapterId, page}); + } + + unbookmark(seriesId: number, volumeId: number, chapterId: number, page: number) { + return this.httpClient.post(this.baseUrl + 'reader/unbookmark', {seriesId, volumeId, chapterId, page}); + } + + getBookmarks(chapterId: number) { + return this.httpClient.get(this.baseUrl + 'reader/get-bookmarks?chapterId=' + chapterId); + } + + getBookmarksForVolume(volumeId: number) { + return this.httpClient.get(this.baseUrl + 'reader/get-volume-bookmarks?volumeId=' + volumeId); + } + + getBookmarksForSeries(seriesId: number) { + return this.httpClient.get(this.baseUrl + 'reader/get-series-bookmarks?seriesId=' + seriesId); + } + + clearBookmarks(seriesId: number) { + return this.httpClient.post(this.baseUrl + 'reader/remove-bookmarks', {seriesId}); + } + + getProgress(chapterId: number) { + return this.httpClient.get(this.baseUrl + 'reader/get-progress?chapterId=' + chapterId); } getPageUrl(chapterId: number, page: number) { return this.baseUrl + 'reader/image?chapterId=' + chapterId + '&page=' + page; } - getChapterInfo(chapterId: number) { - return this.httpClient.get(this.baseUrl + 'reader/chapter-info?chapterId=' + chapterId); + getChapterInfo(seriesId: number, chapterId: number) { + return this.httpClient.get(this.baseUrl + 'reader/chapter-info?chapterId=' + chapterId + '&seriesId=' + seriesId); } - bookmark(seriesId: number, volumeId: number, chapterId: number, page: number, bookScrollId: string | null = null) { - return this.httpClient.post(this.baseUrl + 'reader/bookmark', {seriesId, volumeId, chapterId, pageNum: page, bookScrollId}); + saveProgress(seriesId: number, volumeId: number, chapterId: number, page: number, bookScrollId: string | null = null) { + return this.httpClient.post(this.baseUrl + 'reader/progress', {seriesId, volumeId, chapterId, pageNum: page, bookScrollId}); } markVolumeRead(seriesId: number, volumeId: number) { diff --git a/UI/Web/src/app/app.module.ts b/UI/Web/src/app/app.module.ts index e447669bc..3beec830c 100644 --- a/UI/Web/src/app/app.module.ts +++ b/UI/Web/src/app/app.module.ts @@ -39,6 +39,7 @@ import { RecentlyAddedComponent } from './recently-added/recently-added.componen import { LibraryCardComponent } from './library-card/library-card.component'; import { SeriesCardComponent } from './series-card/series-card.component'; import { InProgressComponent } from './in-progress/in-progress.component'; +import { BookmarksModalComponent } from './_modals/bookmarks-modal/bookmarks-modal.component'; let sentryProviders: any[] = []; @@ -104,7 +105,8 @@ if (environment.production) { RecentlyAddedComponent, LibraryCardComponent, SeriesCardComponent, - InProgressComponent + InProgressComponent, + BookmarksModalComponent ], imports: [ HttpClientModule, diff --git a/UI/Web/src/app/book-reader/book-reader/book-reader.component.ts b/UI/Web/src/app/book-reader/book-reader/book-reader.component.ts index a4ffa2873..209ff8388 100644 --- a/UI/Web/src/app/book-reader/book-reader/book-reader.component.ts +++ b/UI/Web/src/app/book-reader/book-reader/book-reader.component.ts @@ -114,15 +114,14 @@ export class BookReaderComponent implements OnInit, AfterViewInit, OnDestroy { currentPageAnchor: string = ''; intersectionObserver: IntersectionObserver = new IntersectionObserver((entries) => this.handleIntersection(entries), { threshold: [1] }); /** - * Last seen bookmark part path + * Last seen progress part path */ lastSeenScrollPartPath: string = ''; - - // Temp hack: Override background color for reader and restore it onDestroy + /** + * Hack: Override background color for reader and restore it onDestroy + */ originalBodyColor: string | undefined; - - darkModeStyles = ` *:not(input), *:not(select), *:not(code), *:not(:link), *:not(.ngx-toastr) { color: #dcdcdc !important; @@ -198,11 +197,11 @@ export class BookReaderComponent implements OnInit, AfterViewInit, OnDestroy { /** * After the page has loaded, setup the scroll handler. The scroll handler has 2 parts. One is if there are page anchors setup (aka page anchor elements linked with the - * table of content) then we calculate what has already been reached and grab the last reached one to bookmark. If page anchors aren't setup (toc missing), then try to bookmark + * table of content) then we calculate what has already been reached and grab the last reached one to save progress. If page anchors aren't setup (toc missing), then try to save progress * based on the last seen scroll part (xpath). */ ngAfterViewInit() { - // check scroll offset and if offset is after any of the "id" markers, bookmark it + // check scroll offset and if offset is after any of the "id" markers, save progress fromEvent(window, 'scroll') .pipe(debounceTime(200), takeUntil(this.onDestroy)).subscribe((event) => { if (this.isLoading) return; @@ -215,7 +214,7 @@ export class BookReaderComponent implements OnInit, AfterViewInit, OnDestroy { const alreadyReached = Object.values(this.pageAnchors).filter((i: number) => i <= verticalOffset); if (alreadyReached.length > 0) { this.currentPageAnchor = Object.keys(this.pageAnchors)[alreadyReached.length - 1]; - this.readerService.bookmark(this.seriesId, this.volumeId, this.chapterId, this.pageNum, this.lastSeenScrollPartPath).pipe(take(1)).subscribe(() => {/* No operation */}); + this.readerService.saveProgress(this.seriesId, this.volumeId, this.chapterId, this.pageNum, this.lastSeenScrollPartPath).pipe(take(1)).subscribe(() => {/* No operation */}); return; } else { this.currentPageAnchor = ''; @@ -223,7 +222,7 @@ export class BookReaderComponent implements OnInit, AfterViewInit, OnDestroy { } if (this.lastSeenScrollPartPath !== '') { - this.readerService.bookmark(this.seriesId, this.volumeId, this.chapterId, this.pageNum, this.lastSeenScrollPartPath).pipe(take(1)).subscribe(() => {/* No operation */}); + this.readerService.saveProgress(this.seriesId, this.volumeId, this.chapterId, this.pageNum, this.lastSeenScrollPartPath).pipe(take(1)).subscribe(() => {/* No operation */}); } }); } @@ -279,7 +278,7 @@ export class BookReaderComponent implements OnInit, AfterViewInit, OnDestroy { forkJoin({ chapter: this.seriesService.getChapter(this.chapterId), - bookmark: this.readerService.getBookmark(this.chapterId), + progress: this.readerService.getProgress(this.chapterId), chapters: this.bookService.getBookChapters(this.chapterId), info: this.bookService.getBookInfo(this.chapterId) }).pipe(take(1)).subscribe(results => { @@ -287,17 +286,17 @@ export class BookReaderComponent implements OnInit, AfterViewInit, OnDestroy { this.volumeId = results.chapter.volumeId; this.maxPages = results.chapter.pages; this.chapters = results.chapters; - this.pageNum = results.bookmark.pageNum; + this.pageNum = results.progress.pageNum; this.bookTitle = results.info; if (this.pageNum >= this.maxPages) { this.pageNum = this.maxPages - 1; - this.readerService.bookmark(this.seriesId, this.volumeId, this.chapterId, this.pageNum).pipe(take(1)).subscribe(() => {/* No operation */}); + this.readerService.saveProgress(this.seriesId, this.volumeId, this.chapterId, this.pageNum).pipe(take(1)).subscribe(() => {/* No operation */}); } - // Check if user bookmark has part, if so load it so we scroll to it - this.loadPage(results.bookmark.bookScrollId || undefined); + // Check if user progress has part, if so load it so we scroll to it + this.loadPage(results.progress.bookScrollId || undefined); }, () => { setTimeout(() => { this.closeReader(); @@ -484,7 +483,7 @@ export class BookReaderComponent implements OnInit, AfterViewInit, OnDestroy { loadPage(part?: string | undefined, scrollTop?: number | undefined) { this.isLoading = true; - this.readerService.bookmark(this.seriesId, this.volumeId, this.chapterId, this.pageNum).pipe(take(1)).subscribe(() => {/* No operation */}); + this.readerService.saveProgress(this.seriesId, this.volumeId, this.chapterId, this.pageNum).pipe(take(1)).subscribe(() => {/* No operation */}); this.bookService.getBookPage(this.chapterId, this.pageNum).pipe(take(1)).subscribe(content => { this.page = this.domSanitizer.bypassSecurityTrustHtml(content); diff --git a/UI/Web/src/app/manga-reader/manga-reader.component.html b/UI/Web/src/app/manga-reader/manga-reader.component.html index f37d8a94c..1dd55b6f3 100644 --- a/UI/Web/src/app/manga-reader/manga-reader.component.html +++ b/UI/Web/src/app/manga-reader/manga-reader.component.html @@ -12,6 +12,9 @@ {{subtitle}} +
+ +
diff --git a/UI/Web/src/app/manga-reader/manga-reader.component.ts b/UI/Web/src/app/manga-reader/manga-reader.component.ts index 81395d811..4dc6fe371 100644 --- a/UI/Web/src/app/manga-reader/manga-reader.component.ts +++ b/UI/Web/src/app/manga-reader/manga-reader.component.ts @@ -183,6 +183,10 @@ export class MangaReaderComponent implements OnInit, AfterViewInit, OnDestroy { * If extended settings area is visible. Blocks auto-closing of menu. */ settingsOpen: boolean = false; + /** + * A map of bookmarked pages to anything. Used for O(1) lookup time if a page is bookmarked or not. + */ + bookmarks: {[key: string]: number} = {}; private readonly onDestroy = new Subject(); @@ -191,6 +195,9 @@ export class MangaReaderComponent implements OnInit, AfterViewInit, OnDestroy { + get pageBookmarked() { + return this.bookmarks.hasOwnProperty(this.pageNum); + } get splitIconClass() { @@ -348,13 +355,14 @@ export class MangaReaderComponent implements OnInit, AfterViewInit, OnDestroy { this.pageNum = 1; forkJoin({ - bookmark: this.readerService.getBookmark(this.chapterId), - chapterInfo: this.readerService.getChapterInfo(this.chapterId) + progress: this.readerService.getProgress(this.chapterId), + chapterInfo: this.readerService.getChapterInfo(this.seriesId, this.chapterId), + bookmarks: this.readerService.getBookmarks(this.chapterId) }).pipe(take(1)).subscribe(results => { this.volumeId = results.chapterInfo.volumeId; this.maxPages = results.chapterInfo.pages; - let page = results.bookmark.pageNum; + let page = results.progress.pageNum; if (page >= this.maxPages) { page = this.maxPages - 1; } @@ -367,6 +375,12 @@ export class MangaReaderComponent implements OnInit, AfterViewInit, OnDestroy { this.updateTitle(results.chapterInfo); + // From bookmarks, create map of pages to make lookup time O(1) + this.bookmarks = {}; + results.bookmarks.forEach(bookmark => { + this.bookmarks[bookmark.page] = 1; + }); + this.readerService.getNextChapter(this.seriesId, this.volumeId, this.chapterId).pipe(take(1)).subscribe(chapterId => { this.nextChapterId = chapterId; if (chapterId === CHAPTER_ID_DOESNT_EXIST || chapterId === this.chapterId) { @@ -747,14 +761,14 @@ export class MangaReaderComponent implements OnInit, AfterViewInit, OnDestroy { loadPage() { if (!this.canvas || !this.ctx) { return; } - // Due to the fact that we start at image 0, but page 1, we need the last page to be bookmarked as page + 1 to be completed + // Due to the fact that we start at image 0, but page 1, we need the last page to have progress as page + 1 to be completed let pageNum = this.pageNum; if (this.pageNum == this.maxPages - 1) { pageNum = this.pageNum + 1; } - this.readerService.bookmark(this.seriesId, this.volumeId, this.chapterId, pageNum).pipe(take(1)).subscribe(() => {/* No operation */}); + this.readerService.saveProgress(this.seriesId, this.volumeId, this.chapterId, pageNum).pipe(take(1)).subscribe(() => {/* No operation */}); this.isLoading = true; this.canvasImage = this.cachedImages.current(); @@ -814,13 +828,13 @@ export class MangaReaderComponent implements OnInit, AfterViewInit, OnDestroy { if (this.pageNum >= this.maxPages - 10) { // Tell server to cache the next chapter if (this.nextChapterId > 0 && !this.nextChapterPrefetched) { - this.readerService.getChapterInfo(this.nextChapterId).pipe(take(1)).subscribe(res => { + this.readerService.getChapterInfo(this.seriesId, this.nextChapterId).pipe(take(1)).subscribe(res => { this.nextChapterPrefetched = true; }); } } else if (this.pageNum <= 10) { if (this.prevChapterId > 0 && !this.prevChapterPrefetched) { - this.readerService.getChapterInfo(this.prevChapterId).pipe(take(1)).subscribe(res => { + this.readerService.getChapterInfo(this.seriesId, this.prevChapterId).pipe(take(1)).subscribe(res => { this.prevChapterPrefetched = true; }); } @@ -905,7 +919,7 @@ export class MangaReaderComponent implements OnInit, AfterViewInit, OnDestroy { handleWebtoonPageChange(updatedPageNum: number) { this.setPageNum(updatedPageNum); - this.readerService.bookmark(this.seriesId, this.volumeId, this.chapterId, this.pageNum).pipe(take(1)).subscribe(() => {/* No operation */}); + this.readerService.saveProgress(this.seriesId, this.volumeId, this.chapterId, this.pageNum).pipe(take(1)).subscribe(() => {/* No operation */}); } saveSettings() { @@ -945,4 +959,22 @@ export class MangaReaderComponent implements OnInit, AfterViewInit, OnDestroy { this.updateForm(); } + + /** + * Bookmarks the current page for the chapter + */ + bookmarkPage() { + const pageNum = this.pageNum; + if (this.pageBookmarked) { + // Remove bookmark + this.readerService.unbookmark(this.seriesId, this.volumeId, this.chapterId, pageNum).pipe(take(1)).subscribe(() => { + delete this.bookmarks[pageNum]; + }); + } else { + this.readerService.bookmark(this.seriesId, this.volumeId, this.chapterId, pageNum).pipe(take(1)).subscribe(() => { + this.bookmarks[pageNum] = 1; + }); + } + + } } diff --git a/UI/Web/src/app/series-card/series-card.component.ts b/UI/Web/src/app/series-card/series-card.component.ts index 5eccd3149..471035c3d 100644 --- a/UI/Web/src/app/series-card/series-card.component.ts +++ b/UI/Web/src/app/series-card/series-card.component.ts @@ -10,6 +10,7 @@ import { ImageService } from 'src/app/_services/image.service'; import { ActionFactoryService, Action, ActionItem } from 'src/app/_services/action-factory.service'; import { SeriesService } from 'src/app/_services/series.service'; import { ConfirmService } from '../shared/confirm.service'; +import { ActionService } from '../_services/action.service'; @Component({ selector: 'app-series-card', @@ -30,7 +31,8 @@ export class SeriesCardComponent implements OnInit, OnChanges { constructor(private accountService: AccountService, private router: Router, private seriesService: SeriesService, private toastr: ToastrService, private modalService: NgbModal, private confirmService: ConfirmService, - public imageService: ImageService, private actionFactoryService: ActionFactoryService) { + public imageService: ImageService, private actionFactoryService: ActionFactoryService, + private actionService: ActionService) { this.accountService.currentUser$.pipe(take(1)).subscribe(user => { if (user) { this.isAdmin = this.accountService.hasAdminRole(user); @@ -68,6 +70,9 @@ export class SeriesCardComponent implements OnInit, OnChanges { case(Action.Edit): this.openEditModal(series); break; + case(Action.Bookmarks): + this.actionService.openBookmarkModal(series, (series) => {/* No Operation */ }); + break; default: break; } diff --git a/UI/Web/src/app/series-detail/series-detail.component.html b/UI/Web/src/app/series-detail/series-detail.component.html index 9f27e980d..fe4f347eb 100644 --- a/UI/Web/src/app/series-detail/series-detail.component.html +++ b/UI/Web/src/app/series-detail/series-detail.component.html @@ -13,12 +13,11 @@
-
diff --git a/UI/Web/src/app/series-detail/series-detail.component.ts b/UI/Web/src/app/series-detail/series-detail.component.ts index f57d7fd8a..cb99db874 100644 --- a/UI/Web/src/app/series-detail/series-detail.component.ts +++ b/UI/Web/src/app/series-detail/series-detail.component.ts @@ -150,6 +150,9 @@ export class SeriesDetailComponent implements OnInit { case(Action.Delete): this.deleteSeries(series); break; + case(Action.Bookmarks): + this.actionService.openBookmarkModal(series, (series) => this.actionInProgress = false); + break; default: break; } diff --git a/UI/Web/src/app/shared/_services/download.service.ts b/UI/Web/src/app/shared/_services/download.service.ts index cb6db908e..6b254541c 100644 --- a/UI/Web/src/app/shared/_services/download.service.ts +++ b/UI/Web/src/app/shared/_services/download.service.ts @@ -7,6 +7,8 @@ import { saveAs } from 'file-saver'; import { Chapter } from 'src/app/_models/chapter'; import { Volume } from 'src/app/_models/volume'; import { ToastrService } from 'ngx-toastr'; +import { PageBookmark } from 'src/app/_models/page-bookmark'; +import { map, take } from 'rxjs/operators'; @Injectable({ providedIn: 'root' @@ -85,6 +87,12 @@ export class DownloadService { }); } + downloadBookmarks(bookmarks: PageBookmark[], seriesName: string) { + return this.httpClient.post(this.baseUrl + 'download/bookmarks', {bookmarks}, {observe: 'response', responseType: 'blob' as 'text'}).pipe(take(1), map(resp => { + this.preformSave(resp.body || '', this.getFilenameFromHeader(resp.headers, seriesName)); + })); + } + private preformSave(res: string, filename: string) { const blob = new Blob([res], {type: 'text/plain;charset=utf-8'}); saveAs(blob, filename); diff --git a/UI/Web/src/app/shared/card-item/card-actionables/card-actionables.component.html b/UI/Web/src/app/shared/card-item/card-actionables/card-actionables.component.html index 8f3057ae6..2509711cb 100644 --- a/UI/Web/src/app/shared/card-item/card-actionables/card-actionables.component.html +++ b/UI/Web/src/app/shared/card-item/card-actionables/card-actionables.component.html @@ -2,7 +2,9 @@
- + + +
\ No newline at end of file diff --git a/UI/Web/src/app/shared/card-item/card-actionables/card-actionables.component.ts b/UI/Web/src/app/shared/card-item/card-actionables/card-actionables.component.ts index 37434ff96..b7441e62c 100644 --- a/UI/Web/src/app/shared/card-item/card-actionables/card-actionables.component.ts +++ b/UI/Web/src/app/shared/card-item/card-actionables/card-actionables.component.ts @@ -15,9 +15,15 @@ export class CardActionablesComponent implements OnInit { @Input() disabled: boolean = false; @Output() actionHandler = new EventEmitter>(); + adminActions: ActionItem[] = []; + nonAdminActions: ActionItem[] = []; + + constructor() { } ngOnInit(): void { + this.nonAdminActions = this.actions.filter(item => !item.requiresAdmin); + this.adminActions = this.actions.filter(item => item.requiresAdmin); } preventClick(event: any) { @@ -33,4 +39,7 @@ export class CardActionablesComponent implements OnInit { } } + // TODO: Insert hr to separate admin actions + + } diff --git a/UI/Web/src/app/shared/confirm.service.ts b/UI/Web/src/app/shared/confirm.service.ts index c1ef77393..72344ca08 100644 --- a/UI/Web/src/app/shared/confirm.service.ts +++ b/UI/Web/src/app/shared/confirm.service.ts @@ -1,5 +1,6 @@ import { Injectable } from '@angular/core'; import { NgbModal } from '@ng-bootstrap/ng-bootstrap'; +import { take } from 'rxjs/operators'; import { ConfirmDialogComponent } from './confirm-dialog/confirm-dialog.component'; import { ConfirmConfig } from './confirm-dialog/_models/confirm-config'; @@ -36,9 +37,12 @@ export class ConfirmService { const modalRef = this.modalService.open(ConfirmDialogComponent); modalRef.componentInstance.config = config; - modalRef.closed.subscribe(result => { + modalRef.closed.pipe(take(1)).subscribe(result => { return resolve(result); }); + modalRef.dismissed.pipe(take(1)).subscribe(() => { + return reject(false); + }); }); } @@ -57,9 +61,12 @@ export class ConfirmService { const modalRef = this.modalService.open(ConfirmDialogComponent); modalRef.componentInstance.config = config; - modalRef.closed.subscribe(result => { + modalRef.closed.pipe(take(1)).subscribe(result => { return resolve(result); }); + modalRef.dismissed.pipe(take(1)).subscribe(() => { + return reject(false); + }); }) } } diff --git a/UI/Web/src/styles.scss b/UI/Web/src/styles.scss index 1ce68054c..0e3faf2d4 100644 --- a/UI/Web/src/styles.scss +++ b/UI/Web/src/styles.scss @@ -46,9 +46,10 @@ body { font-family: "EBGaramond", "Helvetica Neue", sans-serif; } -// .disabled, :disabled { -// cursor: not-allowed !important; -// } + +.btn-icon { + cursor: pointer; +} // Slider handle override ::ng-deep {