Introduce reading session tracking with visual insights (#1957)
* Introduce reading session tracking with visual insights (#1957) --------- Co-authored-by: acx10 <acx10@users.noreply.github.com>
This commit is contained in:
+61
@@ -0,0 +1,61 @@
|
||||
package com.adityachandel.booklore.controller;
|
||||
|
||||
import com.adityachandel.booklore.model.dto.request.ReadingSessionRequest;
|
||||
import com.adityachandel.booklore.model.dto.response.ReadingSessionHeatmapResponse;
|
||||
import com.adityachandel.booklore.model.dto.response.ReadingSessionTimelineResponse;
|
||||
import com.adityachandel.booklore.service.ReadingSessionService;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.responses.ApiResponse;
|
||||
import io.swagger.v3.oas.annotations.responses.ApiResponses;
|
||||
import jakarta.validation.Valid;
|
||||
import lombok.AllArgsConstructor;
|
||||
import org.springframework.format.annotation.DateTimeFormat;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
|
||||
@RestController
|
||||
@AllArgsConstructor
|
||||
@RequestMapping("/api/v1/reading-sessions")
|
||||
public class ReadingSessionController {
|
||||
|
||||
private final ReadingSessionService readingSessionService;
|
||||
|
||||
@Operation(summary = "Record a reading session", description = "Receive telemetry from the reader client and persist or log the session.")
|
||||
@ApiResponses({
|
||||
@ApiResponse(responseCode = "202", description = "Reading session accepted"),
|
||||
@ApiResponse(responseCode = "400", description = "Invalid payload")
|
||||
})
|
||||
@PostMapping
|
||||
public ResponseEntity<Void> recordReadingSession(@RequestBody @Valid ReadingSessionRequest request) {
|
||||
readingSessionService.recordSession(request);
|
||||
return ResponseEntity.accepted().build();
|
||||
}
|
||||
|
||||
@Operation(summary = "Get reading session heatmap for a year", description = "Returns daily reading session counts for the authenticated user for a specific year")
|
||||
@ApiResponses({
|
||||
@ApiResponse(responseCode = "200", description = "Heatmap data retrieved successfully"),
|
||||
@ApiResponse(responseCode = "401", description = "Unauthorized")
|
||||
})
|
||||
@GetMapping("/heatmap/year/{year}")
|
||||
public ResponseEntity<List<ReadingSessionHeatmapResponse>> getHeatmapForYear(@PathVariable int year) {
|
||||
List<ReadingSessionHeatmapResponse> heatmapData = readingSessionService.getSessionHeatmapForYear(year);
|
||||
return ResponseEntity.ok(heatmapData);
|
||||
}
|
||||
|
||||
@Operation(summary = "Get reading session timeline for a week", description = "Returns reading sessions grouped by book for calendar timeline view")
|
||||
@ApiResponses({
|
||||
@ApiResponse(responseCode = "200", description = "Timeline data retrieved successfully"),
|
||||
@ApiResponse(responseCode = "400", description = "Invalid week or year"),
|
||||
@ApiResponse(responseCode = "401", description = "Unauthorized")
|
||||
})
|
||||
@GetMapping("/timeline/week/{year}/{week}")
|
||||
public ResponseEntity<List<ReadingSessionTimelineResponse>> getTimelineForWeek(
|
||||
@PathVariable int year,
|
||||
@PathVariable int week) {
|
||||
List<ReadingSessionTimelineResponse> timelineData = readingSessionService.getSessionTimelineForWeek(year, week);
|
||||
return ResponseEntity.ok(timelineData);
|
||||
}
|
||||
}
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
package com.adityachandel.booklore.model.dto;
|
||||
|
||||
import java.time.LocalDate;
|
||||
|
||||
public interface ReadingSessionCountDto {
|
||||
LocalDate getDate();
|
||||
Long getCount();
|
||||
}
|
||||
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
package com.adityachandel.booklore.model.dto;
|
||||
|
||||
import com.adityachandel.booklore.model.enums.BookFileType;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
public interface ReadingSessionTimelineDto {
|
||||
Long getBookId();
|
||||
|
||||
String getBookTitle();
|
||||
|
||||
BookFileType getBookFileType();
|
||||
|
||||
LocalDateTime getStartDate();
|
||||
|
||||
LocalDateTime getEndDate();
|
||||
|
||||
Long getTotalSessions();
|
||||
|
||||
Long getTotalDurationSeconds();
|
||||
}
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
package com.adityachandel.booklore.model.dto.request;
|
||||
|
||||
import com.adityachandel.booklore.model.enums.BookFileType;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import java.time.Instant;
|
||||
|
||||
@Data
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class ReadingSessionRequest {
|
||||
@NotNull
|
||||
private Long bookId;
|
||||
|
||||
private BookFileType bookType;
|
||||
|
||||
@NotNull
|
||||
private Instant startTime;
|
||||
|
||||
@NotNull
|
||||
private Instant endTime;
|
||||
|
||||
@NotNull
|
||||
private Integer durationSeconds;
|
||||
|
||||
@NotNull
|
||||
private Float startProgress;
|
||||
|
||||
@NotNull
|
||||
private Float endProgress;
|
||||
|
||||
@NotNull
|
||||
private Float progressDelta;
|
||||
|
||||
@NotNull
|
||||
private String startLocation;
|
||||
|
||||
@NotNull
|
||||
private String endLocation;
|
||||
}
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
package com.adityachandel.booklore.model.dto.response;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import java.time.LocalDate;
|
||||
|
||||
@Data
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class ReadingSessionHeatmapResponse {
|
||||
private LocalDate date;
|
||||
private Long count;
|
||||
}
|
||||
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
package com.adityachandel.booklore.model.dto.response;
|
||||
|
||||
import com.adityachandel.booklore.model.enums.BookFileType;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Data
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class ReadingSessionTimelineResponse {
|
||||
private Long bookId;
|
||||
private String bookTitle;
|
||||
private BookFileType bookType;
|
||||
private LocalDateTime startDate;
|
||||
private LocalDateTime endDate;
|
||||
private Long totalSessions;
|
||||
private Long totalDurationSeconds;
|
||||
}
|
||||
+4
@@ -66,6 +66,10 @@ public class BookLoreUserEntity {
|
||||
@OneToOne(mappedBy = "bookLoreUser", cascade = CascadeType.ALL, orphanRemoval = true)
|
||||
private KoreaderUserEntity koreaderUser;
|
||||
|
||||
@OneToMany(mappedBy = "user", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY)
|
||||
@Builder.Default
|
||||
private Set<ReadingSessionEntity> readingSessions = new HashSet<>();
|
||||
|
||||
@PrePersist
|
||||
public void prePersist() {
|
||||
this.createdAt = LocalDateTime.now();
|
||||
|
||||
+67
@@ -0,0 +1,67 @@
|
||||
package com.adityachandel.booklore.model.entity;
|
||||
|
||||
import com.adityachandel.booklore.model.enums.BookFileType;
|
||||
import jakarta.persistence.*;
|
||||
import lombok.*;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
@Builder
|
||||
@AllArgsConstructor
|
||||
@NoArgsConstructor
|
||||
@Entity
|
||||
@Table(name = "reading_sessions")
|
||||
public class ReadingSessionEntity {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
|
||||
@ManyToOne(fetch = FetchType.LAZY)
|
||||
@JoinColumn(name = "user_id", nullable = false)
|
||||
private BookLoreUserEntity user;
|
||||
|
||||
@ManyToOne(fetch = FetchType.LAZY)
|
||||
@JoinColumn(name = "book_id", nullable = false)
|
||||
private BookEntity book;
|
||||
|
||||
@Enumerated(EnumType.STRING)
|
||||
@Column(name = "book_type", nullable = false)
|
||||
private BookFileType bookType;
|
||||
|
||||
@Column(name = "start_time", nullable = false)
|
||||
private Instant startTime;
|
||||
|
||||
@Column(name = "end_time", nullable = false)
|
||||
private Instant endTime;
|
||||
|
||||
@Column(name = "duration_seconds", nullable = false)
|
||||
private Integer durationSeconds;
|
||||
|
||||
@Column(name = "start_progress", nullable = false)
|
||||
private Float startProgress;
|
||||
|
||||
@Column(name = "end_progress", nullable = false)
|
||||
private Float endProgress;
|
||||
|
||||
@Column(name = "progress_delta", nullable = false)
|
||||
private Float progressDelta;
|
||||
|
||||
@Column(name = "start_location", nullable = false, length = 500)
|
||||
private String startLocation;
|
||||
|
||||
@Column(name = "end_location", nullable = false, length = 500)
|
||||
private String endLocation;
|
||||
|
||||
@Column(name = "created_at", nullable = false, updatable = false)
|
||||
private LocalDateTime createdAt;
|
||||
|
||||
@PrePersist
|
||||
public void prePersist() {
|
||||
this.createdAt = LocalDateTime.now();
|
||||
}
|
||||
}
|
||||
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
package com.adityachandel.booklore.repository;
|
||||
|
||||
import com.adityachandel.booklore.model.dto.ReadingSessionCountDto;
|
||||
import com.adityachandel.booklore.model.dto.ReadingSessionTimelineDto;
|
||||
import com.adityachandel.booklore.model.entity.ReadingSessionEntity;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.Query;
|
||||
import org.springframework.data.repository.query.Param;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Repository
|
||||
public interface ReadingSessionRepository extends JpaRepository<ReadingSessionEntity, Long> {
|
||||
|
||||
@Query("""
|
||||
SELECT CAST(rs.createdAt AS LocalDate) as date, COUNT(rs) as count
|
||||
FROM ReadingSessionEntity rs
|
||||
WHERE rs.user.id = :userId
|
||||
AND YEAR(rs.createdAt) = :year
|
||||
GROUP BY CAST(rs.createdAt AS LocalDate)
|
||||
ORDER BY date
|
||||
""")
|
||||
List<ReadingSessionCountDto> findSessionCountsByUserAndYear(@Param("userId") Long userId, @Param("year") int year);
|
||||
|
||||
@Query("""
|
||||
SELECT
|
||||
b.id as bookId,
|
||||
b.metadata.title as bookTitle,
|
||||
rs.bookType as bookFileType,
|
||||
MIN(rs.startTime) as startDate,
|
||||
MAX(rs.endTime) as endDate,
|
||||
COUNT(rs) as totalSessions,
|
||||
SUM(rs.durationSeconds) as totalDurationSeconds
|
||||
FROM ReadingSessionEntity rs
|
||||
JOIN rs.book b
|
||||
WHERE rs.user.id = :userId
|
||||
AND YEAR(rs.startTime) = :year
|
||||
AND WEEK(rs.startTime) = :weekOfYear
|
||||
GROUP BY b.id, b.metadata.title, rs.bookType
|
||||
ORDER BY MIN(rs.startTime)
|
||||
""")
|
||||
List<ReadingSessionTimelineDto> findSessionTimelineByUserAndWeek(
|
||||
@Param("userId") Long userId,
|
||||
@Param("year") int year,
|
||||
@Param("weekOfYear") int weekOfYear);
|
||||
}
|
||||
+93
@@ -0,0 +1,93 @@
|
||||
package com.adityachandel.booklore.service;
|
||||
|
||||
import com.adityachandel.booklore.config.security.service.AuthenticationService;
|
||||
import com.adityachandel.booklore.exception.ApiError;
|
||||
import com.adityachandel.booklore.model.dto.BookLoreUser;
|
||||
import com.adityachandel.booklore.model.dto.request.ReadingSessionRequest;
|
||||
import com.adityachandel.booklore.model.dto.response.ReadingSessionHeatmapResponse;
|
||||
import com.adityachandel.booklore.model.dto.response.ReadingSessionTimelineResponse;
|
||||
import com.adityachandel.booklore.model.entity.BookEntity;
|
||||
import com.adityachandel.booklore.model.entity.BookLoreUserEntity;
|
||||
import com.adityachandel.booklore.model.entity.ReadingSessionEntity;
|
||||
import com.adityachandel.booklore.repository.BookRepository;
|
||||
import com.adityachandel.booklore.repository.ReadingSessionRepository;
|
||||
import com.adityachandel.booklore.repository.UserRepository;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.security.core.userdetails.UsernameNotFoundException;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class ReadingSessionService {
|
||||
|
||||
private final AuthenticationService authenticationService;
|
||||
private final ReadingSessionRepository readingSessionRepository;
|
||||
private final BookRepository bookRepository;
|
||||
private final UserRepository userRepository;
|
||||
|
||||
@Transactional
|
||||
public void recordSession(ReadingSessionRequest request) {
|
||||
BookLoreUser authenticatedUser = authenticationService.getAuthenticatedUser();
|
||||
Long userId = authenticatedUser.getId();
|
||||
|
||||
BookLoreUserEntity userEntity = userRepository.findById(userId).orElseThrow(() -> new UsernameNotFoundException("User not found with ID: " + userId));
|
||||
BookEntity book = bookRepository.findById(request.getBookId()).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(request.getBookId()));
|
||||
|
||||
ReadingSessionEntity session = ReadingSessionEntity.builder()
|
||||
.user(userEntity)
|
||||
.book(book)
|
||||
.bookType(request.getBookType())
|
||||
.startTime(request.getStartTime())
|
||||
.endTime(request.getEndTime())
|
||||
.durationSeconds(request.getDurationSeconds())
|
||||
.startProgress(request.getStartProgress())
|
||||
.endProgress(request.getEndProgress())
|
||||
.progressDelta(request.getProgressDelta())
|
||||
.startLocation(request.getStartLocation())
|
||||
.endLocation(request.getEndLocation())
|
||||
.build();
|
||||
|
||||
readingSessionRepository.save(session);
|
||||
|
||||
log.info("Reading session persisted successfully: sessionId={}, userId={}, bookId={}, duration={}s", session.getId(), userId, request.getBookId(), request.getDurationSeconds());
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public List<ReadingSessionHeatmapResponse> getSessionHeatmapForYear(int year) {
|
||||
BookLoreUser authenticatedUser = authenticationService.getAuthenticatedUser();
|
||||
Long userId = authenticatedUser.getId();
|
||||
|
||||
return readingSessionRepository.findSessionCountsByUserAndYear(userId, year)
|
||||
.stream()
|
||||
.map(dto -> ReadingSessionHeatmapResponse.builder()
|
||||
.date(dto.getDate())
|
||||
.count(dto.getCount())
|
||||
.build())
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public List<ReadingSessionTimelineResponse> getSessionTimelineForWeek(int year, int week) {
|
||||
BookLoreUser authenticatedUser = authenticationService.getAuthenticatedUser();
|
||||
Long userId = authenticatedUser.getId();
|
||||
|
||||
return readingSessionRepository.findSessionTimelineByUserAndWeek(userId, year, week)
|
||||
.stream()
|
||||
.map(dto -> ReadingSessionTimelineResponse.builder()
|
||||
.bookId(dto.getBookId())
|
||||
.bookType(dto.getBookFileType())
|
||||
.bookTitle(dto.getBookTitle())
|
||||
.startDate(dto.getStartDate())
|
||||
.endDate(dto.getEndDate())
|
||||
.totalSessions(dto.getTotalSessions())
|
||||
.totalDurationSeconds(dto.getTotalDurationSeconds())
|
||||
.build())
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
CREATE TABLE IF NOT EXISTS reading_sessions
|
||||
(
|
||||
id BIGINT AUTO_INCREMENT PRIMARY KEY,
|
||||
user_id BIGINT NOT NULL,
|
||||
book_id BIGINT NOT NULL,
|
||||
book_type VARCHAR(10) NOT NULL,
|
||||
start_time DATETIME NOT NULL,
|
||||
end_time DATETIME NOT NULL,
|
||||
duration_seconds INTEGER NOT NULL,
|
||||
start_progress FLOAT NOT NULL,
|
||||
end_progress FLOAT NOT NULL,
|
||||
progress_delta FLOAT NOT NULL,
|
||||
start_location VARCHAR(500) NOT NULL,
|
||||
end_location VARCHAR(500) NOT NULL,
|
||||
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
CONSTRAINT fk_reading_session_user FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE CASCADE,
|
||||
CONSTRAINT fk_reading_session_book FOREIGN KEY (book_id) REFERENCES book (id) ON DELETE CASCADE
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_reading_session_user_time ON reading_sessions (user_id, start_time DESC);
|
||||
CREATE INDEX IF NOT EXISTS idx_reading_session_book ON reading_sessions (book_id, start_time DESC);
|
||||
CREATE INDEX IF NOT EXISTS idx_reading_session_user_book ON reading_sessions (user_id, book_id, start_time DESC);
|
||||
Reference in New Issue
Block a user