Feat/komga api (#2071)

* Implement Komga API endpoints with OPDS authentication

Co-authored-by: farfromrefug <655344+farfromrefug@users.noreply.github.com>

* Add database migration and documentation for Komga API

Co-authored-by: farfromrefug <655344+farfromrefug@users.noreply.github.com>

* Address code review comments - improve performance and maintainability

Co-authored-by: farfromrefug <655344+farfromrefug@users.noreply.github.com>

* chore: update with main develop

* chore: log cleanup

* chore: fixed switch with missing types

* chore: missing case

* Merge pull request #4 from farfromrefug/copilot/fix-500-error-on-books-api

Fix NPE in Komga books API when pageCount is null and add unpaged parameter

* Add collections endpoint and page download with PNG conversion support

Co-authored-by: farfromrefug <655344+farfromrefug@users.noreply.github.com>

* Address code review feedback for better resource management and error messages

Co-authored-by: farfromrefug <655344+farfromrefug@users.noreply.github.com>

* Fix convert parameter to match specification (convert=png)

Co-authored-by: farfromrefug <655344+farfromrefug@users.noreply.github.com>

* chore: renamed migration

* chore: migration

* chore: migration fix

* chore: should work now

* chore: settings

* chore: working with mihon

* Initial plan

* Add clean query parameter for Komga API endpoints

Co-authored-by: farfromrefug <655344+farfromrefug@users.noreply.github.com>

* Address code review comments - remove unused imports and add @Primary annotation

Co-authored-by: farfromrefug <655344+farfromrefug@users.noreply.github.com>

* Add demo test to illustrate clean mode effectiveness

Co-authored-by: farfromrefug <655344+farfromrefug@users.noreply.github.com>

* Support both ?clean and ?clean=true syntax

Co-authored-by: farfromrefug <655344+farfromrefug@users.noreply.github.com>

* Filter out empty arrays in clean mode

Co-authored-by: farfromrefug <655344+farfromrefug@users.noreply.github.com>

* chore: missing field

* chore: missing field

* chore: fix error with missing number

* fix: added groupUnknown API parameters to sort by "Unknown Series" (true by default)

* Initial plan

* Convert groupUnknown from query parameter to Booklore setting

Co-authored-by: farfromrefug <655344+farfromrefug@users.noreply.github.com>

* Remove unused groupUnknown variables from service and mapper

Co-authored-by: farfromrefug <655344+farfromrefug@users.noreply.github.com>

* chore: fix seriesTitle in ungrouped unknowns

* Initial plan

* Optimize Komga API performance for series listing

- Optimize getAllSeries to only convert series on current page to DTOs
- Optimize getBooksBySeries to fetch books only once (not twice)
- Add database query methods for future optimizations
- Update tests to work with new optimizations
- All existing tests pass

Co-authored-by: farfromrefug <655344+farfromrefug@users.noreply.github.com>

* Clean up unused database query methods in BookRepository

Remove unused optimization queries that don't align with application-level series grouping logic

Co-authored-by: farfromrefug <655344+farfromrefug@users.noreply.github.com>

* Optimize getAllSeries to query distinct series names from database

- Add database queries to fetch distinct series names directly (no need to load all books)
- Add queries to fetch books only for specific series (when building DTOs)
- Support both groupUnknown=true and groupUnknown=false modes
- Add test to verify optimization works and books aren't loaded unnecessarily
- Performance improvement: For 1000+ books grouped into 100+ series, now only queries series names (~100 rows) instead of loading all books (~1000+ rows), then loads books only for the current page (~20-50 books per series on page)

Co-authored-by: farfromrefug <655344+farfromrefug@users.noreply.github.com>

* chore: migration fix from merge

* chore: address comments

* fix: handle getBookPage for PDF/CBX

* chore: rename migration

* chore: komga specific series queries fix

* chore: komga tests fix

* chore: front end komga tests

---------

Co-authored-by: Aditya Chandel <8075870+adityachandelgit@users.noreply.github.com>
Co-authored-by: ACX <8075870+acx10@users.noreply.github.com>
Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
This commit is contained in:
farfromrefuge
2026-01-19 08:44:53 -07:00
committed by GitHub
co-authored by farfromrefug Aditya Chandel ACX copilot-swe-agent[bot]
parent 4253322d2c
commit 69c3c88375
43 changed files with 3071 additions and 5 deletions
@@ -0,0 +1,147 @@
package com.adityachandel.booklore.config;
import com.adityachandel.booklore.context.KomgaCleanContext;
import com.adityachandel.booklore.model.dto.komga.KomgaBookMetadataDto;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import static org.assertj.core.api.Assertions.assertThat;
class KomgaCleanFilterTest {
private ObjectMapper objectMapper;
@BeforeEach
void setup() {
// Create ObjectMapper with our custom configuration
JacksonConfig config = new JacksonConfig();
objectMapper = config.komgaCleanObjectMapper(new org.springframework.http.converter.json.Jackson2ObjectMapperBuilder());
}
@AfterEach
void cleanup() {
KomgaCleanContext.clear();
}
@Test
void shouldExcludeLockFieldsInCleanMode() throws Exception {
// Given: Clean mode is enabled
KomgaCleanContext.setCleanMode(true);
KomgaBookMetadataDto metadata = KomgaBookMetadataDto.builder()
.title("Test Book")
.titleLock(true)
.summary("Test Summary")
.summaryLock(false)
.build();
// When: Serializing to JSON
String json = objectMapper.writeValueAsString(metadata);
Map<String, Object> result = objectMapper.readValue(json, Map.class);
// Then: Lock fields should be excluded
assertThat(result).containsKey("title");
assertThat(result).containsKey("summary");
assertThat(result).doesNotContainKey("titleLock");
assertThat(result).doesNotContainKey("summaryLock");
}
@Test
void shouldExcludeNullValuesInCleanMode() throws Exception {
// Given: Clean mode is enabled
KomgaCleanContext.setCleanMode(true);
KomgaBookMetadataDto metadata = KomgaBookMetadataDto.builder()
.title("Test Book")
.summary(null) // Null value
.number("1")
.releaseDate(null) // Null value
.build();
// When: Serializing to JSON
String json = objectMapper.writeValueAsString(metadata);
Map<String, Object> result = objectMapper.readValue(json, Map.class);
// Then: Null values should be excluded
assertThat(result).containsKey("title");
assertThat(result).containsKey("number");
assertThat(result).doesNotContainKey("summary");
assertThat(result).doesNotContainKey("releaseDate");
}
@Test
void shouldExcludeEmptyArraysInCleanMode() throws Exception {
// Given: Clean mode is enabled
KomgaCleanContext.setCleanMode(true);
KomgaBookMetadataDto metadata = KomgaBookMetadataDto.builder()
.title("Test Book")
.authors(new ArrayList<>()) // Empty list
.tags(new ArrayList<>()) // Empty list
.build();
// When: Serializing to JSON
String json = objectMapper.writeValueAsString(metadata);
Map<String, Object> result = objectMapper.readValue(json, Map.class);
// Then: Empty arrays should be excluded
assertThat(result).containsKey("title");
assertThat(result).doesNotContainKey("authors");
assertThat(result).doesNotContainKey("tags");
}
@Test
void shouldIncludeNonEmptyArraysInCleanMode() throws Exception {
// Given: Clean mode is enabled
KomgaCleanContext.setCleanMode(true);
List<String> tags = new ArrayList<>();
tags.add("fiction");
tags.add("adventure");
KomgaBookMetadataDto metadata = KomgaBookMetadataDto.builder()
.title("Test Book")
.tags(tags) // Non-empty list
.build();
// When: Serializing to JSON
String json = objectMapper.writeValueAsString(metadata);
Map<String, Object> result = objectMapper.readValue(json, Map.class);
// Then: Non-empty arrays should be included
assertThat(result).containsKey("title");
assertThat(result).containsKey("tags");
assertThat((List<?>) result.get("tags")).hasSize(2);
}
@Test
void shouldIncludeAllFieldsWhenCleanModeDisabled() throws Exception {
// Given: Clean mode is disabled (default)
KomgaCleanContext.setCleanMode(false);
KomgaBookMetadataDto metadata = KomgaBookMetadataDto.builder()
.title("Test Book")
.titleLock(true)
.summary(null) // Null value
.summaryLock(false)
.authors(new ArrayList<>()) // Empty list
.build();
// When: Serializing to JSON
String json = objectMapper.writeValueAsString(metadata);
Map<String, Object> result = objectMapper.readValue(json, Map.class);
// Then: Lock fields and empty arrays should be included
assertThat(result).containsKey("title");
assertThat(result).containsKey("titleLock");
assertThat(result).containsKey("summaryLock");
assertThat(result).containsKey("authors");
// Note: null values are excluded by @JsonInclude(JsonInclude.Include.NON_NULL) regardless
}
}
@@ -0,0 +1,84 @@
package com.adityachandel.booklore.config;
import com.adityachandel.booklore.context.KomgaCleanContext;
import com.adityachandel.booklore.model.dto.komga.KomgaSeriesMetadataDto;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Demonstrates the JSON output differences with and without clean mode.
*/
class KomgaCleanModeDemo {
private ObjectMapper objectMapper;
@BeforeEach
void setup() {
JacksonConfig config = new JacksonConfig();
objectMapper = config.komgaCleanObjectMapper(new org.springframework.http.converter.json.Jackson2ObjectMapperBuilder());
}
@AfterEach
void cleanup() {
KomgaCleanContext.clear();
}
@Test
void demonstrateCleanModeEffect() throws Exception {
// Create a sample series metadata
KomgaSeriesMetadataDto metadata = KomgaSeriesMetadataDto.builder()
.status("ONGOING")
.statusLock(false)
.title("My Awesome Series")
.titleLock(false)
.titleSort("My Awesome Series")
.titleSortLock(false)
.summary(null) // No summary available
.summaryLock(false)
.readingDirection("LEFT_TO_RIGHT")
.readingDirectionLock(false)
.publisher(null) // No publisher available
.publisherLock(false)
.language(null) // No language specified
.languageLock(false)
.genres(new ArrayList<>())
.genresLock(false)
.tags(new ArrayList<>())
.tagsLock(false)
.totalBookCount(10)
.totalBookCountLock(false)
.ageRatingLock(false)
.build();
// Test without clean mode
KomgaCleanContext.setCleanMode(false);
String normalJson = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(metadata);
System.out.println("=== WITHOUT CLEAN MODE ===");
System.out.println(normalJson);
System.out.println("JSON size: " + normalJson.length() + " bytes\n");
// Test with clean mode
KomgaCleanContext.setCleanMode(true);
String cleanJson = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(metadata);
System.out.println("=== WITH CLEAN MODE (clean=true) ===");
System.out.println(cleanJson);
System.out.println("JSON size: " + cleanJson.length() + " bytes\n");
// Verify size difference
System.out.println("Size reduction: " + (normalJson.length() - cleanJson.length()) + " bytes");
System.out.println("Percentage smaller: " + String.format("%.1f", 100.0 * (normalJson.length() - cleanJson.length()) / normalJson.length()) + "%");
// Assert that clean mode produces smaller output
assertThat(cleanJson.length()).isLessThan(normalJson.length());
// Assert that clean JSON doesn't contain "Lock" fields
assertThat(cleanJson).doesNotContain("Lock");
}
}
@@ -0,0 +1,126 @@
package com.adityachandel.booklore.interceptor;
import com.adityachandel.booklore.context.KomgaCleanContext;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.when;
class KomgaCleanInterceptorTest {
private KomgaCleanInterceptor interceptor;
@Mock
private HttpServletRequest request;
@Mock
private HttpServletResponse response;
@BeforeEach
void setup() {
MockitoAnnotations.openMocks(this);
interceptor = new KomgaCleanInterceptor();
}
@AfterEach
void cleanup() {
KomgaCleanContext.clear();
}
@Test
void shouldEnableCleanModeWithParameterWithoutValue() throws Exception {
// Given: Request with ?clean (no value)
when(request.getRequestURI()).thenReturn("/komga/api/v1/series");
when(request.getParameter("clean")).thenReturn(""); // Empty string means parameter present without value
// When: Interceptor processes request
interceptor.preHandle(request, response, new Object());
// Then: Clean mode should be enabled
assertThat(KomgaCleanContext.isCleanMode()).isTrue();
}
@Test
void shouldEnableCleanModeWithParameterSetToTrue() throws Exception {
// Given: Request with ?clean=true
when(request.getRequestURI()).thenReturn("/komga/api/v1/series");
when(request.getParameter("clean")).thenReturn("true");
// When: Interceptor processes request
interceptor.preHandle(request, response, new Object());
// Then: Clean mode should be enabled
assertThat(KomgaCleanContext.isCleanMode()).isTrue();
}
@Test
void shouldEnableCleanModeWithParameterSetToTrueCaseInsensitive() throws Exception {
// Given: Request with ?clean=TRUE
when(request.getRequestURI()).thenReturn("/komga/api/v1/books/123");
when(request.getParameter("clean")).thenReturn("TRUE");
// When: Interceptor processes request
interceptor.preHandle(request, response, new Object());
// Then: Clean mode should be enabled
assertThat(KomgaCleanContext.isCleanMode()).isTrue();
}
@Test
void shouldNotEnableCleanModeWhenParameterAbsent() throws Exception {
// Given: Request without clean parameter
when(request.getRequestURI()).thenReturn("/komga/api/v1/series");
when(request.getParameter("clean")).thenReturn(null);
// When: Interceptor processes request
interceptor.preHandle(request, response, new Object());
// Then: Clean mode should not be enabled
assertThat(KomgaCleanContext.isCleanMode()).isFalse();
}
@Test
void shouldNotEnableCleanModeWhenParameterSetToFalse() throws Exception {
// Given: Request with ?clean=false
when(request.getRequestURI()).thenReturn("/komga/api/v1/series");
when(request.getParameter("clean")).thenReturn("false");
// When: Interceptor processes request
interceptor.preHandle(request, response, new Object());
// Then: Clean mode should not be enabled
assertThat(KomgaCleanContext.isCleanMode()).isFalse();
}
@Test
void shouldNotApplyToNonKomgaEndpoints() throws Exception {
// Given: Request to non-Komga endpoint with clean parameter
when(request.getRequestURI()).thenReturn("/api/v1/books");
when(request.getParameter("clean")).thenReturn("true");
// When: Interceptor processes request
interceptor.preHandle(request, response, new Object());
// Then: Clean mode should not be enabled
assertThat(KomgaCleanContext.isCleanMode()).isFalse();
}
@Test
void shouldClearContextAfterCompletion() throws Exception {
// Given: Clean mode is enabled
KomgaCleanContext.setCleanMode(true);
assertThat(KomgaCleanContext.isCleanMode()).isTrue();
// When: After completion is called
interceptor.afterCompletion(request, response, new Object(), null);
// Then: Context should be cleared
assertThat(KomgaCleanContext.isCleanMode()).isFalse();
}
}
@@ -0,0 +1,247 @@
package com.adityachandel.booklore.mapper.komga;
import com.adityachandel.booklore.context.KomgaCleanContext;
import com.adityachandel.booklore.model.dto.komga.KomgaBookDto;
import com.adityachandel.booklore.model.dto.komga.KomgaSeriesDto;
import com.adityachandel.booklore.model.dto.settings.AppSettings;
import com.adityachandel.booklore.model.entity.BookEntity;
import com.adityachandel.booklore.model.entity.BookFileEntity;
import com.adityachandel.booklore.model.entity.BookMetadataEntity;
import com.adityachandel.booklore.model.entity.LibraryEntity;
import com.adityachandel.booklore.model.enums.BookFileType;
import com.adityachandel.booklore.service.appsettings.AppSettingService;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.when;
@ExtendWith(MockitoExtension.class)
class KomgaMapperTest {
@Mock
private AppSettingService appSettingService;
@InjectMocks
private KomgaMapper mapper;
@AfterEach
void cleanup() {
// Always clean up the context after each test
KomgaCleanContext.clear();
}
@BeforeEach
void setUp() {
// Mock app settings for all tests
AppSettings appSettings = new AppSettings();
appSettings.setKomgaGroupUnknown(true);
when(appSettingService.getAppSettings()).thenReturn(appSettings);
}
@Test
void shouldHandleNullPageCountInMetadata() {
// Given: A book with metadata that has null pageCount
LibraryEntity library = new LibraryEntity();
library.setId(1L);
BookMetadataEntity metadata = BookMetadataEntity.builder()
.title("Test Book")
.seriesName("Test Series")
.pageCount(null) // Explicitly null
.build();
BookEntity book = new BookEntity();
book.setId(100L);
book.setLibrary(library);
book.setMetadata(metadata);
book.setAddedOn(Instant.now());
BookFileEntity pdf = new BookFileEntity();
pdf.setId(100L);
pdf.setBook(book);
pdf.setFileSubPath("author/title");
pdf.setFileName("test-book.pdf");
pdf.setBookType(BookFileType.PDF);
pdf.setBookFormat(true);
book.setBookFiles(List.of(pdf));
// When: Converting to DTO
KomgaBookDto dto = mapper.toKomgaBookDto(book);
// Then: Should not throw NPE and pageCount should default to 0
assertThat(dto).isNotNull();
assertThat(dto.getMedia()).isNotNull();
assertThat(dto.getMedia().getPagesCount()).isEqualTo(0);
}
@Test
void shouldHandleNullMetadata() {
// Given: A book with null metadata
LibraryEntity library = new LibraryEntity();
library.setId(1L);
BookEntity book = new BookEntity();
book.setId(100L);
book.setLibrary(library);
book.setMetadata(null); // Null metadata
book.setAddedOn(Instant.now());
BookFileEntity pdf = new BookFileEntity();
pdf.setId(100L);
pdf.setBook(book);
pdf.setFileSubPath("author/title");
pdf.setFileName("test-book.pdf");
pdf.setBookType(BookFileType.PDF);
pdf.setBookFormat(true);
book.setBookFiles(List.of(pdf));
// When: Converting to DTO
KomgaBookDto dto = mapper.toKomgaBookDto(book);
// Then: Should not throw NPE and pageCount should default to 0
assertThat(dto).isNotNull();
assertThat(dto.getMedia()).isNotNull();
assertThat(dto.getMedia().getPagesCount()).isEqualTo(0);
}
@Test
void shouldHandleValidPageCount() {
// Given: A book with metadata that has valid pageCount
LibraryEntity library = new LibraryEntity();
library.setId(1L);
BookMetadataEntity metadata = BookMetadataEntity.builder()
.title("Test Book")
.seriesName("Test Series")
.pageCount(250)
.build();
BookEntity book = new BookEntity();
book.setId(100L);
book.setLibrary(library);
book.setMetadata(metadata);
book.setAddedOn(Instant.now());
BookFileEntity pdf = new BookFileEntity();
pdf.setId(100L);
pdf.setBook(book);
pdf.setFileSubPath("author/title");
pdf.setFileName("test-book.pdf");
pdf.setBookType(BookFileType.PDF);
pdf.setBookFormat(true);
book.setBookFiles(List.of(pdf));
// When: Converting to DTO
KomgaBookDto dto = mapper.toKomgaBookDto(book);
// Then: Should use the actual pageCount
assertThat(dto).isNotNull();
assertThat(dto.getMedia()).isNotNull();
assertThat(dto.getMedia().getPagesCount()).isEqualTo(250);
}
@Test
void shouldReturnNullForEmptyFieldsInCleanMode() {
// Given: Clean mode is enabled
KomgaCleanContext.setCleanMode(true);
LibraryEntity library = new LibraryEntity();
library.setId(1L);
List<BookEntity> books = new ArrayList<>();
BookEntity book = new BookEntity();
book.setId(100L);
book.setLibrary(library);
book.setAddedOn(Instant.now());
BookFileEntity pdf = new BookFileEntity();
pdf.setId(100L);
pdf.setBook(book);
pdf.setFileSubPath("author/title");
pdf.setFileName("test-book.pdf");
pdf.setBookType(BookFileType.PDF);
pdf.setBookFormat(true);
book.setBookFiles(List.of(pdf));
// Book with metadata but empty fields
BookMetadataEntity metadata = BookMetadataEntity.builder()
.title("Test Book")
.seriesName("Test Series")
.description(null)
.language(null)
.publisher(null)
.build();
book.setMetadata(metadata);
books.add(book);
// When: Converting to series DTO
KomgaSeriesDto seriesDto = mapper.toKomgaSeriesDto("Test Series", 1L, books);
// Then: Empty fields should be null (not empty strings) in clean mode
assertThat(seriesDto).isNotNull();
assertThat(seriesDto.getMetadata()).isNotNull();
assertThat(seriesDto.getMetadata().getSummary()).isNull();
assertThat(seriesDto.getMetadata().getLanguage()).isNull();
assertThat(seriesDto.getMetadata().getPublisher()).isNull();
}
@Test
void shouldReturnDefaultValuesWhenCleanModeDisabled() {
// Given: Clean mode is disabled (default)
KomgaCleanContext.setCleanMode(false);
LibraryEntity library = new LibraryEntity();
library.setId(1L);
List<BookEntity> books = new ArrayList<>();
BookEntity book = new BookEntity();
book.setId(100L);
book.setLibrary(library);
book.setAddedOn(Instant.now());
BookFileEntity pdf = new BookFileEntity();
pdf.setId(100L);
pdf.setBook(book);
pdf.setFileSubPath("author/title");
pdf.setFileName("test-book.pdf");
pdf.setBookType(BookFileType.PDF);
pdf.setBookFormat(true);
book.setBookFiles(List.of(pdf));
// Book with metadata but empty fields
BookMetadataEntity metadata = BookMetadataEntity.builder()
.title("Test Book")
.seriesName("Test Series")
.description(null)
.language(null)
.publisher(null)
.build();
book.setMetadata(metadata);
books.add(book);
// When: Converting to series DTO
KomgaSeriesDto seriesDto = mapper.toKomgaSeriesDto("Test Series", 1L, books);
// Then: Empty fields should have default values (not null)
assertThat(seriesDto).isNotNull();
assertThat(seriesDto.getMetadata()).isNotNull();
assertThat(seriesDto.getMetadata().getSummary()).isEqualTo("");
assertThat(seriesDto.getMetadata().getLanguage()).isEqualTo("en");
assertThat(seriesDto.getMetadata().getPublisher()).isEqualTo("");
}
}
@@ -0,0 +1,249 @@
package com.adityachandel.booklore.service.komga;
import com.adityachandel.booklore.mapper.komga.KomgaMapper;
import com.adityachandel.booklore.model.dto.komga.KomgaBookDto;
import com.adityachandel.booklore.model.dto.komga.KomgaPageDto;
import com.adityachandel.booklore.model.dto.komga.KomgaPageableDto;
import com.adityachandel.booklore.model.dto.komga.KomgaSeriesDto;
import com.adityachandel.booklore.model.dto.settings.AppSettings;
import com.adityachandel.booklore.model.entity.BookEntity;
import com.adityachandel.booklore.model.entity.BookFileEntity;
import com.adityachandel.booklore.model.entity.BookMetadataEntity;
import com.adityachandel.booklore.model.entity.LibraryEntity;
import com.adityachandel.booklore.model.enums.BookFileType;
import com.adityachandel.booklore.repository.BookRepository;
import com.adityachandel.booklore.repository.LibraryRepository;
import com.adityachandel.booklore.service.MagicShelfService;
import com.adityachandel.booklore.service.appsettings.AppSettingService;
import com.adityachandel.booklore.service.reader.CbxReaderService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.*;
import static org.mockito.Mockito.*;
@ExtendWith(MockitoExtension.class)
class KomgaServiceTest {
@Mock
private BookRepository bookRepository;
@Mock
private LibraryRepository libraryRepository;
@Mock
private KomgaMapper komgaMapper;
@Mock
private MagicShelfService magicShelfService;
@Mock
private CbxReaderService cbxReaderService;
@Mock
private AppSettingService appSettingService;
@InjectMocks
private KomgaService komgaService;
private LibraryEntity library;
private List<BookEntity> seriesBooks;
@BeforeEach
void setUp() {
library = new LibraryEntity();
library.setId(1L);
// Mock app settings (lenient because not all tests use this)
AppSettings appSettings = new AppSettings();
appSettings.setKomgaGroupUnknown(true);
lenient().when(appSettingService.getAppSettings()).thenReturn(appSettings);
// Create multiple books for testing pagination
seriesBooks = new ArrayList<>();
for (int i = 1; i <= 50; i++) {
BookMetadataEntity metadata = BookMetadataEntity.builder()
.title("Book " + i)
.seriesName("Test Series")
.seriesNumber((float) i)
.pageCount(null) // Test null pageCount
.build();
BookEntity book = new BookEntity();
book.setId((long) i);
book.setLibrary(library);
book.setMetadata(metadata);
book.setAddedOn(Instant.now());
BookFileEntity pdf = new BookFileEntity();
pdf.setId((long) i);
pdf.setBook(book);
pdf.setFileSubPath("author/title");
pdf.setFileName("book-" + i + ".pdf");
pdf.setBookType(BookFileType.PDF);
pdf.setBookFormat(true);
book.setBookFiles(List.of(pdf));
seriesBooks.add(book);
}
}
@Test
void shouldReturnAllBooksWhenUnpagedIsTrue() {
// Given
when(bookRepository.findAllWithMetadataByLibraryId(anyLong())).thenReturn(seriesBooks);
// Mock mapper.getBookSeriesName to return "test-series" for all books
for (BookEntity book : seriesBooks) {
when(komgaMapper.getBookSeriesName(book)).thenReturn("test-series");
}
// Mock the mapper to return DTOs
for (BookEntity book : seriesBooks) {
KomgaBookDto dto = KomgaBookDto.builder()
.id(book.getId().toString())
.name(book.getMetadata().getTitle())
.build();
when(komgaMapper.toKomgaBookDto(book)).thenReturn(dto);
}
// When: Request with unpaged=true
KomgaPageableDto<KomgaBookDto> result = komgaService.getBooksBySeries("1-test-series", 0, 20, true);
// Then: Should return all 50 books
assertThat(result).isNotNull();
assertThat(result.getContent()).hasSize(50);
assertThat(result.getTotalElements()).isEqualTo(50);
assertThat(result.getTotalPages()).isEqualTo(1);
assertThat(result.getSize()).isEqualTo(50);
assertThat(result.getNumber()).isEqualTo(0);
}
@Test
void shouldReturnPagedBooksWhenUnpagedIsFalse() {
// Given
when(bookRepository.findAllWithMetadataByLibraryId(anyLong())).thenReturn(seriesBooks);
// Mock mapper.getBookSeriesName to return "test-series" for all books
for (BookEntity book : seriesBooks) {
when(komgaMapper.getBookSeriesName(book)).thenReturn("test-series");
}
// Mock the mapper to return DTOs (only for the books that will be used)
for (int i = 0; i < 20; i++) {
BookEntity book = seriesBooks.get(i);
KomgaBookDto dto = KomgaBookDto.builder()
.id(book.getId().toString())
.name(book.getMetadata().getTitle())
.build();
when(komgaMapper.toKomgaBookDto(book)).thenReturn(dto);
}
// When: Request with unpaged=false and page size 20
KomgaPageableDto<KomgaBookDto> result = komgaService.getBooksBySeries("1-test-series", 0, 20, false);
// Then: Should return first page with 20 books
assertThat(result).isNotNull();
assertThat(result.getContent()).hasSize(20);
assertThat(result.getTotalElements()).isEqualTo(50);
assertThat(result.getTotalPages()).isEqualTo(3);
assertThat(result.getSize()).isEqualTo(20);
assertThat(result.getNumber()).isEqualTo(0);
}
@Test
void shouldHandleNullPageCountInGetBookPages() {
// Given: Book with null pageCount
BookMetadataEntity metadata = BookMetadataEntity.builder()
.title("Test Book")
.pageCount(null)
.build();
BookEntity book = new BookEntity();
book.setId(100L);
book.setMetadata(metadata);
when(bookRepository.findById(100L)).thenReturn(Optional.of(book));
// When: Get book pages
List<KomgaPageDto> pages = komgaService.getBookPages(100L);
// Then: Should return empty list without throwing NPE
assertThat(pages).isNotNull();
assertThat(pages).isEmpty();
}
@Test
void shouldReturnCorrectPagesWhenPageCountIsValid() {
// Given: Book with valid pageCount
BookMetadataEntity metadata = BookMetadataEntity.builder()
.title("Test Book")
.pageCount(5)
.build();
BookEntity book = new BookEntity();
book.setId(100L);
book.setMetadata(metadata);
when(bookRepository.findById(100L)).thenReturn(Optional.of(book));
// When: Get book pages
List<KomgaPageDto> pages = komgaService.getBookPages(100L);
// Then: Should return 5 pages
assertThat(pages).isNotNull();
assertThat(pages).hasSize(5);
assertThat(pages.get(0).getNumber()).isEqualTo(1);
assertThat(pages.get(4).getNumber()).isEqualTo(5);
}
@Test
void shouldGetAllSeriesOptimized() {
// Given: Mock the optimized repository method
List<String> seriesNames = List.of("Series A", "Series B", "Series C");
when(bookRepository.findDistinctSeriesNamesGroupedByLibraryId(anyLong(), anyString()))
.thenReturn(seriesNames);
// Mock books for the first page (Series A and Series B only)
List<BookEntity> seriesABooks = List.of(seriesBooks.get(0), seriesBooks.get(1));
List<BookEntity> seriesBBooks = List.of(seriesBooks.get(2), seriesBooks.get(3));
when(bookRepository.findBooksBySeriesNameGroupedByLibraryId("Series A", 1L, "Unknown Series"))
.thenReturn(seriesABooks);
when(bookRepository.findBooksBySeriesNameGroupedByLibraryId("Series B", 1L, "Unknown Series"))
.thenReturn(seriesBBooks);
when(komgaMapper.getUnknownSeriesName()).thenReturn("Unknown Series");
when(komgaMapper.toKomgaSeriesDto(eq("Series A"), anyLong(), any()))
.thenReturn(KomgaSeriesDto.builder().id("1-series-a").name("Series A").booksCount(2).build());
when(komgaMapper.toKomgaSeriesDto(eq("Series B"), anyLong(), any()))
.thenReturn(KomgaSeriesDto.builder().id("1-series-b").name("Series B").booksCount(2).build());
// When: Request first page with size 2
KomgaPageableDto<KomgaSeriesDto> result = komgaService.getAllSeries(1L, 0, 2, false);
// Then: Should return only 2 series (not all 3)
assertThat(result).isNotNull();
assertThat(result.getContent()).hasSize(2);
assertThat(result.getTotalElements()).isEqualTo(3);
assertThat(result.getTotalPages()).isEqualTo(2);
assertThat(result.getNumber()).isEqualTo(0);
assertThat(result.getFirst()).isTrue();
assertThat(result.getLast()).isFalse();
// Verify that only books for Series A and B were loaded (optimization check)
verify(bookRepository, never()).findAllWithMetadataByLibraryId(anyLong());
verify(bookRepository, never()).findAllWithMetadata();
}
}