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:
@@ -6,21 +6,13 @@ import io.swagger.v3.oas.annotations.responses.ApiResponse;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import lombok.AllArgsConstructor;
|
||||
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.dto.BookMetadata;
|
||||
import org.booklore.exception.ApiError;
|
||||
import org.booklore.model.dto.request.IsbnLookupRequest;
|
||||
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.MetadataReplaceMode;
|
||||
import org.booklore.repository.BookRepository;
|
||||
import org.booklore.service.audit.AuditService;
|
||||
import org.booklore.service.metadata.BookMetadataService;
|
||||
import org.booklore.service.metadata.BookMetadataUpdater;
|
||||
import org.booklore.service.metadata.MetadataManagementService;
|
||||
import org.booklore.service.metadata.MetadataMatchService;
|
||||
import org.springframework.http.MediaType;
|
||||
@@ -39,12 +31,8 @@ import java.util.List;
|
||||
public class MetadataController {
|
||||
|
||||
private final BookMetadataService bookMetadataService;
|
||||
private final BookMetadataUpdater bookMetadataUpdater;
|
||||
private final BookMetadataMapper bookMetadataMapper;
|
||||
private final MetadataMatchService metadataMatchService;
|
||||
private final BookRepository bookRepository;
|
||||
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.")
|
||||
@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 = "Merge categories") @RequestParam(defaultValue = "false") boolean mergeCategories,
|
||||
@Parameter(description = "Replace mode") @RequestParam(defaultValue = "REPLACE_ALL") MetadataReplaceMode replaceMode) {
|
||||
BookEntity bookEntity = bookRepository.findAllWithMetadataByIds(java.util.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());
|
||||
BookMetadata bookMetadata = bookMetadataMapper.toBookMetadata(bookEntity.getMetadata(), true);
|
||||
BookMetadata bookMetadata = bookMetadataService.updateBookMetadata(bookId, metadataUpdateWrapper, mergeCategories, replaceMode);
|
||||
return ResponseEntity.ok(bookMetadata);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
package org.booklore.model.dto;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.Instant;
|
||||
|
||||
public interface BookTimelineDto {
|
||||
Long getBookId();
|
||||
String getTitle();
|
||||
Integer getPageCount();
|
||||
LocalDateTime getFirstSessionDate();
|
||||
LocalDateTime getLastSessionDate();
|
||||
Instant getFirstSessionStart();
|
||||
Instant getLastSessionEnd();
|
||||
Integer getTotalSessions();
|
||||
Long getTotalDurationSeconds();
|
||||
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();
|
||||
}
|
||||
+1
-1
@@ -10,7 +10,7 @@ import lombok.NoArgsConstructor;
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class FavoriteReadingDaysResponse {
|
||||
private Integer dayOfWeek; // 1=Monday, 7=Sunday
|
||||
private Integer dayOfWeek; // 1=Sunday, 7=Saturday
|
||||
private String dayName;
|
||||
private Long sessionCount;
|
||||
private Long totalDurationSeconds;
|
||||
|
||||
@@ -36,6 +36,7 @@ public class LibraryEntity {
|
||||
private List<BookEntity> bookEntities = new ArrayList<>();
|
||||
|
||||
@OneToMany(mappedBy = "library", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY)
|
||||
@BatchSize(size = 20)
|
||||
@Builder.Default
|
||||
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
|
||||
// ============================================
|
||||
|
||||
@Query(value = "SELECT b.id FROM BookEntity b WHERE (b.deleted IS NULL OR b.deleted = false) ORDER BY function('RAND')", nativeQuery = false)
|
||||
List<Long> findRandomBookIds();
|
||||
@Query("SELECT b.id FROM BookEntity b WHERE (b.deleted IS NULL OR b.deleted = false) ORDER BY function('RAND')")
|
||||
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)
|
||||
List<Long> findRandomBookIdsByLibraryIds(@Param("libraryIds") Collection<Long> libraryIds);
|
||||
@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, Pageable pageable);
|
||||
|
||||
// ============================================
|
||||
// AUTHORS - Distinct Authors List
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package org.booklore.repository;
|
||||
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.PageRequest;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.booklore.model.entity.BookEntity;
|
||||
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)")
|
||||
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"})
|
||||
@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)")
|
||||
List<BookEntity> findAllFullBooks();
|
||||
|
||||
@Query(value = """
|
||||
SELECT DISTINCT b.* FROM book b
|
||||
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("SELECT b FROM BookEntity b WHERE (b.deleted IS NULL OR b.deleted = false) AND b.id > :afterId ORDER BY b.id")
|
||||
List<BookEntity> findBooksForMigrationBatch(@Param("afterId") long afterId, Pageable pageable);
|
||||
|
||||
@Query("""
|
||||
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,
|
||||
@Param("folderPath") String folderPath);
|
||||
|
||||
@Query(value = """
|
||||
SELECT b.*
|
||||
FROM book b
|
||||
JOIN book_file bf ON bf.book_id = b.id
|
||||
WHERE b.library_id = :libraryId
|
||||
AND b.library_path_id = :libraryPathId
|
||||
AND bf.file_sub_path = :fileSubPath
|
||||
AND bf.file_name = :fileName
|
||||
AND bf.is_book = true
|
||||
LIMIT 1
|
||||
""", nativeQuery = true)
|
||||
Optional<BookEntity> findByLibraryIdAndLibraryPathIdAndFileSubPathAndFileName(
|
||||
@Query("""
|
||||
SELECT b FROM BookEntity b
|
||||
JOIN b.bookFiles bf
|
||||
WHERE b.library.id = :libraryId
|
||||
AND b.libraryPath.id = :libraryPathId
|
||||
AND bf.fileSubPath = :fileSubPath
|
||||
AND bf.fileName = :fileName
|
||||
AND bf.isBookFormat = true
|
||||
ORDER BY b.id ASC
|
||||
""")
|
||||
List<BookEntity> findByLibraryIdAndLibraryPathIdAndFileSubPathAndFileName(
|
||||
@Param("libraryId") Long libraryId,
|
||||
@Param("libraryPathId") Long libraryPathId,
|
||||
@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)")
|
||||
long countByIdIn(@Param("bookIds") List<Long> bookIds);
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
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.Pageable;
|
||||
import org.springframework.data.jpa.repository.Query;
|
||||
@@ -12,29 +12,7 @@ import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
public interface NotebookEntryRepository extends Repository<AnnotationEntity, 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 '\\\\')";
|
||||
public interface NotebookEntryRepository extends Repository<NotebookEntryView, Long> {
|
||||
|
||||
interface EntryProjection {
|
||||
Long getId();
|
||||
@@ -63,64 +41,75 @@ public interface NotebookEntryRepository extends Repository<AnnotationEntity, Lo
|
||||
Instant getCoverUpdatedOn();
|
||||
}
|
||||
|
||||
@Query(value = "SELECT t.id, t.type, t.book_id AS bookId, t.book_title AS bookTitle, " +
|
||||
"t.text, t.note, t.color, t.style, t.chapter_title AS chapterTitle, " +
|
||||
"(SELECT bf.book_type FROM book_file bf WHERE bf.book_id = t.book_id ORDER BY bf.id LIMIT 1) AS primaryBookType, " +
|
||||
"t.created_at AS createdAt, t.updated_at AS updatedAt " +
|
||||
"FROM (" + ENTRIES_UNION + ") t" + ENTRIES_FILTER,
|
||||
countQuery = "SELECT COUNT(*) FROM (" + ENTRIES_UNION + ") t" + ENTRIES_FILTER,
|
||||
nativeQuery = true)
|
||||
@Query(value = """
|
||||
SELECT ne.originalId as id,
|
||||
ne.entryType as type,
|
||||
ne.bookId as bookId,
|
||||
ne.bookTitle as bookTitle,
|
||||
ne.textContent as text,
|
||||
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,
|
||||
@Param("types") Set<String> types,
|
||||
@Param("bookId") Long bookId,
|
||||
@Param("search") String search,
|
||||
Pageable pageable);
|
||||
|
||||
@Query(value = "SELECT DISTINCT t.book_id AS bookId, t.book_title AS bookTitle FROM (" +
|
||||
"SELECT a.book_id, bm.title AS book_title FROM annotations a " +
|
||||
"JOIN book_metadata bm ON bm.book_id = a.book_id WHERE a.user_id = :userId " +
|
||||
"UNION " +
|
||||
"SELECT n.book_id, bm.title AS book_title FROM book_notes_v2 n " +
|
||||
"JOIN book_metadata bm ON bm.book_id = n.book_id WHERE n.user_id = :userId " +
|
||||
"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)
|
||||
@Query("""
|
||||
SELECT DISTINCT ne.bookId as bookId, ne.bookTitle as bookTitle
|
||||
FROM NotebookEntryView ne
|
||||
WHERE ne.userId = :userId
|
||||
AND (:search IS NULL OR ne.bookTitle LIKE :search ESCAPE '\\')
|
||||
ORDER BY ne.bookTitle
|
||||
""")
|
||||
List<BookProjection> findBooksWithAnnotations(@Param("userId") Long userId,
|
||||
@Param("search") String search,
|
||||
Pageable pageable);
|
||||
|
||||
@Query(value = "SELECT t.book_id AS bookId, t.book_title AS bookTitle, " +
|
||||
"COUNT(*) AS noteCount, t.cover_updated_on AS coverUpdatedOn " +
|
||||
"FROM (" +
|
||||
"SELECT a.book_id, a.user_id, bm.title AS book_title, bm.cover_updated_on " +
|
||||
"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, bm.cover_updated_on " +
|
||||
"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, bm.cover_updated_on " +
|
||||
"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 '\\\\')" +
|
||||
" GROUP BY t.book_id, t.book_title, t.cover_updated_on" +
|
||||
" ORDER BY t.book_title",
|
||||
countQuery = "SELECT COUNT(*) FROM (" +
|
||||
"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)
|
||||
@Query(value = """
|
||||
SELECT ne.bookId as bookId,
|
||||
ne.bookTitle as bookTitle,
|
||||
count(ne) as noteCount,
|
||||
ne.coverUpdatedOn as coverUpdatedOn
|
||||
FROM NotebookEntryView ne
|
||||
WHERE ne.userId = :userId
|
||||
AND (:search IS NULL OR ne.bookTitle LIKE :search ESCAPE '\\')
|
||||
GROUP BY ne.bookId, ne.bookTitle, ne.coverUpdatedOn
|
||||
ORDER BY ne.bookTitle
|
||||
""",
|
||||
countQuery = """
|
||||
SELECT count(DISTINCT ne.bookId)
|
||||
FROM NotebookEntryView ne
|
||||
WHERE ne.userId = :userId
|
||||
AND (:search IS NULL OR ne.bookTitle LIKE :search ESCAPE '\\')
|
||||
""")
|
||||
Page<BookWithCountProjection> findBooksWithAnnotationsPaginated(@Param("userId") Long userId,
|
||||
@Param("search") String search,
|
||||
Pageable pageable);
|
||||
|
||||
+164
-263
@@ -16,53 +16,35 @@ import java.util.List;
|
||||
@Repository
|
||||
public interface ReadingSessionRepository extends JpaRepository<ReadingSessionEntity, Long> {
|
||||
|
||||
@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
|
||||
GROUP BY DATE(CONVERT_TZ(start_time, '+00:00', :tzOffset))
|
||||
ORDER BY date
|
||||
""", nativeQuery = true)
|
||||
List<ReadingSessionCountDto> findSessionCountsByUserAndYear(
|
||||
@Query("""
|
||||
SELECT rs.startTime
|
||||
FROM ReadingSessionEntity rs
|
||||
WHERE rs.user.id = :userId
|
||||
AND rs.startTime >= :periodStart AND rs.startTime < :periodEnd
|
||||
ORDER BY rs.startTime
|
||||
""")
|
||||
List<Instant> findSessionStartTimesByUserAndPeriod(
|
||||
@Param("userId") Long userId,
|
||||
@Param("year") int year,
|
||||
@Param("tzOffset") String tzOffset);
|
||||
@Param("periodStart") Instant periodStart,
|
||||
@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("""
|
||||
SELECT
|
||||
b.id as bookId,
|
||||
COALESCE(b.metadata.title,
|
||||
(SELECT bf.fileName FROM BookFileEntity bf WHERE bf.book.id = b.id ORDER BY bf.id ASC LIMIT 1),
|
||||
'Unknown Book') as bookTitle,
|
||||
rs.bookType as bookFileType,
|
||||
rs.startTime as startDate,
|
||||
rs.endTime as endDate,
|
||||
1L as totalSessions,
|
||||
rs.durationSeconds as totalDurationSeconds
|
||||
FROM ReadingSessionEntity rs
|
||||
JOIN rs.book b
|
||||
WHERE rs.user.id = :userId
|
||||
AND rs.startTime >= :startOfWeek AND rs.startTime < :endOfWeek
|
||||
ORDER BY rs.startTime
|
||||
""")
|
||||
@Query("""
|
||||
SELECT
|
||||
b.id as bookId,
|
||||
coalesce(b.metadata.title,
|
||||
(SELECT bf.fileName FROM BookFileEntity bf WHERE bf.book.id = b.id ORDER BY bf.id ASC LIMIT 1),
|
||||
'Unknown Book') as bookTitle,
|
||||
rs.bookType as bookFileType,
|
||||
rs.startTime as startDate,
|
||||
rs.endTime as endDate,
|
||||
1L as totalSessions,
|
||||
rs.durationSeconds as totalDurationSeconds
|
||||
FROM ReadingSessionEntity rs
|
||||
JOIN rs.book b
|
||||
WHERE rs.user.id = :userId
|
||||
AND rs.startTime >= :startOfWeek AND rs.startTime < :endOfWeek
|
||||
ORDER BY rs.startTime
|
||||
""")
|
||||
List<ReadingSessionTimelineDto> findSessionTimelineByUserAndWeek(
|
||||
@Param("userId") Long userId,
|
||||
@Param("startOfWeek") Instant startOfWeek,
|
||||
@@ -70,61 +52,56 @@ public interface ReadingSessionRepository extends JpaRepository<ReadingSessionEn
|
||||
|
||||
@Query("""
|
||||
SELECT
|
||||
CAST(rs.createdAt AS LocalDate) as date,
|
||||
AVG(rs.progressDelta / (rs.durationSeconds / 60.0)) as avgProgressPerMinute,
|
||||
COUNT(rs) as totalSessions
|
||||
cast(rs.createdAt as LocalDate) as date,
|
||||
avg(rs.progressDelta / (rs.durationSeconds / 60.0)) as avgProgressPerMinute,
|
||||
count(rs) as totalSessions
|
||||
FROM ReadingSessionEntity rs
|
||||
WHERE rs.user.id = :userId
|
||||
AND rs.durationSeconds > 0
|
||||
AND rs.progressDelta > 0
|
||||
AND YEAR(rs.createdAt) = :year
|
||||
GROUP BY CAST(rs.createdAt AS LocalDate)
|
||||
AND rs.createdAt >= :periodStart AND rs.createdAt < :periodEnd
|
||||
GROUP BY cast(rs.createdAt as LocalDate)
|
||||
ORDER BY date
|
||||
""")
|
||||
List<ReadingSpeedDto> findReadingSpeedByUserAndYear(@Param("userId") Long userId, @Param("year") int year);
|
||||
|
||||
@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(
|
||||
List<ReadingSpeedDto> findReadingSpeedByUserAndYear(
|
||||
@Param("userId") Long userId,
|
||||
@Param("year") Integer year,
|
||||
@Param("month") Integer month,
|
||||
@Param("tzOffset") String tzOffset);
|
||||
@Param("periodStart") java.time.LocalDateTime periodStart,
|
||||
@Param("periodEnd") java.time.LocalDateTime periodEnd);
|
||||
|
||||
@Query(value = """
|
||||
SELECT
|
||||
DAYOFWEEK(CONVERT_TZ(start_time, '+00:00', :tzOffset)) as dayOfWeek,
|
||||
COUNT(*) as sessionCount,
|
||||
COALESCE(SUM(duration_seconds), 0) 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 DAYOFWEEK(CONVERT_TZ(start_time, '+00:00', :tzOffset))
|
||||
ORDER BY dayOfWeek
|
||||
""", nativeQuery = true)
|
||||
List<FavoriteReadingDayDto> findFavoriteReadingDaysByUser(
|
||||
@Query("""
|
||||
SELECT rs.startTime as startTime,
|
||||
coalesce(rs.durationSeconds, 0) as durationSeconds
|
||||
FROM ReadingSessionEntity rs
|
||||
WHERE rs.user.id = :userId
|
||||
AND (:periodStart IS NULL OR rs.startTime >= :periodStart)
|
||||
AND (:periodEnd IS NULL OR rs.startTime < :periodEnd)
|
||||
ORDER BY rs.startTime
|
||||
""")
|
||||
List<SessionTimestampDto> findSessionTimestampsByUser(
|
||||
@Param("userId") Long userId,
|
||||
@Param("year") Integer year,
|
||||
@Param("month") Integer month,
|
||||
@Param("tzOffset") String tzOffset);
|
||||
@Param("periodStart") Instant periodStart,
|
||||
@Param("periodEnd") Instant periodEnd);
|
||||
|
||||
@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("""
|
||||
SELECT
|
||||
c.name as genre,
|
||||
COUNT(DISTINCT b.id) as bookCount,
|
||||
COUNT(rs) as totalSessions,
|
||||
SUM(rs.durationSeconds) as totalDurationSeconds
|
||||
count(distinct b.id) as bookCount,
|
||||
count(rs) as totalSessions,
|
||||
sum(rs.durationSeconds) as totalDurationSeconds
|
||||
FROM ReadingSessionEntity rs
|
||||
JOIN rs.book b
|
||||
JOIN b.metadata.categories c
|
||||
@@ -157,19 +134,19 @@ public interface ReadingSessionRepository extends JpaRepository<ReadingSessionEn
|
||||
@Query("""
|
||||
SELECT
|
||||
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,
|
||||
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.endTime as endTime,
|
||||
rs.durationSeconds as durationSeconds
|
||||
coalesce(rs.durationSeconds, 0) as durationSeconds
|
||||
FROM ReadingSessionEntity rs
|
||||
JOIN rs.book b
|
||||
JOIN UserBookProgressEntity ubp ON ubp.book.id = b.id AND ubp.user.id = rs.user.id
|
||||
WHERE rs.user.id = :userId
|
||||
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
|
||||
""")
|
||||
List<PageTurnerSessionDto> findPageTurnerSessionsByUser(@Param("userId") Long userId);
|
||||
@@ -177,7 +154,7 @@ public interface ReadingSessionRepository extends JpaRepository<ReadingSessionEn
|
||||
@Query("""
|
||||
SELECT
|
||||
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.endProgress as endProgress
|
||||
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
|
||||
WHERE rs.user.id = :userId
|
||||
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
|
||||
ORDER BY b.id, rs.startTime ASC
|
||||
""")
|
||||
@@ -193,148 +170,87 @@ public interface ReadingSessionRepository extends JpaRepository<ReadingSessionEn
|
||||
@Param("userId") Long userId,
|
||||
@Param("year") int year);
|
||||
|
||||
@Query(value = """
|
||||
SELECT DATE(CONVERT_TZ(start_time, '+00:00', :tzOffset)) as date,
|
||||
COUNT(*) as count
|
||||
FROM reading_sessions
|
||||
WHERE user_id = :userId
|
||||
GROUP BY DATE(CONVERT_TZ(start_time, '+00:00', :tzOffset))
|
||||
ORDER BY date
|
||||
""", 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);
|
||||
@Query("""
|
||||
SELECT rs.startTime
|
||||
FROM ReadingSessionEntity rs
|
||||
WHERE rs.user.id = :userId
|
||||
ORDER BY rs.startTime
|
||||
""")
|
||||
List<Instant> findAllSessionStartTimesByUser(@Param("userId") Long userId);
|
||||
|
||||
// ========================================================================
|
||||
// Listening (audiobook) stats
|
||||
// ========================================================================
|
||||
|
||||
@Query(value = """
|
||||
SELECT DATE(CONVERT_TZ(start_time, '+00:00', :tzOffset)) as date,
|
||||
COUNT(*) as sessions,
|
||||
COALESCE(ROUND(SUM(duration_seconds) / 60.0), 0) as durationMinutes
|
||||
FROM reading_sessions
|
||||
WHERE user_id = :userId
|
||||
AND book_type = 'AUDIOBOOK'
|
||||
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<ListeningHeatmapDto> findListeningSessionsByUserAndMonth(
|
||||
@Query("""
|
||||
SELECT rs.startTime as startTime,
|
||||
coalesce(rs.durationSeconds, 0) as durationSeconds
|
||||
FROM ReadingSessionEntity rs
|
||||
WHERE rs.user.id = :userId
|
||||
AND rs.bookType = org.booklore.model.enums.BookFileType.AUDIOBOOK
|
||||
AND (:periodStart IS NULL OR rs.startTime >= :periodStart)
|
||||
AND (:periodEnd IS NULL OR rs.startTime < :periodEnd)
|
||||
ORDER BY rs.startTime
|
||||
""")
|
||||
List<SessionTimestampDto> findListeningTimestampsByUser(
|
||||
@Param("userId") Long userId,
|
||||
@Param("year") int year,
|
||||
@Param("month") int month,
|
||||
@Param("tzOffset") String tzOffset);
|
||||
@Param("periodStart") Instant periodStart,
|
||||
@Param("periodEnd") Instant periodEnd);
|
||||
|
||||
@Query(value = """
|
||||
SELECT YEAR(CONVERT_TZ(start_time, '+00:00', :tzOffset)) as year,
|
||||
WEEK(CONVERT_TZ(start_time, '+00:00', :tzOffset), 3) as week,
|
||||
COALESCE(SUM(duration_seconds), 0) as totalDurationSeconds,
|
||||
COUNT(*) as sessions
|
||||
FROM reading_sessions
|
||||
WHERE user_id = :userId
|
||||
AND book_type = 'AUDIOBOOK'
|
||||
AND CONVERT_TZ(start_time, '+00:00', :tzOffset) >= DATE_SUB(NOW(), INTERVAL :weeks WEEK)
|
||||
GROUP BY year, week
|
||||
ORDER BY year, week
|
||||
""", nativeQuery = true)
|
||||
List<WeeklyListeningTrendDto> findWeeklyListeningTrend(
|
||||
@Query("""
|
||||
SELECT rs.startTime as startTime,
|
||||
coalesce(rs.durationSeconds, 0) as durationSeconds
|
||||
FROM ReadingSessionEntity rs
|
||||
WHERE rs.user.id = :userId
|
||||
AND rs.bookType = org.booklore.model.enums.BookFileType.AUDIOBOOK
|
||||
ORDER BY rs.startTime DESC
|
||||
""")
|
||||
List<SessionTimestampDto> findListeningTimestampsByUserPaged(
|
||||
@Param("userId") Long userId,
|
||||
@Param("weeks") int weeks,
|
||||
@Param("tzOffset") String tzOffset);
|
||||
Pageable pageable);
|
||||
|
||||
@Query(value = """
|
||||
SELECT rs.book_id as bookId,
|
||||
COALESCE(bm.title, 'Unknown') as title,
|
||||
COALESCE(MAX(rs.end_progress), 0) as maxProgress,
|
||||
COALESCE(MAX(bf.duration_seconds), 0) as totalDurationSeconds,
|
||||
SUM(rs.duration_seconds) as listenedDurationSeconds
|
||||
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 book_file bf ON bf.book_id = b.id AND bf.book_type = 'AUDIOBOOK'
|
||||
WHERE rs.user_id = :userId
|
||||
AND rs.book_type = 'AUDIOBOOK'
|
||||
GROUP BY rs.book_id, bm.title
|
||||
""", nativeQuery = true)
|
||||
@Query("""
|
||||
SELECT b.id as bookId,
|
||||
coalesce(bm.title, 'Unknown') as title,
|
||||
max(rs.endProgress) as maxProgress,
|
||||
coalesce(max(bf.durationSeconds), 0L) as totalDurationSeconds,
|
||||
sum(rs.durationSeconds) as listenedDurationSeconds
|
||||
FROM ReadingSessionEntity rs
|
||||
JOIN rs.book b
|
||||
LEFT JOIN b.metadata bm
|
||||
LEFT JOIN b.bookFiles bf ON bf.bookType = org.booklore.model.enums.BookFileType.AUDIOBOOK
|
||||
WHERE rs.user.id = :userId
|
||||
AND rs.bookType = org.booklore.model.enums.BookFileType.AUDIOBOOK
|
||||
GROUP BY b.id, bm.title
|
||||
""")
|
||||
List<AudiobookProgressDto> findAudiobookProgressByUser(@Param("userId") Long userId);
|
||||
|
||||
@Query(value = """
|
||||
SELECT YEAR(COALESCE(ubp.date_finished, ubp.read_status_modified_time)) as year,
|
||||
MONTH(COALESCE(ubp.date_finished, ubp.read_status_modified_time)) as month,
|
||||
COUNT(*) as booksCompleted
|
||||
FROM user_book_progress ubp
|
||||
WHERE ubp.user_id = :userId
|
||||
AND ubp.read_status = 'READ'
|
||||
AND COALESCE(ubp.date_finished, ubp.read_status_modified_time) IS NOT NULL
|
||||
@Query("""
|
||||
SELECT year(coalesce(ubp.dateFinished, ubp.readStatusModifiedTime)) as year,
|
||||
month(coalesce(ubp.dateFinished, ubp.readStatusModifiedTime)) as month,
|
||||
count(ubp) as booksCompleted
|
||||
FROM UserBookProgressEntity ubp
|
||||
WHERE ubp.user.id = :userId
|
||||
AND ubp.readStatus = org.booklore.model.enums.ReadStatus.READ
|
||||
AND coalesce(ubp.dateFinished, ubp.readStatusModifiedTime) IS NOT NULL
|
||||
AND EXISTS (
|
||||
SELECT 1 FROM reading_sessions rs
|
||||
WHERE rs.book_id = ubp.book_id
|
||||
AND rs.user_id = ubp.user_id
|
||||
AND rs.book_type = 'AUDIOBOOK'
|
||||
SELECT 1 FROM ReadingSessionEntity rs
|
||||
WHERE rs.book.id = ubp.book.id
|
||||
AND rs.user.id = ubp.user.id
|
||||
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
|
||||
""", nativeQuery = true)
|
||||
""")
|
||||
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("""
|
||||
SELECT
|
||||
c.name as genre,
|
||||
COUNT(DISTINCT b.id) as bookCount,
|
||||
COUNT(rs) as totalSessions,
|
||||
SUM(rs.durationSeconds) as totalDurationSeconds
|
||||
count(distinct b.id) as bookCount,
|
||||
count(rs) as totalSessions,
|
||||
sum(rs.durationSeconds) as totalDurationSeconds
|
||||
FROM ReadingSessionEntity rs
|
||||
JOIN rs.book b
|
||||
JOIN b.metadata.categories c
|
||||
@@ -345,58 +261,43 @@ public interface ReadingSessionRepository extends JpaRepository<ReadingSessionEn
|
||||
""")
|
||||
List<GenreStatisticsDto> findListeningGenreStatisticsByUser(@Param("userId") Long userId);
|
||||
|
||||
@Query(value = """
|
||||
@Query("""
|
||||
SELECT a.name as authorName,
|
||||
COUNT(DISTINCT rs.book_id) as bookCount,
|
||||
COUNT(*) as totalSessions,
|
||||
COALESCE(SUM(rs.duration_seconds), 0) as totalDurationSeconds
|
||||
FROM reading_sessions rs
|
||||
JOIN book_metadata_author_mapping bam ON bam.book_id = rs.book_id
|
||||
JOIN author a ON a.id = bam.author_id
|
||||
WHERE rs.user_id = :userId
|
||||
AND rs.book_type = 'AUDIOBOOK'
|
||||
count(distinct rs.book.id) as bookCount,
|
||||
count(rs) as totalSessions,
|
||||
coalesce(sum(rs.durationSeconds), 0L) as totalDurationSeconds
|
||||
FROM ReadingSessionEntity rs
|
||||
JOIN rs.book b
|
||||
JOIN b.metadata m
|
||||
JOIN m.authors a
|
||||
WHERE rs.user.id = :userId
|
||||
AND rs.bookType = org.booklore.model.enums.BookFileType.AUDIOBOOK
|
||||
GROUP BY a.name
|
||||
ORDER BY totalDurationSeconds DESC
|
||||
""", nativeQuery = true)
|
||||
""")
|
||||
List<ListeningAuthorDto> findListeningAuthorStatsByUser(@Param("userId") Long userId);
|
||||
|
||||
@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 rs.book_type = 'AUDIOBOOK'
|
||||
ORDER BY rs.start_time DESC
|
||||
LIMIT 500
|
||||
""", nativeQuery = true)
|
||||
List<SessionScatterDto> findListeningSessionScatterByUser(
|
||||
@Param("userId") Long userId,
|
||||
@Param("tzOffset") String tzOffset);
|
||||
|
||||
@Query(value = """
|
||||
SELECT rs.book_id as bookId,
|
||||
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)
|
||||
@Query("""
|
||||
SELECT b.id as bookId,
|
||||
coalesce(bm.title, 'Unknown') as title,
|
||||
bm.pageCount as pageCount,
|
||||
min(rs.startTime) as firstSessionStart,
|
||||
max(rs.endTime) as lastSessionEnd,
|
||||
count(rs) as totalSessions,
|
||||
coalesce(sum(rs.durationSeconds), 0L) as totalDurationSeconds,
|
||||
coalesce(max(rs.endProgress), 0.0) / 100.0 as maxProgress,
|
||||
ubp.readStatus as readStatus
|
||||
FROM ReadingSessionEntity rs
|
||||
JOIN rs.book b
|
||||
LEFT JOIN b.metadata bm
|
||||
LEFT JOIN b.userBookProgress ubp ON ubp.user.id = rs.user.id
|
||||
WHERE rs.user.id = :userId
|
||||
AND rs.startTime >= :periodStart AND rs.startTime < :periodEnd
|
||||
GROUP BY b.id, bm.title, bm.pageCount, ubp.readStatus
|
||||
ORDER BY firstSessionStart
|
||||
""")
|
||||
List<BookTimelineDto> findBookTimelineByUserAndYear(
|
||||
@Param("userId") Long userId,
|
||||
@Param("year") int year,
|
||||
@Param("tzOffset") String tzOffset);
|
||||
@Param("periodStart") Instant periodStart,
|
||||
@Param("periodEnd") Instant periodEnd);
|
||||
}
|
||||
|
||||
@@ -6,11 +6,9 @@ import org.booklore.config.security.service.AuthenticationService;
|
||||
import org.booklore.exception.ApiError;
|
||||
import org.booklore.model.dto.BookLoreUser;
|
||||
import org.booklore.model.dto.CompletionRaceSessionDto;
|
||||
import org.booklore.model.dto.request.ReadingSessionRequest;
|
||||
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.ReadingSessionCountDto;
|
||||
import org.booklore.model.dto.response.*;
|
||||
import org.booklore.model.entity.BookEntity;
|
||||
import org.booklore.model.entity.BookLoreUserEntity;
|
||||
@@ -33,11 +31,12 @@ import java.time.Instant;
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZoneId;
|
||||
import java.time.ZoneOffset;
|
||||
import java.time.format.TextStyle;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.time.temporal.TemporalAdjusters;
|
||||
import java.time.temporal.WeekFields;
|
||||
import java.util.*;
|
||||
import java.util.function.Function;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Slf4j
|
||||
@@ -52,9 +51,43 @@ public class ReadingSessionService {
|
||||
private final UserRepository userRepository;
|
||||
private final UserBookProgressRepository userBookProgressRepository;
|
||||
|
||||
private String getTimezoneOffset() {
|
||||
ZoneOffset offset = ZoneId.systemDefault().getRules().getOffset(Instant.now());
|
||||
return offset.getId().equals("Z") ? "+00:00" : offset.getId();
|
||||
record PeriodBounds(Instant start, Instant end) {}
|
||||
|
||||
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
|
||||
@@ -86,29 +119,23 @@ public class ReadingSessionService {
|
||||
}
|
||||
|
||||
public List<ReadingSessionHeatmapResponse> getSessionHeatmapForYear(int year) {
|
||||
BookLoreUser authenticatedUser = authenticationService.getAuthenticatedUser();
|
||||
Long userId = authenticatedUser.getId();
|
||||
Long userId = authenticationService.getAuthenticatedUser().getId();
|
||||
ZoneId zone = ZoneId.systemDefault();
|
||||
PeriodBounds bounds = computeYearBounds(year);
|
||||
|
||||
return readingSessionRepository.findSessionCountsByUserAndYear(userId, year, getTimezoneOffset())
|
||||
.stream()
|
||||
.map(dto -> ReadingSessionHeatmapResponse.builder()
|
||||
.date(dto.getDate())
|
||||
.count(dto.getCount())
|
||||
.build())
|
||||
.collect(Collectors.toList());
|
||||
return groupByLocalDate(
|
||||
readingSessionRepository.findSessionStartTimesByUserAndPeriod(userId, bounds.start(), bounds.end()),
|
||||
zone);
|
||||
}
|
||||
|
||||
public List<ReadingSessionHeatmapResponse> getSessionHeatmapForMonth(int year, int month) {
|
||||
BookLoreUser authenticatedUser = authenticationService.getAuthenticatedUser();
|
||||
Long userId = authenticatedUser.getId();
|
||||
Long userId = authenticationService.getAuthenticatedUser().getId();
|
||||
ZoneId zone = ZoneId.systemDefault();
|
||||
PeriodBounds bounds = computeMonthBounds(year, month);
|
||||
|
||||
return readingSessionRepository.findSessionCountsByUserAndYearAndMonth(userId, year, month, getTimezoneOffset())
|
||||
.stream()
|
||||
.map(dto -> ReadingSessionHeatmapResponse.builder()
|
||||
.date(dto.getDate())
|
||||
.count(dto.getCount())
|
||||
.build())
|
||||
.collect(Collectors.toList());
|
||||
return groupByLocalDate(
|
||||
readingSessionRepository.findSessionStartTimesByUserAndPeriod(userId, bounds.start(), bounds.end()),
|
||||
zone);
|
||||
}
|
||||
|
||||
public List<ReadingSessionTimelineResponse> getSessionTimelineForWeek(int year, int week) {
|
||||
@@ -138,7 +165,10 @@ public class ReadingSessionService {
|
||||
BookLoreUser authenticatedUser = authenticationService.getAuthenticatedUser();
|
||||
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()
|
||||
.map(dto -> ReadingSpeedResponse.builder()
|
||||
.date(dto.getDate())
|
||||
@@ -149,33 +179,53 @@ public class ReadingSessionService {
|
||||
}
|
||||
|
||||
public List<PeakHoursResponse> getPeakReadingHours(Integer year, Integer month) {
|
||||
BookLoreUser authenticatedUser = authenticationService.getAuthenticatedUser();
|
||||
Long userId = authenticatedUser.getId();
|
||||
Long userId = authenticationService.getAuthenticatedUser().getId();
|
||||
ZoneId zone = ZoneId.systemDefault();
|
||||
PeriodBounds bounds = computeOptionalBounds(year, month);
|
||||
|
||||
return readingSessionRepository.findPeakReadingHoursByUser(userId, year, month, getTimezoneOffset())
|
||||
.stream()
|
||||
.map(dto -> PeakHoursResponse.builder()
|
||||
.hourOfDay(dto.getHourOfDay())
|
||||
.sessionCount(dto.getSessionCount())
|
||||
.totalDurationSeconds(dto.getTotalDurationSeconds())
|
||||
var sessions = readingSessionRepository.findSessionTimestampsByUser(userId, bounds.start(), bounds.end());
|
||||
|
||||
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())
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
public List<FavoriteReadingDaysResponse> getFavoriteReadingDays(Integer year, Integer month) {
|
||||
BookLoreUser authenticatedUser = authenticationService.getAuthenticatedUser();
|
||||
Long userId = authenticatedUser.getId();
|
||||
Long userId = authenticationService.getAuthenticatedUser().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())
|
||||
.stream()
|
||||
.map(dto -> FavoriteReadingDaysResponse.builder()
|
||||
.dayOfWeek(dto.getDayOfWeek())
|
||||
.dayName(dayNames[dto.getDayOfWeek() - 1])
|
||||
.sessionCount(dto.getSessionCount())
|
||||
.totalDurationSeconds(dto.getTotalDurationSeconds())
|
||||
.build())
|
||||
Map<DayOfWeek, long[]> weekdayTotals = new EnumMap<>(DayOfWeek.class);
|
||||
for (var dto : sessions) {
|
||||
DayOfWeek dow = dto.getStartTime().atZone(zone).toLocalDate().getDayOfWeek();
|
||||
weekdayTotals.merge(dow, new long[]{1, dto.getDurationSeconds()},
|
||||
(a, b) -> new long[]{a[0] + b[0], a[1] + b[1]});
|
||||
}
|
||||
|
||||
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());
|
||||
}
|
||||
|
||||
@@ -399,16 +449,10 @@ public class ReadingSessionService {
|
||||
}
|
||||
|
||||
public List<ReadingSessionHeatmapResponse> getReadingDates() {
|
||||
BookLoreUser authenticatedUser = authenticationService.getAuthenticatedUser();
|
||||
Long userId = authenticatedUser.getId();
|
||||
Long userId = authenticationService.getAuthenticatedUser().getId();
|
||||
ZoneId zone = ZoneId.systemDefault();
|
||||
|
||||
return readingSessionRepository.findAllSessionCountsByUser(userId, getTimezoneOffset())
|
||||
.stream()
|
||||
.map(dto -> ReadingSessionHeatmapResponse.builder()
|
||||
.date(dto.getDate())
|
||||
.count(dto.getCount())
|
||||
.build())
|
||||
.collect(Collectors.toList());
|
||||
return groupByLocalDate(readingSessionRepository.findAllSessionStartTimesByUser(userId), zone);
|
||||
}
|
||||
|
||||
public BookDistributionsResponse getBookDistributions() {
|
||||
@@ -485,29 +529,34 @@ public class ReadingSessionService {
|
||||
}
|
||||
|
||||
public List<SessionScatterResponse> getSessionScatter(int year) {
|
||||
BookLoreUser authenticatedUser = authenticationService.getAuthenticatedUser();
|
||||
Long userId = authenticatedUser.getId();
|
||||
Long userId = authenticationService.getAuthenticatedUser().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()
|
||||
.map(dto -> SessionScatterResponse.builder()
|
||||
.hourOfDay(dto.getHourOfDay())
|
||||
.durationMinutes(dto.getDurationMinutes())
|
||||
.dayOfWeek(dto.getDayOfWeek())
|
||||
.build())
|
||||
.map(dto -> {
|
||||
var zdt = dto.getStartTime().atZone(zone);
|
||||
return SessionScatterResponse.builder()
|
||||
.hourOfDay(zdt.getHour() + zdt.getMinute() / 60.0)
|
||||
.durationMinutes(dto.getDurationSeconds() / 60.0)
|
||||
.dayOfWeek(toSundayFirstDow(zdt.getDayOfWeek()))
|
||||
.build();
|
||||
})
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
public ReadingStreakResponse getReadingStreak() {
|
||||
BookLoreUser authenticatedUser = authenticationService.getAuthenticatedUser();
|
||||
Long userId = authenticatedUser.getId();
|
||||
Long userId = authenticationService.getAuthenticatedUser().getId();
|
||||
ZoneId zone = ZoneId.systemDefault();
|
||||
|
||||
List<ReadingSessionCountDto> allDates = readingSessionRepository.findAllSessionCountsByUser(userId, getTimezoneOffset());
|
||||
Set<LocalDate> readingDays = allDates.stream()
|
||||
.map(ReadingSessionCountDto::getDate)
|
||||
Set<LocalDate> readingDays = readingSessionRepository.findAllSessionStartTimesByUser(userId)
|
||||
.stream()
|
||||
.map(instant -> instant.atZone(zone).toLocalDate())
|
||||
.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)
|
||||
int currentStreak = 0;
|
||||
@@ -556,23 +605,21 @@ public class ReadingSessionService {
|
||||
}
|
||||
|
||||
public List<BookTimelineResponse> getBookTimeline(int year) {
|
||||
BookLoreUser authenticatedUser = authenticationService.getAuthenticatedUser();
|
||||
Long userId = authenticatedUser.getId();
|
||||
String tzOffset = getTimezoneOffset();
|
||||
|
||||
Long userId = authenticationService.getAuthenticatedUser().getId();
|
||||
ZoneId zone = ZoneId.systemDefault();
|
||||
PeriodBounds bounds = computeYearBounds(year);
|
||||
|
||||
return readingSessionRepository.findBookTimelineByUserAndYear(userId, year, tzOffset)
|
||||
return readingSessionRepository.findBookTimelineByUserAndYear(userId, bounds.start(), bounds.end())
|
||||
.stream()
|
||||
.map(dto -> BookTimelineResponse.builder()
|
||||
.bookId(dto.getBookId())
|
||||
.title(dto.getTitle())
|
||||
.pageCount(dto.getPageCount())
|
||||
.firstSessionDate(dto.getFirstSessionDate() != null
|
||||
? dto.getFirstSessionDate().toLocalDate()
|
||||
.firstSessionDate(dto.getFirstSessionStart() != null
|
||||
? dto.getFirstSessionStart().atZone(zone).toLocalDate()
|
||||
: null)
|
||||
.lastSessionDate(dto.getLastSessionDate() != null
|
||||
? dto.getLastSessionDate().toLocalDate()
|
||||
.lastSessionDate(dto.getLastSessionEnd() != null
|
||||
? dto.getLastSessionEnd().atZone(zone).toLocalDate()
|
||||
: null)
|
||||
.totalSessions(dto.getTotalSessions())
|
||||
.totalDurationSeconds(dto.getTotalDurationSeconds())
|
||||
@@ -606,26 +653,54 @@ public class ReadingSessionService {
|
||||
|
||||
public List<ListeningHeatmapResponse> getListeningHeatmapForMonth(int year, int month) {
|
||||
Long userId = authenticationService.getAuthenticatedUser().getId();
|
||||
return readingSessionRepository.findListeningSessionsByUserAndMonth(userId, year, month, getTimezoneOffset())
|
||||
.stream()
|
||||
.map(dto -> ListeningHeatmapResponse.builder()
|
||||
.date(dto.getDate())
|
||||
.sessions(dto.getSessions())
|
||||
.durationMinutes(dto.getDurationMinutes())
|
||||
ZoneId zone = ZoneId.systemDefault();
|
||||
PeriodBounds bounds = computeMonthBounds(year, month);
|
||||
|
||||
var sessions = readingSessionRepository.findListeningTimestampsByUser(userId, bounds.start(), bounds.end());
|
||||
|
||||
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())
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
public List<WeeklyListeningTrendResponse> getWeeklyListeningTrend(int weeks) {
|
||||
Long userId = authenticationService.getAuthenticatedUser().getId();
|
||||
return readingSessionRepository.findWeeklyListeningTrend(userId, weeks, getTimezoneOffset())
|
||||
.stream()
|
||||
.map(dto -> WeeklyListeningTrendResponse.builder()
|
||||
.year(dto.getYear())
|
||||
.week(dto.getWeek())
|
||||
.totalDurationSeconds(dto.getTotalDurationSeconds())
|
||||
.sessions(dto.getSessions())
|
||||
.build())
|
||||
ZoneId zone = ZoneId.systemDefault();
|
||||
Instant cutoffDate = Instant.now().minus(weeks * 7L, ChronoUnit.DAYS);
|
||||
|
||||
var sessions = readingSessionRepository.findListeningTimestampsByUser(userId, cutoffDate, null);
|
||||
|
||||
Map<String, long[]> weeklyMap = new LinkedHashMap<>();
|
||||
for (var dto : sessions) {
|
||||
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());
|
||||
}
|
||||
|
||||
@@ -667,18 +742,18 @@ public class ReadingSessionService {
|
||||
|
||||
public List<MonthlyPaceResponse> getMonthlyListeningPace(int months) {
|
||||
Long userId = authenticationService.getAuthenticatedUser().getId();
|
||||
ZoneId zone = ZoneId.systemDefault();
|
||||
|
||||
// Get completed audiobooks by month
|
||||
var completedByMonth = readingSessionRepository.findMonthlyCompletedAudiobooks(userId);
|
||||
|
||||
// Get listening durations by month
|
||||
var durationsByMonth = readingSessionRepository.findMonthlyListeningDurations(userId, getTimezoneOffset());
|
||||
var allSessions = readingSessionRepository.findListeningTimestampsByUser(userId, null, null);
|
||||
Map<String, Long> durationMap = new HashMap<>();
|
||||
for (var durDto : durationsByMonth) {
|
||||
durationMap.put(durDto.getYear() + "-" + durDto.getMonth(), durDto.getTotalDurationSeconds());
|
||||
for (var dto : allSessions) {
|
||||
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()
|
||||
.limit(months)
|
||||
.map(dto -> {
|
||||
@@ -726,12 +801,23 @@ public class ReadingSessionService {
|
||||
|
||||
public List<PeakHoursResponse> getListeningPeakHours(Integer year, Integer month) {
|
||||
Long userId = authenticationService.getAuthenticatedUser().getId();
|
||||
return readingSessionRepository.findListeningPeakHoursByUser(userId, year, month, getTimezoneOffset())
|
||||
.stream()
|
||||
.map(dto -> PeakHoursResponse.builder()
|
||||
.hourOfDay(dto.getHourOfDay())
|
||||
.sessionCount(dto.getSessionCount())
|
||||
.totalDurationSeconds(dto.getTotalDurationSeconds())
|
||||
ZoneId zone = ZoneId.systemDefault();
|
||||
PeriodBounds bounds = computeOptionalBounds(year, month);
|
||||
|
||||
var sessions = readingSessionRepository.findListeningTimestampsByUser(userId, bounds.start(), bounds.end());
|
||||
|
||||
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())
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
@@ -771,13 +857,18 @@ public class ReadingSessionService {
|
||||
|
||||
public List<SessionScatterResponse> getListeningSessionScatter() {
|
||||
Long userId = authenticationService.getAuthenticatedUser().getId();
|
||||
return readingSessionRepository.findListeningSessionScatterByUser(userId, getTimezoneOffset())
|
||||
ZoneId zone = ZoneId.systemDefault();
|
||||
|
||||
return readingSessionRepository.findListeningTimestampsByUserPaged(userId, PageRequest.of(0, 500))
|
||||
.stream()
|
||||
.map(dto -> SessionScatterResponse.builder()
|
||||
.hourOfDay(dto.getHourOfDay())
|
||||
.durationMinutes(dto.getDurationMinutes())
|
||||
.dayOfWeek(dto.getDayOfWeek())
|
||||
.build())
|
||||
.map(dto -> {
|
||||
var zdt = dto.getStartTime().atZone(zone);
|
||||
return SessionScatterResponse.builder()
|
||||
.hourOfDay(zdt.getHour() + zdt.getMinute() / 60.0)
|
||||
.durationMinutes(dto.getDurationSeconds() / 60.0)
|
||||
.dayOfWeek(toSundayFirstDow(zdt.getDayOfWeek()))
|
||||
.build();
|
||||
})
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
|
||||
@@ -60,19 +60,19 @@ public class BookCreatorService {
|
||||
}
|
||||
|
||||
public BookEntity createShellBook(LibraryFile libraryFile, BookFileType bookFileType) {
|
||||
Optional<BookEntity> existingBookOpt = bookRepository.findByLibraryIdAndLibraryPathIdAndFileSubPathAndFileName(
|
||||
Optional<BookEntity> existing = bookRepository.findFirstByLibraryIdAndLibraryPathIdAndFileSubPathAndFileName(
|
||||
libraryFile.getLibraryEntity().getId(),
|
||||
libraryFile.getLibraryPathEntity().getId(),
|
||||
libraryFile.getFileSubPath(),
|
||||
libraryFile.getFileName());
|
||||
|
||||
if (existingBookOpt.isPresent()) {
|
||||
if (existing.isPresent()) {
|
||||
log.warn("Book already exists for file: {}", libraryFile.getFileName());
|
||||
long fileSizeKb = calculateFileSize(libraryFile);
|
||||
String newHash = libraryFile.isFolderBased()
|
||||
? FileFingerprint.generateFolderHash(libraryFile.getFullPath())
|
||||
: FileFingerprint.generateHash(libraryFile.getFullPath());
|
||||
BookEntity existingBook = existingBookOpt.get();
|
||||
BookEntity existingBook = existing.get();
|
||||
BookFileEntity primaryFile = existingBook.getPrimaryBookFile();
|
||||
primaryFile.setCurrentHash(newHash);
|
||||
primaryFile.setInitialHash(newHash);
|
||||
|
||||
@@ -240,7 +240,7 @@ public class BookDownloadService {
|
||||
}
|
||||
|
||||
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();
|
||||
if (primaryFile == null) {
|
||||
|
||||
@@ -41,9 +41,6 @@ import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.stereotype.Service;
|
||||
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 java.io.File;
|
||||
@@ -79,7 +76,6 @@ public class BookDropService {
|
||||
private final FileMovingHelper fileMovingHelper;
|
||||
private final MonitoringRegistrationService monitoringRegistrationService;
|
||||
private final ApplicationEventPublisher eventPublisher;
|
||||
private final PlatformTransactionManager transactionManager;
|
||||
|
||||
private static final int CHUNK_SIZE = 100;
|
||||
|
||||
@@ -292,7 +288,7 @@ public class BookDropService {
|
||||
private void reregisterAffectedLibraries(Set<Long> libraryIds) {
|
||||
for (Long libraryId : libraryIds) {
|
||||
try {
|
||||
LibraryEntity library = libraryRepository.findById(libraryId).orElse(null);
|
||||
LibraryEntity library = libraryRepository.findByIdWithPaths(libraryId).orElse(null);
|
||||
if (library != null) {
|
||||
for (LibraryPathEntity libPath : library.getLibraryPaths()) {
|
||||
Path libraryRoot = Path.of(libPath.getPath());
|
||||
@@ -376,7 +372,7 @@ public class BookDropService {
|
||||
}
|
||||
|
||||
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));
|
||||
|
||||
LibraryPathEntity path = library.getLibraryPaths().stream()
|
||||
@@ -472,32 +468,31 @@ public class BookDropService {
|
||||
.orElseThrow(() -> ApiError.INVALID_FILE_FORMAT.createException("Unsupported file extension"))
|
||||
.getType());
|
||||
|
||||
// Post-processing runs in REQUIRES_NEW so it gets a fresh REPEATABLE_READ snapshot
|
||||
// that can see the book committed by processFile()'s own REQUIRES_NEW transaction
|
||||
TransactionTemplate newTx = new TransactionTemplate(transactionManager);
|
||||
newTx.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
|
||||
// Post-processing runs in the same transaction as processFile (which uses
|
||||
// PROPAGATION_REQUIRED and joins this TX). The book entity is flushed but
|
||||
// not committed a REQUIRES_NEW here would start a separate TX whose
|
||||
// REPEATABLE_READ snapshot cannot see the uncommitted book, causing
|
||||
// "Book ID missing after import".
|
||||
Long bookId = fileProcessResult.getBook().getId();
|
||||
newTx.executeWithoutResult(status -> {
|
||||
BookEntity bookEntity = bookRepository.findByIdWithBookFiles(bookId)
|
||||
.orElseThrow(() -> ApiError.FILE_NOT_FOUND.createException("Book ID missing after import"));
|
||||
BookEntity bookEntity = bookRepository.findByIdWithBookFiles(bookId)
|
||||
.orElseThrow(() -> ApiError.FILE_NOT_FOUND.createException("Book ID missing after import"));
|
||||
|
||||
MetadataUpdateContext context = MetadataUpdateContext.builder()
|
||||
.bookEntity(bookEntity)
|
||||
.metadataUpdateWrapper(MetadataUpdateWrapper.builder()
|
||||
.metadata(metadata)
|
||||
.build())
|
||||
.updateThumbnail(metadata.getThumbnailUrl() != null)
|
||||
.mergeCategories(false)
|
||||
.replaceMode(MetadataReplaceMode.REPLACE_WHEN_PROVIDED)
|
||||
.mergeMoods(true)
|
||||
.mergeTags(true)
|
||||
.build();
|
||||
MetadataUpdateContext context = MetadataUpdateContext.builder()
|
||||
.bookEntity(bookEntity)
|
||||
.metadataUpdateWrapper(MetadataUpdateWrapper.builder()
|
||||
.metadata(metadata)
|
||||
.build())
|
||||
.updateThumbnail(metadata.getThumbnailUrl() != null)
|
||||
.mergeCategories(false)
|
||||
.replaceMode(MetadataReplaceMode.REPLACE_WHEN_PROVIDED)
|
||||
.mergeMoods(true)
|
||||
.mergeTags(true)
|
||||
.build();
|
||||
|
||||
metadataRefreshService.updateBookMetadata(context);
|
||||
metadataRefreshService.updateBookMetadata(context);
|
||||
eventPublisher.publishEvent(new BookAddedEvent(fileProcessResult.getBook()));
|
||||
|
||||
notificationService.sendMessage(Topic.BOOK_ADD, fileProcessResult.getBook());
|
||||
});
|
||||
notificationService.sendMessage(Topic.BOOK_ADD, fileProcessResult.getBook());
|
||||
|
||||
cleanupBookdropData(bookdropFile);
|
||||
|
||||
|
||||
@@ -71,7 +71,7 @@ public class FileMoveService {
|
||||
sleep(EVENT_DRAIN_TIMEOUT_MS);
|
||||
} finally {
|
||||
for (Long libraryId : allAffectedLibraryIds) {
|
||||
libraryRepository.findById(libraryId)
|
||||
libraryRepository.findByIdWithPaths(libraryId)
|
||||
.ifPresent(library -> monitoringRegistrationService.registerLibrary(libraryMapper.toLibrary(library)));
|
||||
}
|
||||
}
|
||||
@@ -101,7 +101,7 @@ public class FileMoveService {
|
||||
|
||||
try {
|
||||
Optional<BookEntity> optionalBook = bookRepository.findByIdWithBookFiles(bookId);
|
||||
Optional<LibraryEntity> optionalLibrary = libraryRepository.findById(targetLibraryId);
|
||||
Optional<LibraryEntity> optionalLibrary = libraryRepository.findByIdWithPaths(targetLibraryId);
|
||||
if (optionalBook.isEmpty()) {
|
||||
log.warn("Book not found for move operation: bookId={}", bookId);
|
||||
return;
|
||||
@@ -268,6 +268,17 @@ public class FileMoveService {
|
||||
|
||||
Long libraryId = bookEntity.getLibraryPath().getLibrary().getId();
|
||||
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;
|
||||
Map<Long, PlannedMove> plannedMovesByBookFileId = new HashMap<>();
|
||||
Set<Path> sourceParentsToCleanup = new HashSet<>();
|
||||
@@ -392,13 +403,17 @@ public class FileMoveService {
|
||||
throw e;
|
||||
}
|
||||
|
||||
// Clean up empty parent directories
|
||||
Set<Path> libraryRoots = bookWithFiles.getLibraryPath().getLibrary().getLibraryPaths().stream()
|
||||
.map(LibraryPathEntity::getPath)
|
||||
.map(Paths::get)
|
||||
.map(Path::toAbsolutePath)
|
||||
.map(Path::normalize)
|
||||
.collect(Collectors.toCollection(HashSet::new));
|
||||
// Clean up empty parent directories – load library paths via a separate query
|
||||
// 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(Paths::get)
|
||||
.map(Path::toAbsolutePath)
|
||||
.map(Path::normalize)
|
||||
.collect(Collectors.toCollection(HashSet::new)))
|
||||
.orElseGet(HashSet::new);
|
||||
// Also protect the source library root so cleanup doesn't traverse above it
|
||||
libraryRoots.add(Paths.get(bookWithFiles.getLibraryPath().getPath()).toAbsolutePath().normalize());
|
||||
|
||||
@@ -434,10 +449,11 @@ public class FileMoveService {
|
||||
|
||||
if (isLibraryMonitoredWhenCalled) {
|
||||
log.debug("Registering library paths for library {} with root {}", libraryId, libraryRoot);
|
||||
LibraryEntity libraryEntity = bookEntity.getLibraryPath().getLibrary();
|
||||
Library library = libraryMapper.toLibrary(libraryEntity);
|
||||
library.setWatch(true);
|
||||
monitoringRegistrationService.registerLibrary(library);
|
||||
libraryRepository.findByIdWithPaths(libraryId).ifPresent(lib -> {
|
||||
Library library = libraryMapper.toLibrary(lib);
|
||||
library.setWatch(true);
|
||||
monitoringRegistrationService.registerLibrary(library);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+1
-1
@@ -52,7 +52,7 @@ public class LibraryProcessingService {
|
||||
|
||||
@Transactional
|
||||
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()));
|
||||
try {
|
||||
List<LibraryFile> libraryFiles = libraryFileHelper.getLibraryFiles(libraryEntity);
|
||||
|
||||
@@ -67,6 +67,28 @@ public class BookMetadataService {
|
||||
private final PlatformTransactionManager transactionManager;
|
||||
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)
|
||||
public Flux<BookMetadata> getProspectiveMetadataListForBookId(long bookId, FetchMetadataRequest request) {
|
||||
@@ -210,26 +232,6 @@ public class BookMetadataService {
|
||||
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
|
||||
public void bulkUpdateMetadata(BulkMetadataUpdateRequest request, boolean mergeCategories, boolean mergeMoods, boolean mergeTags) {
|
||||
MetadataClearFlags clearFlags = metadataClearFlagsMapper.toClearFlags(request);
|
||||
|
||||
+4
-3
@@ -6,6 +6,7 @@ import org.booklore.service.migration.Migration;
|
||||
import org.booklore.util.BookCoverUtils;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.data.domain.PageRequest;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.List;
|
||||
@@ -33,10 +34,10 @@ public class GenerateCoverHashMigration implements Migration {
|
||||
|
||||
int batchSize = 1000;
|
||||
int processedCount = 0;
|
||||
int offset = 0;
|
||||
long lastId = 0;
|
||||
|
||||
while (true) {
|
||||
List<BookEntity> bookBatch = bookRepository.findBooksForMigrationBatch(offset, batchSize);
|
||||
List<BookEntity> bookBatch = bookRepository.findBooksForMigrationBatch(lastId, PageRequest.of(0, batchSize));
|
||||
if (bookBatch.isEmpty()) break;
|
||||
|
||||
for (BookEntity book : bookBatch) {
|
||||
@@ -47,7 +48,7 @@ public class GenerateCoverHashMigration implements Migration {
|
||||
|
||||
bookRepository.saveAll(bookBatch);
|
||||
processedCount += bookBatch.size();
|
||||
offset += batchSize;
|
||||
lastId = bookBatch.getLast().getId();
|
||||
|
||||
log.info("Migration progress: {} books processed", processedCount);
|
||||
|
||||
|
||||
+4
-3
@@ -7,6 +7,7 @@ import org.booklore.service.migration.Migration;
|
||||
import org.booklore.util.BookUtils;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.data.domain.PageRequest;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.List;
|
||||
@@ -34,10 +35,10 @@ public class PopulateSearchTextMigration implements Migration {
|
||||
|
||||
int batchSize = 1000;
|
||||
int processedCount = 0;
|
||||
int offset = 0;
|
||||
long lastId = 0;
|
||||
|
||||
while (true) {
|
||||
List<BookEntity> bookBatch = bookRepository.findBooksForMigrationBatch(offset, batchSize);
|
||||
List<BookEntity> bookBatch = bookRepository.findBooksForMigrationBatch(lastId, PageRequest.of(0, batchSize));
|
||||
if (bookBatch.isEmpty()) break;
|
||||
|
||||
List<Long> bookIds = bookBatch.stream().map(BookEntity::getId).toList();
|
||||
@@ -56,7 +57,7 @@ public class PopulateSearchTextMigration implements Migration {
|
||||
|
||||
bookRepository.saveAll(books);
|
||||
processedCount += books.size();
|
||||
offset += batchSize;
|
||||
lastId = bookBatch.getLast().getId();
|
||||
|
||||
log.info("Migration progress: {} books processed", processedCount);
|
||||
|
||||
|
||||
@@ -161,19 +161,23 @@ public class OpdsBookService {
|
||||
}
|
||||
|
||||
public List<Book> getRandomBooks(Long userId, int count) {
|
||||
if (count < 1) {
|
||||
return List.of();
|
||||
}
|
||||
|
||||
List<Library> accessibleLibraries = getAccessibleLibraries(userId);
|
||||
if (accessibleLibraries == null || accessibleLibraries.isEmpty()) {
|
||||
return List.of();
|
||||
}
|
||||
|
||||
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()) {
|
||||
return List.of();
|
||||
}
|
||||
|
||||
List<BookEntity> books = bookOpdsRepository.findAllWithMetadataByIds(ids.stream().limit(count).toList());
|
||||
List<BookEntity> books = bookOpdsRepository.findAllWithMetadataByIds(ids);
|
||||
if (userId != null) {
|
||||
books = contentRestrictionService.applyRestrictions(books, userId);
|
||||
}
|
||||
|
||||
@@ -64,7 +64,6 @@ spring:
|
||||
pool-name: BookloreHikariPool
|
||||
auto-commit: false # Required counterpart to provider_disables_autocommit
|
||||
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
|
||||
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
|
||||
|
||||
+3
@@ -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;
|
||||
|
||||
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.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.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.extension.ExtendWith;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class MetadataControllerTest {
|
||||
@@ -27,61 +23,41 @@ class MetadataControllerTest {
|
||||
@Mock
|
||||
private BookMetadataService bookMetadataService;
|
||||
@Mock
|
||||
private BookMetadataUpdater bookMetadataUpdater;
|
||||
@Mock
|
||||
private AuthenticationService authenticationService;
|
||||
@Mock
|
||||
private BookMetadataMapper bookMetadataMapper;
|
||||
@Mock
|
||||
private MetadataMatchService metadataMatchService;
|
||||
@Mock
|
||||
private DuckDuckGoCoverService duckDuckGoCoverService;
|
||||
@Mock
|
||||
private BookRepository bookRepository;
|
||||
@Mock
|
||||
private MetadataManagementService metadataManagementService;
|
||||
@Mock
|
||||
private AuditService auditService;
|
||||
|
||||
@InjectMocks
|
||||
private MetadataController metadataController;
|
||||
|
||||
private MetadataUpdateContext captureContextFromUpdate(MetadataReplaceMode replaceMode) {
|
||||
@Test
|
||||
void updateMetadata_delegatesToService() {
|
||||
long bookId = 1L;
|
||||
MetadataUpdateWrapper wrapper = MetadataUpdateWrapper.builder().build();
|
||||
BookEntity bookEntity = new BookEntity();
|
||||
bookEntity.setId(bookId);
|
||||
bookEntity.setMetadata(new BookMetadataEntity());
|
||||
MetadataReplaceMode replaceMode = MetadataReplaceMode.REPLACE_ALL;
|
||||
BookMetadata expected = new BookMetadata();
|
||||
|
||||
when(bookRepository.findAllWithMetadataByIds(java.util.Collections.singleton(bookId))).thenReturn(java.util.List.of(bookEntity));
|
||||
when(bookMetadataMapper.toBookMetadata(any(), anyBoolean())).thenReturn(new BookMetadata());
|
||||
when(bookMetadataService.updateBookMetadata(bookId, wrapper, true, replaceMode))
|
||||
.thenReturn(expected);
|
||||
|
||||
metadataController.updateMetadata(wrapper, bookId, true, replaceMode);
|
||||
ResponseEntity<BookMetadata> response = metadataController.updateMetadata(wrapper, bookId, true, replaceMode);
|
||||
|
||||
ArgumentCaptor<MetadataUpdateContext> captor = ArgumentCaptor.forClass(MetadataUpdateContext.class);
|
||||
verify(bookMetadataUpdater).setBookMetadata(captor.capture());
|
||||
return captor.getValue();
|
||||
assertThat(response.getBody()).isSameAs(expected);
|
||||
verify(bookMetadataService).updateBookMetadata(bookId, wrapper, true, replaceMode);
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateMetadata_shouldDisableMergingForTagsAndMoods() {
|
||||
MetadataUpdateContext context = captureContextFromUpdate(MetadataReplaceMode.REPLACE_ALL);
|
||||
void updateMetadata_passesReplaceModeToService() {
|
||||
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");
|
||||
assertFalse(context.isMergeMoods(), "mergeMoods should be false to allow deletion of moods");
|
||||
}
|
||||
when(bookMetadataService.updateBookMetadata(bookId, wrapper, false, replaceMode))
|
||||
.thenReturn(expected);
|
||||
|
||||
@Test
|
||||
void updateMetadata_shouldPassReplaceModeFromParam() {
|
||||
MetadataUpdateContext context = captureContextFromUpdate(MetadataReplaceMode.REPLACE_WHEN_PROVIDED);
|
||||
metadataController.updateMetadata(wrapper, bookId, false, replaceMode);
|
||||
|
||||
assertEquals(MetadataReplaceMode.REPLACE_WHEN_PROVIDED, context.getReplaceMode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateMetadata_shouldDefaultToReplaceAll() {
|
||||
MetadataUpdateContext context = captureContextFromUpdate(MetadataReplaceMode.REPLACE_ALL);
|
||||
|
||||
assertEquals(MetadataReplaceMode.REPLACE_ALL, context.getReplaceMode());
|
||||
verify(bookMetadataService).updateBookMetadata(bookId, wrapper, false, replaceMode);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -311,7 +311,7 @@ class OpdsBookServiceTest {
|
||||
List<Library> libs = List.of(Library.builder().id(1L).watch(false).build());
|
||||
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);
|
||||
when(bookOpdsRepository.findAllWithMetadataByIds(anyList())).thenReturn(List.of(entity));
|
||||
Book book = Book.builder().id(1L).build();
|
||||
@@ -750,7 +750,7 @@ class OpdsBookServiceTest {
|
||||
BookEntity allowedEntity = 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()))
|
||||
.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.PageRequest;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.transaction.PlatformTransactionManager;
|
||||
import org.springframework.transaction.TransactionStatus;
|
||||
import tools.jackson.databind.ObjectMapper;
|
||||
|
||||
import java.io.IOException;
|
||||
@@ -90,8 +88,6 @@ class BookDropServiceTest {
|
||||
private FileMovingHelper fileMovingHelper;
|
||||
@Mock
|
||||
private ApplicationEventPublisher eventPublisher;
|
||||
@Mock
|
||||
private PlatformTransactionManager transactionManager;
|
||||
|
||||
@InjectMocks
|
||||
private BookDropService bookDropService;
|
||||
@@ -127,9 +123,6 @@ class BookDropServiceTest {
|
||||
bookdropFile.setFileName("test-book.pdf");
|
||||
|
||||
Files.createFile(tempDir.resolve("test-book.pdf"));
|
||||
|
||||
TransactionStatus txStatus = mock(TransactionStatus.class);
|
||||
lenient().when(transactionManager.getTransaction(any())).thenReturn(txStatus);
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
@@ -249,7 +242,7 @@ class BookDropServiceTest {
|
||||
|
||||
when(bookdropFileRepository.findAllExcludingIdsFlat(any())).thenReturn(List.of(1L));
|
||||
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(fileMovingHelper.getFileNamingPattern(libraryEntity)).thenReturn("{title}");
|
||||
when(fileMovingHelper.generateNewFilePath(anyString(), any(), anyString(), anyString()))
|
||||
@@ -298,7 +291,7 @@ class BookDropServiceTest {
|
||||
|
||||
when(bookdropFileRepository.findAllIds()).thenReturn(List.of(1L));
|
||||
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();
|
||||
when(objectMapper.readValue(anyString(), eq(BookMetadata.class))).thenReturn(metadata);
|
||||
@@ -399,7 +392,7 @@ class BookDropServiceTest {
|
||||
|
||||
when(bookdropFileRepository.findAllIds()).thenReturn(List.of(2L));
|
||||
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();
|
||||
metadata.setTitle("Missing Book");
|
||||
@@ -431,7 +424,7 @@ class BookDropServiceTest {
|
||||
|
||||
when(bookdropFileRepository.findAllIds()).thenReturn(List.of(1L));
|
||||
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();
|
||||
when(objectMapper.readValue(anyString(), eq(BookMetadata.class))).thenReturn(metadata);
|
||||
@@ -463,7 +456,7 @@ class BookDropServiceTest {
|
||||
|
||||
when(bookdropFileRepository.findAllIds()).thenReturn(List.of(1L));
|
||||
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();
|
||||
pathEntity.setId(1L);
|
||||
@@ -530,7 +523,7 @@ class BookDropServiceTest {
|
||||
request.setFiles(List.of(finalizeFile));
|
||||
|
||||
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(fileMovingHelper.getFileNamingPattern(libraryEntity)).thenReturn("{title}");
|
||||
when(fileMovingHelper.generateNewFilePath(anyString(), any(), anyString(), anyString()))
|
||||
@@ -587,7 +580,7 @@ class BookDropServiceTest {
|
||||
request.setFiles(List.of(finalizeFile));
|
||||
|
||||
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(fileMovingHelper.getFileNamingPattern(libraryEntity)).thenReturn("{title}");
|
||||
when(fileMovingHelper.generateNewFilePath(anyString(), any(), anyString(), anyString()))
|
||||
@@ -622,4 +615,58 @@ class BookDropServiceTest {
|
||||
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");
|
||||
}
|
||||
|
||||
@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.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
@@ -179,6 +180,7 @@ class FileMoveServiceOrderingTest {
|
||||
mockStandardBehavior(book, target);
|
||||
when(monitoringRegistrationService.isLibraryMonitored(1L)).thenReturn(true);
|
||||
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();
|
||||
when(libraryMapper.toLibrary(any(LibraryEntity.class))).thenReturn(dto);
|
||||
|
||||
@@ -315,6 +317,7 @@ class FileMoveServiceOrderingTest {
|
||||
doThrow(new IOException("fail")).when(fileMoveHelper).commitMove(any(), any());
|
||||
when(monitoringRegistrationService.isLibraryMonitored(1L)).thenReturn(true);
|
||||
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();
|
||||
when(libraryMapper.toLibrary(any(LibraryEntity.class))).thenReturn(dto);
|
||||
|
||||
|
||||
@@ -147,6 +147,7 @@ class FileMoveServiceTest {
|
||||
private void mockMonitoredLibrary() {
|
||||
when(monitoringRegistrationService.isLibraryMonitored(1L)).thenReturn(true);
|
||||
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());
|
||||
}
|
||||
|
||||
@@ -633,6 +634,7 @@ class FileMoveServiceTest {
|
||||
mockStandardBehavior(book, target);
|
||||
when(monitoringRegistrationService.isLibraryMonitored(1L)).thenReturn(true);
|
||||
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();
|
||||
when(libraryMapper.toLibrary(any(LibraryEntity.class))).thenReturn(dto);
|
||||
|
||||
@@ -669,6 +671,7 @@ class FileMoveServiceTest {
|
||||
mockStandardBehavior(book, target);
|
||||
when(monitoringRegistrationService.isLibraryMonitored(1L)).thenReturn(false);
|
||||
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());
|
||||
|
||||
service.moveSingleFile(book);
|
||||
@@ -781,7 +784,7 @@ class FileMoveServiceTest {
|
||||
private void mockBulkMoveSetup(BookEntity book, Path targetPath) throws IOException {
|
||||
when(bookRepository.findById(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.generateNewFilePath(eq(book), eq(targetLibraryPath), anyString())).thenReturn(targetPath);
|
||||
@@ -947,7 +950,7 @@ class FileMoveServiceTest {
|
||||
|
||||
when(bookRepository.findById(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")));
|
||||
|
||||
FileMoveRequest request = new FileMoveRequest();
|
||||
@@ -978,7 +981,7 @@ class FileMoveServiceTest {
|
||||
|
||||
when(bookRepository.findById(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")));
|
||||
|
||||
FileMoveRequest request = new FileMoveRequest();
|
||||
@@ -1008,7 +1011,7 @@ class FileMoveServiceTest {
|
||||
|
||||
when(bookRepository.findById(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")));
|
||||
|
||||
FileMoveRequest request = new FileMoveRequest();
|
||||
@@ -1044,8 +1047,8 @@ class FileMoveServiceTest {
|
||||
|
||||
when(bookRepository.findById(100L)).thenReturn(Optional.of(book));
|
||||
when(bookRepository.findByIdWithBookFiles(100L)).thenReturn(Optional.of(book));
|
||||
when(libraryRepository.findById(1L)).thenReturn(Optional.of(library));
|
||||
when(libraryRepository.findById(2L)).thenReturn(Optional.of(targetLibrary));
|
||||
when(libraryRepository.findByIdWithPaths(1L)).thenReturn(Optional.of(library));
|
||||
when(libraryRepository.findByIdWithPaths(2L)).thenReturn(Optional.of(targetLibrary));
|
||||
when(monitoringRegistrationService.getPathsForLibraries(anySet())).thenReturn(Set.of(Paths.get("/library"), Paths.get("/target")));
|
||||
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.findByIdWithBookFiles(100L)).thenReturn(Optional.of(book));
|
||||
when(libraryRepository.findById(1L)).thenReturn(Optional.of(library));
|
||||
when(libraryRepository.findById(2L)).thenReturn(Optional.of(targetLibrary));
|
||||
when(libraryRepository.findByIdWithPaths(1L)).thenReturn(Optional.of(library));
|
||||
when(libraryRepository.findByIdWithPaths(2L)).thenReturn(Optional.of(targetLibrary));
|
||||
when(monitoringRegistrationService.getPathsForLibraries(anySet())).thenReturn(Set.of(Paths.get("/library"), Paths.get("/target")));
|
||||
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
|
||||
@DisplayName("NetworkStorageGating")
|
||||
class NetworkStorageGating {
|
||||
|
||||
+5
-5
@@ -95,7 +95,7 @@ class LibraryProcessingServiceTest {
|
||||
existingBook.getPrimaryBookFile().setFileName("book1.epub");
|
||||
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));
|
||||
|
||||
LibraryFile existingFile = LibraryFile.builder()
|
||||
@@ -157,7 +157,7 @@ class LibraryProcessingServiceTest {
|
||||
existingBook.getPrimaryBookFile().setFileName("book1.epub");
|
||||
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));
|
||||
|
||||
LibraryFile existingFile = LibraryFile.builder()
|
||||
@@ -191,7 +191,7 @@ class LibraryProcessingServiceTest {
|
||||
pathEntity.setId(10L);
|
||||
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());
|
||||
|
||||
LibraryFile newFile1 = LibraryFile.builder()
|
||||
@@ -239,7 +239,7 @@ class LibraryProcessingServiceTest {
|
||||
pathEntity.setId(10L);
|
||||
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());
|
||||
|
||||
LibraryFile newFileInSub = LibraryFile.builder()
|
||||
@@ -284,7 +284,7 @@ class LibraryProcessingServiceTest {
|
||||
pathEntity.setId(10L);
|
||||
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());
|
||||
|
||||
LibraryFile additionalFileAsLibraryFile = LibraryFile.builder()
|
||||
|
||||
Reference in New Issue
Block a user