diff --git a/backend/src/main/java/org/booklore/controller/UserStatsController.java b/backend/src/main/java/org/booklore/controller/UserStatsController.java index 4d69b382d..d12745608 100644 --- a/backend/src/main/java/org/booklore/controller/UserStatsController.java +++ b/backend/src/main/java/org/booklore/controller/UserStatsController.java @@ -296,6 +296,19 @@ public class UserStatsController { return ResponseEntity.ok(readingSessionService.getListeningPeakHours(year, month)); } + @Operation( + summary = "Get listening favorite days", + description = "Returns listening activity distribution by day of week. Can be filtered by year and/or month.", + operationId = "getListeningFavoriteDays" + ) + @GetMapping("/listening/favorite-days") + @PreAuthorize("@securityUtil.canAccessUserStats() or @securityUtil.isAdmin()") + public ResponseEntity> getListeningFavoriteDays( + @RequestParam(required = false) Integer year, + @RequestParam(required = false) Integer month) { + return ResponseEntity.ok(readingSessionService.getListeningFavoriteDays(year, month)); + } + @Operation( summary = "Get listening genre statistics", description = "Returns listening statistics grouped by audiobook genres/categories.", diff --git a/backend/src/main/java/org/booklore/repository/ReadingSessionRepository.java b/backend/src/main/java/org/booklore/repository/ReadingSessionRepository.java index 5b0b05173..9a1fb5805 100644 --- a/backend/src/main/java/org/booklore/repository/ReadingSessionRepository.java +++ b/backend/src/main/java/org/booklore/repository/ReadingSessionRepository.java @@ -3,6 +3,8 @@ package org.booklore.repository; import org.booklore.model.dto.*; import org.booklore.model.entity.ReadingSessionEntity; +import org.springframework.data.jpa.repository.QueryHints; +import jakarta.persistence.QueryHint; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.JpaRepository; @@ -11,19 +13,37 @@ import org.springframework.data.repository.query.Param; import org.springframework.stereotype.Repository; import java.time.Instant; +import java.time.LocalDate; import java.util.List; +import java.util.stream.Stream; @Repository public interface ReadingSessionRepository extends JpaRepository { + @QueryHints(@QueryHint(name = "org.hibernate.fetchSize", value = "200")) @Query(""" SELECT rs.startTime FROM ReadingSessionEntity rs WHERE rs.user.id = :userId + AND rs.bookType != org.booklore.model.enums.BookFileType.AUDIOBOOK AND rs.startTime >= :periodStart AND rs.startTime < :periodEnd ORDER BY rs.startTime """) - List findSessionStartTimesByUserAndPeriod( + Stream findReadingSessionStartTimesByUserAndPeriod( + @Param("userId") Long userId, + @Param("periodStart") Instant periodStart, + @Param("periodEnd") Instant periodEnd); + + @QueryHints(@QueryHint(name = "org.hibernate.fetchSize", value = "200")) + @Query(""" + SELECT rs.startTime + FROM ReadingSessionEntity rs + WHERE rs.user.id = :userId + AND rs.bookType = org.booklore.model.enums.BookFileType.AUDIOBOOK + AND rs.startTime >= :periodStart AND rs.startTime < :periodEnd + ORDER BY rs.startTime + """) + Stream findListeningSessionStartTimesByUserAndPeriod( @Param("userId") Long userId, @Param("periodStart") Instant periodStart, @Param("periodEnd") Instant periodEnd); @@ -131,6 +151,7 @@ public interface ReadingSessionRepository extends JpaRepository findPageTurnerSessionsByUser(@Param("userId") Long userId); + Stream findPageTurnerSessionsByUser(@Param("userId") Long userId); + @QueryHints(@QueryHint(name = "org.hibernate.fetchSize", value = "200")) @Query(""" SELECT b.id as bookId, @@ -166,17 +188,59 @@ public interface ReadingSessionRepository extends JpaRepository findCompletionRaceSessionsByUserAndYear( + Stream findCompletionRaceSessionsByUserAndYear( @Param("userId") Long userId, @Param("year") int year); + @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 findReadingSessionTimestampsByUser( + @Param("userId") Long userId, + @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.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 findListeningSessionTimestampsByUser( + @Param("userId") Long userId, + @Param("periodStart") Instant periodStart, + @Param("periodEnd") Instant periodEnd); + + @QueryHints(@QueryHint(name = "org.hibernate.fetchSize", value = "200")) @Query(""" SELECT rs.startTime FROM ReadingSessionEntity rs WHERE rs.user.id = :userId + AND rs.bookType != org.booklore.model.enums.BookFileType.AUDIOBOOK ORDER BY rs.startTime """) - List findAllSessionStartTimesByUser(@Param("userId") Long userId); + Stream findAllReadingSessionStartTimesByUser(@Param("userId") Long userId); + + @QueryHints(@QueryHint(name = "org.hibernate.fetchSize", value = "200")) + @Query(""" + SELECT rs.startTime + FROM ReadingSessionEntity rs + WHERE rs.user.id = :userId + AND rs.bookType = org.booklore.model.enums.BookFileType.AUDIOBOOK + ORDER BY rs.startTime + """) + Stream findAllListeningSessionStartTimesByUser(@Param("userId") Long userId); // ======================================================================== // Listening (audiobook) stats diff --git a/backend/src/main/java/org/booklore/service/ReadingSessionService.java b/backend/src/main/java/org/booklore/service/ReadingSessionService.java index 1fda8b716..6c4c6af37 100644 --- a/backend/src/main/java/org/booklore/service/ReadingSessionService.java +++ b/backend/src/main/java/org/booklore/service/ReadingSessionService.java @@ -4,11 +4,8 @@ import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; 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.PageTurnerSessionDto; +import org.booklore.model.dto.*; import org.booklore.model.dto.request.ReadingSessionRequest; -import org.booklore.model.dto.ProgressPercentDto; import org.booklore.model.dto.response.*; import org.booklore.model.entity.BookEntity; import org.booklore.model.entity.BookLoreUserEntity; @@ -38,6 +35,7 @@ import java.time.temporal.WeekFields; import java.util.*; import java.util.function.Function; import java.util.stream.Collectors; +import java.util.stream.Stream; @Slf4j @Service @@ -73,8 +71,8 @@ public class ReadingSessionService { return computeMonthBounds(year, month); } - private List groupByLocalDate(List startTimes, ZoneId zone) { - return startTimes.stream() + private List groupByLocalDate(Stream startTimes, ZoneId zone) { + return startTimes .map(instant -> instant.atZone(zone).toLocalDate()) .collect(Collectors.groupingBy(Function.identity(), Collectors.counting())) .entrySet().stream() @@ -86,6 +84,40 @@ public class ReadingSessionService { .toList(); } + private List computePeakHours(List sessions, ZoneId zone) { + Map hourlyStats = new TreeMap<>(); // hour -> [count, duration] + for (var s : sessions) { + int hour = s.getStartTime().atZone(zone).getHour(); + hourlyStats.merge(hour, new long[]{1, s.getDurationSeconds()}, + (a, b) -> new long[]{a[0] + b[0], a[1] + b[1]}); + } + return hourlyStats.entrySet().stream() + .map(e -> PeakHoursResponse.builder() + .hourOfDay(e.getKey()) + .sessionCount(e.getValue()[0]) + .totalDurationSeconds(e.getValue()[1]) + .build()) + .toList(); + } + + private List computeFavoriteDays(List sessions, ZoneId zone) { + Map dailyStats = new EnumMap<>(DayOfWeek.class); + for (var s : sessions) { + DayOfWeek dow = s.getStartTime().atZone(zone).getDayOfWeek(); + dailyStats.merge(dow, new long[]{1, s.getDurationSeconds()}, + (a, b) -> new long[]{a[0] + b[0], a[1] + b[1]}); + } + return dailyStats.entrySet().stream() + .map(e -> FavoriteReadingDaysResponse.builder() + .dayOfWeek(toSundayFirstDow(e.getKey())) + .dayName(e.getKey().getDisplayName(TextStyle.FULL, Locale.ENGLISH)) + .sessionCount(e.getValue()[0]) + .totalDurationSeconds(e.getValue()[1]) + .build()) + .sorted(Comparator.comparingInt(FavoriteReadingDaysResponse::getDayOfWeek)) + .toList(); + } + private static int toSundayFirstDow(DayOfWeek dow) { return (dow.getValue() % 7) + 1; } @@ -123,9 +155,9 @@ public class ReadingSessionService { ZoneId zone = ZoneId.systemDefault(); PeriodBounds bounds = computeYearBounds(year); - return groupByLocalDate( - readingSessionRepository.findSessionStartTimesByUserAndPeriod(userId, bounds.start(), bounds.end()), - zone); + try (var startTimes = readingSessionRepository.findReadingSessionStartTimesByUserAndPeriod(userId, bounds.start(), bounds.end())) { + return groupByLocalDate(startTimes, zone); + } } public List getSessionHeatmapForMonth(int year, int month) { @@ -133,9 +165,9 @@ public class ReadingSessionService { ZoneId zone = ZoneId.systemDefault(); PeriodBounds bounds = computeMonthBounds(year, month); - return groupByLocalDate( - readingSessionRepository.findSessionStartTimesByUserAndPeriod(userId, bounds.start(), bounds.end()), - zone); + try (var startTimes = readingSessionRepository.findReadingSessionStartTimesByUserAndPeriod(userId, bounds.start(), bounds.end())) { + return groupByLocalDate(startTimes, zone); + } } public List getSessionTimelineForWeek(int year, int week) { @@ -183,22 +215,8 @@ public class ReadingSessionService { ZoneId zone = ZoneId.systemDefault(); PeriodBounds bounds = computeOptionalBounds(year, month); - var sessions = readingSessionRepository.findSessionTimestampsByUser(userId, bounds.start(), bounds.end()); - - Map 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()) - .toList(); + var sessions = readingSessionRepository.findReadingSessionTimestampsByUser(userId, bounds.start(), bounds.end()); + return computePeakHours(sessions, zone); } public List getFavoriteReadingDays(Integer year, Integer month) { @@ -206,27 +224,8 @@ public class ReadingSessionService { ZoneId zone = ZoneId.systemDefault(); PeriodBounds bounds = computeOptionalBounds(year, month); - var sessions = readingSessionRepository.findSessionTimestampsByUser(userId, bounds.start(), bounds.end()); - - Map 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)) - .toList(); + var sessions = readingSessionRepository.findReadingSessionTimestampsByUser(userId, bounds.start(), bounds.end()); + return computeFavoriteDays(sessions, zone); } public List getGenreStatistics() { @@ -338,15 +337,31 @@ public class ReadingSessionService { BookLoreUser authenticatedUser = authenticationService.getAuthenticatedUser(); Long userId = authenticatedUser.getId(); - var sessions = readingSessionRepository.findPageTurnerSessionsByUser(userId); + List responses = new ArrayList<>(); + Set bookIdsToFetch = new HashSet<>(); - Map> sessionsByBook = sessions.stream() - .collect(Collectors.groupingBy(PageTurnerSessionDto::getBookId, LinkedHashMap::new, Collectors.toList())); + try (var sessionStream = readingSessionRepository.findPageTurnerSessionsByUser(userId)) { + Iterator it = sessionStream.iterator(); + Long currentBookId = null; + List currentBookSessions = new ArrayList<>(); - Set bookIds = sessionsByBook.keySet(); - Map> bookCategories = new HashMap<>(); - if (!bookIds.isEmpty()) { - bookRepository.findAllWithMetadataByIds(bookIds).forEach(book -> { + while (it.hasNext()) { + PageTurnerSessionDto session = it.next(); + if (currentBookId != null && !currentBookId.equals(session.getBookId())) { + processPageTurnerBook(currentBookSessions, responses, bookIdsToFetch); + currentBookSessions.clear(); + } + currentBookId = session.getBookId(); + currentBookSessions.add(session); + } + if (!currentBookSessions.isEmpty()) { + processPageTurnerBook(currentBookSessions, responses, bookIdsToFetch); + } + } + + if (!bookIdsToFetch.isEmpty()) { + Map> bookCategories = new HashMap<>(); + bookRepository.findAllWithMetadataByIds(bookIdsToFetch).forEach(book -> { List categories = book.getMetadata() != null && book.getMetadata().getCategories() != null ? book.getMetadata().getCategories().stream() .map(CategoryEntity::getName) @@ -355,90 +370,103 @@ public class ReadingSessionService { : List.of(); bookCategories.put(book.getId(), categories); }); + responses.forEach(r -> r.setCategories(bookCategories.getOrDefault(r.getBookId(), List.of()))); } - return sessionsByBook.entrySet().stream() - .filter(entry -> entry.getValue().size() >= 2) - .map(entry -> { - Long bookId = entry.getKey(); - List bookSessions = entry.getValue(); - PageTurnerSessionDto first = bookSessions.getFirst(); - - List durations = bookSessions.stream() - .map(s -> s.getDurationSeconds() != null ? s.getDurationSeconds().doubleValue() : 0.0) - .toList(); - - List gaps = new ArrayList<>(); - for (int i = 1; i < bookSessions.size(); i++) { - Instant prevEnd = bookSessions.get(i - 1).getEndTime(); - Instant currStart = bookSessions.get(i).getStartTime(); - if (prevEnd != null && currStart != null) { - gaps.add((double) ChronoUnit.HOURS.between(prevEnd, currStart)); - } - } - - double sessionAcceleration = linearRegressionSlope(durations); - double gapReduction = gaps.size() >= 2 ? linearRegressionSlope(gaps) : 0.0; - - int totalSessions = bookSessions.size(); - int lastQuarterStart = (int) Math.floor(totalSessions * 0.75); - double firstThreeQuartersAvg = durations.subList(0, lastQuarterStart).stream() - .mapToDouble(Double::doubleValue).average().orElse(0); - double lastQuarterAvg = durations.subList(lastQuarterStart, totalSessions).stream() - .mapToDouble(Double::doubleValue).average().orElse(0); - boolean finishBurst = lastQuarterAvg > firstThreeQuartersAvg; - - double accelScore = Math.min(1.0, Math.max(0.0, (sessionAcceleration + 50) / 100.0)); - double gapScore = Math.min(1.0, Math.max(0.0, (-gapReduction + 50) / 100.0)); - double burstScore = finishBurst ? 1.0 : 0.0; - - int gripScore = (int) Math.round( - Math.min(100, Math.max(0, accelScore * 35 + gapScore * 35 + burstScore * 30))); - - double avgDuration = durations.stream().mapToDouble(Double::doubleValue).average().orElse(0); - - return PageTurnerScoreResponse.builder() - .bookId(bookId) - .bookTitle(first.getBookTitle()) - .categories(bookCategories.getOrDefault(bookId, List.of())) - .pageCount(first.getPageCount()) - .personalRating(first.getPersonalRating()) - .gripScore(gripScore) - .totalSessions((long) totalSessions) - .avgSessionDurationSeconds(Math.round(avgDuration * 100.0) / 100.0) - .sessionAcceleration(Math.round(sessionAcceleration * 100.0) / 100.0) - .gapReduction(Math.round(gapReduction * 100.0) / 100.0) - .finishBurst(finishBurst) - .build(); - }) + return responses.stream() .sorted(Comparator.comparingInt(PageTurnerScoreResponse::getGripScore).reversed()) .toList(); } + private void processPageTurnerBook(List bookSessions, List responses, Set bookIdsToFetch) { + if (bookSessions.size() < 2) return; + + PageTurnerSessionDto first = bookSessions.getFirst(); + Long bookId = first.getBookId(); + bookIdsToFetch.add(bookId); + + List durations = bookSessions.stream() + .map(s -> s.getDurationSeconds() != null ? s.getDurationSeconds().doubleValue() : 0.0) + .toList(); + + List gaps = new ArrayList<>(); + for (int i = 1; i < bookSessions.size(); i++) { + Instant prevEnd = bookSessions.get(i - 1).getEndTime(); + Instant currStart = bookSessions.get(i).getStartTime(); + if (prevEnd != null && currStart != null) { + gaps.add((double) ChronoUnit.HOURS.between(prevEnd, currStart)); + } + } + + double sessionAcceleration = linearRegressionSlope(durations); + double gapReduction = gaps.size() >= 2 ? linearRegressionSlope(gaps) : 0.0; + + int totalSessions = bookSessions.size(); + int lastQuarterStart = (int) Math.floor(totalSessions * 0.75); + double firstThreeQuartersAvg = durations.subList(0, lastQuarterStart).stream() + .mapToDouble(Double::doubleValue).average().orElse(0); + double lastQuarterAvg = durations.subList(lastQuarterStart, totalSessions).stream() + .mapToDouble(Double::doubleValue).average().orElse(0); + boolean finishBurst = lastQuarterAvg > firstThreeQuartersAvg; + + double accelScore = Math.min(1.0, Math.max(0.0, (sessionAcceleration + 50) / 100.0)); + double gapScore = Math.min(1.0, Math.max(0.0, (-gapReduction + 50) / 100.0)); + double burstScore = finishBurst ? 1.0 : 0.0; + + int gripScore = (int) Math.round( + Math.min(100, Math.max(0, accelScore * 35 + gapScore * 35 + burstScore * 30))); + + double avgDuration = durations.stream().mapToDouble(Double::doubleValue).average().orElse(0); + + responses.add(PageTurnerScoreResponse.builder() + .bookId(bookId) + .bookTitle(first.getBookTitle()) + .pageCount(first.getPageCount()) + .personalRating(first.getPersonalRating()) + .gripScore(gripScore) + .totalSessions((long) totalSessions) + .avgSessionDurationSeconds(Math.round(avgDuration * 100.0) / 100.0) + .sessionAcceleration(Math.round(sessionAcceleration * 100.0) / 100.0) + .gapReduction(Math.round(gapReduction * 100.0) / 100.0) + .finishBurst(finishBurst) + .build()); + } + private static final int COMPLETION_RACE_BOOK_LIMIT = 10; public List getCompletionRace(int year) { BookLoreUser authenticatedUser = authenticationService.getAuthenticatedUser(); Long userId = authenticatedUser.getId(); - var allSessions = readingSessionRepository.findCompletionRaceSessionsByUserAndYear(userId, year); + Deque> bookBuffer = new ArrayDeque<>(); - // Collect unique book IDs in order of appearance, take last N (most recently finished) - LinkedHashSet allBookIds = allSessions.stream() - .map(CompletionRaceSessionDto::getBookId) - .collect(Collectors.toCollection(LinkedHashSet::new)); + try (var sessionStream = readingSessionRepository.findCompletionRaceSessionsByUserAndYear(userId, year)) { + Iterator it = sessionStream.iterator(); + Long currentBookId = null; + List currentBookSessions = new ArrayList<>(); - Set limitedBookIds; - if (allBookIds.size() > COMPLETION_RACE_BOOK_LIMIT) { - limitedBookIds = allBookIds.stream() - .skip(allBookIds.size() - COMPLETION_RACE_BOOK_LIMIT) - .collect(Collectors.toSet()); - } else { - limitedBookIds = allBookIds; + while (it.hasNext()) { + CompletionRaceSessionDto session = it.next(); + if (currentBookId != null && !currentBookId.equals(session.getBookId())) { + bookBuffer.addLast(new ArrayList<>(currentBookSessions)); + if (bookBuffer.size() > COMPLETION_RACE_BOOK_LIMIT) { + bookBuffer.removeFirst(); + } + currentBookSessions.clear(); + } + currentBookId = session.getBookId(); + currentBookSessions.add(session); + } + if (!currentBookSessions.isEmpty()) { + bookBuffer.addLast(currentBookSessions); + if (bookBuffer.size() > COMPLETION_RACE_BOOK_LIMIT) { + bookBuffer.removeFirst(); + } + } } - return allSessions.stream() - .filter(dto -> limitedBookIds.contains(dto.getBookId())) + return bookBuffer.stream() + .flatMap(List::stream) .map(dto -> CompletionRaceResponse.builder() .bookId(dto.getBookId()) .bookTitle(dto.getBookTitle()) @@ -452,7 +480,9 @@ public class ReadingSessionService { Long userId = authenticationService.getAuthenticatedUser().getId(); ZoneId zone = ZoneId.systemDefault(); - return groupByLocalDate(readingSessionRepository.findAllSessionStartTimesByUser(userId), zone); + try (var startTimes = readingSessionRepository.findAllReadingSessionStartTimesByUser(userId)) { + return groupByLocalDate(startTimes, zone); + } } public BookDistributionsResponse getBookDistributions() { @@ -551,10 +581,12 @@ public class ReadingSessionService { Long userId = authenticationService.getAuthenticatedUser().getId(); ZoneId zone = ZoneId.systemDefault(); - Set readingDays = readingSessionRepository.findAllSessionStartTimesByUser(userId) - .stream() - .map(instant -> instant.atZone(zone).toLocalDate()) - .collect(Collectors.toCollection(TreeSet::new)); + Set readingDays; + try (var startTimes = readingSessionRepository.findAllReadingSessionStartTimesByUser(userId)) { + readingDays = startTimes + .map(instant -> instant.atZone(zone).toLocalDate()) + .collect(Collectors.toCollection(TreeSet::new)); + } LocalDate today = LocalDate.now(zone); @@ -804,26 +836,22 @@ public class ReadingSessionService { ZoneId zone = ZoneId.systemDefault(); PeriodBounds bounds = computeOptionalBounds(year, month); - var sessions = readingSessionRepository.findListeningTimestampsByUser(userId, bounds.start(), bounds.end()); + var sessions = readingSessionRepository.findListeningSessionTimestampsByUser(userId, bounds.start(), bounds.end()); + return computePeakHours(sessions, zone); + } - Map 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]}); - } + public List getListeningFavoriteDays(Integer year, Integer month) { + Long userId = authenticationService.getAuthenticatedUser().getId(); + ZoneId zone = ZoneId.systemDefault(); + PeriodBounds bounds = computeOptionalBounds(year, month); - return hourlyTotals.entrySet().stream() - .map(e -> PeakHoursResponse.builder() - .hourOfDay(e.getKey()) - .sessionCount(e.getValue()[0]) - .totalDurationSeconds(e.getValue()[1]) - .build()) - .toList(); + var sessions = readingSessionRepository.findListeningSessionTimestampsByUser(userId, bounds.start(), bounds.end()); + return computeFavoriteDays(sessions, zone); } public List getListeningGenreStatistics() { Long userId = authenticationService.getAuthenticatedUser().getId(); + return readingSessionRepository.findListeningGenreStatisticsByUser(userId) .stream() .map(dto -> { @@ -844,6 +872,7 @@ public class ReadingSessionService { public List getListeningAuthorStats() { Long userId = authenticationService.getAuthenticatedUser().getId(); + return readingSessionRepository.findListeningAuthorStatsByUser(userId) .stream() .map(dto -> ListeningAuthorResponse.builder()