Skip to content

Commit

Permalink
Small Logging Improvement (#3389)
Browse files Browse the repository at this point in the history
  • Loading branch information
majora2007 authored Nov 21, 2024
1 parent 17a5d0d commit 349645b
Show file tree
Hide file tree
Showing 4 changed files with 26 additions and 31 deletions.
52 changes: 24 additions & 28 deletions API/Controllers/ReaderController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Microsoft.IdentityModel.Tokens;
using MimeTypes;

namespace API.Controllers;
Expand Down Expand Up @@ -90,7 +89,7 @@ public async Task<ActionResult> GetPdf(int chapterId, string apiKey, bool extrac
}
catch (Exception)
{
_cacheService.CleanupChapters(new []{ chapterId });
_cacheService.CleanupChapters([chapterId]);
throw;
}
}
Expand All @@ -105,7 +104,8 @@ public async Task<ActionResult> GetPdf(int chapterId, string apiKey, bool extrac
/// <param name="extractPdf">Should Kavita extract pdf into images. Defaults to false.</param>
/// <returns></returns>
[HttpGet("image")]
[ResponseCache(CacheProfileName = ResponseCacheProfiles.Hour, VaryByQueryKeys = new []{"chapterId", "page", "extractPdf", "apiKey"})]
[ResponseCache(CacheProfileName = ResponseCacheProfiles.Hour, VaryByQueryKeys = ["chapterId", "page", "extractPdf", "apiKey"
])]
[AllowAnonymous]
public async Task<ActionResult> GetImage(int chapterId, int page, string apiKey, bool extractPdf = false)
{
Expand All @@ -117,7 +117,7 @@ public async Task<ActionResult> GetImage(int chapterId, int page, string apiKey,
{
var chapter = await _cacheService.Ensure(chapterId, extractPdf);
if (chapter == null) return NoContent();
_logger.LogInformation("Fetching Page {PageNum} on Chapter {ChapterId}", page, chapterId);

var path = _cacheService.GetCachedPagePath(chapter.Id, page);
if (string.IsNullOrEmpty(path) || !System.IO.File.Exists(path))
return BadRequest(await _localizationService.Translate(userId, "no-image-for-page", page));
Expand All @@ -127,7 +127,7 @@ public async Task<ActionResult> GetImage(int chapterId, int page, string apiKey,
}
catch (Exception)
{
_cacheService.CleanupChapters(new []{ chapterId });
_cacheService.CleanupChapters([chapterId]);
throw;
}
}
Expand All @@ -140,7 +140,7 @@ public async Task<ActionResult> GetImage(int chapterId, int page, string apiKey,
/// <param name="apiKey"></param>
/// <returns></returns>
[HttpGet("thumbnail")]
[ResponseCache(CacheProfileName = ResponseCacheProfiles.Hour, VaryByQueryKeys = new []{"chapterId", "pageNum", "apiKey"})]
[ResponseCache(CacheProfileName = ResponseCacheProfiles.Hour, VaryByQueryKeys = ["chapterId", "pageNum", "apiKey"])]
[AllowAnonymous]
public async Task<ActionResult> GetThumbnail(int chapterId, int pageNum, string apiKey)
{
Expand All @@ -164,14 +164,14 @@ public async Task<ActionResult> GetThumbnail(int chapterId, int pageNum, string
/// <remarks>We must use api key as bookmarks could be leaked to other users via the API</remarks>
/// <returns></returns>
[HttpGet("bookmark-image")]
[ResponseCache(CacheProfileName = ResponseCacheProfiles.Hour, VaryByQueryKeys = new []{"seriesId", "page", "apiKey"})]
[ResponseCache(CacheProfileName = ResponseCacheProfiles.Hour, VaryByQueryKeys = ["seriesId", "page", "apiKey"])]
[AllowAnonymous]
public async Task<ActionResult> GetBookmarkImage(int seriesId, string apiKey, int page)
{
if (page < 0) page = 0;
var userId = await _unitOfWork.UserRepository.GetUserIdByApiKeyAsync(apiKey);
if (userId == 0) return Unauthorized();

if (page < 0) page = 0;
var totalPages = await _cacheService.CacheBookmarkForSeries(userId, seriesId);
if (page > totalPages)
{
Expand All @@ -188,7 +188,7 @@ public async Task<ActionResult> GetBookmarkImage(int seriesId, string apiKey, in
}
catch (Exception)
{
_cacheService.CleanupBookmarks(new []{ seriesId });
_cacheService.CleanupBookmarks([seriesId]);
throw;
}
}
Expand All @@ -202,12 +202,13 @@ public async Task<ActionResult> GetBookmarkImage(int seriesId, string apiKey, in
/// <param name="extractPdf"></param>
/// <returns></returns>
[HttpGet("file-dimensions")]
[ResponseCache(CacheProfileName = ResponseCacheProfiles.Hour, VaryByQueryKeys = new []{"chapterId", "extractPdf"})]
[ResponseCache(CacheProfileName = ResponseCacheProfiles.Hour, VaryByQueryKeys = ["chapterId", "extractPdf"])]
public async Task<ActionResult<IEnumerable<FileDimensionDto>>> GetFileDimensions(int chapterId, bool extractPdf = false)
{
if (chapterId <= 0) return ArraySegment<FileDimensionDto>.Empty;
var chapter = await _cacheService.Ensure(chapterId, extractPdf);
if (chapter == null) return NoContent();

return Ok(_cacheService.GetCachedFileDimensions(_cacheService.GetCachePath(chapterId)));
}

Expand All @@ -220,7 +221,8 @@ public async Task<ActionResult<IEnumerable<FileDimensionDto>>> GetFileDimensions
/// <param name="includeDimensions">Include file dimensions. Only useful for image based reading</param>
/// <returns></returns>
[HttpGet("chapter-info")]
[ResponseCache(CacheProfileName = ResponseCacheProfiles.Hour, VaryByQueryKeys = new []{"chapterId", "extractPdf", "includeDimensions"})]
[ResponseCache(CacheProfileName = ResponseCacheProfiles.Hour, VaryByQueryKeys = ["chapterId", "extractPdf", "includeDimensions"
])]
public async Task<ActionResult<ChapterInfoDto>> GetChapterInfo(int chapterId, bool extractPdf = false, bool includeDimensions = false)
{
if (chapterId <= 0) return Ok(null); // This can happen occasionally from UI, we should just ignore
Expand Down Expand Up @@ -260,6 +262,7 @@ public async Task<ActionResult<ChapterInfoDto>> GetChapterInfo(int chapterId, bo
}

if (info.ChapterTitle is {Length: > 0}) {
// TODO: Can we rework the logic of generating titles for the UI and instead calculate that in the DB?
info.Title += " - " + info.ChapterTitle;
}

Expand Down Expand Up @@ -291,7 +294,7 @@ public async Task<ActionResult<ChapterInfoDto>> GetChapterInfo(int chapterId, bo
/// <param name="includeDimensions">Include file dimensions (extra I/O). Defaults to true.</param>
/// <returns></returns>
[HttpGet("bookmark-info")]
[ResponseCache(CacheProfileName = ResponseCacheProfiles.Hour, VaryByQueryKeys = new []{"seriesId", "includeDimensions"})]
[ResponseCache(CacheProfileName = ResponseCacheProfiles.Hour, VaryByQueryKeys = ["seriesId", "includeDimensions"])]
public async Task<ActionResult<BookmarkInfoDto>> GetBookmarkInfo(int seriesId, bool includeDimensions = true)
{
var totalPages = await _cacheService.CacheBookmarkForSeries(User.GetUserId(), seriesId);
Expand Down Expand Up @@ -375,13 +378,10 @@ public async Task<ActionResult> MarkVolumeAsUnread(MarkVolumeReadDto markVolumeR
var chapters = await _unitOfWork.ChapterRepository.GetChaptersAsync(markVolumeReadDto.VolumeId);
await _readerService.MarkChaptersAsUnread(user, markVolumeReadDto.SeriesId, chapters);

if (await _unitOfWork.CommitAsync())
{
BackgroundJob.Enqueue(() => _scrobblingService.ScrobbleReadingUpdate(user.Id, markVolumeReadDto.SeriesId));
return Ok();
}
if (!await _unitOfWork.CommitAsync()) return BadRequest(await _localizationService.Translate(User.GetUserId(), "generic-read-progress"));

return BadRequest(await _localizationService.Translate(User.GetUserId(), "generic-read-progress"));
BackgroundJob.Enqueue(() => _scrobblingService.ScrobbleReadingUpdate(user.Id, markVolumeReadDto.SeriesId));
return Ok();
}

/// <summary>
Expand Down Expand Up @@ -551,7 +551,7 @@ public async Task<ActionResult<ProgressDto>> GetProgress(int chapterId)
}

/// <summary>
/// Save page against Chapter for logged in user
/// Save page against Chapter for authenticated user
/// </summary>
/// <param name="progressDto"></param>
/// <returns></returns>
Expand Down Expand Up @@ -769,7 +769,7 @@ public async Task<ActionResult> UnBookmarkPage(BookmarkDto bookmarkDto)
/// <param name="volumeId"></param>
/// <param name="currentChapterId"></param>
/// <returns>chapter id for next manga</returns>
[ResponseCache(CacheProfileName = "Hour", VaryByQueryKeys = new [] { "seriesId", "volumeId", "currentChapterId"})]
[ResponseCache(CacheProfileName = "Hour", VaryByQueryKeys = ["seriesId", "volumeId", "currentChapterId"])]
[HttpGet("next-chapter")]
public async Task<ActionResult<int>> GetNextChapter(int seriesId, int volumeId, int currentChapterId)
{
Expand All @@ -787,7 +787,7 @@ public async Task<ActionResult<int>> GetNextChapter(int seriesId, int volumeId,
/// <param name="volumeId"></param>
/// <param name="currentChapterId"></param>
/// <returns>chapter id for next manga</returns>
[ResponseCache(CacheProfileName = "Hour", VaryByQueryKeys = new [] { "seriesId", "volumeId", "currentChapterId"})]
[ResponseCache(CacheProfileName = "Hour", VaryByQueryKeys = ["seriesId", "volumeId", "currentChapterId"])]
[HttpGet("prev-chapter")]
public async Task<ActionResult<int>> GetPreviousChapter(int seriesId, int volumeId, int currentChapterId)
{
Expand All @@ -801,7 +801,7 @@ public async Task<ActionResult<int>> GetPreviousChapter(int seriesId, int volume
/// <param name="seriesId"></param>
/// <returns></returns>
[HttpGet("time-left")]
[ResponseCache(CacheProfileName = "Hour", VaryByQueryKeys = new [] { "seriesId"})]
[ResponseCache(CacheProfileName = "Hour", VaryByQueryKeys = ["seriesId"])]
public async Task<ActionResult<HourEstimateRangeDto>> GetEstimateToCompletion(int seriesId)
{
var userId = User.GetUserId();
Expand Down Expand Up @@ -899,12 +899,8 @@ public async Task<ActionResult> CreatePersonalToC(CreatePersonalToCDto dto)
[HttpGet("all-chapter-progress")]
public async Task<ActionResult<IEnumerable<FullProgressDto>>> GetProgressForChapter(int chapterId)
{
if (User.IsInRole(PolicyConstants.AdminRole))
{
return Ok(await _unitOfWork.AppUserProgressRepository.GetUserProgressForChapter(chapterId));
}

return Ok(await _unitOfWork.AppUserProgressRepository.GetUserProgressForChapter(chapterId, User.GetUserId()));
var userId = User.IsInRole(PolicyConstants.AdminRole) ? 0 : User.GetUserId();
return Ok(await _unitOfWork.AppUserProgressRepository.GetUserProgressForChapter(chapterId, userId));

}
}
2 changes: 0 additions & 2 deletions API/Services/CacheService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -118,8 +118,6 @@ public IEnumerable<FileDimensionDto> GetCachedFileDimensions(string cachePath)
Cache.MaxFiles = originalCacheSize;
}

_logger.LogDebug("File Dimensions call for {Length} images took {Time}ms", dimensions.Count, sw.ElapsedMilliseconds);

return dimensions;
}

Expand Down
2 changes: 1 addition & 1 deletion API/Services/Plus/ScrobblingService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -345,7 +345,7 @@ await _unitOfWork.AppUserProgressRepository.GetHighestFullyReadChapterForSeries(

_unitOfWork.ScrobbleRepository.Attach(evt);
await _unitOfWork.CommitAsync();
_logger.LogDebug("Added Scrobbling Read update on {SeriesName} with Userid {UserId} ", series.Name, userId);
_logger.LogDebug("Added Scrobbling Read update on {SeriesName} - Volume: {VolumeNumber} Chapter: {ChapterNumber} for User: {UserId}", series.Name, evt.VolumeNumber, evt.ChapterNumber, userId);
}
catch (Exception ex)
{
Expand Down
1 change: 1 addition & 0 deletions API/Services/ReaderService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -291,6 +291,7 @@ public async Task<bool> SaveReadingProgress(ProgressDto progressDto, int userId)
_unitOfWork.AppUserProgressRepository.Update(userProgress);
}

_logger.LogDebug("Saving Progress on Chapter {ChapterId} from Series {SeriesId} to {PageNum}", progressDto.ChapterId, progressDto.SeriesId, progressDto.PageNum);
userProgress?.MarkModified();

if (!_unitOfWork.HasChanges() || await _unitOfWork.CommitAsync())
Expand Down

0 comments on commit 349645b

Please sign in to comment.