fix(dto): add DailyListeningDto and update session-related DTOs to use LocalDate (#403)

* fix(dto): add DailyListeningDto and update session-related DTOs to use LocalDate

* refactor(metadata): fix metadata update process and improve library entity fetching

* refactor(tests): update MetadataControllerTest and update library repository method calls

* refactor(services): remove unused annotations and methods in Book services

* refactor(services): replace findById with findByIdWithPaths in BookDropService and related tests

* chore: remove bad test

* chore(sql): rename reading session booktype index migration file

* chore(sql): rename reading session booktype index migration file

* refactor(sql): simplify reading session DTOs and replace timezone-dependent queries
This commit is contained in:
brios
2026-04-22 17:27:14 -04:00
committed by Zach Yale
parent 4bca3f6674
commit e2d6c1bf11
35 changed files with 836 additions and 710 deletions
@@ -6,21 +6,13 @@ import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.AllArgsConstructor; import lombok.AllArgsConstructor;
import org.booklore.config.security.annotation.CheckBookAccess; import org.booklore.config.security.annotation.CheckBookAccess;
import org.booklore.mapper.BookMetadataMapper;
import org.booklore.model.MetadataUpdateContext;
import org.booklore.model.MetadataUpdateWrapper; import org.booklore.model.MetadataUpdateWrapper;
import org.booklore.model.dto.BookMetadata; import org.booklore.model.dto.BookMetadata;
import org.booklore.exception.ApiError;
import org.booklore.model.dto.request.IsbnLookupRequest; import org.booklore.model.dto.request.IsbnLookupRequest;
import org.booklore.model.dto.request.*; import org.booklore.model.dto.request.*;
import org.booklore.model.entity.BookEntity;
import org.booklore.model.enums.AuditAction;
import org.booklore.model.enums.MetadataProvider; import org.booklore.model.enums.MetadataProvider;
import org.booklore.model.enums.MetadataReplaceMode; import org.booklore.model.enums.MetadataReplaceMode;
import org.booklore.repository.BookRepository;
import org.booklore.service.audit.AuditService;
import org.booklore.service.metadata.BookMetadataService; import org.booklore.service.metadata.BookMetadataService;
import org.booklore.service.metadata.BookMetadataUpdater;
import org.booklore.service.metadata.MetadataManagementService; import org.booklore.service.metadata.MetadataManagementService;
import org.booklore.service.metadata.MetadataMatchService; import org.booklore.service.metadata.MetadataMatchService;
import org.springframework.http.MediaType; import org.springframework.http.MediaType;
@@ -39,12 +31,8 @@ import java.util.List;
public class MetadataController { public class MetadataController {
private final BookMetadataService bookMetadataService; private final BookMetadataService bookMetadataService;
private final BookMetadataUpdater bookMetadataUpdater;
private final BookMetadataMapper bookMetadataMapper;
private final MetadataMatchService metadataMatchService; private final MetadataMatchService metadataMatchService;
private final BookRepository bookRepository;
private final MetadataManagementService metadataManagementService; private final MetadataManagementService metadataManagementService;
private final AuditService auditService;
@Operation(summary = "Get prospective metadata for a book", description = "Fetch prospective metadata for a book by its ID. Requires metadata edit permission or admin.") @Operation(summary = "Get prospective metadata for a book", description = "Fetch prospective metadata for a book by its ID. Requires metadata edit permission or admin.")
@ApiResponse(responseCode = "200", description = "Prospective metadata returned successfully") @ApiResponse(responseCode = "200", description = "Prospective metadata returned successfully")
@@ -67,23 +55,7 @@ public class MetadataController {
@Parameter(description = "ID of the book") @PathVariable long bookId, @Parameter(description = "ID of the book") @PathVariable long bookId,
@Parameter(description = "Merge categories") @RequestParam(defaultValue = "false") boolean mergeCategories, @Parameter(description = "Merge categories") @RequestParam(defaultValue = "false") boolean mergeCategories,
@Parameter(description = "Replace mode") @RequestParam(defaultValue = "REPLACE_ALL") MetadataReplaceMode replaceMode) { @Parameter(description = "Replace mode") @RequestParam(defaultValue = "REPLACE_ALL") MetadataReplaceMode replaceMode) {
BookEntity bookEntity = bookRepository.findAllWithMetadataByIds(java.util.Collections.singleton(bookId)).stream() BookMetadata bookMetadata = bookMetadataService.updateBookMetadata(bookId, metadataUpdateWrapper, mergeCategories, replaceMode);
.findFirst()
.orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId));
MetadataUpdateContext context = MetadataUpdateContext.builder()
.bookEntity(bookEntity)
.metadataUpdateWrapper(metadataUpdateWrapper)
.updateThumbnail(true)
.mergeCategories(mergeCategories)
.replaceMode(replaceMode)
.mergeMoods(false)
.mergeTags(false)
.build();
bookMetadataUpdater.setBookMetadata(context);
auditService.log(AuditAction.METADATA_UPDATED, "Book", bookId, "Updated metadata for book: " + bookEntity.getMetadata().getTitle());
BookMetadata bookMetadata = bookMetadataMapper.toBookMetadata(bookEntity.getMetadata(), true);
return ResponseEntity.ok(bookMetadata); return ResponseEntity.ok(bookMetadata);
} }
@@ -1,13 +1,13 @@
package org.booklore.model.dto; package org.booklore.model.dto;
import java.time.LocalDateTime; import java.time.Instant;
public interface BookTimelineDto { public interface BookTimelineDto {
Long getBookId(); Long getBookId();
String getTitle(); String getTitle();
Integer getPageCount(); Integer getPageCount();
LocalDateTime getFirstSessionDate(); Instant getFirstSessionStart();
LocalDateTime getLastSessionDate(); Instant getLastSessionEnd();
Integer getTotalSessions(); Integer getTotalSessions();
Long getTotalDurationSeconds(); Long getTotalDurationSeconds();
Double getMaxProgress(); Double getMaxProgress();
@@ -1,8 +0,0 @@
package org.booklore.model.dto;
public interface FavoriteReadingDayDto {
Integer getDayOfWeek();
Long getSessionCount();
Long getTotalDurationSeconds();
}
@@ -1,9 +0,0 @@
package org.booklore.model.dto;
import java.time.LocalDate;
public interface ListeningHeatmapDto {
LocalDate getDate();
Long getSessions();
Long getDurationMinutes();
}
@@ -1,7 +0,0 @@
package org.booklore.model.dto;
public interface MonthlyListeningDurationDto {
Integer getYear();
Integer getMonth();
Long getTotalDurationSeconds();
}
@@ -1,8 +0,0 @@
package org.booklore.model.dto;
public interface PeakReadingHourDto {
Integer getHourOfDay();
Long getSessionCount();
Long getTotalDurationSeconds();
}
@@ -1,9 +0,0 @@
package org.booklore.model.dto;
import java.time.LocalDate;
public interface ReadingSessionCountDto {
LocalDate getDate();
Long getCount();
}
@@ -1,7 +0,0 @@
package org.booklore.model.dto;
public interface SessionScatterDto {
Double getHourOfDay();
Double getDurationMinutes();
Integer getDayOfWeek();
}
@@ -0,0 +1,8 @@
package org.booklore.model.dto;
import java.time.Instant;
public interface SessionTimestampDto {
Instant getStartTime();
Integer getDurationSeconds();
}
@@ -1,8 +0,0 @@
package org.booklore.model.dto;
public interface WeeklyListeningTrendDto {
Integer getYear();
Integer getWeek();
Long getTotalDurationSeconds();
Long getSessions();
}
@@ -10,7 +10,7 @@ import lombok.NoArgsConstructor;
@NoArgsConstructor @NoArgsConstructor
@AllArgsConstructor @AllArgsConstructor
public class FavoriteReadingDaysResponse { public class FavoriteReadingDaysResponse {
private Integer dayOfWeek; // 1=Monday, 7=Sunday private Integer dayOfWeek; // 1=Sunday, 7=Saturday
private String dayName; private String dayName;
private Long sessionCount; private Long sessionCount;
private Long totalDurationSeconds; private Long totalDurationSeconds;
@@ -36,6 +36,7 @@ public class LibraryEntity {
private List<BookEntity> bookEntities = new ArrayList<>(); private List<BookEntity> bookEntities = new ArrayList<>();
@OneToMany(mappedBy = "library", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY) @OneToMany(mappedBy = "library", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY)
@BatchSize(size = 20)
@Builder.Default @Builder.Default
private List<LibraryPathEntity> libraryPaths = new ArrayList<>(); private List<LibraryPathEntity> libraryPaths = new ArrayList<>();
@@ -0,0 +1,117 @@
package org.booklore.model.entity;
import jakarta.persistence.*;
import lombok.Getter;
import org.hibernate.annotations.Immutable;
import org.hibernate.annotations.Subselect;
import org.hibernate.annotations.Synchronize;
import java.time.Instant;
import java.time.LocalDateTime;
@Getter
@Entity
@Immutable
@Subselect("""
SELECT a.id * 3 AS id,
a.id AS original_id,
'HIGHLIGHT' AS entry_type,
a.user_id,
a.book_id,
bm.title AS book_title,
a.text AS text_content,
a.note AS note_content,
a.color,
a.style,
a.chapter_title,
(SELECT bf.book_type FROM book_file bf WHERE bf.book_id = a.book_id ORDER BY bf.id LIMIT 1) AS primary_book_type,
bm.cover_updated_on,
a.created_at,
a.updated_at
FROM annotations a
JOIN book_metadata bm ON bm.book_id = a.book_id
UNION ALL
SELECT n.id * 3 + 1,
n.id,
'NOTE',
n.user_id,
n.book_id,
bm.title,
n.selected_text,
n.note_content,
n.color,
NULL,
n.chapter_title,
(SELECT bf.book_type FROM book_file bf WHERE bf.book_id = n.book_id ORDER BY bf.id LIMIT 1),
bm.cover_updated_on,
n.created_at,
n.updated_at
FROM book_notes_v2 n
JOIN book_metadata bm ON bm.book_id = n.book_id
UNION ALL
SELECT b.id * 3 + 2,
b.id,
'BOOKMARK',
b.user_id,
b.book_id,
bm.title,
b.title,
b.notes,
b.color,
NULL,
NULL,
(SELECT bf.book_type FROM book_file bf WHERE bf.book_id = b.book_id ORDER BY bf.id LIMIT 1),
bm.cover_updated_on,
b.created_at,
b.updated_at
FROM book_marks b
JOIN book_metadata bm ON bm.book_id = b.book_id
""")
@Synchronize({"annotations", "book_notes_v2", "book_marks", "book_metadata", "book_file"})
public class NotebookEntryView {
@Id
private Long id;
@Column(name = "original_id")
private Long originalId;
@Column(name = "entry_type")
private String entryType;
@Column(name = "user_id")
private Long userId;
@Column(name = "book_id")
private Long bookId;
@Column(name = "book_title")
private String bookTitle;
@Column(name = "text_content")
private String textContent;
@Column(name = "note_content")
private String noteContent;
@Column(name = "color")
private String color;
@Column(name = "style")
private String style;
@Column(name = "chapter_title")
private String chapterTitle;
@Column(name = "primary_book_type")
private String primaryBookType;
@Column(name = "cover_updated_on")
private Instant coverUpdatedOn;
@Column(name = "created_at")
private LocalDateTime createdAt;
@Column(name = "updated_at")
private LocalDateTime updatedAt;
}
@@ -142,11 +142,11 @@ public interface BookOpdsRepository extends JpaRepository<BookEntity, Long>, Jpa
// RANDOM BOOKS - "Surprise Me" Feed // RANDOM BOOKS - "Surprise Me" Feed
// ============================================ // ============================================
@Query(value = "SELECT b.id FROM BookEntity b WHERE (b.deleted IS NULL OR b.deleted = false) ORDER BY function('RAND')", nativeQuery = false) @Query("SELECT b.id FROM BookEntity b WHERE (b.deleted IS NULL OR b.deleted = false) ORDER BY function('RAND')")
List<Long> findRandomBookIds(); List<Long> findRandomBookIds(Pageable pageable);
@Query(value = "SELECT b.id FROM BookEntity b WHERE b.library.id IN :libraryIds AND (b.deleted IS NULL OR b.deleted = false) ORDER BY function('RAND')", nativeQuery = false) @Query("SELECT b.id FROM BookEntity b WHERE b.library.id IN :libraryIds AND (b.deleted IS NULL OR b.deleted = false) ORDER BY function('RAND')")
List<Long> findRandomBookIdsByLibraryIds(@Param("libraryIds") Collection<Long> libraryIds); List<Long> findRandomBookIdsByLibraryIds(@Param("libraryIds") Collection<Long> libraryIds, Pageable pageable);
// ============================================ // ============================================
// AUTHORS - Distinct Authors List // AUTHORS - Distinct Authors List
@@ -1,6 +1,7 @@
package org.booklore.repository; package org.booklore.repository;
import org.springframework.data.domain.Page; import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
import org.booklore.model.entity.BookEntity; import org.booklore.model.entity.BookEntity;
import org.booklore.model.entity.LibraryPathEntity; import org.booklore.model.entity.LibraryPathEntity;
@@ -33,6 +34,16 @@ public interface BookRepository extends JpaRepository<BookEntity, Long>, JpaSpec
@Query("SELECT b FROM BookEntity b WHERE b.id = :id AND (b.deleted IS NULL OR b.deleted = false)") @Query("SELECT b FROM BookEntity b WHERE b.id = :id AND (b.deleted IS NULL OR b.deleted = false)")
Optional<BookEntity> findByIdFull(@Param("id") Long id); Optional<BookEntity> findByIdFull(@Param("id") Long id);
@EntityGraph(attributePaths = { "metadata", "metadata.authors", "metadata.categories", "metadata.tags", "metadata.comicMetadata", "libraryPath", "bookFiles" })
@Query("SELECT b FROM BookEntity b WHERE b.id = :id AND (b.deleted IS NULL OR b.deleted = false)")
Optional<BookEntity> findByIdForKoboDownload(@Param("id") Long id);
// Minimal graph for summary mapping: metadata (OneToOne), library (ManyToOne), bookFiles (OneToMany).
// metadata.authors is intentionally excluded — @BatchSize on BookMetadataEntity.authors
// triggers a batched query when first accessed, so no N+1 occurs.
@EntityGraph(attributePaths = { "metadata", "library", "bookFiles" })
@Query("SELECT b FROM BookEntity b WHERE b.id IN :bookIds AND (b.deleted IS NULL OR b.deleted = false)")
List<BookEntity> findAllForSummaryByIds(@Param("bookIds") Collection<Long> bookIds);
@EntityGraph(attributePaths = {"bookFiles", "metadata", "library", "libraryPath"}) @EntityGraph(attributePaths = {"bookFiles", "metadata", "library", "libraryPath"})
@Query("SELECT b FROM BookEntity b JOIN b.bookFiles bf WHERE bf.currentHash = :currentHash AND bf.isBookFormat = true AND (b.deleted IS NULL OR b.deleted = false)") @Query("SELECT b FROM BookEntity b JOIN b.bookFiles bf WHERE bf.currentHash = :currentHash AND bf.isBookFormat = true AND (b.deleted IS NULL OR b.deleted = false)")
@@ -123,14 +134,8 @@ public interface BookRepository extends JpaRepository<BookEntity, Long>, JpaSpec
@Query("SELECT b FROM BookEntity b WHERE (b.deleted IS NULL OR b.deleted = false)") @Query("SELECT b FROM BookEntity b WHERE (b.deleted IS NULL OR b.deleted = false)")
List<BookEntity> findAllFullBooks(); List<BookEntity> findAllFullBooks();
@Query(value = """ @Query("SELECT b FROM BookEntity b WHERE (b.deleted IS NULL OR b.deleted = false) AND b.id > :afterId ORDER BY b.id")
SELECT DISTINCT b.* FROM book b List<BookEntity> findBooksForMigrationBatch(@Param("afterId") long afterId, Pageable pageable);
LEFT JOIN book_metadata m ON b.id = m.book_id
WHERE (b.deleted IS NULL OR b.deleted = false)
ORDER BY b.id
LIMIT :limit OFFSET :offset
""", nativeQuery = true)
List<BookEntity> findBooksForMigrationBatch(@Param("offset") int offset, @Param("limit") int limit);
@Query(""" @Query("""
SELECT DISTINCT b FROM BookEntity b SELECT DISTINCT b FROM BookEntity b
@@ -166,22 +171,29 @@ public interface BookRepository extends JpaRepository<BookEntity, Long>, JpaSpec
List<BookEntity> findBooksWithFilesUnderPath(@Param("libraryPathId") Long libraryPathId, List<BookEntity> findBooksWithFilesUnderPath(@Param("libraryPathId") Long libraryPathId,
@Param("folderPath") String folderPath); @Param("folderPath") String folderPath);
@Query(value = """ @Query("""
SELECT b.* SELECT b FROM BookEntity b
FROM book b JOIN b.bookFiles bf
JOIN book_file bf ON bf.book_id = b.id WHERE b.library.id = :libraryId
WHERE b.library_id = :libraryId AND b.libraryPath.id = :libraryPathId
AND b.library_path_id = :libraryPathId AND bf.fileSubPath = :fileSubPath
AND bf.file_sub_path = :fileSubPath AND bf.fileName = :fileName
AND bf.file_name = :fileName AND bf.isBookFormat = true
AND bf.is_book = true ORDER BY b.id ASC
LIMIT 1 """)
""", nativeQuery = true) List<BookEntity> findByLibraryIdAndLibraryPathIdAndFileSubPathAndFileName(
Optional<BookEntity> findByLibraryIdAndLibraryPathIdAndFileSubPathAndFileName(
@Param("libraryId") Long libraryId, @Param("libraryId") Long libraryId,
@Param("libraryPathId") Long libraryPathId, @Param("libraryPathId") Long libraryPathId,
@Param("fileSubPath") String fileSubPath, @Param("fileSubPath") String fileSubPath,
@Param("fileName") String fileName); @Param("fileName") String fileName,
Pageable pageable);
default Optional<BookEntity> findFirstByLibraryIdAndLibraryPathIdAndFileSubPathAndFileName(
Long libraryId, Long libraryPathId, String fileSubPath, String fileName) {
return findByLibraryIdAndLibraryPathIdAndFileSubPathAndFileName(
libraryId, libraryPathId, fileSubPath, fileName, PageRequest.of(0, 1))
.stream().findFirst();
}
@Query("SELECT COUNT(b.id) FROM BookEntity b WHERE b.id IN :bookIds AND (b.deleted IS NULL OR b.deleted = false)") @Query("SELECT COUNT(b.id) FROM BookEntity b WHERE b.id IN :bookIds AND (b.deleted IS NULL OR b.deleted = false)")
long countByIdIn(@Param("bookIds") List<Long> bookIds); long countByIdIn(@Param("bookIds") List<Long> bookIds);
@@ -1,6 +1,6 @@
package org.booklore.repository; package org.booklore.repository;
import org.booklore.model.entity.AnnotationEntity; import org.booklore.model.entity.NotebookEntryView;
import org.springframework.data.domain.Page; import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.Query; import org.springframework.data.jpa.repository.Query;
@@ -12,29 +12,7 @@ import java.time.LocalDateTime;
import java.util.List; import java.util.List;
import java.util.Set; import java.util.Set;
public interface NotebookEntryRepository extends Repository<AnnotationEntity, Long> { public interface NotebookEntryRepository extends Repository<NotebookEntryView, Long> {
String ENTRIES_UNION =
"SELECT a.id, 'HIGHLIGHT' AS type, a.user_id, a.book_id, bm.title AS book_title, " +
"a.text, a.note, a.color, a.style, a.chapter_title, a.created_at, a.updated_at " +
"FROM annotations a JOIN book_metadata bm ON bm.book_id = a.book_id " +
"UNION ALL " +
"SELECT n.id, 'NOTE' AS type, n.user_id, n.book_id, bm.title AS book_title, " +
"n.selected_text, n.note_content, n.color, NULL, n.chapter_title, n.created_at, n.updated_at " +
"FROM book_notes_v2 n JOIN book_metadata bm ON bm.book_id = n.book_id " +
"UNION ALL " +
"SELECT b.id, 'BOOKMARK' AS type, b.user_id, b.book_id, bm.title AS book_title, " +
"b.title, b.notes, b.color, NULL, NULL, b.created_at, b.updated_at " +
"FROM book_marks b JOIN book_metadata bm ON bm.book_id = b.book_id";
String ENTRIES_FILTER =
" WHERE t.user_id = :userId AND t.type IN (:types)" +
" AND (:bookId IS NULL OR t.book_id = :bookId)" +
" AND (:search IS NULL" +
" OR t.text LIKE :search ESCAPE '\\\\'" +
" OR t.note LIKE :search ESCAPE '\\\\'" +
" OR t.book_title LIKE :search ESCAPE '\\\\'" +
" OR t.chapter_title LIKE :search ESCAPE '\\\\')";
interface EntryProjection { interface EntryProjection {
Long getId(); Long getId();
@@ -63,64 +41,75 @@ public interface NotebookEntryRepository extends Repository<AnnotationEntity, Lo
Instant getCoverUpdatedOn(); Instant getCoverUpdatedOn();
} }
@Query(value = "SELECT t.id, t.type, t.book_id AS bookId, t.book_title AS bookTitle, " + @Query(value = """
"t.text, t.note, t.color, t.style, t.chapter_title AS chapterTitle, " + SELECT ne.originalId as id,
"(SELECT bf.book_type FROM book_file bf WHERE bf.book_id = t.book_id ORDER BY bf.id LIMIT 1) AS primaryBookType, " + ne.entryType as type,
"t.created_at AS createdAt, t.updated_at AS updatedAt " + ne.bookId as bookId,
"FROM (" + ENTRIES_UNION + ") t" + ENTRIES_FILTER, ne.bookTitle as bookTitle,
countQuery = "SELECT COUNT(*) FROM (" + ENTRIES_UNION + ") t" + ENTRIES_FILTER, ne.textContent as text,
nativeQuery = true) ne.noteContent as note,
ne.color as color,
ne.style as style,
ne.chapterTitle as chapterTitle,
ne.primaryBookType as primaryBookType,
ne.createdAt as createdAt,
ne.updatedAt as updatedAt
FROM NotebookEntryView ne
WHERE ne.userId = :userId
AND ne.entryType IN :types
AND (:bookId IS NULL OR ne.bookId = :bookId)
AND (:search IS NULL
OR ne.textContent LIKE :search ESCAPE '\\'
OR ne.noteContent LIKE :search ESCAPE '\\'
OR ne.bookTitle LIKE :search ESCAPE '\\'
OR ne.chapterTitle LIKE :search ESCAPE '\\')
""",
countQuery = """
SELECT count(ne)
FROM NotebookEntryView ne
WHERE ne.userId = :userId
AND ne.entryType IN :types
AND (:bookId IS NULL OR ne.bookId = :bookId)
AND (:search IS NULL
OR ne.textContent LIKE :search ESCAPE '\\'
OR ne.noteContent LIKE :search ESCAPE '\\'
OR ne.bookTitle LIKE :search ESCAPE '\\'
OR ne.chapterTitle LIKE :search ESCAPE '\\')
""")
Page<EntryProjection> findEntries(@Param("userId") Long userId, Page<EntryProjection> findEntries(@Param("userId") Long userId,
@Param("types") Set<String> types, @Param("types") Set<String> types,
@Param("bookId") Long bookId, @Param("bookId") Long bookId,
@Param("search") String search, @Param("search") String search,
Pageable pageable); Pageable pageable);
@Query(value = "SELECT DISTINCT t.book_id AS bookId, t.book_title AS bookTitle FROM (" + @Query("""
"SELECT a.book_id, bm.title AS book_title FROM annotations a " + SELECT DISTINCT ne.bookId as bookId, ne.bookTitle as bookTitle
"JOIN book_metadata bm ON bm.book_id = a.book_id WHERE a.user_id = :userId " + FROM NotebookEntryView ne
"UNION " + WHERE ne.userId = :userId
"SELECT n.book_id, bm.title AS book_title FROM book_notes_v2 n " + AND (:search IS NULL OR ne.bookTitle LIKE :search ESCAPE '\\')
"JOIN book_metadata bm ON bm.book_id = n.book_id WHERE n.user_id = :userId " + ORDER BY ne.bookTitle
"UNION " + """)
"SELECT b.book_id, bm.title AS book_title FROM book_marks b " +
"JOIN book_metadata bm ON bm.book_id = b.book_id WHERE b.user_id = :userId" +
") t WHERE (:search IS NULL OR t.book_title LIKE :search ESCAPE '\\\\') " +
"ORDER BY t.book_title",
nativeQuery = true)
List<BookProjection> findBooksWithAnnotations(@Param("userId") Long userId, List<BookProjection> findBooksWithAnnotations(@Param("userId") Long userId,
@Param("search") String search, @Param("search") String search,
Pageable pageable); Pageable pageable);
@Query(value = "SELECT t.book_id AS bookId, t.book_title AS bookTitle, " + @Query(value = """
"COUNT(*) AS noteCount, t.cover_updated_on AS coverUpdatedOn " + SELECT ne.bookId as bookId,
"FROM (" + ne.bookTitle as bookTitle,
"SELECT a.book_id, a.user_id, bm.title AS book_title, bm.cover_updated_on " + count(ne) as noteCount,
"FROM annotations a JOIN book_metadata bm ON bm.book_id = a.book_id " + ne.coverUpdatedOn as coverUpdatedOn
"UNION ALL " + FROM NotebookEntryView ne
"SELECT n.book_id, n.user_id, bm.title AS book_title, bm.cover_updated_on " + WHERE ne.userId = :userId
"FROM book_notes_v2 n JOIN book_metadata bm ON bm.book_id = n.book_id " + AND (:search IS NULL OR ne.bookTitle LIKE :search ESCAPE '\\')
"UNION ALL " + GROUP BY ne.bookId, ne.bookTitle, ne.coverUpdatedOn
"SELECT b.book_id, b.user_id, bm.title AS book_title, bm.cover_updated_on " + ORDER BY ne.bookTitle
"FROM book_marks b JOIN book_metadata bm ON bm.book_id = b.book_id" + """,
") t WHERE t.user_id = :userId" + countQuery = """
" AND (:search IS NULL OR t.book_title LIKE :search ESCAPE '\\\\')" + SELECT count(DISTINCT ne.bookId)
" GROUP BY t.book_id, t.book_title, t.cover_updated_on" + FROM NotebookEntryView ne
" ORDER BY t.book_title", WHERE ne.userId = :userId
countQuery = "SELECT COUNT(*) FROM (" + AND (:search IS NULL OR ne.bookTitle LIKE :search ESCAPE '\\')
"SELECT DISTINCT t.book_id FROM (" + """)
"SELECT a.book_id, a.user_id, bm.title AS book_title " +
"FROM annotations a JOIN book_metadata bm ON bm.book_id = a.book_id " +
"UNION ALL " +
"SELECT n.book_id, n.user_id, bm.title AS book_title " +
"FROM book_notes_v2 n JOIN book_metadata bm ON bm.book_id = n.book_id " +
"UNION ALL " +
"SELECT b.book_id, b.user_id, bm.title AS book_title " +
"FROM book_marks b JOIN book_metadata bm ON bm.book_id = b.book_id" +
") t WHERE t.user_id = :userId" +
" AND (:search IS NULL OR t.book_title LIKE :search ESCAPE '\\\\')" +
") cnt",
nativeQuery = true)
Page<BookWithCountProjection> findBooksWithAnnotationsPaginated(@Param("userId") Long userId, Page<BookWithCountProjection> findBooksWithAnnotationsPaginated(@Param("userId") Long userId,
@Param("search") String search, @Param("search") String search,
Pageable pageable); Pageable pageable);
@@ -16,40 +16,22 @@ import java.util.List;
@Repository @Repository
public interface ReadingSessionRepository extends JpaRepository<ReadingSessionEntity, Long> { public interface ReadingSessionRepository extends JpaRepository<ReadingSessionEntity, Long> {
@Query(value = """ @Query("""
SELECT DATE(CONVERT_TZ(start_time, '+00:00', :tzOffset)) as date, SELECT rs.startTime
COUNT(*) as count FROM ReadingSessionEntity rs
FROM reading_sessions WHERE rs.user.id = :userId
WHERE user_id = :userId AND rs.startTime >= :periodStart AND rs.startTime < :periodEnd
AND YEAR(CONVERT_TZ(start_time, '+00:00', :tzOffset)) = :year ORDER BY rs.startTime
GROUP BY DATE(CONVERT_TZ(start_time, '+00:00', :tzOffset)) """)
ORDER BY date List<Instant> findSessionStartTimesByUserAndPeriod(
""", nativeQuery = true)
List<ReadingSessionCountDto> findSessionCountsByUserAndYear(
@Param("userId") Long userId, @Param("userId") Long userId,
@Param("year") int year, @Param("periodStart") Instant periodStart,
@Param("tzOffset") String tzOffset); @Param("periodEnd") Instant periodEnd);
@Query(value = """
SELECT DATE(CONVERT_TZ(start_time, '+00:00', :tzOffset)) as date,
COUNT(*) as count
FROM reading_sessions
WHERE user_id = :userId
AND YEAR(CONVERT_TZ(start_time, '+00:00', :tzOffset)) = :year
AND MONTH(CONVERT_TZ(start_time, '+00:00', :tzOffset)) = :month
GROUP BY DATE(CONVERT_TZ(start_time, '+00:00', :tzOffset))
ORDER BY date
""", nativeQuery = true)
List<ReadingSessionCountDto> findSessionCountsByUserAndYearAndMonth(
@Param("userId") Long userId,
@Param("year") int year,
@Param("month") int month,
@Param("tzOffset") String tzOffset);
@Query(""" @Query("""
SELECT SELECT
b.id as bookId, b.id as bookId,
COALESCE(b.metadata.title, coalesce(b.metadata.title,
(SELECT bf.fileName FROM BookFileEntity bf WHERE bf.book.id = b.id ORDER BY bf.id ASC LIMIT 1), (SELECT bf.fileName FROM BookFileEntity bf WHERE bf.book.id = b.id ORDER BY bf.id ASC LIMIT 1),
'Unknown Book') as bookTitle, 'Unknown Book') as bookTitle,
rs.bookType as bookFileType, rs.bookType as bookFileType,
@@ -70,61 +52,56 @@ public interface ReadingSessionRepository extends JpaRepository<ReadingSessionEn
@Query(""" @Query("""
SELECT SELECT
CAST(rs.createdAt AS LocalDate) as date, cast(rs.createdAt as LocalDate) as date,
AVG(rs.progressDelta / (rs.durationSeconds / 60.0)) as avgProgressPerMinute, avg(rs.progressDelta / (rs.durationSeconds / 60.0)) as avgProgressPerMinute,
COUNT(rs) as totalSessions count(rs) as totalSessions
FROM ReadingSessionEntity rs FROM ReadingSessionEntity rs
WHERE rs.user.id = :userId WHERE rs.user.id = :userId
AND rs.durationSeconds > 0 AND rs.durationSeconds > 0
AND rs.progressDelta > 0 AND rs.progressDelta > 0
AND YEAR(rs.createdAt) = :year AND rs.createdAt >= :periodStart AND rs.createdAt < :periodEnd
GROUP BY CAST(rs.createdAt AS LocalDate) GROUP BY cast(rs.createdAt as LocalDate)
ORDER BY date ORDER BY date
""") """)
List<ReadingSpeedDto> findReadingSpeedByUserAndYear(@Param("userId") Long userId, @Param("year") int year); List<ReadingSpeedDto> findReadingSpeedByUserAndYear(
@Query(value = """
SELECT
HOUR(CONVERT_TZ(start_time, '+00:00', :tzOffset)) as hourOfDay,
COUNT(*) as sessionCount,
SUM(duration_seconds) as totalDurationSeconds
FROM reading_sessions
WHERE user_id = :userId
AND (:year IS NULL OR YEAR(CONVERT_TZ(start_time, '+00:00', :tzOffset)) = :year)
AND (:month IS NULL OR MONTH(CONVERT_TZ(start_time, '+00:00', :tzOffset)) = :month)
GROUP BY HOUR(CONVERT_TZ(start_time, '+00:00', :tzOffset))
ORDER BY hourOfDay
""", nativeQuery = true)
List<PeakReadingHourDto> findPeakReadingHoursByUser(
@Param("userId") Long userId, @Param("userId") Long userId,
@Param("year") Integer year, @Param("periodStart") java.time.LocalDateTime periodStart,
@Param("month") Integer month, @Param("periodEnd") java.time.LocalDateTime periodEnd);
@Param("tzOffset") String tzOffset);
@Query(value = """ @Query("""
SELECT SELECT rs.startTime as startTime,
DAYOFWEEK(CONVERT_TZ(start_time, '+00:00', :tzOffset)) as dayOfWeek, coalesce(rs.durationSeconds, 0) as durationSeconds
COUNT(*) as sessionCount, FROM ReadingSessionEntity rs
COALESCE(SUM(duration_seconds), 0) as totalDurationSeconds WHERE rs.user.id = :userId
FROM reading_sessions AND (:periodStart IS NULL OR rs.startTime >= :periodStart)
WHERE user_id = :userId AND (:periodEnd IS NULL OR rs.startTime < :periodEnd)
AND (:year IS NULL OR YEAR(CONVERT_TZ(start_time, '+00:00', :tzOffset)) = :year) ORDER BY rs.startTime
AND (:month IS NULL OR MONTH(CONVERT_TZ(start_time, '+00:00', :tzOffset)) = :month) """)
GROUP BY DAYOFWEEK(CONVERT_TZ(start_time, '+00:00', :tzOffset)) List<SessionTimestampDto> findSessionTimestampsByUser(
ORDER BY dayOfWeek
""", nativeQuery = true)
List<FavoriteReadingDayDto> findFavoriteReadingDaysByUser(
@Param("userId") Long userId, @Param("userId") Long userId,
@Param("year") Integer year, @Param("periodStart") Instant periodStart,
@Param("month") Integer month, @Param("periodEnd") Instant periodEnd);
@Param("tzOffset") String tzOffset);
@Query("""
SELECT rs.startTime as startTime,
coalesce(rs.durationSeconds, 0) as durationSeconds
FROM ReadingSessionEntity rs
WHERE rs.user.id = :userId
AND rs.startTime >= :periodStart AND rs.startTime < :periodEnd
ORDER BY rs.startTime DESC
""")
List<SessionTimestampDto> findSessionTimestampsByUserInPeriod(
@Param("userId") Long userId,
@Param("periodStart") Instant periodStart,
@Param("periodEnd") Instant periodEnd,
Pageable pageable);
@Query(""" @Query("""
SELECT SELECT
c.name as genre, c.name as genre,
COUNT(DISTINCT b.id) as bookCount, count(distinct b.id) as bookCount,
COUNT(rs) as totalSessions, count(rs) as totalSessions,
SUM(rs.durationSeconds) as totalDurationSeconds sum(rs.durationSeconds) as totalDurationSeconds
FROM ReadingSessionEntity rs FROM ReadingSessionEntity rs
JOIN rs.book b JOIN rs.book b
JOIN b.metadata.categories c JOIN b.metadata.categories c
@@ -157,19 +134,19 @@ public interface ReadingSessionRepository extends JpaRepository<ReadingSessionEn
@Query(""" @Query("""
SELECT SELECT
b.id as bookId, b.id as bookId,
COALESCE(b.metadata.title, 'Unknown Book') as bookTitle, coalesce(b.metadata.title, 'Unknown Book') as bookTitle,
b.metadata.pageCount as pageCount, b.metadata.pageCount as pageCount,
ubp.personalRating as personalRating, ubp.personalRating as personalRating,
COALESCE(ubp.dateFinished, ubp.readStatusModifiedTime, ubp.lastReadTime) as dateFinished, coalesce(ubp.dateFinished, ubp.readStatusModifiedTime, ubp.lastReadTime) as dateFinished,
rs.startTime as startTime, rs.startTime as startTime,
rs.endTime as endTime, rs.endTime as endTime,
rs.durationSeconds as durationSeconds coalesce(rs.durationSeconds, 0) as durationSeconds
FROM ReadingSessionEntity rs FROM ReadingSessionEntity rs
JOIN rs.book b JOIN rs.book b
JOIN UserBookProgressEntity ubp ON ubp.book.id = b.id AND ubp.user.id = rs.user.id JOIN UserBookProgressEntity ubp ON ubp.book.id = b.id AND ubp.user.id = rs.user.id
WHERE rs.user.id = :userId WHERE rs.user.id = :userId
AND ubp.readStatus = org.booklore.model.enums.ReadStatus.READ AND ubp.readStatus = org.booklore.model.enums.ReadStatus.READ
AND COALESCE(ubp.dateFinished, ubp.readStatusModifiedTime, ubp.lastReadTime) IS NOT NULL AND coalesce(ubp.dateFinished, ubp.readStatusModifiedTime, ubp.lastReadTime) IS NOT NULL
ORDER BY b.id, rs.startTime ASC ORDER BY b.id, rs.startTime ASC
""") """)
List<PageTurnerSessionDto> findPageTurnerSessionsByUser(@Param("userId") Long userId); List<PageTurnerSessionDto> findPageTurnerSessionsByUser(@Param("userId") Long userId);
@@ -177,7 +154,7 @@ public interface ReadingSessionRepository extends JpaRepository<ReadingSessionEn
@Query(""" @Query("""
SELECT SELECT
b.id as bookId, b.id as bookId,
COALESCE(b.metadata.title, 'Unknown Book') as bookTitle, coalesce(b.metadata.title, 'Unknown Book') as bookTitle,
rs.startTime as sessionDate, rs.startTime as sessionDate,
rs.endProgress as endProgress rs.endProgress as endProgress
FROM ReadingSessionEntity rs FROM ReadingSessionEntity rs
@@ -185,7 +162,7 @@ public interface ReadingSessionRepository extends JpaRepository<ReadingSessionEn
JOIN UserBookProgressEntity ubp ON ubp.book.id = b.id AND ubp.user.id = rs.user.id JOIN UserBookProgressEntity ubp ON ubp.book.id = b.id AND ubp.user.id = rs.user.id
WHERE rs.user.id = :userId WHERE rs.user.id = :userId
AND ubp.readStatus = org.booklore.model.enums.ReadStatus.READ AND ubp.readStatus = org.booklore.model.enums.ReadStatus.READ
AND YEAR(COALESCE(ubp.dateFinished, ubp.readStatusModifiedTime, ubp.lastReadTime)) = :year AND year(coalesce(ubp.dateFinished, ubp.readStatusModifiedTime, ubp.lastReadTime)) = :year
AND rs.endProgress IS NOT NULL AND rs.endProgress IS NOT NULL
ORDER BY b.id, rs.startTime ASC ORDER BY b.id, rs.startTime ASC
""") """)
@@ -193,148 +170,87 @@ public interface ReadingSessionRepository extends JpaRepository<ReadingSessionEn
@Param("userId") Long userId, @Param("userId") Long userId,
@Param("year") int year); @Param("year") int year);
@Query(value = """ @Query("""
SELECT DATE(CONVERT_TZ(start_time, '+00:00', :tzOffset)) as date, SELECT rs.startTime
COUNT(*) as count FROM ReadingSessionEntity rs
FROM reading_sessions WHERE rs.user.id = :userId
WHERE user_id = :userId ORDER BY rs.startTime
GROUP BY DATE(CONVERT_TZ(start_time, '+00:00', :tzOffset)) """)
ORDER BY date List<Instant> findAllSessionStartTimesByUser(@Param("userId") Long userId);
""", nativeQuery = true)
List<ReadingSessionCountDto> findAllSessionCountsByUser(
@Param("userId") Long userId,
@Param("tzOffset") String tzOffset);
@Query(value = """
SELECT
HOUR(CONVERT_TZ(rs.start_time, '+00:00', :tzOffset))
+ MINUTE(CONVERT_TZ(rs.start_time, '+00:00', :tzOffset)) / 60.0 as hourOfDay,
rs.duration_seconds / 60.0 as durationMinutes,
DAYOFWEEK(CONVERT_TZ(rs.start_time, '+00:00', :tzOffset)) as dayOfWeek
FROM reading_sessions rs
WHERE rs.user_id = :userId
AND YEAR(CONVERT_TZ(rs.start_time, '+00:00', :tzOffset)) = :year
ORDER BY rs.start_time DESC
LIMIT 500
""", nativeQuery = true)
List<SessionScatterDto> findSessionScatterByUserAndYear(
@Param("userId") Long userId,
@Param("year") int year,
@Param("tzOffset") String tzOffset);
// ======================================================================== // ========================================================================
// Listening (audiobook) stats // Listening (audiobook) stats
// ======================================================================== // ========================================================================
@Query(value = """ @Query("""
SELECT DATE(CONVERT_TZ(start_time, '+00:00', :tzOffset)) as date, SELECT rs.startTime as startTime,
COUNT(*) as sessions, coalesce(rs.durationSeconds, 0) as durationSeconds
COALESCE(ROUND(SUM(duration_seconds) / 60.0), 0) as durationMinutes FROM ReadingSessionEntity rs
FROM reading_sessions WHERE rs.user.id = :userId
WHERE user_id = :userId AND rs.bookType = org.booklore.model.enums.BookFileType.AUDIOBOOK
AND book_type = 'AUDIOBOOK' AND (:periodStart IS NULL OR rs.startTime >= :periodStart)
AND YEAR(CONVERT_TZ(start_time, '+00:00', :tzOffset)) = :year AND (:periodEnd IS NULL OR rs.startTime < :periodEnd)
AND MONTH(CONVERT_TZ(start_time, '+00:00', :tzOffset)) = :month ORDER BY rs.startTime
GROUP BY DATE(CONVERT_TZ(start_time, '+00:00', :tzOffset)) """)
ORDER BY date List<SessionTimestampDto> findListeningTimestampsByUser(
""", nativeQuery = true)
List<ListeningHeatmapDto> findListeningSessionsByUserAndMonth(
@Param("userId") Long userId, @Param("userId") Long userId,
@Param("year") int year, @Param("periodStart") Instant periodStart,
@Param("month") int month, @Param("periodEnd") Instant periodEnd);
@Param("tzOffset") String tzOffset);
@Query(value = """ @Query("""
SELECT YEAR(CONVERT_TZ(start_time, '+00:00', :tzOffset)) as year, SELECT rs.startTime as startTime,
WEEK(CONVERT_TZ(start_time, '+00:00', :tzOffset), 3) as week, coalesce(rs.durationSeconds, 0) as durationSeconds
COALESCE(SUM(duration_seconds), 0) as totalDurationSeconds, FROM ReadingSessionEntity rs
COUNT(*) as sessions WHERE rs.user.id = :userId
FROM reading_sessions AND rs.bookType = org.booklore.model.enums.BookFileType.AUDIOBOOK
WHERE user_id = :userId ORDER BY rs.startTime DESC
AND book_type = 'AUDIOBOOK' """)
AND CONVERT_TZ(start_time, '+00:00', :tzOffset) >= DATE_SUB(NOW(), INTERVAL :weeks WEEK) List<SessionTimestampDto> findListeningTimestampsByUserPaged(
GROUP BY year, week
ORDER BY year, week
""", nativeQuery = true)
List<WeeklyListeningTrendDto> findWeeklyListeningTrend(
@Param("userId") Long userId, @Param("userId") Long userId,
@Param("weeks") int weeks, Pageable pageable);
@Param("tzOffset") String tzOffset);
@Query(value = """ @Query("""
SELECT rs.book_id as bookId, SELECT b.id as bookId,
COALESCE(bm.title, 'Unknown') as title, coalesce(bm.title, 'Unknown') as title,
COALESCE(MAX(rs.end_progress), 0) as maxProgress, max(rs.endProgress) as maxProgress,
COALESCE(MAX(bf.duration_seconds), 0) as totalDurationSeconds, coalesce(max(bf.durationSeconds), 0L) as totalDurationSeconds,
SUM(rs.duration_seconds) as listenedDurationSeconds sum(rs.durationSeconds) as listenedDurationSeconds
FROM reading_sessions rs FROM ReadingSessionEntity rs
JOIN book b ON rs.book_id = b.id JOIN rs.book b
LEFT JOIN book_metadata bm ON bm.book_id = b.id LEFT JOIN b.metadata bm
LEFT JOIN book_file bf ON bf.book_id = b.id AND bf.book_type = 'AUDIOBOOK' LEFT JOIN b.bookFiles bf ON bf.bookType = org.booklore.model.enums.BookFileType.AUDIOBOOK
WHERE rs.user_id = :userId WHERE rs.user.id = :userId
AND rs.book_type = 'AUDIOBOOK' AND rs.bookType = org.booklore.model.enums.BookFileType.AUDIOBOOK
GROUP BY rs.book_id, bm.title GROUP BY b.id, bm.title
""", nativeQuery = true) """)
List<AudiobookProgressDto> findAudiobookProgressByUser(@Param("userId") Long userId); List<AudiobookProgressDto> findAudiobookProgressByUser(@Param("userId") Long userId);
@Query(value = """ @Query("""
SELECT YEAR(COALESCE(ubp.date_finished, ubp.read_status_modified_time)) as year, SELECT year(coalesce(ubp.dateFinished, ubp.readStatusModifiedTime)) as year,
MONTH(COALESCE(ubp.date_finished, ubp.read_status_modified_time)) as month, month(coalesce(ubp.dateFinished, ubp.readStatusModifiedTime)) as month,
COUNT(*) as booksCompleted count(ubp) as booksCompleted
FROM user_book_progress ubp FROM UserBookProgressEntity ubp
WHERE ubp.user_id = :userId WHERE ubp.user.id = :userId
AND ubp.read_status = 'READ' AND ubp.readStatus = org.booklore.model.enums.ReadStatus.READ
AND COALESCE(ubp.date_finished, ubp.read_status_modified_time) IS NOT NULL AND coalesce(ubp.dateFinished, ubp.readStatusModifiedTime) IS NOT NULL
AND EXISTS ( AND EXISTS (
SELECT 1 FROM reading_sessions rs SELECT 1 FROM ReadingSessionEntity rs
WHERE rs.book_id = ubp.book_id WHERE rs.book.id = ubp.book.id
AND rs.user_id = ubp.user_id AND rs.user.id = ubp.user.id
AND rs.book_type = 'AUDIOBOOK' AND rs.bookType = org.booklore.model.enums.BookFileType.AUDIOBOOK
) )
GROUP BY year, month GROUP BY year(coalesce(ubp.dateFinished, ubp.readStatusModifiedTime)),
month(coalesce(ubp.dateFinished, ubp.readStatusModifiedTime))
ORDER BY year DESC, month DESC ORDER BY year DESC, month DESC
""", nativeQuery = true) """)
List<MonthlyCompletedAudiobookDto> findMonthlyCompletedAudiobooks(@Param("userId") Long userId); List<MonthlyCompletedAudiobookDto> findMonthlyCompletedAudiobooks(@Param("userId") Long userId);
@Query(value = """
SELECT YEAR(CONVERT_TZ(start_time, '+00:00', :tzOffset)) as year,
MONTH(CONVERT_TZ(start_time, '+00:00', :tzOffset)) as month,
COALESCE(SUM(duration_seconds), 0) as totalDurationSeconds
FROM reading_sessions
WHERE user_id = :userId
AND book_type = 'AUDIOBOOK'
GROUP BY year, month
ORDER BY year DESC, month DESC
""", nativeQuery = true)
List<MonthlyListeningDurationDto> findMonthlyListeningDurations(
@Param("userId") Long userId,
@Param("tzOffset") String tzOffset);
@Query(value = """
SELECT
HOUR(CONVERT_TZ(start_time, '+00:00', :tzOffset)) as hourOfDay,
COUNT(*) as sessionCount,
SUM(duration_seconds) as totalDurationSeconds
FROM reading_sessions
WHERE user_id = :userId
AND book_type = 'AUDIOBOOK'
AND (:year IS NULL OR YEAR(CONVERT_TZ(start_time, '+00:00', :tzOffset)) = :year)
AND (:month IS NULL OR MONTH(CONVERT_TZ(start_time, '+00:00', :tzOffset)) = :month)
GROUP BY HOUR(CONVERT_TZ(start_time, '+00:00', :tzOffset))
ORDER BY hourOfDay
""", nativeQuery = true)
List<PeakReadingHourDto> findListeningPeakHoursByUser(
@Param("userId") Long userId,
@Param("year") Integer year,
@Param("month") Integer month,
@Param("tzOffset") String tzOffset);
@Query(""" @Query("""
SELECT SELECT
c.name as genre, c.name as genre,
COUNT(DISTINCT b.id) as bookCount, count(distinct b.id) as bookCount,
COUNT(rs) as totalSessions, count(rs) as totalSessions,
SUM(rs.durationSeconds) as totalDurationSeconds sum(rs.durationSeconds) as totalDurationSeconds
FROM ReadingSessionEntity rs FROM ReadingSessionEntity rs
JOIN rs.book b JOIN rs.book b
JOIN b.metadata.categories c JOIN b.metadata.categories c
@@ -345,58 +261,43 @@ public interface ReadingSessionRepository extends JpaRepository<ReadingSessionEn
""") """)
List<GenreStatisticsDto> findListeningGenreStatisticsByUser(@Param("userId") Long userId); List<GenreStatisticsDto> findListeningGenreStatisticsByUser(@Param("userId") Long userId);
@Query(value = """ @Query("""
SELECT a.name as authorName, SELECT a.name as authorName,
COUNT(DISTINCT rs.book_id) as bookCount, count(distinct rs.book.id) as bookCount,
COUNT(*) as totalSessions, count(rs) as totalSessions,
COALESCE(SUM(rs.duration_seconds), 0) as totalDurationSeconds coalesce(sum(rs.durationSeconds), 0L) as totalDurationSeconds
FROM reading_sessions rs FROM ReadingSessionEntity rs
JOIN book_metadata_author_mapping bam ON bam.book_id = rs.book_id JOIN rs.book b
JOIN author a ON a.id = bam.author_id JOIN b.metadata m
WHERE rs.user_id = :userId JOIN m.authors a
AND rs.book_type = 'AUDIOBOOK' WHERE rs.user.id = :userId
AND rs.bookType = org.booklore.model.enums.BookFileType.AUDIOBOOK
GROUP BY a.name GROUP BY a.name
ORDER BY totalDurationSeconds DESC ORDER BY totalDurationSeconds DESC
""", nativeQuery = true) """)
List<ListeningAuthorDto> findListeningAuthorStatsByUser(@Param("userId") Long userId); List<ListeningAuthorDto> findListeningAuthorStatsByUser(@Param("userId") Long userId);
@Query(value = """ @Query("""
SELECT SELECT b.id as bookId,
HOUR(CONVERT_TZ(rs.start_time, '+00:00', :tzOffset)) coalesce(bm.title, 'Unknown') as title,
+ MINUTE(CONVERT_TZ(rs.start_time, '+00:00', :tzOffset)) / 60.0 as hourOfDay, bm.pageCount as pageCount,
rs.duration_seconds / 60.0 as durationMinutes, min(rs.startTime) as firstSessionStart,
DAYOFWEEK(CONVERT_TZ(rs.start_time, '+00:00', :tzOffset)) as dayOfWeek max(rs.endTime) as lastSessionEnd,
FROM reading_sessions rs count(rs) as totalSessions,
WHERE rs.user_id = :userId coalesce(sum(rs.durationSeconds), 0L) as totalDurationSeconds,
AND rs.book_type = 'AUDIOBOOK' coalesce(max(rs.endProgress), 0.0) / 100.0 as maxProgress,
ORDER BY rs.start_time DESC ubp.readStatus as readStatus
LIMIT 500 FROM ReadingSessionEntity rs
""", nativeQuery = true) JOIN rs.book b
List<SessionScatterDto> findListeningSessionScatterByUser( LEFT JOIN b.metadata bm
@Param("userId") Long userId, LEFT JOIN b.userBookProgress ubp ON ubp.user.id = rs.user.id
@Param("tzOffset") String tzOffset); WHERE rs.user.id = :userId
AND rs.startTime >= :periodStart AND rs.startTime < :periodEnd
@Query(value = """ GROUP BY b.id, bm.title, bm.pageCount, ubp.readStatus
SELECT rs.book_id as bookId, ORDER BY firstSessionStart
COALESCE(bm.title, 'Unknown') as title, """)
bm.page_count as pageCount,
MIN(CONVERT_TZ(rs.start_time, '+00:00', :tzOffset)) as firstSessionDate,
MAX(CONVERT_TZ(rs.end_time, '+00:00', :tzOffset)) as lastSessionDate,
COUNT(*) as totalSessions,
COALESCE(SUM(rs.duration_seconds), 0) as totalDurationSeconds,
COALESCE(MAX(rs.end_progress), 0) / 100.0 as maxProgress,
ubp.read_status as readStatus
FROM reading_sessions rs
JOIN book b ON rs.book_id = b.id
LEFT JOIN book_metadata bm ON bm.book_id = b.id
LEFT JOIN user_book_progress ubp ON ubp.book_id = rs.book_id AND ubp.user_id = rs.user_id
WHERE rs.user_id = :userId
AND YEAR(CONVERT_TZ(rs.start_time, '+00:00', :tzOffset)) = :year
GROUP BY rs.book_id, bm.title, bm.page_count, ubp.read_status
ORDER BY firstSessionDate
""", nativeQuery = true)
List<BookTimelineDto> findBookTimelineByUserAndYear( List<BookTimelineDto> findBookTimelineByUserAndYear(
@Param("userId") Long userId, @Param("userId") Long userId,
@Param("year") int year, @Param("periodStart") Instant periodStart,
@Param("tzOffset") String tzOffset); @Param("periodEnd") Instant periodEnd);
} }
@@ -6,11 +6,9 @@ import org.booklore.config.security.service.AuthenticationService;
import org.booklore.exception.ApiError; import org.booklore.exception.ApiError;
import org.booklore.model.dto.BookLoreUser; import org.booklore.model.dto.BookLoreUser;
import org.booklore.model.dto.CompletionRaceSessionDto; import org.booklore.model.dto.CompletionRaceSessionDto;
import org.booklore.model.dto.request.ReadingSessionRequest;
import org.booklore.model.dto.PageTurnerSessionDto; import org.booklore.model.dto.PageTurnerSessionDto;
import org.booklore.model.dto.BookTimelineDto; import org.booklore.model.dto.request.ReadingSessionRequest;
import org.booklore.model.dto.ProgressPercentDto; import org.booklore.model.dto.ProgressPercentDto;
import org.booklore.model.dto.ReadingSessionCountDto;
import org.booklore.model.dto.response.*; import org.booklore.model.dto.response.*;
import org.booklore.model.entity.BookEntity; import org.booklore.model.entity.BookEntity;
import org.booklore.model.entity.BookLoreUserEntity; import org.booklore.model.entity.BookLoreUserEntity;
@@ -33,11 +31,12 @@ import java.time.Instant;
import java.time.LocalDate; import java.time.LocalDate;
import java.time.LocalDateTime; import java.time.LocalDateTime;
import java.time.ZoneId; import java.time.ZoneId;
import java.time.ZoneOffset; import java.time.format.TextStyle;
import java.time.temporal.ChronoUnit; import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalAdjusters; import java.time.temporal.TemporalAdjusters;
import java.time.temporal.WeekFields; import java.time.temporal.WeekFields;
import java.util.*; import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors; import java.util.stream.Collectors;
@Slf4j @Slf4j
@@ -52,9 +51,43 @@ public class ReadingSessionService {
private final UserRepository userRepository; private final UserRepository userRepository;
private final UserBookProgressRepository userBookProgressRepository; private final UserBookProgressRepository userBookProgressRepository;
private String getTimezoneOffset() { record PeriodBounds(Instant start, Instant end) {}
ZoneOffset offset = ZoneId.systemDefault().getRules().getOffset(Instant.now());
return offset.getId().equals("Z") ? "+00:00" : offset.getId(); private PeriodBounds computeYearBounds(int year) {
ZoneId zone = ZoneId.systemDefault();
Instant start = LocalDate.of(year, 1, 1).atStartOfDay(zone).toInstant();
Instant end = LocalDate.of(year + 1, 1, 1).atStartOfDay(zone).toInstant();
return new PeriodBounds(start, end);
}
private PeriodBounds computeMonthBounds(int year, int month) {
ZoneId zone = ZoneId.systemDefault();
Instant start = LocalDate.of(year, month, 1).atStartOfDay(zone).toInstant();
Instant end = LocalDate.of(year, month, 1).plusMonths(1).atStartOfDay(zone).toInstant();
return new PeriodBounds(start, end);
}
private PeriodBounds computeOptionalBounds(Integer year, Integer month) {
if (year == null) return new PeriodBounds(null, null);
if (month == null) return computeYearBounds(year);
return computeMonthBounds(year, month);
}
private List<ReadingSessionHeatmapResponse> groupByLocalDate(List<Instant> startTimes, ZoneId zone) {
return startTimes.stream()
.map(instant -> instant.atZone(zone).toLocalDate())
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
.entrySet().stream()
.map(e -> ReadingSessionHeatmapResponse.builder()
.date(e.getKey())
.count(e.getValue())
.build())
.sorted(Comparator.comparing(ReadingSessionHeatmapResponse::getDate))
.collect(Collectors.toList());
}
private static int toSundayFirstDow(DayOfWeek dow) {
return (dow.getValue() % 7) + 1;
} }
@Transactional @Transactional
@@ -86,29 +119,23 @@ public class ReadingSessionService {
} }
public List<ReadingSessionHeatmapResponse> getSessionHeatmapForYear(int year) { public List<ReadingSessionHeatmapResponse> getSessionHeatmapForYear(int year) {
BookLoreUser authenticatedUser = authenticationService.getAuthenticatedUser(); Long userId = authenticationService.getAuthenticatedUser().getId();
Long userId = authenticatedUser.getId(); ZoneId zone = ZoneId.systemDefault();
PeriodBounds bounds = computeYearBounds(year);
return readingSessionRepository.findSessionCountsByUserAndYear(userId, year, getTimezoneOffset()) return groupByLocalDate(
.stream() readingSessionRepository.findSessionStartTimesByUserAndPeriod(userId, bounds.start(), bounds.end()),
.map(dto -> ReadingSessionHeatmapResponse.builder() zone);
.date(dto.getDate())
.count(dto.getCount())
.build())
.collect(Collectors.toList());
} }
public List<ReadingSessionHeatmapResponse> getSessionHeatmapForMonth(int year, int month) { public List<ReadingSessionHeatmapResponse> getSessionHeatmapForMonth(int year, int month) {
BookLoreUser authenticatedUser = authenticationService.getAuthenticatedUser(); Long userId = authenticationService.getAuthenticatedUser().getId();
Long userId = authenticatedUser.getId(); ZoneId zone = ZoneId.systemDefault();
PeriodBounds bounds = computeMonthBounds(year, month);
return readingSessionRepository.findSessionCountsByUserAndYearAndMonth(userId, year, month, getTimezoneOffset()) return groupByLocalDate(
.stream() readingSessionRepository.findSessionStartTimesByUserAndPeriod(userId, bounds.start(), bounds.end()),
.map(dto -> ReadingSessionHeatmapResponse.builder() zone);
.date(dto.getDate())
.count(dto.getCount())
.build())
.collect(Collectors.toList());
} }
public List<ReadingSessionTimelineResponse> getSessionTimelineForWeek(int year, int week) { public List<ReadingSessionTimelineResponse> getSessionTimelineForWeek(int year, int week) {
@@ -138,7 +165,10 @@ public class ReadingSessionService {
BookLoreUser authenticatedUser = authenticationService.getAuthenticatedUser(); BookLoreUser authenticatedUser = authenticationService.getAuthenticatedUser();
Long userId = authenticatedUser.getId(); Long userId = authenticatedUser.getId();
return readingSessionRepository.findReadingSpeedByUserAndYear(userId, year) LocalDateTime periodStart = LocalDateTime.of(year, 1, 1, 0, 0);
LocalDateTime periodEnd = LocalDateTime.of(year + 1, 1, 1, 0, 0);
return readingSessionRepository.findReadingSpeedByUserAndYear(userId, periodStart, periodEnd)
.stream() .stream()
.map(dto -> ReadingSpeedResponse.builder() .map(dto -> ReadingSpeedResponse.builder()
.date(dto.getDate()) .date(dto.getDate())
@@ -149,33 +179,53 @@ public class ReadingSessionService {
} }
public List<PeakHoursResponse> getPeakReadingHours(Integer year, Integer month) { public List<PeakHoursResponse> getPeakReadingHours(Integer year, Integer month) {
BookLoreUser authenticatedUser = authenticationService.getAuthenticatedUser(); Long userId = authenticationService.getAuthenticatedUser().getId();
Long userId = authenticatedUser.getId(); ZoneId zone = ZoneId.systemDefault();
PeriodBounds bounds = computeOptionalBounds(year, month);
return readingSessionRepository.findPeakReadingHoursByUser(userId, year, month, getTimezoneOffset()) var sessions = readingSessionRepository.findSessionTimestampsByUser(userId, bounds.start(), bounds.end());
.stream()
.map(dto -> PeakHoursResponse.builder() Map<Integer, long[]> hourlyTotals = new TreeMap<>();
.hourOfDay(dto.getHourOfDay()) for (var dto : sessions) {
.sessionCount(dto.getSessionCount()) int hour = dto.getStartTime().atZone(zone).getHour();
.totalDurationSeconds(dto.getTotalDurationSeconds()) hourlyTotals.merge(hour, new long[]{1, dto.getDurationSeconds()},
(a, b) -> new long[]{a[0] + b[0], a[1] + b[1]});
}
return hourlyTotals.entrySet().stream()
.map(e -> PeakHoursResponse.builder()
.hourOfDay(e.getKey())
.sessionCount(e.getValue()[0])
.totalDurationSeconds(e.getValue()[1])
.build()) .build())
.collect(Collectors.toList()); .collect(Collectors.toList());
} }
public List<FavoriteReadingDaysResponse> getFavoriteReadingDays(Integer year, Integer month) { public List<FavoriteReadingDaysResponse> getFavoriteReadingDays(Integer year, Integer month) {
BookLoreUser authenticatedUser = authenticationService.getAuthenticatedUser(); Long userId = authenticationService.getAuthenticatedUser().getId();
Long userId = authenticatedUser.getId(); ZoneId zone = ZoneId.systemDefault();
PeriodBounds bounds = computeOptionalBounds(year, month);
String[] dayNames = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}; var sessions = readingSessionRepository.findSessionTimestampsByUser(userId, bounds.start(), bounds.end());
return readingSessionRepository.findFavoriteReadingDaysByUser(userId, year, month, getTimezoneOffset()) Map<DayOfWeek, long[]> weekdayTotals = new EnumMap<>(DayOfWeek.class);
.stream() for (var dto : sessions) {
.map(dto -> FavoriteReadingDaysResponse.builder() DayOfWeek dow = dto.getStartTime().atZone(zone).toLocalDate().getDayOfWeek();
.dayOfWeek(dto.getDayOfWeek()) weekdayTotals.merge(dow, new long[]{1, dto.getDurationSeconds()},
.dayName(dayNames[dto.getDayOfWeek() - 1]) (a, b) -> new long[]{a[0] + b[0], a[1] + b[1]});
.sessionCount(dto.getSessionCount()) }
.totalDurationSeconds(dto.getTotalDurationSeconds())
.build()) return weekdayTotals.entrySet().stream()
.map(entry -> {
DayOfWeek dow = entry.getKey();
return FavoriteReadingDaysResponse.builder()
.dayOfWeek(toSundayFirstDow(dow))
.dayName(dow.getDisplayName(TextStyle.FULL, Locale.ENGLISH))
.sessionCount(entry.getValue()[0])
.totalDurationSeconds(entry.getValue()[1])
.build();
})
.sorted(Comparator.comparingInt(FavoriteReadingDaysResponse::getDayOfWeek))
.collect(Collectors.toList()); .collect(Collectors.toList());
} }
@@ -399,16 +449,10 @@ public class ReadingSessionService {
} }
public List<ReadingSessionHeatmapResponse> getReadingDates() { public List<ReadingSessionHeatmapResponse> getReadingDates() {
BookLoreUser authenticatedUser = authenticationService.getAuthenticatedUser(); Long userId = authenticationService.getAuthenticatedUser().getId();
Long userId = authenticatedUser.getId(); ZoneId zone = ZoneId.systemDefault();
return readingSessionRepository.findAllSessionCountsByUser(userId, getTimezoneOffset()) return groupByLocalDate(readingSessionRepository.findAllSessionStartTimesByUser(userId), zone);
.stream()
.map(dto -> ReadingSessionHeatmapResponse.builder()
.date(dto.getDate())
.count(dto.getCount())
.build())
.collect(Collectors.toList());
} }
public BookDistributionsResponse getBookDistributions() { public BookDistributionsResponse getBookDistributions() {
@@ -485,29 +529,34 @@ public class ReadingSessionService {
} }
public List<SessionScatterResponse> getSessionScatter(int year) { public List<SessionScatterResponse> getSessionScatter(int year) {
BookLoreUser authenticatedUser = authenticationService.getAuthenticatedUser(); Long userId = authenticationService.getAuthenticatedUser().getId();
Long userId = authenticatedUser.getId(); ZoneId zone = ZoneId.systemDefault();
PeriodBounds bounds = computeYearBounds(year);
return readingSessionRepository.findSessionScatterByUserAndYear(userId, year, getTimezoneOffset()) return readingSessionRepository.findSessionTimestampsByUserInPeriod(userId, bounds.start(), bounds.end(),
PageRequest.of(0, 500))
.stream() .stream()
.map(dto -> SessionScatterResponse.builder() .map(dto -> {
.hourOfDay(dto.getHourOfDay()) var zdt = dto.getStartTime().atZone(zone);
.durationMinutes(dto.getDurationMinutes()) return SessionScatterResponse.builder()
.dayOfWeek(dto.getDayOfWeek()) .hourOfDay(zdt.getHour() + zdt.getMinute() / 60.0)
.build()) .durationMinutes(dto.getDurationSeconds() / 60.0)
.dayOfWeek(toSundayFirstDow(zdt.getDayOfWeek()))
.build();
})
.collect(Collectors.toList()); .collect(Collectors.toList());
} }
public ReadingStreakResponse getReadingStreak() { public ReadingStreakResponse getReadingStreak() {
BookLoreUser authenticatedUser = authenticationService.getAuthenticatedUser(); Long userId = authenticationService.getAuthenticatedUser().getId();
Long userId = authenticatedUser.getId(); ZoneId zone = ZoneId.systemDefault();
List<ReadingSessionCountDto> allDates = readingSessionRepository.findAllSessionCountsByUser(userId, getTimezoneOffset()); Set<LocalDate> readingDays = readingSessionRepository.findAllSessionStartTimesByUser(userId)
Set<LocalDate> readingDays = allDates.stream() .stream()
.map(ReadingSessionCountDto::getDate) .map(instant -> instant.atZone(zone).toLocalDate())
.collect(Collectors.toCollection(TreeSet::new)); .collect(Collectors.toCollection(TreeSet::new));
LocalDate today = LocalDate.now(); LocalDate today = LocalDate.now(zone);
// Current streak: consecutive days backwards from today (allow yesterday as last active day) // Current streak: consecutive days backwards from today (allow yesterday as last active day)
int currentStreak = 0; int currentStreak = 0;
@@ -556,23 +605,21 @@ public class ReadingSessionService {
} }
public List<BookTimelineResponse> getBookTimeline(int year) { public List<BookTimelineResponse> getBookTimeline(int year) {
BookLoreUser authenticatedUser = authenticationService.getAuthenticatedUser(); Long userId = authenticationService.getAuthenticatedUser().getId();
Long userId = authenticatedUser.getId();
String tzOffset = getTimezoneOffset();
ZoneId zone = ZoneId.systemDefault(); ZoneId zone = ZoneId.systemDefault();
PeriodBounds bounds = computeYearBounds(year);
return readingSessionRepository.findBookTimelineByUserAndYear(userId, year, tzOffset) return readingSessionRepository.findBookTimelineByUserAndYear(userId, bounds.start(), bounds.end())
.stream() .stream()
.map(dto -> BookTimelineResponse.builder() .map(dto -> BookTimelineResponse.builder()
.bookId(dto.getBookId()) .bookId(dto.getBookId())
.title(dto.getTitle()) .title(dto.getTitle())
.pageCount(dto.getPageCount()) .pageCount(dto.getPageCount())
.firstSessionDate(dto.getFirstSessionDate() != null .firstSessionDate(dto.getFirstSessionStart() != null
? dto.getFirstSessionDate().toLocalDate() ? dto.getFirstSessionStart().atZone(zone).toLocalDate()
: null) : null)
.lastSessionDate(dto.getLastSessionDate() != null .lastSessionDate(dto.getLastSessionEnd() != null
? dto.getLastSessionDate().toLocalDate() ? dto.getLastSessionEnd().atZone(zone).toLocalDate()
: null) : null)
.totalSessions(dto.getTotalSessions()) .totalSessions(dto.getTotalSessions())
.totalDurationSeconds(dto.getTotalDurationSeconds()) .totalDurationSeconds(dto.getTotalDurationSeconds())
@@ -606,26 +653,54 @@ public class ReadingSessionService {
public List<ListeningHeatmapResponse> getListeningHeatmapForMonth(int year, int month) { public List<ListeningHeatmapResponse> getListeningHeatmapForMonth(int year, int month) {
Long userId = authenticationService.getAuthenticatedUser().getId(); Long userId = authenticationService.getAuthenticatedUser().getId();
return readingSessionRepository.findListeningSessionsByUserAndMonth(userId, year, month, getTimezoneOffset()) ZoneId zone = ZoneId.systemDefault();
.stream() PeriodBounds bounds = computeMonthBounds(year, month);
.map(dto -> ListeningHeatmapResponse.builder()
.date(dto.getDate()) var sessions = readingSessionRepository.findListeningTimestampsByUser(userId, bounds.start(), bounds.end());
.sessions(dto.getSessions())
.durationMinutes(dto.getDurationMinutes()) Map<LocalDate, long[]> dailyTotals = new TreeMap<>();
for (var dto : sessions) {
LocalDate date = dto.getStartTime().atZone(zone).toLocalDate();
dailyTotals.merge(date, new long[]{1, dto.getDurationSeconds()},
(a, b) -> new long[]{a[0] + b[0], a[1] + b[1]});
}
return dailyTotals.entrySet().stream()
.map(e -> ListeningHeatmapResponse.builder()
.date(e.getKey())
.sessions(e.getValue()[0])
.durationMinutes(Math.round(e.getValue()[1] / 60.0))
.build()) .build())
.collect(Collectors.toList()); .collect(Collectors.toList());
} }
public List<WeeklyListeningTrendResponse> getWeeklyListeningTrend(int weeks) { public List<WeeklyListeningTrendResponse> getWeeklyListeningTrend(int weeks) {
Long userId = authenticationService.getAuthenticatedUser().getId(); Long userId = authenticationService.getAuthenticatedUser().getId();
return readingSessionRepository.findWeeklyListeningTrend(userId, weeks, getTimezoneOffset()) ZoneId zone = ZoneId.systemDefault();
.stream() Instant cutoffDate = Instant.now().minus(weeks * 7L, ChronoUnit.DAYS);
.map(dto -> WeeklyListeningTrendResponse.builder()
.year(dto.getYear()) var sessions = readingSessionRepository.findListeningTimestampsByUser(userId, cutoffDate, null);
.week(dto.getWeek())
.totalDurationSeconds(dto.getTotalDurationSeconds()) Map<String, long[]> weeklyMap = new LinkedHashMap<>();
.sessions(dto.getSessions()) for (var dto : sessions) {
.build()) LocalDate date = dto.getStartTime().atZone(zone).toLocalDate();
int isoYear = date.get(WeekFields.ISO.weekBasedYear());
int isoWeek = date.get(WeekFields.ISO.weekOfWeekBasedYear());
String key = isoYear + "-" + isoWeek;
weeklyMap.merge(key, new long[]{dto.getDurationSeconds(), 1},
(a, b) -> new long[]{a[0] + b[0], a[1] + b[1]});
}
return weeklyMap.entrySet().stream()
.map(entry -> {
String[] parts = entry.getKey().split("-");
return WeeklyListeningTrendResponse.builder()
.year(Integer.parseInt(parts[0]))
.week(Integer.parseInt(parts[1]))
.totalDurationSeconds(entry.getValue()[0])
.sessions(entry.getValue()[1])
.build();
})
.collect(Collectors.toList()); .collect(Collectors.toList());
} }
@@ -667,18 +742,18 @@ public class ReadingSessionService {
public List<MonthlyPaceResponse> getMonthlyListeningPace(int months) { public List<MonthlyPaceResponse> getMonthlyListeningPace(int months) {
Long userId = authenticationService.getAuthenticatedUser().getId(); Long userId = authenticationService.getAuthenticatedUser().getId();
ZoneId zone = ZoneId.systemDefault();
// Get completed audiobooks by month
var completedByMonth = readingSessionRepository.findMonthlyCompletedAudiobooks(userId); var completedByMonth = readingSessionRepository.findMonthlyCompletedAudiobooks(userId);
// Get listening durations by month var allSessions = readingSessionRepository.findListeningTimestampsByUser(userId, null, null);
var durationsByMonth = readingSessionRepository.findMonthlyListeningDurations(userId, getTimezoneOffset());
Map<String, Long> durationMap = new HashMap<>(); Map<String, Long> durationMap = new HashMap<>();
for (var durDto : durationsByMonth) { for (var dto : allSessions) {
durationMap.put(durDto.getYear() + "-" + durDto.getMonth(), durDto.getTotalDurationSeconds()); var date = dto.getStartTime().atZone(zone).toLocalDate();
String key = date.getYear() + "-" + date.getMonthValue();
durationMap.merge(key, (long) dto.getDurationSeconds(), Long::sum);
} }
// Merge and limit to N months
return completedByMonth.stream() return completedByMonth.stream()
.limit(months) .limit(months)
.map(dto -> { .map(dto -> {
@@ -726,12 +801,23 @@ public class ReadingSessionService {
public List<PeakHoursResponse> getListeningPeakHours(Integer year, Integer month) { public List<PeakHoursResponse> getListeningPeakHours(Integer year, Integer month) {
Long userId = authenticationService.getAuthenticatedUser().getId(); Long userId = authenticationService.getAuthenticatedUser().getId();
return readingSessionRepository.findListeningPeakHoursByUser(userId, year, month, getTimezoneOffset()) ZoneId zone = ZoneId.systemDefault();
.stream() PeriodBounds bounds = computeOptionalBounds(year, month);
.map(dto -> PeakHoursResponse.builder()
.hourOfDay(dto.getHourOfDay()) var sessions = readingSessionRepository.findListeningTimestampsByUser(userId, bounds.start(), bounds.end());
.sessionCount(dto.getSessionCount())
.totalDurationSeconds(dto.getTotalDurationSeconds()) Map<Integer, long[]> hourlyTotals = new TreeMap<>();
for (var dto : sessions) {
int hour = dto.getStartTime().atZone(zone).getHour();
hourlyTotals.merge(hour, new long[]{1, dto.getDurationSeconds()},
(a, b) -> new long[]{a[0] + b[0], a[1] + b[1]});
}
return hourlyTotals.entrySet().stream()
.map(e -> PeakHoursResponse.builder()
.hourOfDay(e.getKey())
.sessionCount(e.getValue()[0])
.totalDurationSeconds(e.getValue()[1])
.build()) .build())
.collect(Collectors.toList()); .collect(Collectors.toList());
} }
@@ -771,13 +857,18 @@ public class ReadingSessionService {
public List<SessionScatterResponse> getListeningSessionScatter() { public List<SessionScatterResponse> getListeningSessionScatter() {
Long userId = authenticationService.getAuthenticatedUser().getId(); Long userId = authenticationService.getAuthenticatedUser().getId();
return readingSessionRepository.findListeningSessionScatterByUser(userId, getTimezoneOffset()) ZoneId zone = ZoneId.systemDefault();
return readingSessionRepository.findListeningTimestampsByUserPaged(userId, PageRequest.of(0, 500))
.stream() .stream()
.map(dto -> SessionScatterResponse.builder() .map(dto -> {
.hourOfDay(dto.getHourOfDay()) var zdt = dto.getStartTime().atZone(zone);
.durationMinutes(dto.getDurationMinutes()) return SessionScatterResponse.builder()
.dayOfWeek(dto.getDayOfWeek()) .hourOfDay(zdt.getHour() + zdt.getMinute() / 60.0)
.build()) .durationMinutes(dto.getDurationSeconds() / 60.0)
.dayOfWeek(toSundayFirstDow(zdt.getDayOfWeek()))
.build();
})
.collect(Collectors.toList()); .collect(Collectors.toList());
} }
@@ -60,19 +60,19 @@ public class BookCreatorService {
} }
public BookEntity createShellBook(LibraryFile libraryFile, BookFileType bookFileType) { public BookEntity createShellBook(LibraryFile libraryFile, BookFileType bookFileType) {
Optional<BookEntity> existingBookOpt = bookRepository.findByLibraryIdAndLibraryPathIdAndFileSubPathAndFileName( Optional<BookEntity> existing = bookRepository.findFirstByLibraryIdAndLibraryPathIdAndFileSubPathAndFileName(
libraryFile.getLibraryEntity().getId(), libraryFile.getLibraryEntity().getId(),
libraryFile.getLibraryPathEntity().getId(), libraryFile.getLibraryPathEntity().getId(),
libraryFile.getFileSubPath(), libraryFile.getFileSubPath(),
libraryFile.getFileName()); libraryFile.getFileName());
if (existingBookOpt.isPresent()) { if (existing.isPresent()) {
log.warn("Book already exists for file: {}", libraryFile.getFileName()); log.warn("Book already exists for file: {}", libraryFile.getFileName());
long fileSizeKb = calculateFileSize(libraryFile); long fileSizeKb = calculateFileSize(libraryFile);
String newHash = libraryFile.isFolderBased() String newHash = libraryFile.isFolderBased()
? FileFingerprint.generateFolderHash(libraryFile.getFullPath()) ? FileFingerprint.generateFolderHash(libraryFile.getFullPath())
: FileFingerprint.generateHash(libraryFile.getFullPath()); : FileFingerprint.generateHash(libraryFile.getFullPath());
BookEntity existingBook = existingBookOpt.get(); BookEntity existingBook = existing.get();
BookFileEntity primaryFile = existingBook.getPrimaryBookFile(); BookFileEntity primaryFile = existingBook.getPrimaryBookFile();
primaryFile.setCurrentHash(newHash); primaryFile.setCurrentHash(newHash);
primaryFile.setInitialHash(newHash); primaryFile.setInitialHash(newHash);
@@ -240,7 +240,7 @@ public class BookDownloadService {
} }
public void downloadKoboBook(Long bookId, HttpServletResponse response) { public void downloadKoboBook(Long bookId, HttpServletResponse response) {
BookEntity bookEntity = bookRepository.findByIdWithBookFiles(bookId).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId)); BookEntity bookEntity = bookRepository.findByIdForKoboDownload(bookId).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId));
var primaryFile = bookEntity.getPrimaryBookFile(); var primaryFile = bookEntity.getPrimaryBookFile();
if (primaryFile == null) { if (primaryFile == null) {
@@ -41,9 +41,6 @@ import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.support.TransactionTemplate;
import tools.jackson.databind.ObjectMapper; import tools.jackson.databind.ObjectMapper;
import java.io.File; import java.io.File;
@@ -79,7 +76,6 @@ public class BookDropService {
private final FileMovingHelper fileMovingHelper; private final FileMovingHelper fileMovingHelper;
private final MonitoringRegistrationService monitoringRegistrationService; private final MonitoringRegistrationService monitoringRegistrationService;
private final ApplicationEventPublisher eventPublisher; private final ApplicationEventPublisher eventPublisher;
private final PlatformTransactionManager transactionManager;
private static final int CHUNK_SIZE = 100; private static final int CHUNK_SIZE = 100;
@@ -292,7 +288,7 @@ public class BookDropService {
private void reregisterAffectedLibraries(Set<Long> libraryIds) { private void reregisterAffectedLibraries(Set<Long> libraryIds) {
for (Long libraryId : libraryIds) { for (Long libraryId : libraryIds) {
try { try {
LibraryEntity library = libraryRepository.findById(libraryId).orElse(null); LibraryEntity library = libraryRepository.findByIdWithPaths(libraryId).orElse(null);
if (library != null) { if (library != null) {
for (LibraryPathEntity libPath : library.getLibraryPaths()) { for (LibraryPathEntity libPath : library.getLibraryPaths()) {
Path libraryRoot = Path.of(libPath.getPath()); Path libraryRoot = Path.of(libPath.getPath());
@@ -376,7 +372,7 @@ public class BookDropService {
} }
private BookdropFileResult moveFile(long libraryId, long pathId, BookMetadata metadata, BookdropFileEntity bookdropFile) { private BookdropFileResult moveFile(long libraryId, long pathId, BookMetadata metadata, BookdropFileEntity bookdropFile) {
LibraryEntity library = libraryRepository.findById(libraryId) LibraryEntity library = libraryRepository.findByIdWithPaths(libraryId)
.orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException(libraryId)); .orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException(libraryId));
LibraryPathEntity path = library.getLibraryPaths().stream() LibraryPathEntity path = library.getLibraryPaths().stream()
@@ -472,12 +468,12 @@ public class BookDropService {
.orElseThrow(() -> ApiError.INVALID_FILE_FORMAT.createException("Unsupported file extension")) .orElseThrow(() -> ApiError.INVALID_FILE_FORMAT.createException("Unsupported file extension"))
.getType()); .getType());
// Post-processing runs in REQUIRES_NEW so it gets a fresh REPEATABLE_READ snapshot // Post-processing runs in the same transaction as processFile (which uses
// that can see the book committed by processFile()'s own REQUIRES_NEW transaction // PROPAGATION_REQUIRED and joins this TX). The book entity is flushed but
TransactionTemplate newTx = new TransactionTemplate(transactionManager); // not committed a REQUIRES_NEW here would start a separate TX whose
newTx.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); // REPEATABLE_READ snapshot cannot see the uncommitted book, causing
// "Book ID missing after import".
Long bookId = fileProcessResult.getBook().getId(); Long bookId = fileProcessResult.getBook().getId();
newTx.executeWithoutResult(status -> {
BookEntity bookEntity = bookRepository.findByIdWithBookFiles(bookId) BookEntity bookEntity = bookRepository.findByIdWithBookFiles(bookId)
.orElseThrow(() -> ApiError.FILE_NOT_FOUND.createException("Book ID missing after import")); .orElseThrow(() -> ApiError.FILE_NOT_FOUND.createException("Book ID missing after import"));
@@ -497,7 +493,6 @@ public class BookDropService {
eventPublisher.publishEvent(new BookAddedEvent(fileProcessResult.getBook())); eventPublisher.publishEvent(new BookAddedEvent(fileProcessResult.getBook()));
notificationService.sendMessage(Topic.BOOK_ADD, fileProcessResult.getBook()); notificationService.sendMessage(Topic.BOOK_ADD, fileProcessResult.getBook());
});
cleanupBookdropData(bookdropFile); cleanupBookdropData(bookdropFile);
@@ -71,7 +71,7 @@ public class FileMoveService {
sleep(EVENT_DRAIN_TIMEOUT_MS); sleep(EVENT_DRAIN_TIMEOUT_MS);
} finally { } finally {
for (Long libraryId : allAffectedLibraryIds) { for (Long libraryId : allAffectedLibraryIds) {
libraryRepository.findById(libraryId) libraryRepository.findByIdWithPaths(libraryId)
.ifPresent(library -> monitoringRegistrationService.registerLibrary(libraryMapper.toLibrary(library))); .ifPresent(library -> monitoringRegistrationService.registerLibrary(libraryMapper.toLibrary(library)));
} }
} }
@@ -101,7 +101,7 @@ public class FileMoveService {
try { try {
Optional<BookEntity> optionalBook = bookRepository.findByIdWithBookFiles(bookId); Optional<BookEntity> optionalBook = bookRepository.findByIdWithBookFiles(bookId);
Optional<LibraryEntity> optionalLibrary = libraryRepository.findById(targetLibraryId); Optional<LibraryEntity> optionalLibrary = libraryRepository.findByIdWithPaths(targetLibraryId);
if (optionalBook.isEmpty()) { if (optionalBook.isEmpty()) {
log.warn("Book not found for move operation: bookId={}", bookId); log.warn("Book not found for move operation: bookId={}", bookId);
return; return;
@@ -268,6 +268,17 @@ public class FileMoveService {
Long libraryId = bookEntity.getLibraryPath().getLibrary().getId(); Long libraryId = bookEntity.getLibraryPath().getLibrary().getId();
Path libraryRoot = Paths.get(bookEntity.getLibraryPath().getPath()).toAbsolutePath().normalize(); Path libraryRoot = Paths.get(bookEntity.getLibraryPath().getPath()).toAbsolutePath().normalize();
// Evict the L1-cached LibraryEntity so that findByIdWithPaths() returns a fresh
// instance with libraryPaths eagerly loaded. Without this, the caller's EntityGraph
// (e.g. findAllWithMetadataByIds) may have loaded the LibraryEntity without
// libraryPaths, poisoning the L1 cache and causing a LazyInitializationException
// when libraryPaths is accessed later (OSIV is disabled).
LibraryEntity cachedLibrary = bookEntity.getLibraryPath().getLibrary();
if (entityManager.contains(cachedLibrary)) {
entityManager.detach(cachedLibrary);
}
boolean isLibraryMonitoredWhenCalled = false; boolean isLibraryMonitoredWhenCalled = false;
Map<Long, PlannedMove> plannedMovesByBookFileId = new HashMap<>(); Map<Long, PlannedMove> plannedMovesByBookFileId = new HashMap<>();
Set<Path> sourceParentsToCleanup = new HashSet<>(); Set<Path> sourceParentsToCleanup = new HashSet<>();
@@ -392,13 +403,17 @@ public class FileMoveService {
throw e; throw e;
} }
// Clean up empty parent directories // Clean up empty parent directories – load library paths via a separate query
Set<Path> libraryRoots = bookWithFiles.getLibraryPath().getLibrary().getLibraryPaths().stream() // to avoid LazyInitializationException (OSIV is disabled) and MultipleBagFetchException
// (cannot eagerly fetch both bookFiles and libraryPaths in the same EntityGraph).
Set<Path> libraryRoots = libraryRepository.findByIdWithPaths(libraryId)
.map(lib -> lib.getLibraryPaths().stream()
.map(LibraryPathEntity::getPath) .map(LibraryPathEntity::getPath)
.map(Paths::get) .map(Paths::get)
.map(Path::toAbsolutePath) .map(Path::toAbsolutePath)
.map(Path::normalize) .map(Path::normalize)
.collect(Collectors.toCollection(HashSet::new)); .collect(Collectors.toCollection(HashSet::new)))
.orElseGet(HashSet::new);
// Also protect the source library root so cleanup doesn't traverse above it // Also protect the source library root so cleanup doesn't traverse above it
libraryRoots.add(Paths.get(bookWithFiles.getLibraryPath().getPath()).toAbsolutePath().normalize()); libraryRoots.add(Paths.get(bookWithFiles.getLibraryPath().getPath()).toAbsolutePath().normalize());
@@ -434,10 +449,11 @@ public class FileMoveService {
if (isLibraryMonitoredWhenCalled) { if (isLibraryMonitoredWhenCalled) {
log.debug("Registering library paths for library {} with root {}", libraryId, libraryRoot); log.debug("Registering library paths for library {} with root {}", libraryId, libraryRoot);
LibraryEntity libraryEntity = bookEntity.getLibraryPath().getLibrary(); libraryRepository.findByIdWithPaths(libraryId).ifPresent(lib -> {
Library library = libraryMapper.toLibrary(libraryEntity); Library library = libraryMapper.toLibrary(lib);
library.setWatch(true); library.setWatch(true);
monitoringRegistrationService.registerLibrary(library); monitoringRegistrationService.registerLibrary(library);
});
} }
} }
@@ -52,7 +52,7 @@ public class LibraryProcessingService {
@Transactional @Transactional
public void processLibrary(long libraryId) { public void processLibrary(long libraryId) {
LibraryEntity libraryEntity = libraryRepository.findById(libraryId).orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException(libraryId)); LibraryEntity libraryEntity = libraryRepository.findByIdWithPaths(libraryId).orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException(libraryId));
notificationService.sendMessage(Topic.LOG, LogNotification.info("Started processing library: " + libraryEntity.getName())); notificationService.sendMessage(Topic.LOG, LogNotification.info("Started processing library: " + libraryEntity.getName()));
try { try {
List<LibraryFile> libraryFiles = libraryFileHelper.getLibraryFiles(libraryEntity); List<LibraryFile> libraryFiles = libraryFileHelper.getLibraryFiles(libraryEntity);
@@ -67,6 +67,28 @@ public class BookMetadataService {
private final PlatformTransactionManager transactionManager; private final PlatformTransactionManager transactionManager;
private final AppSettingService appSettingService; private final AppSettingService appSettingService;
@Transactional
public BookMetadata updateBookMetadata(long bookId, MetadataUpdateWrapper metadataUpdateWrapper,
boolean mergeCategories, MetadataReplaceMode replaceMode) {
BookEntity bookEntity = bookRepository.findAllWithMetadataByIds(Collections.singleton(bookId)).stream()
.findFirst()
.orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId));
MetadataUpdateContext context = MetadataUpdateContext.builder()
.bookEntity(bookEntity)
.metadataUpdateWrapper(metadataUpdateWrapper)
.updateThumbnail(true)
.mergeCategories(mergeCategories)
.replaceMode(replaceMode)
.mergeMoods(false)
.mergeTags(false)
.build();
bookMetadataUpdater.setBookMetadata(context);
auditService.log(AuditAction.METADATA_UPDATED, "Book", bookId,
"Updated metadata for book: " + bookEntity.getMetadata().getTitle());
return bookMetadataMapper.toBookMetadata(bookEntity.getMetadata(), true);
}
@Transactional(readOnly = true) @Transactional(readOnly = true)
public Flux<BookMetadata> getProspectiveMetadataListForBookId(long bookId, FetchMetadataRequest request) { public Flux<BookMetadata> getProspectiveMetadataListForBookId(long bookId, FetchMetadataRequest request) {
@@ -210,26 +232,6 @@ public class BookMetadataService {
return metadataExtractorFactory.extractMetadata(primaryFile.getBookType(), FileUtils.getBookFullPath(bookEntity).toFile()); return metadataExtractorFactory.extractMetadata(primaryFile.getBookType(), FileUtils.getBookFullPath(bookEntity).toFile());
} }
@Transactional
public BookMetadata updateMetadata(long bookId, MetadataUpdateWrapper wrapper, boolean mergeCategories) {
BookEntity bookEntity = bookRepository.findByIdFull(bookId)
.orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId));
MetadataUpdateContext context = MetadataUpdateContext.builder()
.bookEntity(bookEntity)
.metadataUpdateWrapper(wrapper)
.updateThumbnail(true)
.mergeCategories(mergeCategories)
.replaceMode(MetadataReplaceMode.REPLACE_ALL)
.mergeMoods(false)
.mergeTags(false)
.build();
bookMetadataUpdater.setBookMetadata(context);
auditService.log(AuditAction.METADATA_UPDATED, "Book", bookId, "Updated metadata for book: " + bookEntity.getMetadata().getTitle());
return bookMetadataMapper.toBookMetadata(bookEntity.getMetadata(), true);
}
@Transactional @Transactional
public void bulkUpdateMetadata(BulkMetadataUpdateRequest request, boolean mergeCategories, boolean mergeMoods, boolean mergeTags) { public void bulkUpdateMetadata(BulkMetadataUpdateRequest request, boolean mergeCategories, boolean mergeMoods, boolean mergeTags) {
MetadataClearFlags clearFlags = metadataClearFlagsMapper.toClearFlags(request); MetadataClearFlags clearFlags = metadataClearFlagsMapper.toClearFlags(request);
@@ -6,6 +6,7 @@ import org.booklore.service.migration.Migration;
import org.booklore.util.BookCoverUtils; import org.booklore.util.BookCoverUtils;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import java.util.List; import java.util.List;
@@ -33,10 +34,10 @@ public class GenerateCoverHashMigration implements Migration {
int batchSize = 1000; int batchSize = 1000;
int processedCount = 0; int processedCount = 0;
int offset = 0; long lastId = 0;
while (true) { while (true) {
List<BookEntity> bookBatch = bookRepository.findBooksForMigrationBatch(offset, batchSize); List<BookEntity> bookBatch = bookRepository.findBooksForMigrationBatch(lastId, PageRequest.of(0, batchSize));
if (bookBatch.isEmpty()) break; if (bookBatch.isEmpty()) break;
for (BookEntity book : bookBatch) { for (BookEntity book : bookBatch) {
@@ -47,7 +48,7 @@ public class GenerateCoverHashMigration implements Migration {
bookRepository.saveAll(bookBatch); bookRepository.saveAll(bookBatch);
processedCount += bookBatch.size(); processedCount += bookBatch.size();
offset += batchSize; lastId = bookBatch.getLast().getId();
log.info("Migration progress: {} books processed", processedCount); log.info("Migration progress: {} books processed", processedCount);
@@ -7,6 +7,7 @@ import org.booklore.service.migration.Migration;
import org.booklore.util.BookUtils; import org.booklore.util.BookUtils;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import java.util.List; import java.util.List;
@@ -34,10 +35,10 @@ public class PopulateSearchTextMigration implements Migration {
int batchSize = 1000; int batchSize = 1000;
int processedCount = 0; int processedCount = 0;
int offset = 0; long lastId = 0;
while (true) { while (true) {
List<BookEntity> bookBatch = bookRepository.findBooksForMigrationBatch(offset, batchSize); List<BookEntity> bookBatch = bookRepository.findBooksForMigrationBatch(lastId, PageRequest.of(0, batchSize));
if (bookBatch.isEmpty()) break; if (bookBatch.isEmpty()) break;
List<Long> bookIds = bookBatch.stream().map(BookEntity::getId).toList(); List<Long> bookIds = bookBatch.stream().map(BookEntity::getId).toList();
@@ -56,7 +57,7 @@ public class PopulateSearchTextMigration implements Migration {
bookRepository.saveAll(books); bookRepository.saveAll(books);
processedCount += books.size(); processedCount += books.size();
offset += batchSize; lastId = bookBatch.getLast().getId();
log.info("Migration progress: {} books processed", processedCount); log.info("Migration progress: {} books processed", processedCount);
@@ -161,19 +161,23 @@ public class OpdsBookService {
} }
public List<Book> getRandomBooks(Long userId, int count) { public List<Book> getRandomBooks(Long userId, int count) {
if (count < 1) {
return List.of();
}
List<Library> accessibleLibraries = getAccessibleLibraries(userId); List<Library> accessibleLibraries = getAccessibleLibraries(userId);
if (accessibleLibraries == null || accessibleLibraries.isEmpty()) { if (accessibleLibraries == null || accessibleLibraries.isEmpty()) {
return List.of(); return List.of();
} }
List<Long> libraryIds = accessibleLibraries.stream().map(Library::getId).toList(); List<Long> libraryIds = accessibleLibraries.stream().map(Library::getId).toList();
List<Long> ids = bookOpdsRepository.findRandomBookIdsByLibraryIds(libraryIds); List<Long> ids = bookOpdsRepository.findRandomBookIdsByLibraryIds(libraryIds, PageRequest.of(0, count));
if (ids.isEmpty()) { if (ids.isEmpty()) {
return List.of(); return List.of();
} }
List<BookEntity> books = bookOpdsRepository.findAllWithMetadataByIds(ids.stream().limit(count).toList()); List<BookEntity> books = bookOpdsRepository.findAllWithMetadataByIds(ids);
if (userId != null) { if (userId != null) {
books = contentRestrictionService.applyRestrictions(books, userId); books = contentRestrictionService.applyRestrictions(books, userId);
} }
@@ -64,7 +64,6 @@ spring:
pool-name: BookloreHikariPool pool-name: BookloreHikariPool
auto-commit: false # Required counterpart to provider_disables_autocommit auto-commit: false # Required counterpart to provider_disables_autocommit
max-lifetime: 580000 # 9.6 minutes (avoid DB-side connection cuts) max-lifetime: 580000 # 9.6 minutes (avoid DB-side connection cuts)
connection-test-query: SELECT 1
connection-timeout: 30000 # 30s to acquire a connection before timeout connection-timeout: 30000 # 30s to acquire a connection before timeout
maximum-pool-size: 5 # Virtual threads don't need large pools; 5 is enough for a self-hosted app maximum-pool-size: 5 # Virtual threads don't need large pools; 5 is enough for a self-hosted app
minimum-idle: 1 # Minimal warm connections; virtual threads handle bursts minimum-idle: 1 # Minimal warm connections; virtual threads handle bursts
@@ -0,0 +1,3 @@
-- Covering index for audiobook-filtered queries (listening stats)
CREATE INDEX IF NOT EXISTS idx_reading_session_user_booktype
ON reading_sessions (user_id, book_type, start_time DESC);
@@ -1,25 +1,21 @@
package org.booklore.controller; package org.booklore.controller;
import org.booklore.config.security.service.AuthenticationService;
import org.booklore.mapper.BookMetadataMapper;
import org.booklore.model.MetadataUpdateContext;
import org.booklore.model.MetadataUpdateWrapper; import org.booklore.model.MetadataUpdateWrapper;
import org.booklore.model.dto.BookMetadata; import org.booklore.model.dto.BookMetadata;
import org.booklore.model.entity.BookEntity;
import org.booklore.model.entity.BookMetadataEntity;
import org.booklore.repository.BookRepository;
import org.booklore.service.audit.AuditService;
import org.booklore.model.enums.MetadataReplaceMode; import org.booklore.model.enums.MetadataReplaceMode;
import org.booklore.service.metadata.*; import org.booklore.service.metadata.BookMetadataService;
import org.booklore.service.metadata.MetadataManagementService;
import org.booklore.service.metadata.MetadataMatchService;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.InjectMocks; import org.mockito.InjectMocks;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension; import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.http.ResponseEntity;
import static org.junit.jupiter.api.Assertions.*; import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.*; import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@ExtendWith(MockitoExtension.class) @ExtendWith(MockitoExtension.class)
class MetadataControllerTest { class MetadataControllerTest {
@@ -27,61 +23,41 @@ class MetadataControllerTest {
@Mock @Mock
private BookMetadataService bookMetadataService; private BookMetadataService bookMetadataService;
@Mock @Mock
private BookMetadataUpdater bookMetadataUpdater;
@Mock
private AuthenticationService authenticationService;
@Mock
private BookMetadataMapper bookMetadataMapper;
@Mock
private MetadataMatchService metadataMatchService; private MetadataMatchService metadataMatchService;
@Mock @Mock
private DuckDuckGoCoverService duckDuckGoCoverService;
@Mock
private BookRepository bookRepository;
@Mock
private MetadataManagementService metadataManagementService; private MetadataManagementService metadataManagementService;
@Mock
private AuditService auditService;
@InjectMocks @InjectMocks
private MetadataController metadataController; private MetadataController metadataController;
private MetadataUpdateContext captureContextFromUpdate(MetadataReplaceMode replaceMode) { @Test
void updateMetadata_delegatesToService() {
long bookId = 1L; long bookId = 1L;
MetadataUpdateWrapper wrapper = MetadataUpdateWrapper.builder().build(); MetadataUpdateWrapper wrapper = MetadataUpdateWrapper.builder().build();
BookEntity bookEntity = new BookEntity(); MetadataReplaceMode replaceMode = MetadataReplaceMode.REPLACE_ALL;
bookEntity.setId(bookId); BookMetadata expected = new BookMetadata();
bookEntity.setMetadata(new BookMetadataEntity());
when(bookRepository.findAllWithMetadataByIds(java.util.Collections.singleton(bookId))).thenReturn(java.util.List.of(bookEntity)); when(bookMetadataService.updateBookMetadata(bookId, wrapper, true, replaceMode))
when(bookMetadataMapper.toBookMetadata(any(), anyBoolean())).thenReturn(new BookMetadata()); .thenReturn(expected);
metadataController.updateMetadata(wrapper, bookId, true, replaceMode); ResponseEntity<BookMetadata> response = metadataController.updateMetadata(wrapper, bookId, true, replaceMode);
ArgumentCaptor<MetadataUpdateContext> captor = ArgumentCaptor.forClass(MetadataUpdateContext.class); assertThat(response.getBody()).isSameAs(expected);
verify(bookMetadataUpdater).setBookMetadata(captor.capture()); verify(bookMetadataService).updateBookMetadata(bookId, wrapper, true, replaceMode);
return captor.getValue();
} }
@Test @Test
void updateMetadata_shouldDisableMergingForTagsAndMoods() { void updateMetadata_passesReplaceModeToService() {
MetadataUpdateContext context = captureContextFromUpdate(MetadataReplaceMode.REPLACE_ALL); long bookId = 1L;
MetadataUpdateWrapper wrapper = MetadataUpdateWrapper.builder().build();
MetadataReplaceMode replaceMode = MetadataReplaceMode.REPLACE_WHEN_PROVIDED;
BookMetadata expected = new BookMetadata();
assertFalse(context.isMergeTags(), "mergeTags should be false to allow deletion of tags"); when(bookMetadataService.updateBookMetadata(bookId, wrapper, false, replaceMode))
assertFalse(context.isMergeMoods(), "mergeMoods should be false to allow deletion of moods"); .thenReturn(expected);
}
@Test metadataController.updateMetadata(wrapper, bookId, false, replaceMode);
void updateMetadata_shouldPassReplaceModeFromParam() {
MetadataUpdateContext context = captureContextFromUpdate(MetadataReplaceMode.REPLACE_WHEN_PROVIDED);
assertEquals(MetadataReplaceMode.REPLACE_WHEN_PROVIDED, context.getReplaceMode()); verify(bookMetadataService).updateBookMetadata(bookId, wrapper, false, replaceMode);
}
@Test
void updateMetadata_shouldDefaultToReplaceAll() {
MetadataUpdateContext context = captureContextFromUpdate(MetadataReplaceMode.REPLACE_ALL);
assertEquals(MetadataReplaceMode.REPLACE_ALL, context.getReplaceMode());
} }
} }
@@ -311,7 +311,7 @@ class OpdsBookServiceTest {
List<Library> libs = List.of(Library.builder().id(1L).watch(false).build()); List<Library> libs = List.of(Library.builder().id(1L).watch(false).build());
doReturn(libs).when(spy).getAccessibleLibraries(details.getOpdsUserV2().getUserId()); doReturn(libs).when(spy).getAccessibleLibraries(details.getOpdsUserV2().getUserId());
when(bookOpdsRepository.findRandomBookIdsByLibraryIds(anyList())).thenReturn(List.of(1L, 2L)); when(bookOpdsRepository.findRandomBookIdsByLibraryIds(anyList(), any())).thenReturn(List.of(1L, 2L));
BookEntity entity = mock(BookEntity.class); BookEntity entity = mock(BookEntity.class);
when(bookOpdsRepository.findAllWithMetadataByIds(anyList())).thenReturn(List.of(entity)); when(bookOpdsRepository.findAllWithMetadataByIds(anyList())).thenReturn(List.of(entity));
Book book = Book.builder().id(1L).build(); Book book = Book.builder().id(1L).build();
@@ -750,7 +750,7 @@ class OpdsBookServiceTest {
BookEntity allowedEntity = mock(BookEntity.class); BookEntity allowedEntity = mock(BookEntity.class);
BookEntity restrictedEntity = mock(BookEntity.class); BookEntity restrictedEntity = mock(BookEntity.class);
when(bookOpdsRepository.findRandomBookIdsByLibraryIds(anyList())).thenReturn(List.of(1L, 2L)); when(bookOpdsRepository.findRandomBookIdsByLibraryIds(anyList(), any())).thenReturn(List.of(1L, 2L));
when(bookOpdsRepository.findAllWithMetadataByIds(anyList())) when(bookOpdsRepository.findAllWithMetadataByIds(anyList()))
.thenReturn(List.of(allowedEntity, restrictedEntity)); .thenReturn(List.of(allowedEntity, restrictedEntity));
@@ -42,8 +42,6 @@ import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl; import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Pageable;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionStatus;
import tools.jackson.databind.ObjectMapper; import tools.jackson.databind.ObjectMapper;
import java.io.IOException; import java.io.IOException;
@@ -90,8 +88,6 @@ class BookDropServiceTest {
private FileMovingHelper fileMovingHelper; private FileMovingHelper fileMovingHelper;
@Mock @Mock
private ApplicationEventPublisher eventPublisher; private ApplicationEventPublisher eventPublisher;
@Mock
private PlatformTransactionManager transactionManager;
@InjectMocks @InjectMocks
private BookDropService bookDropService; private BookDropService bookDropService;
@@ -127,9 +123,6 @@ class BookDropServiceTest {
bookdropFile.setFileName("test-book.pdf"); bookdropFile.setFileName("test-book.pdf");
Files.createFile(tempDir.resolve("test-book.pdf")); Files.createFile(tempDir.resolve("test-book.pdf"));
TransactionStatus txStatus = mock(TransactionStatus.class);
lenient().when(transactionManager.getTransaction(any())).thenReturn(txStatus);
} }
@AfterEach @AfterEach
@@ -249,7 +242,7 @@ class BookDropServiceTest {
when(bookdropFileRepository.findAllExcludingIdsFlat(any())).thenReturn(List.of(1L)); when(bookdropFileRepository.findAllExcludingIdsFlat(any())).thenReturn(List.of(1L));
when(bookdropFileRepository.findAllById(any())).thenReturn(List.of(bookdropFileEntity)); when(bookdropFileRepository.findAllById(any())).thenReturn(List.of(bookdropFileEntity));
when(libraryRepository.findById(1L)).thenReturn(Optional.of(libraryEntity)); when(libraryRepository.findByIdWithPaths(1L)).thenReturn(Optional.of(libraryEntity));
when(objectMapper.readValue(anyString(), eq(BookMetadata.class))).thenReturn(metadata); when(objectMapper.readValue(anyString(), eq(BookMetadata.class))).thenReturn(metadata);
when(fileMovingHelper.getFileNamingPattern(libraryEntity)).thenReturn("{title}"); when(fileMovingHelper.getFileNamingPattern(libraryEntity)).thenReturn("{title}");
when(fileMovingHelper.generateNewFilePath(anyString(), any(), anyString(), anyString())) when(fileMovingHelper.generateNewFilePath(anyString(), any(), anyString(), anyString()))
@@ -298,7 +291,7 @@ class BookDropServiceTest {
when(bookdropFileRepository.findAllIds()).thenReturn(List.of(1L)); when(bookdropFileRepository.findAllIds()).thenReturn(List.of(1L));
when(bookdropFileRepository.findAllById(any())).thenReturn(List.of(bookdropFileEntity)); when(bookdropFileRepository.findAllById(any())).thenReturn(List.of(bookdropFileEntity));
when(libraryRepository.findById(999L)).thenReturn(Optional.empty()); when(libraryRepository.findByIdWithPaths(999L)).thenReturn(Optional.empty());
BookMetadata metadata = new BookMetadata(); BookMetadata metadata = new BookMetadata();
when(objectMapper.readValue(anyString(), eq(BookMetadata.class))).thenReturn(metadata); when(objectMapper.readValue(anyString(), eq(BookMetadata.class))).thenReturn(metadata);
@@ -399,7 +392,7 @@ class BookDropServiceTest {
when(bookdropFileRepository.findAllIds()).thenReturn(List.of(2L)); when(bookdropFileRepository.findAllIds()).thenReturn(List.of(2L));
when(bookdropFileRepository.findAllById(any())).thenReturn(List.of(missingFileEntity)); when(bookdropFileRepository.findAllById(any())).thenReturn(List.of(missingFileEntity));
when(libraryRepository.findById(1L)).thenReturn(Optional.of(libraryEntity)); when(libraryRepository.findByIdWithPaths(1L)).thenReturn(Optional.of(libraryEntity));
BookMetadata metadata = new BookMetadata(); BookMetadata metadata = new BookMetadata();
metadata.setTitle("Missing Book"); metadata.setTitle("Missing Book");
@@ -431,7 +424,7 @@ class BookDropServiceTest {
when(bookdropFileRepository.findAllIds()).thenReturn(List.of(1L)); when(bookdropFileRepository.findAllIds()).thenReturn(List.of(1L));
when(bookdropFileRepository.findAllById(any())).thenReturn(List.of(bookdropFileEntity)); when(bookdropFileRepository.findAllById(any())).thenReturn(List.of(bookdropFileEntity));
when(libraryRepository.findById(1L)).thenReturn(Optional.of(libraryEntity)); when(libraryRepository.findByIdWithPaths(1L)).thenReturn(Optional.of(libraryEntity));
BookMetadata metadata = new BookMetadata(); BookMetadata metadata = new BookMetadata();
when(objectMapper.readValue(anyString(), eq(BookMetadata.class))).thenReturn(metadata); when(objectMapper.readValue(anyString(), eq(BookMetadata.class))).thenReturn(metadata);
@@ -463,7 +456,7 @@ class BookDropServiceTest {
when(bookdropFileRepository.findAllIds()).thenReturn(List.of(1L)); when(bookdropFileRepository.findAllIds()).thenReturn(List.of(1L));
when(bookdropFileRepository.findAllById(any())).thenReturn(List.of(bookdropFileEntity)); when(bookdropFileRepository.findAllById(any())).thenReturn(List.of(bookdropFileEntity));
when(libraryRepository.findById(1L)).thenReturn(Optional.of(libraryEntity)); when(libraryRepository.findByIdWithPaths(1L)).thenReturn(Optional.of(libraryEntity));
LibraryPathEntity pathEntity = new LibraryPathEntity(); LibraryPathEntity pathEntity = new LibraryPathEntity();
pathEntity.setId(1L); pathEntity.setId(1L);
@@ -530,7 +523,7 @@ class BookDropServiceTest {
request.setFiles(List.of(finalizeFile)); request.setFiles(List.of(finalizeFile));
when(bookdropFileRepository.findAllById(any())).thenReturn(List.of(bookdropFileEntity)); when(bookdropFileRepository.findAllById(any())).thenReturn(List.of(bookdropFileEntity));
when(libraryRepository.findById(1L)).thenReturn(Optional.of(libraryEntity)); when(libraryRepository.findByIdWithPaths(1L)).thenReturn(Optional.of(libraryEntity));
when(objectMapper.readValue(anyString(), eq(BookMetadata.class))).thenReturn(new BookMetadata()); when(objectMapper.readValue(anyString(), eq(BookMetadata.class))).thenReturn(new BookMetadata());
when(fileMovingHelper.getFileNamingPattern(libraryEntity)).thenReturn("{title}"); when(fileMovingHelper.getFileNamingPattern(libraryEntity)).thenReturn("{title}");
when(fileMovingHelper.generateNewFilePath(anyString(), any(), anyString(), anyString())) when(fileMovingHelper.generateNewFilePath(anyString(), any(), anyString(), anyString()))
@@ -587,7 +580,7 @@ class BookDropServiceTest {
request.setFiles(List.of(finalizeFile)); request.setFiles(List.of(finalizeFile));
when(bookdropFileRepository.findAllById(any())).thenReturn(List.of(bookdropFileEntity)); when(bookdropFileRepository.findAllById(any())).thenReturn(List.of(bookdropFileEntity));
when(libraryRepository.findById(1L)).thenReturn(Optional.of(libraryEntity)); when(libraryRepository.findByIdWithPaths(1L)).thenReturn(Optional.of(libraryEntity));
when(objectMapper.readValue(anyString(), eq(BookMetadata.class))).thenReturn(new BookMetadata()); when(objectMapper.readValue(anyString(), eq(BookMetadata.class))).thenReturn(new BookMetadata());
when(fileMovingHelper.getFileNamingPattern(libraryEntity)).thenReturn("{title}"); when(fileMovingHelper.getFileNamingPattern(libraryEntity)).thenReturn("{title}");
when(fileMovingHelper.generateNewFilePath(anyString(), any(), anyString(), anyString())) when(fileMovingHelper.generateNewFilePath(anyString(), any(), anyString(), anyString()))
@@ -622,4 +615,58 @@ class BookDropServiceTest {
assertTrue(Files.exists(sourceFile), "Source file should be preserved on failure"); assertTrue(Files.exists(sourceFile), "Source file should be preserved on failure");
assertFalse(Files.exists(targetDir.resolve("moved-book.pdf")), "Target file should be cleaned up on failure"); assertFalse(Files.exists(targetDir.resolve("moved-book.pdf")), "Target file should be cleaned up on failure");
} }
@Test
void finalizeImport_usesEagerPathsQueryForMoveFile() throws Exception {
BookdropFinalizeRequest request = new BookdropFinalizeRequest();
request.setSelectAll(true);
request.setDefaultLibraryId(1L);
request.setDefaultPathId(1L);
when(bookdropFileRepository.findAllIds()).thenReturn(List.of(1L));
when(bookdropFileRepository.findAllById(any())).thenReturn(List.of(bookdropFileEntity));
// Only findByIdWithPaths is stubbed findById would return empty/null, causing test failure
when(libraryRepository.findByIdWithPaths(1L)).thenReturn(Optional.of(libraryEntity));
BookMetadata metadata = new BookMetadata();
when(objectMapper.readValue(anyString(), eq(BookMetadata.class))).thenReturn(metadata);
when(fileMovingHelper.getFileNamingPattern(libraryEntity)).thenReturn("{title}");
when(fileMovingHelper.generateNewFilePath(anyString(), any(), anyString(), anyString()))
.thenReturn(tempDir.resolve("target-file.pdf"));
try (MockedStatic<Files> filesMock = mockStatic(Files.class, withSettings().lenient())) {
filesMock.when(() -> Files.exists(any(Path.class))).thenReturn(false);
bookDropService.finalizeImport(request);
verify(libraryRepository, atLeastOnce()).findByIdWithPaths(1L);
verify(libraryRepository, never()).findById(1L);
}
}
@Test
void finalizeImport_usesEagerPathsQueryForReregistration() throws Exception {
BookdropFinalizeRequest request = new BookdropFinalizeRequest();
request.setSelectAll(true);
request.setDefaultLibraryId(1L);
request.setDefaultPathId(1L);
when(bookdropFileRepository.findAllIds()).thenReturn(List.of(1L));
when(bookdropFileRepository.findAllById(any())).thenReturn(List.of(bookdropFileEntity));
when(libraryRepository.findByIdWithPaths(1L)).thenReturn(Optional.of(libraryEntity));
BookMetadata metadata = new BookMetadata();
when(objectMapper.readValue(anyString(), eq(BookMetadata.class))).thenReturn(metadata);
when(fileMovingHelper.getFileNamingPattern(libraryEntity)).thenReturn("{title}");
when(fileMovingHelper.generateNewFilePath(anyString(), any(), anyString(), anyString()))
.thenReturn(tempDir.resolve("target-file.pdf"));
try (MockedStatic<Files> filesMock = mockStatic(Files.class, withSettings().lenient())) {
filesMock.when(() -> Files.exists(any(Path.class))).thenReturn(false);
bookDropService.finalizeImport(request);
// findByIdWithPaths is called for both moveFile and reregisterAffectedLibraries
verify(libraryRepository, atLeast(2)).findByIdWithPaths(1L);
}
}
} }
@@ -35,6 +35,7 @@ import java.nio.file.Paths;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.Optional;
import java.util.Set; import java.util.Set;
import java.util.function.Consumer; import java.util.function.Consumer;
@@ -179,6 +180,7 @@ class FileMoveServiceOrderingTest {
mockStandardBehavior(book, target); mockStandardBehavior(book, target);
when(monitoringRegistrationService.isLibraryMonitored(1L)).thenReturn(true); when(monitoringRegistrationService.isLibraryMonitored(1L)).thenReturn(true);
when(monitoringRegistrationService.getPathsForLibraries(Set.of(1L))).thenReturn(Set.of(Paths.get("/library"))); when(monitoringRegistrationService.getPathsForLibraries(Set.of(1L))).thenReturn(Set.of(Paths.get("/library")));
when(libraryRepository.findByIdWithPaths(1L)).thenReturn(Optional.of(library));
Library dto = Library.builder().build(); Library dto = Library.builder().build();
when(libraryMapper.toLibrary(any(LibraryEntity.class))).thenReturn(dto); when(libraryMapper.toLibrary(any(LibraryEntity.class))).thenReturn(dto);
@@ -315,6 +317,7 @@ class FileMoveServiceOrderingTest {
doThrow(new IOException("fail")).when(fileMoveHelper).commitMove(any(), any()); doThrow(new IOException("fail")).when(fileMoveHelper).commitMove(any(), any());
when(monitoringRegistrationService.isLibraryMonitored(1L)).thenReturn(true); when(monitoringRegistrationService.isLibraryMonitored(1L)).thenReturn(true);
when(monitoringRegistrationService.getPathsForLibraries(Set.of(1L))).thenReturn(Set.of(Paths.get("/library"))); when(monitoringRegistrationService.getPathsForLibraries(Set.of(1L))).thenReturn(Set.of(Paths.get("/library")));
when(libraryRepository.findByIdWithPaths(1L)).thenReturn(Optional.of(library));
Library dto = Library.builder().build(); Library dto = Library.builder().build();
when(libraryMapper.toLibrary(any(LibraryEntity.class))).thenReturn(dto); when(libraryMapper.toLibrary(any(LibraryEntity.class))).thenReturn(dto);
@@ -147,6 +147,7 @@ class FileMoveServiceTest {
private void mockMonitoredLibrary() { private void mockMonitoredLibrary() {
when(monitoringRegistrationService.isLibraryMonitored(1L)).thenReturn(true); when(monitoringRegistrationService.isLibraryMonitored(1L)).thenReturn(true);
when(monitoringRegistrationService.getPathsForLibraries(Set.of(1L))).thenReturn(Set.of(Paths.get("/library"))); when(monitoringRegistrationService.getPathsForLibraries(Set.of(1L))).thenReturn(Set.of(Paths.get("/library")));
when(libraryRepository.findByIdWithPaths(1L)).thenReturn(Optional.of(library));
when(libraryMapper.toLibrary(any(LibraryEntity.class))).thenReturn(Library.builder().build()); when(libraryMapper.toLibrary(any(LibraryEntity.class))).thenReturn(Library.builder().build());
} }
@@ -633,6 +634,7 @@ class FileMoveServiceTest {
mockStandardBehavior(book, target); mockStandardBehavior(book, target);
when(monitoringRegistrationService.isLibraryMonitored(1L)).thenReturn(true); when(monitoringRegistrationService.isLibraryMonitored(1L)).thenReturn(true);
when(monitoringRegistrationService.getPathsForLibraries(Set.of(1L))).thenReturn(Set.of(Paths.get("/library"))); when(monitoringRegistrationService.getPathsForLibraries(Set.of(1L))).thenReturn(Set.of(Paths.get("/library")));
when(libraryRepository.findByIdWithPaths(1L)).thenReturn(Optional.of(library));
Library dto = Library.builder().watch(false).build(); Library dto = Library.builder().watch(false).build();
when(libraryMapper.toLibrary(any(LibraryEntity.class))).thenReturn(dto); when(libraryMapper.toLibrary(any(LibraryEntity.class))).thenReturn(dto);
@@ -669,6 +671,7 @@ class FileMoveServiceTest {
mockStandardBehavior(book, target); mockStandardBehavior(book, target);
when(monitoringRegistrationService.isLibraryMonitored(1L)).thenReturn(false); when(monitoringRegistrationService.isLibraryMonitored(1L)).thenReturn(false);
when(monitoringRegistrationService.getPathsForLibraries(Set.of(1L))).thenReturn(Set.of(Paths.get("/library"))); when(monitoringRegistrationService.getPathsForLibraries(Set.of(1L))).thenReturn(Set.of(Paths.get("/library")));
when(libraryRepository.findByIdWithPaths(1L)).thenReturn(Optional.of(library));
when(libraryMapper.toLibrary(any(LibraryEntity.class))).thenReturn(Library.builder().build()); when(libraryMapper.toLibrary(any(LibraryEntity.class))).thenReturn(Library.builder().build());
service.moveSingleFile(book); service.moveSingleFile(book);
@@ -781,7 +784,7 @@ class FileMoveServiceTest {
private void mockBulkMoveSetup(BookEntity book, Path targetPath) throws IOException { private void mockBulkMoveSetup(BookEntity book, Path targetPath) throws IOException {
when(bookRepository.findById(100L)).thenReturn(Optional.of(book)); when(bookRepository.findById(100L)).thenReturn(Optional.of(book));
when(bookRepository.findByIdWithBookFiles(100L)).thenReturn(Optional.of(book)); when(bookRepository.findByIdWithBookFiles(100L)).thenReturn(Optional.of(book));
when(libraryRepository.findById(2L)).thenReturn(Optional.of(targetLibrary)); when(libraryRepository.findByIdWithPaths(2L)).thenReturn(Optional.of(targetLibrary));
when(fileMoveHelper.getFileNamingPattern(targetLibrary)).thenReturn("{title}"); when(fileMoveHelper.getFileNamingPattern(targetLibrary)).thenReturn("{title}");
when(fileMoveHelper.generateNewFilePath(eq(book), eq(targetLibraryPath), anyString())).thenReturn(targetPath); when(fileMoveHelper.generateNewFilePath(eq(book), eq(targetLibraryPath), anyString())).thenReturn(targetPath);
@@ -947,7 +950,7 @@ class FileMoveServiceTest {
when(bookRepository.findById(100L)).thenReturn(Optional.of(book)); when(bookRepository.findById(100L)).thenReturn(Optional.of(book));
when(bookRepository.findByIdWithBookFiles(100L)).thenReturn(Optional.of(book)); when(bookRepository.findByIdWithBookFiles(100L)).thenReturn(Optional.of(book));
when(libraryRepository.findById(2L)).thenReturn(Optional.empty()); when(libraryRepository.findByIdWithPaths(2L)).thenReturn(Optional.empty());
when(monitoringRegistrationService.getPathsForLibraries(anySet())).thenReturn(Set.of(Paths.get("/library"))); when(monitoringRegistrationService.getPathsForLibraries(anySet())).thenReturn(Set.of(Paths.get("/library")));
FileMoveRequest request = new FileMoveRequest(); FileMoveRequest request = new FileMoveRequest();
@@ -978,7 +981,7 @@ class FileMoveServiceTest {
when(bookRepository.findById(100L)).thenReturn(Optional.of(book)); when(bookRepository.findById(100L)).thenReturn(Optional.of(book));
when(bookRepository.findByIdWithBookFiles(100L)).thenReturn(Optional.of(book)); when(bookRepository.findByIdWithBookFiles(100L)).thenReturn(Optional.of(book));
when(libraryRepository.findById(2L)).thenReturn(Optional.of(targetLibrary)); when(libraryRepository.findByIdWithPaths(2L)).thenReturn(Optional.of(targetLibrary));
when(monitoringRegistrationService.getPathsForLibraries(anySet())).thenReturn(Set.of(Paths.get("/library"))); when(monitoringRegistrationService.getPathsForLibraries(anySet())).thenReturn(Set.of(Paths.get("/library")));
FileMoveRequest request = new FileMoveRequest(); FileMoveRequest request = new FileMoveRequest();
@@ -1008,7 +1011,7 @@ class FileMoveServiceTest {
when(bookRepository.findById(100L)).thenReturn(Optional.of(book)); when(bookRepository.findById(100L)).thenReturn(Optional.of(book));
when(bookRepository.findByIdWithBookFiles(100L)).thenReturn(Optional.of(book)); when(bookRepository.findByIdWithBookFiles(100L)).thenReturn(Optional.of(book));
when(libraryRepository.findById(2L)).thenReturn(Optional.of(targetLibrary)); when(libraryRepository.findByIdWithPaths(2L)).thenReturn(Optional.of(targetLibrary));
when(monitoringRegistrationService.getPathsForLibraries(anySet())).thenReturn(Set.of(Paths.get("/library"))); when(monitoringRegistrationService.getPathsForLibraries(anySet())).thenReturn(Set.of(Paths.get("/library")));
FileMoveRequest request = new FileMoveRequest(); FileMoveRequest request = new FileMoveRequest();
@@ -1044,8 +1047,8 @@ class FileMoveServiceTest {
when(bookRepository.findById(100L)).thenReturn(Optional.of(book)); when(bookRepository.findById(100L)).thenReturn(Optional.of(book));
when(bookRepository.findByIdWithBookFiles(100L)).thenReturn(Optional.of(book)); when(bookRepository.findByIdWithBookFiles(100L)).thenReturn(Optional.of(book));
when(libraryRepository.findById(1L)).thenReturn(Optional.of(library)); when(libraryRepository.findByIdWithPaths(1L)).thenReturn(Optional.of(library));
when(libraryRepository.findById(2L)).thenReturn(Optional.of(targetLibrary)); when(libraryRepository.findByIdWithPaths(2L)).thenReturn(Optional.of(targetLibrary));
when(monitoringRegistrationService.getPathsForLibraries(anySet())).thenReturn(Set.of(Paths.get("/library"), Paths.get("/target"))); when(monitoringRegistrationService.getPathsForLibraries(anySet())).thenReturn(Set.of(Paths.get("/library"), Paths.get("/target")));
when(libraryMapper.toLibrary(any(LibraryEntity.class))).thenReturn(Library.builder().build()); when(libraryMapper.toLibrary(any(LibraryEntity.class))).thenReturn(Library.builder().build());
@@ -1085,8 +1088,8 @@ class FileMoveServiceTest {
when(bookRepository.findById(100L)).thenReturn(Optional.of(book)); when(bookRepository.findById(100L)).thenReturn(Optional.of(book));
when(bookRepository.findByIdWithBookFiles(100L)).thenReturn(Optional.of(book)); when(bookRepository.findByIdWithBookFiles(100L)).thenReturn(Optional.of(book));
when(libraryRepository.findById(1L)).thenReturn(Optional.of(library)); when(libraryRepository.findByIdWithPaths(1L)).thenReturn(Optional.of(library));
when(libraryRepository.findById(2L)).thenReturn(Optional.of(targetLibrary)); when(libraryRepository.findByIdWithPaths(2L)).thenReturn(Optional.of(targetLibrary));
when(monitoringRegistrationService.getPathsForLibraries(anySet())).thenReturn(Set.of(Paths.get("/library"), Paths.get("/target"))); when(monitoringRegistrationService.getPathsForLibraries(anySet())).thenReturn(Set.of(Paths.get("/library"), Paths.get("/target")));
when(libraryMapper.toLibrary(any(LibraryEntity.class))).thenReturn(Library.builder().build()); when(libraryMapper.toLibrary(any(LibraryEntity.class))).thenReturn(Library.builder().build());
@@ -1112,6 +1115,47 @@ class FileMoveServiceTest {
} }
} }
@Nested
@DisplayName("moveSingleFile - L1 Cache Eviction")
class MoveSingleFileL1CacheEviction {
@Test
@DisplayName("evicts L1-cached LibraryEntity before file move to avoid LazyInitializationException")
void evictsCachedLibraryWhenPresentInPersistenceContext() throws IOException {
BookFileEntity epub = createBookFile(1L, "Book.epub", "path", true, false);
BookEntity book = createBook(List.of(epub));
Path target = Paths.get("/library/new/path/NewName.epub");
when(entityManager.contains(library)).thenReturn(true);
mockStandardBehavior(book, target);
mockUnmonitoredLibrary();
service.moveSingleFile(book);
verify(entityManager).contains(library);
verify(entityManager).detach(library);
}
@Test
@DisplayName("skips eviction when LibraryEntity is not in persistence context")
void skipsEvictionWhenNotInPersistenceContext() throws IOException {
BookFileEntity epub = createBookFile(1L, "Book.epub", "path", true, false);
BookEntity book = createBook(List.of(epub));
Path target = Paths.get("/library/new/path/NewName.epub");
when(entityManager.contains(library)).thenReturn(false);
mockStandardBehavior(book, target);
mockUnmonitoredLibrary();
service.moveSingleFile(book);
verify(entityManager).contains(library);
verify(entityManager, never()).detach(any());
}
}
@Nested @Nested
@DisplayName("NetworkStorageGating") @DisplayName("NetworkStorageGating")
class NetworkStorageGating { class NetworkStorageGating {
@@ -95,7 +95,7 @@ class LibraryProcessingServiceTest {
existingBook.getPrimaryBookFile().setFileName("book1.epub"); existingBook.getPrimaryBookFile().setFileName("book1.epub");
libraryEntity.setBookEntities(List.of(existingBook)); libraryEntity.setBookEntities(List.of(existingBook));
when(libraryRepository.findById(libraryId)).thenReturn(Optional.of(libraryEntity)); when(libraryRepository.findByIdWithPaths(libraryId)).thenReturn(Optional.of(libraryEntity));
when(bookRepository.findAllByLibraryIdForRescan(libraryId)).thenReturn(List.of(existingBook)); when(bookRepository.findAllByLibraryIdForRescan(libraryId)).thenReturn(List.of(existingBook));
LibraryFile existingFile = LibraryFile.builder() LibraryFile existingFile = LibraryFile.builder()
@@ -157,7 +157,7 @@ class LibraryProcessingServiceTest {
existingBook.getPrimaryBookFile().setFileName("book1.epub"); existingBook.getPrimaryBookFile().setFileName("book1.epub");
libraryEntity.setBookEntities(List.of(existingBook)); libraryEntity.setBookEntities(List.of(existingBook));
when(libraryRepository.findById(libraryId)).thenReturn(Optional.of(libraryEntity)); when(libraryRepository.findByIdWithPaths(libraryId)).thenReturn(Optional.of(libraryEntity));
when(bookRepository.findAllByLibraryIdForRescan(libraryId)).thenReturn(List.of(existingBook)); when(bookRepository.findAllByLibraryIdForRescan(libraryId)).thenReturn(List.of(existingBook));
LibraryFile existingFile = LibraryFile.builder() LibraryFile existingFile = LibraryFile.builder()
@@ -191,7 +191,7 @@ class LibraryProcessingServiceTest {
pathEntity.setId(10L); pathEntity.setId(10L);
pathEntity.setPath("/library"); pathEntity.setPath("/library");
when(libraryRepository.findById(libraryId)).thenReturn(Optional.of(libraryEntity)); when(libraryRepository.findByIdWithPaths(libraryId)).thenReturn(Optional.of(libraryEntity));
when(bookRepository.findAllByLibraryIdForRescan(libraryId)).thenReturn(Collections.emptyList()); when(bookRepository.findAllByLibraryIdForRescan(libraryId)).thenReturn(Collections.emptyList());
LibraryFile newFile1 = LibraryFile.builder() LibraryFile newFile1 = LibraryFile.builder()
@@ -239,7 +239,7 @@ class LibraryProcessingServiceTest {
pathEntity.setId(10L); pathEntity.setId(10L);
pathEntity.setPath("/library"); pathEntity.setPath("/library");
when(libraryRepository.findById(libraryId)).thenReturn(Optional.of(libraryEntity)); when(libraryRepository.findByIdWithPaths(libraryId)).thenReturn(Optional.of(libraryEntity));
when(bookRepository.findAllByLibraryIdForRescan(libraryId)).thenReturn(Collections.emptyList()); when(bookRepository.findAllByLibraryIdForRescan(libraryId)).thenReturn(Collections.emptyList());
LibraryFile newFileInSub = LibraryFile.builder() LibraryFile newFileInSub = LibraryFile.builder()
@@ -284,7 +284,7 @@ class LibraryProcessingServiceTest {
pathEntity.setId(10L); pathEntity.setId(10L);
pathEntity.setPath("/library"); pathEntity.setPath("/library");
when(libraryRepository.findById(libraryId)).thenReturn(Optional.of(libraryEntity)); when(libraryRepository.findByIdWithPaths(libraryId)).thenReturn(Optional.of(libraryEntity));
when(bookRepository.findAllByLibraryIdForRescan(libraryId)).thenReturn(Collections.emptyList()); when(bookRepository.findAllByLibraryIdForRescan(libraryId)).thenReturn(Collections.emptyList());
LibraryFile additionalFileAsLibraryFile = LibraryFile.builder() LibraryFile additionalFileAsLibraryFile = LibraryFile.builder()