refactor(stats): push bulk queries to streams, deduplicate aggregation logic (#937)
This commit is contained in:
@@ -296,6 +296,19 @@ public class UserStatsController {
|
|||||||
return ResponseEntity.ok(readingSessionService.getListeningPeakHours(year, month));
|
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<List<FavoriteReadingDaysResponse>> getListeningFavoriteDays(
|
||||||
|
@RequestParam(required = false) Integer year,
|
||||||
|
@RequestParam(required = false) Integer month) {
|
||||||
|
return ResponseEntity.ok(readingSessionService.getListeningFavoriteDays(year, month));
|
||||||
|
}
|
||||||
|
|
||||||
@Operation(
|
@Operation(
|
||||||
summary = "Get listening genre statistics",
|
summary = "Get listening genre statistics",
|
||||||
description = "Returns listening statistics grouped by audiobook genres/categories.",
|
description = "Returns listening statistics grouped by audiobook genres/categories.",
|
||||||
|
|||||||
@@ -3,6 +3,8 @@ package org.booklore.repository;
|
|||||||
import org.booklore.model.dto.*;
|
import org.booklore.model.dto.*;
|
||||||
|
|
||||||
import org.booklore.model.entity.ReadingSessionEntity;
|
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.Page;
|
||||||
import org.springframework.data.domain.Pageable;
|
import org.springframework.data.domain.Pageable;
|
||||||
import org.springframework.data.jpa.repository.JpaRepository;
|
import org.springframework.data.jpa.repository.JpaRepository;
|
||||||
@@ -11,19 +13,37 @@ import org.springframework.data.repository.query.Param;
|
|||||||
import org.springframework.stereotype.Repository;
|
import org.springframework.stereotype.Repository;
|
||||||
|
|
||||||
import java.time.Instant;
|
import java.time.Instant;
|
||||||
|
import java.time.LocalDate;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
import java.util.stream.Stream;
|
||||||
|
|
||||||
@Repository
|
@Repository
|
||||||
public interface ReadingSessionRepository extends JpaRepository<ReadingSessionEntity, Long> {
|
public interface ReadingSessionRepository extends JpaRepository<ReadingSessionEntity, Long> {
|
||||||
|
|
||||||
|
@QueryHints(@QueryHint(name = "org.hibernate.fetchSize", value = "200"))
|
||||||
@Query("""
|
@Query("""
|
||||||
SELECT rs.startTime
|
SELECT rs.startTime
|
||||||
FROM ReadingSessionEntity rs
|
FROM ReadingSessionEntity rs
|
||||||
WHERE rs.user.id = :userId
|
WHERE rs.user.id = :userId
|
||||||
|
AND rs.bookType != org.booklore.model.enums.BookFileType.AUDIOBOOK
|
||||||
AND rs.startTime >= :periodStart AND rs.startTime < :periodEnd
|
AND rs.startTime >= :periodStart AND rs.startTime < :periodEnd
|
||||||
ORDER BY rs.startTime
|
ORDER BY rs.startTime
|
||||||
""")
|
""")
|
||||||
List<Instant> findSessionStartTimesByUserAndPeriod(
|
Stream<Instant> 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<Instant> findListeningSessionStartTimesByUserAndPeriod(
|
||||||
@Param("userId") Long userId,
|
@Param("userId") Long userId,
|
||||||
@Param("periodStart") Instant periodStart,
|
@Param("periodStart") Instant periodStart,
|
||||||
@Param("periodEnd") Instant periodEnd);
|
@Param("periodEnd") Instant periodEnd);
|
||||||
@@ -131,6 +151,7 @@ public interface ReadingSessionRepository extends JpaRepository<ReadingSessionEn
|
|||||||
@Param("bookId") Long bookId,
|
@Param("bookId") Long bookId,
|
||||||
Pageable pageable);
|
Pageable pageable);
|
||||||
|
|
||||||
|
@QueryHints(@QueryHint(name = "org.hibernate.fetchSize", value = "200"))
|
||||||
@Query("""
|
@Query("""
|
||||||
SELECT
|
SELECT
|
||||||
b.id as bookId,
|
b.id as bookId,
|
||||||
@@ -149,8 +170,9 @@ public interface ReadingSessionRepository extends JpaRepository<ReadingSessionEn
|
|||||||
AND coalesce(ubp.dateFinished, ubp.readStatusModifiedTime, ubp.lastReadTime) IS NOT NULL
|
AND coalesce(ubp.dateFinished, ubp.readStatusModifiedTime, ubp.lastReadTime) IS NOT NULL
|
||||||
ORDER BY b.id, rs.startTime ASC
|
ORDER BY b.id, rs.startTime ASC
|
||||||
""")
|
""")
|
||||||
List<PageTurnerSessionDto> findPageTurnerSessionsByUser(@Param("userId") Long userId);
|
Stream<PageTurnerSessionDto> findPageTurnerSessionsByUser(@Param("userId") Long userId);
|
||||||
|
|
||||||
|
@QueryHints(@QueryHint(name = "org.hibernate.fetchSize", value = "200"))
|
||||||
@Query("""
|
@Query("""
|
||||||
SELECT
|
SELECT
|
||||||
b.id as bookId,
|
b.id as bookId,
|
||||||
@@ -166,17 +188,59 @@ public interface ReadingSessionRepository extends JpaRepository<ReadingSessionEn
|
|||||||
AND rs.endProgress IS NOT NULL
|
AND rs.endProgress IS NOT NULL
|
||||||
ORDER BY b.id, rs.startTime ASC
|
ORDER BY b.id, rs.startTime ASC
|
||||||
""")
|
""")
|
||||||
List<CompletionRaceSessionDto> findCompletionRaceSessionsByUserAndYear(
|
Stream<CompletionRaceSessionDto> findCompletionRaceSessionsByUserAndYear(
|
||||||
@Param("userId") Long userId,
|
@Param("userId") Long userId,
|
||||||
@Param("year") int year);
|
@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<SessionTimestampDto> 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<SessionTimestampDto> findListeningSessionTimestampsByUser(
|
||||||
|
@Param("userId") Long userId,
|
||||||
|
@Param("periodStart") Instant periodStart,
|
||||||
|
@Param("periodEnd") Instant periodEnd);
|
||||||
|
|
||||||
|
@QueryHints(@QueryHint(name = "org.hibernate.fetchSize", value = "200"))
|
||||||
@Query("""
|
@Query("""
|
||||||
SELECT rs.startTime
|
SELECT rs.startTime
|
||||||
FROM ReadingSessionEntity rs
|
FROM ReadingSessionEntity rs
|
||||||
WHERE rs.user.id = :userId
|
WHERE rs.user.id = :userId
|
||||||
|
AND rs.bookType != org.booklore.model.enums.BookFileType.AUDIOBOOK
|
||||||
ORDER BY rs.startTime
|
ORDER BY rs.startTime
|
||||||
""")
|
""")
|
||||||
List<Instant> findAllSessionStartTimesByUser(@Param("userId") Long userId);
|
Stream<Instant> 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<Instant> findAllListeningSessionStartTimesByUser(@Param("userId") Long userId);
|
||||||
|
|
||||||
// ========================================================================
|
// ========================================================================
|
||||||
// Listening (audiobook) stats
|
// Listening (audiobook) stats
|
||||||
|
|||||||
@@ -4,11 +4,8 @@ import lombok.RequiredArgsConstructor;
|
|||||||
import lombok.extern.slf4j.Slf4j;
|
import lombok.extern.slf4j.Slf4j;
|
||||||
import org.booklore.config.security.service.AuthenticationService;
|
import org.booklore.config.security.service.AuthenticationService;
|
||||||
import org.booklore.exception.ApiError;
|
import org.booklore.exception.ApiError;
|
||||||
import org.booklore.model.dto.BookLoreUser;
|
import org.booklore.model.dto.*;
|
||||||
import org.booklore.model.dto.CompletionRaceSessionDto;
|
|
||||||
import org.booklore.model.dto.PageTurnerSessionDto;
|
|
||||||
import org.booklore.model.dto.request.ReadingSessionRequest;
|
import org.booklore.model.dto.request.ReadingSessionRequest;
|
||||||
import org.booklore.model.dto.ProgressPercentDto;
|
|
||||||
import org.booklore.model.dto.response.*;
|
import org.booklore.model.dto.response.*;
|
||||||
import org.booklore.model.entity.BookEntity;
|
import org.booklore.model.entity.BookEntity;
|
||||||
import org.booklore.model.entity.BookLoreUserEntity;
|
import org.booklore.model.entity.BookLoreUserEntity;
|
||||||
@@ -38,6 +35,7 @@ import java.time.temporal.WeekFields;
|
|||||||
import java.util.*;
|
import java.util.*;
|
||||||
import java.util.function.Function;
|
import java.util.function.Function;
|
||||||
import java.util.stream.Collectors;
|
import java.util.stream.Collectors;
|
||||||
|
import java.util.stream.Stream;
|
||||||
|
|
||||||
@Slf4j
|
@Slf4j
|
||||||
@Service
|
@Service
|
||||||
@@ -73,8 +71,8 @@ public class ReadingSessionService {
|
|||||||
return computeMonthBounds(year, month);
|
return computeMonthBounds(year, month);
|
||||||
}
|
}
|
||||||
|
|
||||||
private List<ReadingSessionHeatmapResponse> groupByLocalDate(List<Instant> startTimes, ZoneId zone) {
|
private List<ReadingSessionHeatmapResponse> groupByLocalDate(Stream<Instant> startTimes, ZoneId zone) {
|
||||||
return startTimes.stream()
|
return startTimes
|
||||||
.map(instant -> instant.atZone(zone).toLocalDate())
|
.map(instant -> instant.atZone(zone).toLocalDate())
|
||||||
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
|
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
|
||||||
.entrySet().stream()
|
.entrySet().stream()
|
||||||
@@ -86,6 +84,40 @@ public class ReadingSessionService {
|
|||||||
.toList();
|
.toList();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private List<PeakHoursResponse> computePeakHours(List<SessionTimestampDto> sessions, ZoneId zone) {
|
||||||
|
Map<Integer, long[]> 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<FavoriteReadingDaysResponse> computeFavoriteDays(List<SessionTimestampDto> sessions, ZoneId zone) {
|
||||||
|
Map<DayOfWeek, long[]> 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) {
|
private static int toSundayFirstDow(DayOfWeek dow) {
|
||||||
return (dow.getValue() % 7) + 1;
|
return (dow.getValue() % 7) + 1;
|
||||||
}
|
}
|
||||||
@@ -123,9 +155,9 @@ public class ReadingSessionService {
|
|||||||
ZoneId zone = ZoneId.systemDefault();
|
ZoneId zone = ZoneId.systemDefault();
|
||||||
PeriodBounds bounds = computeYearBounds(year);
|
PeriodBounds bounds = computeYearBounds(year);
|
||||||
|
|
||||||
return groupByLocalDate(
|
try (var startTimes = readingSessionRepository.findReadingSessionStartTimesByUserAndPeriod(userId, bounds.start(), bounds.end())) {
|
||||||
readingSessionRepository.findSessionStartTimesByUserAndPeriod(userId, bounds.start(), bounds.end()),
|
return groupByLocalDate(startTimes, zone);
|
||||||
zone);
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public List<ReadingSessionHeatmapResponse> getSessionHeatmapForMonth(int year, int month) {
|
public List<ReadingSessionHeatmapResponse> getSessionHeatmapForMonth(int year, int month) {
|
||||||
@@ -133,9 +165,9 @@ public class ReadingSessionService {
|
|||||||
ZoneId zone = ZoneId.systemDefault();
|
ZoneId zone = ZoneId.systemDefault();
|
||||||
PeriodBounds bounds = computeMonthBounds(year, month);
|
PeriodBounds bounds = computeMonthBounds(year, month);
|
||||||
|
|
||||||
return groupByLocalDate(
|
try (var startTimes = readingSessionRepository.findReadingSessionStartTimesByUserAndPeriod(userId, bounds.start(), bounds.end())) {
|
||||||
readingSessionRepository.findSessionStartTimesByUserAndPeriod(userId, bounds.start(), bounds.end()),
|
return groupByLocalDate(startTimes, zone);
|
||||||
zone);
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public List<ReadingSessionTimelineResponse> getSessionTimelineForWeek(int year, int week) {
|
public List<ReadingSessionTimelineResponse> getSessionTimelineForWeek(int year, int week) {
|
||||||
@@ -183,22 +215,8 @@ public class ReadingSessionService {
|
|||||||
ZoneId zone = ZoneId.systemDefault();
|
ZoneId zone = ZoneId.systemDefault();
|
||||||
PeriodBounds bounds = computeOptionalBounds(year, month);
|
PeriodBounds bounds = computeOptionalBounds(year, month);
|
||||||
|
|
||||||
var sessions = readingSessionRepository.findSessionTimestampsByUser(userId, bounds.start(), bounds.end());
|
var sessions = readingSessionRepository.findReadingSessionTimestampsByUser(userId, bounds.start(), bounds.end());
|
||||||
|
return computePeakHours(sessions, zone);
|
||||||
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())
|
|
||||||
.toList();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public List<FavoriteReadingDaysResponse> getFavoriteReadingDays(Integer year, Integer month) {
|
public List<FavoriteReadingDaysResponse> getFavoriteReadingDays(Integer year, Integer month) {
|
||||||
@@ -206,27 +224,8 @@ public class ReadingSessionService {
|
|||||||
ZoneId zone = ZoneId.systemDefault();
|
ZoneId zone = ZoneId.systemDefault();
|
||||||
PeriodBounds bounds = computeOptionalBounds(year, month);
|
PeriodBounds bounds = computeOptionalBounds(year, month);
|
||||||
|
|
||||||
var sessions = readingSessionRepository.findSessionTimestampsByUser(userId, bounds.start(), bounds.end());
|
var sessions = readingSessionRepository.findReadingSessionTimestampsByUser(userId, bounds.start(), bounds.end());
|
||||||
|
return computeFavoriteDays(sessions, zone);
|
||||||
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))
|
|
||||||
.toList();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public List<GenreStatisticsResponse> getGenreStatistics() {
|
public List<GenreStatisticsResponse> getGenreStatistics() {
|
||||||
@@ -338,15 +337,31 @@ public class ReadingSessionService {
|
|||||||
BookLoreUser authenticatedUser = authenticationService.getAuthenticatedUser();
|
BookLoreUser authenticatedUser = authenticationService.getAuthenticatedUser();
|
||||||
Long userId = authenticatedUser.getId();
|
Long userId = authenticatedUser.getId();
|
||||||
|
|
||||||
var sessions = readingSessionRepository.findPageTurnerSessionsByUser(userId);
|
List<PageTurnerScoreResponse> responses = new ArrayList<>();
|
||||||
|
Set<Long> bookIdsToFetch = new HashSet<>();
|
||||||
|
|
||||||
Map<Long, List<PageTurnerSessionDto>> sessionsByBook = sessions.stream()
|
try (var sessionStream = readingSessionRepository.findPageTurnerSessionsByUser(userId)) {
|
||||||
.collect(Collectors.groupingBy(PageTurnerSessionDto::getBookId, LinkedHashMap::new, Collectors.toList()));
|
Iterator<PageTurnerSessionDto> it = sessionStream.iterator();
|
||||||
|
Long currentBookId = null;
|
||||||
|
List<PageTurnerSessionDto> currentBookSessions = new ArrayList<>();
|
||||||
|
|
||||||
Set<Long> bookIds = sessionsByBook.keySet();
|
while (it.hasNext()) {
|
||||||
Map<Long, List<String>> bookCategories = new HashMap<>();
|
PageTurnerSessionDto session = it.next();
|
||||||
if (!bookIds.isEmpty()) {
|
if (currentBookId != null && !currentBookId.equals(session.getBookId())) {
|
||||||
bookRepository.findAllWithMetadataByIds(bookIds).forEach(book -> {
|
processPageTurnerBook(currentBookSessions, responses, bookIdsToFetch);
|
||||||
|
currentBookSessions.clear();
|
||||||
|
}
|
||||||
|
currentBookId = session.getBookId();
|
||||||
|
currentBookSessions.add(session);
|
||||||
|
}
|
||||||
|
if (!currentBookSessions.isEmpty()) {
|
||||||
|
processPageTurnerBook(currentBookSessions, responses, bookIdsToFetch);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!bookIdsToFetch.isEmpty()) {
|
||||||
|
Map<Long, List<String>> bookCategories = new HashMap<>();
|
||||||
|
bookRepository.findAllWithMetadataByIds(bookIdsToFetch).forEach(book -> {
|
||||||
List<String> categories = book.getMetadata() != null && book.getMetadata().getCategories() != null
|
List<String> categories = book.getMetadata() != null && book.getMetadata().getCategories() != null
|
||||||
? book.getMetadata().getCategories().stream()
|
? book.getMetadata().getCategories().stream()
|
||||||
.map(CategoryEntity::getName)
|
.map(CategoryEntity::getName)
|
||||||
@@ -355,90 +370,103 @@ public class ReadingSessionService {
|
|||||||
: List.of();
|
: List.of();
|
||||||
bookCategories.put(book.getId(), categories);
|
bookCategories.put(book.getId(), categories);
|
||||||
});
|
});
|
||||||
|
responses.forEach(r -> r.setCategories(bookCategories.getOrDefault(r.getBookId(), List.of())));
|
||||||
}
|
}
|
||||||
|
|
||||||
return sessionsByBook.entrySet().stream()
|
return responses.stream()
|
||||||
.filter(entry -> entry.getValue().size() >= 2)
|
|
||||||
.map(entry -> {
|
|
||||||
Long bookId = entry.getKey();
|
|
||||||
List<PageTurnerSessionDto> bookSessions = entry.getValue();
|
|
||||||
PageTurnerSessionDto first = bookSessions.getFirst();
|
|
||||||
|
|
||||||
List<Double> durations = bookSessions.stream()
|
|
||||||
.map(s -> s.getDurationSeconds() != null ? s.getDurationSeconds().doubleValue() : 0.0)
|
|
||||||
.toList();
|
|
||||||
|
|
||||||
List<Double> 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();
|
|
||||||
})
|
|
||||||
.sorted(Comparator.comparingInt(PageTurnerScoreResponse::getGripScore).reversed())
|
.sorted(Comparator.comparingInt(PageTurnerScoreResponse::getGripScore).reversed())
|
||||||
.toList();
|
.toList();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private void processPageTurnerBook(List<PageTurnerSessionDto> bookSessions, List<PageTurnerScoreResponse> responses, Set<Long> bookIdsToFetch) {
|
||||||
|
if (bookSessions.size() < 2) return;
|
||||||
|
|
||||||
|
PageTurnerSessionDto first = bookSessions.getFirst();
|
||||||
|
Long bookId = first.getBookId();
|
||||||
|
bookIdsToFetch.add(bookId);
|
||||||
|
|
||||||
|
List<Double> durations = bookSessions.stream()
|
||||||
|
.map(s -> s.getDurationSeconds() != null ? s.getDurationSeconds().doubleValue() : 0.0)
|
||||||
|
.toList();
|
||||||
|
|
||||||
|
List<Double> 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;
|
private static final int COMPLETION_RACE_BOOK_LIMIT = 10;
|
||||||
|
|
||||||
public List<CompletionRaceResponse> getCompletionRace(int year) {
|
public List<CompletionRaceResponse> getCompletionRace(int year) {
|
||||||
BookLoreUser authenticatedUser = authenticationService.getAuthenticatedUser();
|
BookLoreUser authenticatedUser = authenticationService.getAuthenticatedUser();
|
||||||
Long userId = authenticatedUser.getId();
|
Long userId = authenticatedUser.getId();
|
||||||
|
|
||||||
var allSessions = readingSessionRepository.findCompletionRaceSessionsByUserAndYear(userId, year);
|
Deque<List<CompletionRaceSessionDto>> bookBuffer = new ArrayDeque<>();
|
||||||
|
|
||||||
// Collect unique book IDs in order of appearance, take last N (most recently finished)
|
try (var sessionStream = readingSessionRepository.findCompletionRaceSessionsByUserAndYear(userId, year)) {
|
||||||
LinkedHashSet<Long> allBookIds = allSessions.stream()
|
Iterator<CompletionRaceSessionDto> it = sessionStream.iterator();
|
||||||
.map(CompletionRaceSessionDto::getBookId)
|
Long currentBookId = null;
|
||||||
.collect(Collectors.toCollection(LinkedHashSet::new));
|
List<CompletionRaceSessionDto> currentBookSessions = new ArrayList<>();
|
||||||
|
|
||||||
Set<Long> limitedBookIds;
|
while (it.hasNext()) {
|
||||||
if (allBookIds.size() > COMPLETION_RACE_BOOK_LIMIT) {
|
CompletionRaceSessionDto session = it.next();
|
||||||
limitedBookIds = allBookIds.stream()
|
if (currentBookId != null && !currentBookId.equals(session.getBookId())) {
|
||||||
.skip(allBookIds.size() - COMPLETION_RACE_BOOK_LIMIT)
|
bookBuffer.addLast(new ArrayList<>(currentBookSessions));
|
||||||
.collect(Collectors.toSet());
|
if (bookBuffer.size() > COMPLETION_RACE_BOOK_LIMIT) {
|
||||||
} else {
|
bookBuffer.removeFirst();
|
||||||
limitedBookIds = allBookIds;
|
}
|
||||||
|
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()
|
return bookBuffer.stream()
|
||||||
.filter(dto -> limitedBookIds.contains(dto.getBookId()))
|
.flatMap(List::stream)
|
||||||
.map(dto -> CompletionRaceResponse.builder()
|
.map(dto -> CompletionRaceResponse.builder()
|
||||||
.bookId(dto.getBookId())
|
.bookId(dto.getBookId())
|
||||||
.bookTitle(dto.getBookTitle())
|
.bookTitle(dto.getBookTitle())
|
||||||
@@ -452,7 +480,9 @@ public class ReadingSessionService {
|
|||||||
Long userId = authenticationService.getAuthenticatedUser().getId();
|
Long userId = authenticationService.getAuthenticatedUser().getId();
|
||||||
ZoneId zone = ZoneId.systemDefault();
|
ZoneId zone = ZoneId.systemDefault();
|
||||||
|
|
||||||
return groupByLocalDate(readingSessionRepository.findAllSessionStartTimesByUser(userId), zone);
|
try (var startTimes = readingSessionRepository.findAllReadingSessionStartTimesByUser(userId)) {
|
||||||
|
return groupByLocalDate(startTimes, zone);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public BookDistributionsResponse getBookDistributions() {
|
public BookDistributionsResponse getBookDistributions() {
|
||||||
@@ -551,10 +581,12 @@ public class ReadingSessionService {
|
|||||||
Long userId = authenticationService.getAuthenticatedUser().getId();
|
Long userId = authenticationService.getAuthenticatedUser().getId();
|
||||||
ZoneId zone = ZoneId.systemDefault();
|
ZoneId zone = ZoneId.systemDefault();
|
||||||
|
|
||||||
Set<LocalDate> readingDays = readingSessionRepository.findAllSessionStartTimesByUser(userId)
|
Set<LocalDate> readingDays;
|
||||||
.stream()
|
try (var startTimes = readingSessionRepository.findAllReadingSessionStartTimesByUser(userId)) {
|
||||||
.map(instant -> instant.atZone(zone).toLocalDate())
|
readingDays = startTimes
|
||||||
.collect(Collectors.toCollection(TreeSet::new));
|
.map(instant -> instant.atZone(zone).toLocalDate())
|
||||||
|
.collect(Collectors.toCollection(TreeSet::new));
|
||||||
|
}
|
||||||
|
|
||||||
LocalDate today = LocalDate.now(zone);
|
LocalDate today = LocalDate.now(zone);
|
||||||
|
|
||||||
@@ -804,26 +836,22 @@ public class ReadingSessionService {
|
|||||||
ZoneId zone = ZoneId.systemDefault();
|
ZoneId zone = ZoneId.systemDefault();
|
||||||
PeriodBounds bounds = computeOptionalBounds(year, month);
|
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<Integer, long[]> hourlyTotals = new TreeMap<>();
|
public List<FavoriteReadingDaysResponse> getListeningFavoriteDays(Integer year, Integer month) {
|
||||||
for (var dto : sessions) {
|
Long userId = authenticationService.getAuthenticatedUser().getId();
|
||||||
int hour = dto.getStartTime().atZone(zone).getHour();
|
ZoneId zone = ZoneId.systemDefault();
|
||||||
hourlyTotals.merge(hour, new long[]{1, dto.getDurationSeconds()},
|
PeriodBounds bounds = computeOptionalBounds(year, month);
|
||||||
(a, b) -> new long[]{a[0] + b[0], a[1] + b[1]});
|
|
||||||
}
|
|
||||||
|
|
||||||
return hourlyTotals.entrySet().stream()
|
var sessions = readingSessionRepository.findListeningSessionTimestampsByUser(userId, bounds.start(), bounds.end());
|
||||||
.map(e -> PeakHoursResponse.builder()
|
return computeFavoriteDays(sessions, zone);
|
||||||
.hourOfDay(e.getKey())
|
|
||||||
.sessionCount(e.getValue()[0])
|
|
||||||
.totalDurationSeconds(e.getValue()[1])
|
|
||||||
.build())
|
|
||||||
.toList();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public List<GenreStatisticsResponse> getListeningGenreStatistics() {
|
public List<GenreStatisticsResponse> getListeningGenreStatistics() {
|
||||||
Long userId = authenticationService.getAuthenticatedUser().getId();
|
Long userId = authenticationService.getAuthenticatedUser().getId();
|
||||||
|
|
||||||
return readingSessionRepository.findListeningGenreStatisticsByUser(userId)
|
return readingSessionRepository.findListeningGenreStatisticsByUser(userId)
|
||||||
.stream()
|
.stream()
|
||||||
.map(dto -> {
|
.map(dto -> {
|
||||||
@@ -844,6 +872,7 @@ public class ReadingSessionService {
|
|||||||
|
|
||||||
public List<ListeningAuthorResponse> getListeningAuthorStats() {
|
public List<ListeningAuthorResponse> getListeningAuthorStats() {
|
||||||
Long userId = authenticationService.getAuthenticatedUser().getId();
|
Long userId = authenticationService.getAuthenticatedUser().getId();
|
||||||
|
|
||||||
return readingSessionRepository.findListeningAuthorStatsByUser(userId)
|
return readingSessionRepository.findListeningAuthorStatsByUser(userId)
|
||||||
.stream()
|
.stream()
|
||||||
.map(dto -> ListeningAuthorResponse.builder()
|
.map(dto -> ListeningAuthorResponse.builder()
|
||||||
|
|||||||
Reference in New Issue
Block a user