Kavita/API/Controllers/BookController.cs
Joe Milazzo a545f96a05
First PR of the new year (#1717)
* Fixed a bug on bookmark mode not finding correct image for prefetcher.

* Fixed up the edit series relationship modal on tablet viewports.

* On double page mode, only bookmark 1 page if only 1 pages is renderered on screen.

* Added percentage read of a given library and average hours read per week to user stats.

* Fixed a bug in the reader with paging in bookmark mode

* Added a "This Week" option to top readers history

* Added date ranges for reading time. Added dates that don't have anything, but might remove.

* On phone, when applying a metadata filter, when clicking apply, collapse the filter automatically.

* Disable jump bar and the resuming from last spot when a custom sort is applied.

* Ensure all Regex.Replace or Matches have timeouts set

* Fixed a long standing bug where fit to height on tablets wouldn't center the image

* Streamlined url parsing to be more reliable

* Reduced an additional db query in chapter info.

* Added a missing task to convert covers to webP and added messaging to help the user understand to run it after modifying the setting.

* Changed OPDS to be enabled by default for new installs. This should reduce issues with users being confused about it before it's enabled.

* When there are multiple files for a chapter, show a count card on the series detail to help user understand duplicates exist. Made the unread badge smaller to avoid collision.

* Added Word Count to user stats and wired up average reading per week.

* Fixed word count failing on some epubs

* Removed some debug code

* Don't give more information than is necessary about file paths for page dimensions.

* Fixed a bug where pagination area would be too small when the book's content was less that height on default mode.

* Updated Default layout mode to Scroll for books.

* Added bytes in the UI and at an API layer for CDisplayEx

* Don't log health checks to logs at all.

* Changed Word Count to Length to match the way pages work

* Made reading time more clear when min hours is 0

* Apply more aggressive coalescing when remapping bad metadata keys for epubs.

* Changed the amount of padding between icon and text for side nav item.

* Fixed a NPE on book reader (harmless)

* Fixed an ordering issue where Volume 1 was a single file but also tagged as Chapter 1 and Volume 2 was Chapter 0. Thus Volume 2 was being selected for continue point when Volume 1 should have been.

* When clicking on an activity stream header from dashboard, show the title on the resulting page.

* Removed a property that can't be animated

* Fixed a typeahead typescript issue

* Added Size into Series Info and Added some tooltip and spacing changes to better explain some fields.

* Added size for volume drawers and cleaned up some date edge case handling

* Fixed an annoying bug where when on mobile opening a view with a metadata filter, Kavita would open the filter automatically.
2023-01-02 14:44:29 -08:00

158 lines
5.5 KiB
C#

using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using API.Data;
using API.DTOs.Reader;
using API.Entities.Enums;
using API.Services;
using Kavita.Common;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using VersOne.Epub;
namespace API.Controllers;
public class BookController : BaseApiController
{
private readonly IBookService _bookService;
private readonly IUnitOfWork _unitOfWork;
private readonly ICacheService _cacheService;
public BookController(IBookService bookService,
IUnitOfWork unitOfWork, ICacheService cacheService)
{
_bookService = bookService;
_unitOfWork = unitOfWork;
_cacheService = cacheService;
}
/// <summary>
/// Retrieves information for the PDF and Epub reader
/// </summary>
/// <remarks>This only applies to Epub or PDF files</remarks>
/// <param name="chapterId"></param>
/// <returns></returns>
[HttpGet("{chapterId}/book-info")]
public async Task<ActionResult<BookInfoDto>> GetBookInfo(int chapterId)
{
var dto = await _unitOfWork.ChapterRepository.GetChapterInfoDtoAsync(chapterId);
var bookTitle = string.Empty;
switch (dto.SeriesFormat)
{
case MangaFormat.Epub:
{
var mangaFile = (await _unitOfWork.ChapterRepository.GetFilesForChapterAsync(chapterId)).First();
using var book = await EpubReader.OpenBookAsync(mangaFile.FilePath, BookService.BookReaderOptions);
bookTitle = book.Title;
break;
}
case MangaFormat.Pdf:
{
var mangaFile = (await _unitOfWork.ChapterRepository.GetFilesForChapterAsync(chapterId)).First();
if (string.IsNullOrEmpty(bookTitle))
{
// Override with filename
bookTitle = Path.GetFileNameWithoutExtension(mangaFile.FilePath);
}
break;
}
case MangaFormat.Image:
case MangaFormat.Archive:
case MangaFormat.Unknown:
default:
break;
}
return Ok(new BookInfoDto()
{
ChapterNumber = dto.ChapterNumber,
VolumeNumber = dto.VolumeNumber,
VolumeId = dto.VolumeId,
BookTitle = bookTitle,
SeriesName = dto.SeriesName,
SeriesFormat = dto.SeriesFormat,
SeriesId = dto.SeriesId,
LibraryId = dto.LibraryId,
IsSpecial = dto.IsSpecial,
Pages = dto.Pages,
});
}
/// <summary>
/// This is an entry point to fetch resources from within an epub chapter/book.
/// </summary>
/// <param name="chapterId"></param>
/// <param name="file"></param>
/// <returns></returns>
[HttpGet("{chapterId}/book-resources")]
[ResponseCache(Duration = 60 * 1, Location = ResponseCacheLocation.Client, NoStore = false)]
[AllowAnonymous]
public async Task<ActionResult> GetBookPageResources(int chapterId, [FromQuery] string file)
{
if (chapterId <= 0) return BadRequest("Chapter is not valid");
var chapter = await _unitOfWork.ChapterRepository.GetChapterAsync(chapterId);
using var book = await EpubReader.OpenBookAsync(chapter.Files.ElementAt(0).FilePath, BookService.BookReaderOptions);
var key = BookService.CoalesceKeyForAnyFile(book, file);
if (!book.Content.AllFiles.ContainsKey(key)) return BadRequest("File was not found in book");
var bookFile = book.Content.AllFiles[key];
var content = await bookFile.ReadContentAsBytesAsync();
var contentType = BookService.GetContentType(bookFile.ContentType);
return File(content, contentType, $"{chapterId}-{file}");
}
/// <summary>
/// This will return a list of mappings from ID -> page num. ID will be the xhtml key and page num will be the reading order
/// this is used to rewrite anchors in the book text so that we always load properly in our reader.
/// </summary>
/// <remarks>This is essentially building the table of contents</remarks>
/// <param name="chapterId"></param>
/// <returns></returns>
[HttpGet("{chapterId}/chapters")]
public async Task<ActionResult<ICollection<BookChapterItem>>> GetBookChapters(int chapterId)
{
if (chapterId <= 0) return BadRequest("Chapter is not valid");
var chapter = await _unitOfWork.ChapterRepository.GetChapterAsync(chapterId);
try
{
return Ok(await _bookService.GenerateTableOfContents(chapter));
}
catch (KavitaException ex)
{
return BadRequest(ex.Message);
}
}
/// <summary>
/// This returns a single page within the epub book. All html will be rewritten to be scoped within our reader,
/// all css is scoped, etc.
/// </summary>
/// <param name="chapterId"></param>
/// <param name="page"></param>
/// <returns></returns>
[HttpGet("{chapterId}/book-page")]
public async Task<ActionResult<string>> GetBookPage(int chapterId, [FromQuery] int page)
{
var chapter = await _cacheService.Ensure(chapterId);
var path = _cacheService.GetCachedFile(chapter);
var baseUrl = "//" + Request.Host + Request.PathBase + "/api/";
try
{
return Ok(await _bookService.GetBookPage(page, chapterId, path, baseUrl));
}
catch (KavitaException ex)
{
return BadRequest(ex.Message);
}
}
}