Kavita/API/Controllers/ReaderController.cs
Joseph Milazzo cf4fd2cb9c
Bugs, Enhancements, and Performance (#580)
* Added parser case for "The Duke of Death and His Black Maid - Ch. 177 - The Ball (3).cbz"

* Removed a file that is created and modified every test run.

* Fixed a bad parser case for "Batman Beyond 02 (of 6) (1999)" which was consuming too many characters

* Removed a lot of "Volume" parsing for Comics that don't make sense. This is prep work for the upcoming Comic Rework release.

* Reworked a lot of parsing cases for comics based on naming conventions observed from releases found online.

* Added a way for external scripts to use a user api key to authenticate

* Fixed an issue if the manga only had one page, the bottom menu would be missing page and chapter controls.

* Fixed a bug where on small phones, nav bar could overflow due to scroll to top

* Tweaked a lot of regex for manga parsing to handle some cases where poorly named files, like "Vol. 03 Ch. 21" would end up parsing as Series "Vol. 03".

* Even more handling of parser cases. Manga parser should be as it was but more robust to handle bad naming.

* Fixed: Don't force metadata refresh on Scan Series, only on refresh metadata

* Implemented the ability to automatically refresh after a series scan based on when server finishes. Remove a duplicate API call from series detail.

* Removed another API call for series metadata that isn't needed.

* Refactored Message creation to a factory, hardcoded strings are centralized, and RefreshSeriesMetadata sends an event and is refactored to be async.

* Fixed a bug when really poorly named files are within a folder that contains the series name, fallback couldn't occur due to it being taken as root folder. Now we detect said condition and will go one level higher, resulting in potentially more I/O, but the series will not be deleted.

* Added the Read in Incognito context item for Chapter cards

* Skip an additional check for series summary for series that aren't EPUB or Archive formats.

* Fixed an issue where cover image generation could occur due to a bad check on LastWriteTime on the underlying file.

* Added some extra comic parser tests

* Added a ScanLibrary event (not hooked up in UI)

* Performance improvement on metadata service. Now when we scan for cover image changes, we emit when a change occurs and only then do we update parent entities (array copy).

* Removed an hr from series detail and ensure we update the cover image for series when scan series finishes.

* Updated the infinite scroller to use a Flags pattern for the debug mode. Updated a few logical conditions for mobile.

* Removed the concurrency check on row progress as if too many calls hit the DB, it will throw, but it doesn't matter.

Fixed a bad logic code which could cause scrolling after hitting the bottom of the chapter.

* Ensure prefetching uses totalPages + 1 since we pass in totalPages as - 1 from manga reader

* Fixed issue where last page of webtoon wouldn't be prefetched due to a < instead of <= on prefetching code

* Implemented ability to send images from archives to the UI without incurring any extra memory pressure.

* Dropdown menus now have a darker background

* Webtoon reader now works on mobile.

* Fixed how keyboard presses for up/down/left/right work with MANGA_UD reading mode. See issue #579

* Fixed cont reader for webtoons on mobile

* Fixed a small issue where top spacer would too quickly switch to prev chapter

* Updated user preferences to use same slider style. Removed some css that is not used.

* Added comic parser case for "Saga 001 (2012) (Digital) (Empire-Zone)"

* Added accessibility toggle to reading list order and aligned sliders to all use the same style.

* Removed a todo for checking on new image serving code. It works great.

* Fixed a missing await

* Auth guard will now check if an existing toast is present giving same message before poping the toast.

* Fixed alignment on phones for reading lists

* Moved sorters so they aren't resused between multiple threads. Slightly higher memory footprint.

* Fixed a broken unit test

* Code smells

* More unit test fixing
2021-09-15 11:06:29 -07:00

525 lines
20 KiB
C#

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using API.Data.Repositories;
using API.DTOs;
using API.DTOs.Reader;
using API.Entities;
using API.Extensions;
using API.Interfaces;
using API.Interfaces.Services;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
namespace API.Controllers
{
/// <summary>
/// For all things regarding reading, mainly focusing on non-Book related entities
/// </summary>
public class ReaderController : BaseApiController
{
private readonly ICacheService _cacheService;
private readonly IUnitOfWork _unitOfWork;
private readonly ILogger<ReaderController> _logger;
private readonly IReaderService _readerService;
/// <inheritdoc />
public ReaderController(ICacheService cacheService,
IUnitOfWork unitOfWork, ILogger<ReaderController> logger, IReaderService readerService)
{
_cacheService = cacheService;
_unitOfWork = unitOfWork;
_logger = logger;
_readerService = readerService;
}
/// <summary>
/// Returns an image for a given chapter. Side effect: This will cache the chapter images for reading.
/// </summary>
/// <param name="chapterId"></param>
/// <param name="page"></param>
/// <returns></returns>
[HttpGet("image")]
public async Task<ActionResult> GetImage(int chapterId, int page)
{
if (page < 0) page = 0;
var chapter = await _cacheService.Ensure(chapterId);
if (chapter == null) return BadRequest("There was an issue finding image file for reading");
try
{
var (path, _) = await _cacheService.GetCachedPagePath(chapter, page);
if (string.IsNullOrEmpty(path) || !System.IO.File.Exists(path)) return BadRequest($"No such image for page {page}");
var format = Path.GetExtension(path).Replace(".", "");
return PhysicalFile(path, "image/" + format);
}
catch (Exception)
{
_cacheService.CleanupChapters(new []{ chapterId });
throw;
}
}
/// <summary>
/// Returns various information about a Chapter. Side effect: This will cache the chapter images for reading.
/// </summary>
/// <param name="chapterId"></param>
/// <returns></returns>
[HttpGet("chapter-info")]
public async Task<ActionResult<ChapterInfoDto>> GetChapterInfo(int chapterId)
{
var chapter = await _cacheService.Ensure(chapterId);
if (chapter == null) return BadRequest("Could not find Chapter");
var dto = await _unitOfWork.ChapterRepository.GetChapterInfoDtoAsync(chapterId);
var mangaFile = (await _unitOfWork.ChapterRepository.GetFilesForChapterAsync(chapterId)).First();
return Ok(new ChapterInfoDto()
{
ChapterNumber = dto.ChapterNumber,
VolumeNumber = dto.VolumeNumber,
VolumeId = dto.VolumeId,
FileName = Path.GetFileName(mangaFile.FilePath),
SeriesName = dto.SeriesName,
SeriesFormat = dto.SeriesFormat,
SeriesId = dto.SeriesId,
LibraryId = dto.LibraryId,
IsSpecial = dto.IsSpecial,
Pages = dto.Pages,
});
}
[HttpPost("mark-read")]
public async Task<ActionResult> MarkRead(MarkReadDto markReadDto)
{
var user = await _unitOfWork.UserRepository.GetUserByUsernameAsync(User.GetUsername(), AppUserIncludes.Progress);
var volumes = await _unitOfWork.SeriesRepository.GetVolumes(markReadDto.SeriesId);
user.Progresses ??= new List<AppUserProgress>();
foreach (var volume in volumes)
{
foreach (var chapter in volume.Chapters)
{
var userProgress = GetUserProgressForChapter(user, chapter);
if (userProgress == null)
{
user.Progresses.Add(new AppUserProgress
{
PagesRead = chapter.Pages,
VolumeId = volume.Id,
SeriesId = markReadDto.SeriesId,
ChapterId = chapter.Id
});
}
else
{
userProgress.PagesRead = chapter.Pages;
userProgress.SeriesId = markReadDto.SeriesId;
userProgress.VolumeId = volume.Id;
}
}
}
_unitOfWork.UserRepository.Update(user);
if (await _unitOfWork.CommitAsync())
{
return Ok();
}
return BadRequest("There was an issue saving progress");
}
private static AppUserProgress GetUserProgressForChapter(AppUser user, Chapter chapter)
{
AppUserProgress userProgress = null;
try
{
userProgress =
user.Progresses.SingleOrDefault(x => x.ChapterId == chapter.Id && x.AppUserId == user.Id);
}
catch (Exception)
{
// There is a very rare chance that user progress will duplicate current row. If that happens delete one with less pages
var progresses = user.Progresses.Where(x => x.ChapterId == chapter.Id && x.AppUserId == user.Id).ToList();
if (progresses.Count > 1)
{
user.Progresses = new List<AppUserProgress>()
{
user.Progresses.First()
};
userProgress = user.Progresses.First();
}
}
return userProgress;
}
/// <summary>
/// Marks a Series as Unread (progress)
/// </summary>
/// <param name="markReadDto"></param>
/// <returns></returns>
[HttpPost("mark-unread")]
public async Task<ActionResult> MarkUnread(MarkReadDto markReadDto)
{
var user = await _unitOfWork.UserRepository.GetUserByUsernameAsync(User.GetUsername(), AppUserIncludes.Progress);
var volumes = await _unitOfWork.SeriesRepository.GetVolumes(markReadDto.SeriesId);
user.Progresses ??= new List<AppUserProgress>();
foreach (var volume in volumes)
{
foreach (var chapter in volume.Chapters)
{
var userProgress = GetUserProgressForChapter(user, chapter);
if (userProgress == null) continue;
userProgress.PagesRead = 0;
userProgress.SeriesId = markReadDto.SeriesId;
userProgress.VolumeId = volume.Id;
}
}
_unitOfWork.UserRepository.Update(user);
if (await _unitOfWork.CommitAsync())
{
return Ok();
}
return BadRequest("There was an issue saving progress");
}
/// <summary>
/// Marks all chapters within a volume as unread
/// </summary>
/// <param name="markVolumeReadDto"></param>
/// <returns></returns>
[HttpPost("mark-volume-unread")]
public async Task<ActionResult> MarkVolumeAsUnread(MarkVolumeReadDto markVolumeReadDto)
{
var user = await _unitOfWork.UserRepository.GetUserByUsernameAsync(User.GetUsername(), AppUserIncludes.Progress);
var chapters = await _unitOfWork.ChapterRepository.GetChaptersAsync(markVolumeReadDto.VolumeId);
foreach (var chapter in chapters)
{
user.Progresses ??= new List<AppUserProgress>();
var userProgress = user.Progresses.FirstOrDefault(x => x.ChapterId == chapter.Id && x.AppUserId == user.Id);
if (userProgress == null)
{
user.Progresses.Add(new AppUserProgress
{
PagesRead = 0,
VolumeId = markVolumeReadDto.VolumeId,
SeriesId = markVolumeReadDto.SeriesId,
ChapterId = chapter.Id
});
}
else
{
userProgress.PagesRead = 0;
userProgress.SeriesId = markVolumeReadDto.SeriesId;
userProgress.VolumeId = markVolumeReadDto.VolumeId;
}
}
_unitOfWork.UserRepository.Update(user);
if (await _unitOfWork.CommitAsync())
{
return Ok();
}
return BadRequest("Could not save progress");
}
/// <summary>
/// Marks all chapters within a volume as Read
/// </summary>
/// <param name="markVolumeReadDto"></param>
/// <returns></returns>
[HttpPost("mark-volume-read")]
public async Task<ActionResult> MarkVolumeAsRead(MarkVolumeReadDto markVolumeReadDto)
{
var user = await _unitOfWork.UserRepository.GetUserByUsernameAsync(User.GetUsername(), AppUserIncludes.Progress);
var chapters = await _unitOfWork.ChapterRepository.GetChaptersAsync(markVolumeReadDto.VolumeId);
foreach (var chapter in chapters)
{
user.Progresses ??= new List<AppUserProgress>();
var userProgress = user.Progresses.FirstOrDefault(x => x.ChapterId == chapter.Id && x.AppUserId == user.Id);
if (userProgress == null)
{
user.Progresses.Add(new AppUserProgress
{
PagesRead = chapter.Pages,
VolumeId = markVolumeReadDto.VolumeId,
SeriesId = markVolumeReadDto.SeriesId,
ChapterId = chapter.Id
});
}
else
{
userProgress.PagesRead = chapter.Pages;
userProgress.SeriesId = markVolumeReadDto.SeriesId;
userProgress.VolumeId = markVolumeReadDto.VolumeId;
}
}
_unitOfWork.UserRepository.Update(user);
if (await _unitOfWork.CommitAsync())
{
return Ok();
}
return BadRequest("Could not save progress");
}
/// <summary>
/// Returns Progress (page number) for a chapter for the logged in user
/// </summary>
/// <param name="chapterId"></param>
/// <returns></returns>
[HttpGet("get-progress")]
public async Task<ActionResult<ProgressDto>> GetProgress(int chapterId)
{
var user = await _unitOfWork.UserRepository.GetUserByUsernameAsync(User.GetUsername(), AppUserIncludes.Progress);
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);
}
/// <summary>
/// Save page against Chapter for logged in user
/// </summary>
/// <param name="progressDto"></param>
/// <returns></returns>
[HttpPost("progress")]
public async Task<ActionResult> BookmarkProgress(ProgressDto progressDto)
{
var user = await _unitOfWork.UserRepository.GetUserByUsernameAsync(User.GetUsername());
if (await _readerService.SaveReadingProgress(progressDto, user.Id)) return Ok(true);
return BadRequest("Could not save progress");
}
/// <summary>
/// Returns a list of bookmarked pages for a given Chapter
/// </summary>
/// <param name="chapterId"></param>
/// <returns></returns>
[HttpGet("get-bookmarks")]
public async Task<ActionResult<IEnumerable<BookmarkDto>>> GetBookmarks(int chapterId)
{
var user = await _unitOfWork.UserRepository.GetUserByUsernameAsync(User.GetUsername(), AppUserIncludes.Bookmarks);
if (user.Bookmarks == null) return Ok(Array.Empty<BookmarkDto>());
return Ok(await _unitOfWork.UserRepository.GetBookmarkDtosForChapter(user.Id, chapterId));
}
/// <summary>
/// Returns a list of all bookmarked pages for a User
/// </summary>
/// <returns></returns>
[HttpGet("get-all-bookmarks")]
public async Task<ActionResult<IEnumerable<BookmarkDto>>> GetAllBookmarks()
{
var user = await _unitOfWork.UserRepository.GetUserByUsernameAsync(User.GetUsername(), AppUserIncludes.Bookmarks);
if (user.Bookmarks == null) return Ok(Array.Empty<BookmarkDto>());
return Ok(await _unitOfWork.UserRepository.GetAllBookmarkDtos(user.Id));
}
/// <summary>
/// Removes all bookmarks for all chapters linked to a Series
/// </summary>
/// <param name="dto"></param>
/// <returns></returns>
[HttpPost("remove-bookmarks")]
public async Task<ActionResult> RemoveBookmarks(RemoveBookmarkForSeriesDto dto)
{
var user = await _unitOfWork.UserRepository.GetUserByUsernameAsync(User.GetUsername(), AppUserIncludes.Bookmarks);
if (user.Bookmarks == null) return Ok("Nothing to remove");
try
{
user.Bookmarks = user.Bookmarks.Where(bmk => bmk.SeriesId != dto.SeriesId).ToList();
_unitOfWork.UserRepository.Update(user);
if (await _unitOfWork.CommitAsync())
{
return Ok();
}
}
catch (Exception ex)
{
_logger.LogError(ex, "There was an exception when trying to clear bookmarks");
await _unitOfWork.RollbackAsync();
}
return BadRequest("Could not clear bookmarks");
}
/// <summary>
/// Returns all bookmarked pages for a given volume
/// </summary>
/// <param name="volumeId"></param>
/// <returns></returns>
[HttpGet("get-volume-bookmarks")]
public async Task<ActionResult<IEnumerable<BookmarkDto>>> GetBookmarksForVolume(int volumeId)
{
var user = await _unitOfWork.UserRepository.GetUserByUsernameAsync(User.GetUsername(), AppUserIncludes.Bookmarks);
if (user.Bookmarks == null) return Ok(Array.Empty<BookmarkDto>());
return Ok(await _unitOfWork.UserRepository.GetBookmarkDtosForVolume(user.Id, volumeId));
}
/// <summary>
/// Returns all bookmarked pages for a given series
/// </summary>
/// <param name="seriesId"></param>
/// <returns></returns>
[HttpGet("get-series-bookmarks")]
public async Task<ActionResult<IEnumerable<BookmarkDto>>> GetBookmarksForSeries(int seriesId)
{
var user = await _unitOfWork.UserRepository.GetUserByUsernameAsync(User.GetUsername(), AppUserIncludes.Bookmarks);
if (user.Bookmarks == null) return Ok(Array.Empty<BookmarkDto>());
return Ok(await _unitOfWork.UserRepository.GetBookmarkDtosForSeries(user.Id, seriesId));
}
/// <summary>
/// Bookmarks a page against a Chapter
/// </summary>
/// <param name="bookmarkDto"></param>
/// <returns></returns>
[HttpPost("bookmark")]
public async Task<ActionResult> BookmarkPage(BookmarkDto bookmarkDto)
{
// Don't let user save past total pages.
bookmarkDto.Page = await _readerService.CapPageToChapter(bookmarkDto.ChapterId, bookmarkDto.Page);
try
{
var user = await _unitOfWork.UserRepository.GetUserByUsernameAsync(User.GetUsername(), AppUserIncludes.Bookmarks);
var userBookmark =
await _unitOfWork.UserRepository.GetBookmarkForPage(bookmarkDto.Page, bookmarkDto.ChapterId, user.Id);
if (userBookmark == null)
{
user.Bookmarks ??= new List<AppUserBookmark>();
user.Bookmarks.Add(new AppUserBookmark()
{
Page = bookmarkDto.Page,
VolumeId = bookmarkDto.VolumeId,
SeriesId = bookmarkDto.SeriesId,
ChapterId = bookmarkDto.ChapterId,
});
_unitOfWork.UserRepository.Update(user);
}
if (await _unitOfWork.CommitAsync())
{
return Ok();
}
}
catch (Exception)
{
await _unitOfWork.RollbackAsync();
}
return BadRequest("Could not save bookmark");
}
/// <summary>
/// Removes a bookmarked page for a Chapter
/// </summary>
/// <param name="bookmarkDto"></param>
/// <returns></returns>
[HttpPost("unbookmark")]
public async Task<ActionResult> UnBookmarkPage(BookmarkDto bookmarkDto)
{
var user = await _unitOfWork.UserRepository.GetUserByUsernameAsync(User.GetUsername(), AppUserIncludes.Bookmarks);
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");
}
/// <summary>
/// Returns the next logical chapter from the series.
/// </summary>
/// <example>
/// V1 → V2 → V3 chapter 0 → V3 chapter 10 → SP 01 → SP 02
/// </example>
/// <param name="seriesId"></param>
/// <param name="volumeId"></param>
/// <param name="currentChapterId"></param>
/// <returns>chapter id for next manga</returns>
[HttpGet("next-chapter")]
public async Task<ActionResult<int>> GetNextChapter(int seriesId, int volumeId, int currentChapterId)
{
var userId = await _unitOfWork.UserRepository.GetUserIdByUsernameAsync(User.GetUsername());
return await _readerService.GetNextChapterIdAsync(seriesId, volumeId, currentChapterId, userId);
}
/// <summary>
/// Returns the previous logical chapter from the series.
/// </summary>
/// <example>
/// V1 ← V2 ← V3 chapter 0 ← V3 chapter 10 ← SP 01 ← SP 02
/// </example>
/// <param name="seriesId"></param>
/// <param name="volumeId"></param>
/// <param name="currentChapterId"></param>
/// <returns>chapter id for next manga</returns>
[HttpGet("prev-chapter")]
public async Task<ActionResult<int>> GetPreviousChapter(int seriesId, int volumeId, int currentChapterId)
{
var userId = await _unitOfWork.UserRepository.GetUserIdByUsernameAsync(User.GetUsername());
return await _readerService.GetPrevChapterIdAsync(seriesId, volumeId, currentChapterId, userId);
}
}
}