feat: mobile/app API enhancements

This commit is contained in:
acx10
2026-03-10 21:41:29 -06:00
committed by acx10
parent c336ace238
commit 185422810d
84 changed files with 1936 additions and 643 deletions
@@ -0,0 +1,37 @@
package org.booklore.app.controller;
import org.booklore.app.dto.AppAuthorDetail;
import org.booklore.app.dto.AppAuthorSummary;
import org.booklore.app.dto.AppPageResponse;
import org.booklore.app.service.AppAuthorService;
import lombok.AllArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
@AllArgsConstructor
@RestController
@RequestMapping("/api/v1/app/authors")
public class AppAuthorController {
private final AppAuthorService mobileAuthorService;
@GetMapping
public ResponseEntity<AppPageResponse<AppAuthorSummary>> getAuthors(
@RequestParam(required = false, defaultValue = "0") Integer page,
@RequestParam(required = false, defaultValue = "30") Integer size,
@RequestParam(required = false, defaultValue = "name") String sort,
@RequestParam(required = false, defaultValue = "asc") String dir,
@RequestParam(required = false) Long libraryId,
@RequestParam(required = false) String search,
@RequestParam(required = false) Boolean hasPhoto) {
return ResponseEntity.ok(mobileAuthorService.getAuthors(page, size, sort, dir, libraryId, search, hasPhoto));
}
@GetMapping("/{authorId}")
public ResponseEntity<AppAuthorDetail> getAuthorDetail(
@PathVariable Long authorId) {
return ResponseEntity.ok(mobileAuthorService.getAuthorDetail(authorId));
}
}
@@ -0,0 +1,112 @@
package org.booklore.app.controller;
import org.booklore.app.dto.*;
import org.booklore.app.service.AppBookService;
import org.booklore.model.enums.BookFileType;
import org.booklore.model.enums.ReadStatus;
import jakarta.validation.Valid;
import lombok.AllArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@AllArgsConstructor
@RestController
@RequestMapping("/api/v1/app/books")
public class AppBookController {
private final AppBookService mobileBookService;
@GetMapping
public ResponseEntity<AppPageResponse<AppBookSummary>> getBooks(
@RequestParam(required = false, defaultValue = "0") Integer page,
@RequestParam(required = false, defaultValue = "50") Integer size,
@RequestParam(required = false, defaultValue = "addedOn") String sort,
@RequestParam(required = false, defaultValue = "desc") String dir,
@RequestParam(required = false) Long libraryId,
@RequestParam(required = false) Long shelfId,
@RequestParam(required = false) ReadStatus status,
@RequestParam(required = false) String search,
@RequestParam(required = false) BookFileType fileType,
@RequestParam(required = false) Integer minRating,
@RequestParam(required = false) Integer maxRating,
@RequestParam(required = false) String authors,
@RequestParam(required = false) String language) {
return ResponseEntity.ok(mobileBookService.getBooks(
page, size, sort, dir, libraryId, shelfId, status, search,
fileType, minRating, maxRating, authors, language));
}
@GetMapping("/{bookId}")
public ResponseEntity<AppBookDetail> getBookDetail(
@PathVariable Long bookId) {
return ResponseEntity.ok(mobileBookService.getBookDetail(bookId));
}
@GetMapping("/search")
public ResponseEntity<AppPageResponse<AppBookSummary>> searchBooks(
@RequestParam String q,
@RequestParam(required = false, defaultValue = "0") Integer page,
@RequestParam(required = false, defaultValue = "20") Integer size) {
return ResponseEntity.ok(mobileBookService.searchBooks(q, page, size));
}
@GetMapping("/continue-reading")
public ResponseEntity<List<AppBookSummary>> getContinueReading(
@RequestParam(required = false, defaultValue = "10") Integer limit) {
return ResponseEntity.ok(mobileBookService.getContinueReading(limit));
}
@GetMapping("/continue-listening")
public ResponseEntity<List<AppBookSummary>> getContinueListening(
@RequestParam(required = false, defaultValue = "10") Integer limit) {
return ResponseEntity.ok(mobileBookService.getContinueListening(limit));
}
@GetMapping("/recently-added")
public ResponseEntity<List<AppBookSummary>> getRecentlyAdded(
@RequestParam(required = false, defaultValue = "10") Integer limit) {
return ResponseEntity.ok(mobileBookService.getRecentlyAdded(limit));
}
@GetMapping("/recently-scanned")
public ResponseEntity<List<AppBookSummary>> getRecentlyScanned(
@RequestParam(required = false, defaultValue = "10") Integer limit) {
return ResponseEntity.ok(mobileBookService.getRecentlyScanned(limit));
}
@PutMapping("/{bookId}/status")
public ResponseEntity<Void> updateStatus(
@PathVariable Long bookId,
@Valid @RequestBody UpdateStatusRequest request) {
mobileBookService.updateReadStatus(bookId, request.getStatus());
return ResponseEntity.ok().build();
}
@PutMapping("/{bookId}/rating")
public ResponseEntity<Void> updateRating(
@PathVariable Long bookId,
@Valid @RequestBody UpdateRatingRequest request) {
mobileBookService.updatePersonalRating(bookId, request.getRating());
return ResponseEntity.ok().build();
}
@GetMapping("/random")
public ResponseEntity<AppPageResponse<AppBookSummary>> getRandomBooks(
@RequestParam(required = false, defaultValue = "0") Integer page,
@RequestParam(required = false, defaultValue = "20") Integer size,
@RequestParam(required = false) Long libraryId) {
return ResponseEntity.ok(mobileBookService.getRandomBooks(page, size, libraryId));
}
}
@@ -0,0 +1,26 @@
package org.booklore.app.controller;
import org.booklore.app.dto.AppFilterOptions;
import org.booklore.app.service.AppBookService;
import lombok.AllArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@AllArgsConstructor
@RestController
@RequestMapping("/api/v1/app")
public class AppFilterController {
private final AppBookService mobileBookService;
@GetMapping("/filter-options")
public ResponseEntity<AppFilterOptions> getFilterOptions(
@RequestParam(required = false) Long libraryId,
@RequestParam(required = false) Long shelfId,
@RequestParam(required = false) Long magicShelfId) {
return ResponseEntity.ok(mobileBookService.getFilterOptions(libraryId, shelfId, magicShelfId));
}
}
@@ -1,16 +1,13 @@
package org.booklore.mobile.controller;
package org.booklore.app.controller;
import org.booklore.config.security.service.AuthenticationService;
import org.booklore.mobile.dto.MobileLibrarySummary;
import org.booklore.mobile.mapper.MobileBookMapper;
import org.booklore.app.dto.AppLibrarySummary;
import org.booklore.app.mapper.AppBookMapper;
import org.booklore.model.dto.BookLoreUser;
import org.booklore.model.dto.Library;
import org.booklore.model.entity.LibraryEntity;
import org.booklore.repository.BookRepository;
import org.booklore.repository.LibraryRepository;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.AllArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
@@ -22,20 +19,16 @@ import java.util.stream.Collectors;
@AllArgsConstructor
@RestController
@RequestMapping("/api/mobile/v1/libraries")
@Tag(name = "Mobile Libraries", description = "Mobile-optimized endpoints for library operations")
public class MobileLibraryController {
@RequestMapping("/api/v1/app/libraries")
public class AppLibraryController {
private final AuthenticationService authenticationService;
private final LibraryRepository libraryRepository;
private final BookRepository bookRepository;
private final MobileBookMapper mobileBookMapper;
private final AppBookMapper mobileBookMapper;
@Operation(summary = "Get user's accessible libraries",
description = "Retrieve a list of libraries the current user has access to.")
@ApiResponse(responseCode = "200", description = "Libraries retrieved successfully")
@GetMapping
public ResponseEntity<List<MobileLibrarySummary>> getLibraries() {
public ResponseEntity<List<AppLibrarySummary>> getLibraries() {
BookLoreUser user = authenticationService.getAuthenticatedUser();
List<LibraryEntity> libraries;
@@ -48,7 +41,7 @@ public class MobileLibraryController {
libraries = libraryRepository.findByIdIn(libraryIds);
}
List<MobileLibrarySummary> summaries = libraries.stream()
List<AppLibrarySummary> summaries = libraries.stream()
.map(library -> {
long bookCount = bookRepository.countByLibraryId(library.getId());
return mobileBookMapper.toLibrarySummary(library, bookCount);
@@ -0,0 +1,60 @@
package org.booklore.app.controller;
import org.booklore.app.dto.AppNotebookBookSummary;
import org.booklore.app.dto.AppNotebookEntry;
import org.booklore.app.dto.AppNotebookUpdateRequest;
import org.booklore.app.dto.AppPageResponse;
import org.booklore.app.service.AppNotebookService;
import jakarta.validation.Valid;
import lombok.AllArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.Set;
@AllArgsConstructor
@RestController
@RequestMapping("/api/v1/app/notebook")
public class AppNotebookController {
private final AppNotebookService mobileNotebookService;
@GetMapping("/books")
public ResponseEntity<AppPageResponse<AppNotebookBookSummary>> getBooksWithAnnotations(
@RequestParam(required = false, defaultValue = "0") Integer page,
@RequestParam(required = false, defaultValue = "20") Integer size,
@RequestParam(required = false) String search) {
return ResponseEntity.ok(mobileNotebookService.getBooksWithAnnotations(page, size, search));
}
@GetMapping("/books/{bookId}/entries")
public ResponseEntity<AppPageResponse<AppNotebookEntry>> getEntriesForBook(
@PathVariable Long bookId,
@RequestParam(required = false, defaultValue = "0") Integer page,
@RequestParam(required = false, defaultValue = "20") Integer size,
@RequestParam(required = false) Set<String> types,
@RequestParam(required = false) String search,
@RequestParam(required = false, defaultValue = "date_desc") String sort) {
return ResponseEntity.ok(mobileNotebookService.getEntriesForBook(bookId, page, size, types, search, sort));
}
@PutMapping("/entries/{entryId}")
public ResponseEntity<AppNotebookEntry> updateEntry(
@PathVariable Long entryId,
@RequestParam String type,
@Valid @RequestBody AppNotebookUpdateRequest request) {
return ResponseEntity.ok(mobileNotebookService.updateEntry(entryId, type, request));
}
@DeleteMapping("/entries/{entryId}")
public ResponseEntity<Void> deleteEntry(
@PathVariable Long entryId,
@RequestParam String type) {
mobileNotebookService.deleteEntry(entryId, type);
return ResponseEntity.noContent().build();
}
}
@@ -1,22 +1,22 @@
package org.booklore.mobile.controller;
package org.booklore.app.controller;
import lombok.AllArgsConstructor;
import org.booklore.mobile.dto.MobileBookSummary;
import org.booklore.mobile.dto.MobilePageResponse;
import org.booklore.mobile.dto.MobileSeriesSummary;
import org.booklore.mobile.service.MobileSeriesService;
import org.booklore.app.dto.AppBookSummary;
import org.booklore.app.dto.AppPageResponse;
import org.booklore.app.dto.AppSeriesSummary;
import org.booklore.app.service.AppSeriesService;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
@AllArgsConstructor
@RestController
@RequestMapping("/api/mobile/v1/series")
public class MobileSeriesController {
@RequestMapping("/api/v1/app/series")
public class AppSeriesController {
private final MobileSeriesService mobileSeriesService;
private final AppSeriesService mobileSeriesService;
@GetMapping
public ResponseEntity<MobilePageResponse<MobileSeriesSummary>> getSeries(
public ResponseEntity<AppPageResponse<AppSeriesSummary>> getSeries(
@RequestParam(required = false, defaultValue = "0") Integer page,
@RequestParam(required = false, defaultValue = "20") Integer size,
@RequestParam(required = false, defaultValue = "recentlyAdded") String sort,
@@ -27,14 +27,14 @@ public class MobileSeriesController {
boolean inProgressOnly = "in-progress".equalsIgnoreCase(status);
MobilePageResponse<MobileSeriesSummary> response = mobileSeriesService.getSeries(
AppPageResponse<AppSeriesSummary> response = mobileSeriesService.getSeries(
page, size, sort, dir, libraryId, search, inProgressOnly);
return ResponseEntity.ok(response);
}
@GetMapping("/{seriesName}/books")
public ResponseEntity<MobilePageResponse<MobileBookSummary>> getSeriesBooks(
public ResponseEntity<AppPageResponse<AppBookSummary>> getSeriesBooks(
@PathVariable String seriesName,
@RequestParam(required = false, defaultValue = "0") Integer page,
@RequestParam(required = false, defaultValue = "20") Integer size,
@@ -42,7 +42,7 @@ public class MobileSeriesController {
@RequestParam(required = false, defaultValue = "asc") String dir,
@RequestParam(required = false) Long libraryId) {
MobilePageResponse<MobileBookSummary> response = mobileSeriesService.getSeriesBooks(
AppPageResponse<AppBookSummary> response = mobileSeriesService.getSeriesBooks(
seriesName, page, size, sort, dir, libraryId);
return ResponseEntity.ok(response);
@@ -1,22 +1,20 @@
package org.booklore.mobile.controller;
package org.booklore.app.controller;
import org.booklore.config.security.service.AuthenticationService;
import org.booklore.mobile.dto.MobileMagicShelfSummary;
import org.booklore.mobile.dto.MobileShelfSummary;
import org.booklore.mobile.mapper.MobileBookMapper;
import org.booklore.app.dto.AppBookSummary;
import org.booklore.app.dto.AppMagicShelfSummary;
import org.booklore.app.dto.AppPageResponse;
import org.booklore.app.dto.AppShelfSummary;
import org.booklore.app.mapper.AppBookMapper;
import org.booklore.app.service.AppBookService;
import org.booklore.model.dto.BookLoreUser;
import org.booklore.model.entity.MagicShelfEntity;
import org.booklore.model.entity.ShelfEntity;
import org.booklore.repository.MagicShelfRepository;
import org.booklore.repository.ShelfRepository;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.AllArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.HashSet;
@@ -26,37 +24,31 @@ import java.util.stream.Collectors;
@AllArgsConstructor
@RestController
@RequestMapping("/api/mobile/v1/shelves")
@Tag(name = "Mobile Shelves", description = "Mobile-optimized endpoints for shelf operations")
public class MobileShelfController {
@RequestMapping("/api/v1/app/shelves")
public class AppShelfController {
private final AuthenticationService authenticationService;
private final ShelfRepository shelfRepository;
private final MagicShelfRepository magicShelfRepository;
private final MobileBookMapper mobileBookMapper;
private final AppBookMapper mobileBookMapper;
private final AppBookService mobileBookService;
@Operation(summary = "Get user's shelves",
description = "Retrieve a list of shelves the current user owns or are public.")
@ApiResponse(responseCode = "200", description = "Shelves retrieved successfully")
@GetMapping
public ResponseEntity<List<MobileShelfSummary>> getShelves() {
public ResponseEntity<List<AppShelfSummary>> getShelves() {
BookLoreUser user = authenticationService.getAuthenticatedUser();
Long userId = user.getId();
List<ShelfEntity> shelves = shelfRepository.findByUserIdOrPublicShelfTrue(userId);
List<MobileShelfSummary> summaries = shelves.stream()
List<AppShelfSummary> summaries = shelves.stream()
.map(mobileBookMapper::toShelfSummaryFromEntity)
.collect(Collectors.toList());
return ResponseEntity.ok(summaries);
}
@Operation(summary = "Get user's magic shelves",
description = "Retrieve a list of magic shelves the current user owns or are public.")
@ApiResponse(responseCode = "200", description = "Magic shelves retrieved successfully")
@GetMapping("/magic")
public ResponseEntity<List<MobileMagicShelfSummary>> getMagicShelves() {
public ResponseEntity<List<AppMagicShelfSummary>> getMagicShelves() {
BookLoreUser user = authenticationService.getAuthenticatedUser();
Long userId = user.getId();
@@ -81,10 +73,19 @@ public class MobileShelfController {
}
}
List<MobileMagicShelfSummary> summaries = allShelves.stream()
List<AppMagicShelfSummary> summaries = allShelves.stream()
.map(mobileBookMapper::toMagicShelfSummary)
.collect(Collectors.toList());
return ResponseEntity.ok(summaries);
}
@GetMapping("/magic/{magicShelfId}/books")
public ResponseEntity<AppPageResponse<AppBookSummary>> getBooksByMagicShelf(
@PathVariable Long magicShelfId,
@RequestParam(required = false, defaultValue = "0") Integer page,
@RequestParam(required = false, defaultValue = "20") Integer size) {
return ResponseEntity.ok(mobileBookService.getBooksByMagicShelf(magicShelfId, page, size));
}
}
@@ -0,0 +1,46 @@
package org.booklore.app.controller;
import org.booklore.config.security.service.AuthenticationService;
import org.booklore.app.dto.AppUserInfo;
import org.booklore.model.dto.BookLoreUser;
import org.booklore.service.appsettings.AppSettingService;
import lombok.AllArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@AllArgsConstructor
@RestController
@RequestMapping("/api/v1/app/users")
public class AppUserController {
private final AuthenticationService authenticationService;
private final AppSettingService appSettingService;
@GetMapping("/me")
public ResponseEntity<AppUserInfo> getCurrentUser() {
BookLoreUser user = authenticationService.getAuthenticatedUser();
BookLoreUser.UserPermissions perms = user.getPermissions();
int maxUploadSizeMb = 100; // default
try {
Integer configured = appSettingService.getAppSettings().getMaxFileUploadSizeInMb();
if (configured != null) {
maxUploadSizeMb = configured;
}
} catch (Exception ignored) {
// fall back to default
}
AppUserInfo info = AppUserInfo.builder()
.isAdmin(perms.isAdmin())
.canUpload(perms.isCanUpload())
.canDownload(perms.isCanDownload())
.canAccessBookdrop(perms.isCanAccessBookdrop())
.maxFileUploadSizeMb(maxUploadSizeMb)
.build();
return ResponseEntity.ok(info);
}
}
@@ -1,4 +1,4 @@
package org.booklore.mobile.dto;
package org.booklore.app.dto;
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.AllArgsConstructor;
@@ -11,7 +11,7 @@ import lombok.NoArgsConstructor;
@NoArgsConstructor
@AllArgsConstructor
@JsonInclude(JsonInclude.Include.NON_NULL)
public class MobileAuthorDetail {
public class AppAuthorDetail {
private Long id;
private String name;
private String description;
@@ -1,4 +1,4 @@
package org.booklore.mobile.dto;
package org.booklore.app.dto;
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.AllArgsConstructor;
@@ -11,7 +11,7 @@ import lombok.NoArgsConstructor;
@NoArgsConstructor
@AllArgsConstructor
@JsonInclude(JsonInclude.Include.NON_NULL)
public class MobileAuthorSummary {
public class AppAuthorSummary {
private Long id;
private String name;
private String asin;
@@ -1,4 +1,4 @@
package org.booklore.mobile.dto;
package org.booklore.app.dto;
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.AllArgsConstructor;
@@ -16,7 +16,7 @@ import java.util.Set;
@NoArgsConstructor
@AllArgsConstructor
@JsonInclude(JsonInclude.Include.NON_NULL)
public class MobileBookDetail {
public class AppBookDetail {
private Long id;
private String title;
private List<String> authors;
@@ -40,18 +40,20 @@ public class MobileBookDetail {
private Double goodreadsRating;
private Integer goodreadsReviewCount;
private String libraryName;
private List<MobileShelfSummary> shelves;
private List<AppShelfSummary> shelves;
private Float readProgress;
private String primaryFileType;
private List<String> fileTypes;
private List<MobileBookFile> files;
private List<AppBookFile> files;
private Instant coverUpdatedOn;
private Instant audiobookCoverUpdatedOn;
private Boolean isPhysical;
private EpubProgress epubProgress;
private PdfProgress pdfProgress;
private CbxProgress cbxProgress;
private AudiobookProgress audiobookProgress;
private KoreaderProgress koreaderProgress;
@Data
@Builder
@@ -94,4 +96,15 @@ public class MobileBookDetail {
private Float percentage;
private Instant updatedAt;
}
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public static class KoreaderProgress {
private Float percentage;
private String device;
private String deviceId;
private Instant lastSyncTime;
}
}
@@ -1,4 +1,4 @@
package org.booklore.mobile.dto;
package org.booklore.app.dto;
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.AllArgsConstructor;
@@ -13,7 +13,7 @@ import java.time.Instant;
@NoArgsConstructor
@AllArgsConstructor
@JsonInclude(JsonInclude.Include.NON_NULL)
public class MobileBookFile {
public class AppBookFile {
private Long id;
private Long bookId;
private String fileName;
@@ -1,4 +1,4 @@
package org.booklore.mobile.dto;
package org.booklore.app.dto;
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.AllArgsConstructor;
@@ -14,7 +14,7 @@ import java.util.List;
@NoArgsConstructor
@AllArgsConstructor
@JsonInclude(JsonInclude.Include.NON_NULL)
public class MobileBookSummary {
public class AppBookSummary {
private Long id;
private String title;
private List<String> authors;
@@ -30,4 +30,5 @@ public class MobileBookSummary {
private String primaryFileType;
private Instant coverUpdatedOn;
private Instant audiobookCoverUpdatedOn;
private Boolean isPhysical;
}
@@ -1,4 +1,4 @@
package org.booklore.mobile.dto;
package org.booklore.app.dto;
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.AllArgsConstructor;
@@ -13,7 +13,7 @@ import java.util.List;
@NoArgsConstructor
@AllArgsConstructor
@JsonInclude(JsonInclude.Include.NON_NULL)
public class MobileFilterOptions {
public class AppFilterOptions {
private List<AuthorOption> authors;
private List<LanguageOption> languages;
private List<String> readStatuses;
@@ -1,4 +1,4 @@
package org.booklore.mobile.dto;
package org.booklore.app.dto;
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.AllArgsConstructor;
@@ -14,10 +14,20 @@ import java.util.List;
@NoArgsConstructor
@AllArgsConstructor
@JsonInclude(JsonInclude.Include.NON_NULL)
public class MobileLibrarySummary {
public class AppLibrarySummary {
private Long id;
private String name;
private String icon;
private long bookCount;
private List<BookFileType> allowedFormats;
private List<PathSummary> paths;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public static class PathSummary {
private Long id;
private String path;
}
}
@@ -1,4 +1,4 @@
package org.booklore.mobile.dto;
package org.booklore.app.dto;
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.AllArgsConstructor;
@@ -11,7 +11,7 @@ import lombok.NoArgsConstructor;
@NoArgsConstructor
@AllArgsConstructor
@JsonInclude(JsonInclude.Include.NON_NULL)
public class MobileMagicShelfSummary {
public class AppMagicShelfSummary {
private Long id;
private String name;
private String icon;
@@ -0,0 +1,23 @@
package org.booklore.app.dto;
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.time.Instant;
import java.util.List;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@JsonInclude(JsonInclude.Include.NON_NULL)
public class AppNotebookBookSummary {
private Long bookId;
private String bookTitle;
private int noteCount;
private List<String> authors;
private Instant coverUpdatedOn;
}
@@ -0,0 +1,27 @@
package org.booklore.app.dto;
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.time.LocalDateTime;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@JsonInclude(JsonInclude.Include.NON_NULL)
public class AppNotebookEntry {
private Long id;
private String type;
private Long bookId;
private String text;
private String note;
private String color;
private String style;
private String chapterTitle;
private LocalDateTime createdAt;
private LocalDateTime updatedAt;
}
@@ -0,0 +1,20 @@
package org.booklore.app.dto;
import jakarta.validation.constraints.Pattern;
import jakarta.validation.constraints.Size;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class AppNotebookUpdateRequest {
@Size(max = 5000)
private String note;
@Pattern(regexp = "^#[0-9A-Fa-f]{6}$")
private String color;
}
@@ -1,4 +1,4 @@
package org.booklore.mobile.dto;
package org.booklore.app.dto;
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.AllArgsConstructor;
@@ -13,7 +13,7 @@ import java.util.List;
@NoArgsConstructor
@AllArgsConstructor
@JsonInclude(JsonInclude.Include.NON_NULL)
public class MobilePageResponse<T> {
public class AppPageResponse<T> {
private List<T> content;
private int page;
private int size;
@@ -22,9 +22,9 @@ public class MobilePageResponse<T> {
private boolean hasNext;
private boolean hasPrevious;
public static <T> MobilePageResponse<T> of(List<T> content, int page, int size, long totalElements) {
public static <T> AppPageResponse<T> of(List<T> content, int page, int size, long totalElements) {
int totalPages = size > 0 ? (int) Math.ceil((double) totalElements / size) : 0;
return MobilePageResponse.<T>builder()
return AppPageResponse.<T>builder()
.content(content)
.page(page)
.size(size)
@@ -1,4 +1,4 @@
package org.booklore.mobile.dto;
package org.booklore.app.dto;
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.*;
@@ -11,7 +11,7 @@ import java.util.List;
@NoArgsConstructor
@AllArgsConstructor
@JsonInclude(JsonInclude.Include.NON_NULL)
public class MobileSeriesSummary {
public class AppSeriesSummary {
private String seriesName;
private int bookCount;
private Integer seriesTotal;
@@ -1,4 +1,4 @@
package org.booklore.mobile.dto;
package org.booklore.app.dto;
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.AllArgsConstructor;
@@ -11,7 +11,7 @@ import lombok.NoArgsConstructor;
@NoArgsConstructor
@AllArgsConstructor
@JsonInclude(JsonInclude.Include.NON_NULL)
public class MobileShelfSummary {
public class AppShelfSummary {
private Long id;
private String name;
private String icon;
@@ -0,0 +1,18 @@
package org.booklore.app.dto;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class AppUserInfo {
private boolean isAdmin;
private boolean canUpload;
private boolean canDownload;
private boolean canAccessBookdrop;
private int maxFileUploadSizeMb;
}
@@ -1,4 +1,4 @@
package org.booklore.mobile.dto;
package org.booklore.app.dto;
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.*;
@@ -1,4 +1,4 @@
package org.booklore.mobile.dto;
package org.booklore.app.dto;
import jakarta.validation.constraints.Max;
import jakarta.validation.constraints.Min;
@@ -1,4 +1,4 @@
package org.booklore.mobile.dto;
package org.booklore.app.dto;
import org.booklore.model.enums.ReadStatus;
import jakarta.validation.constraints.NotNull;
@@ -1,11 +1,11 @@
package org.booklore.mobile.mapper;
package org.booklore.app.mapper;
import org.booklore.mobile.dto.MobileBookDetail;
import org.booklore.mobile.dto.MobileBookFile;
import org.booklore.mobile.dto.MobileBookSummary;
import org.booklore.mobile.dto.MobileLibrarySummary;
import org.booklore.mobile.dto.MobileMagicShelfSummary;
import org.booklore.mobile.dto.MobileShelfSummary;
import org.booklore.app.dto.AppBookDetail;
import org.booklore.app.dto.AppBookFile;
import org.booklore.app.dto.AppBookSummary;
import org.booklore.app.dto.AppLibrarySummary;
import org.booklore.app.dto.AppMagicShelfSummary;
import org.booklore.app.dto.AppShelfSummary;
import org.booklore.model.entity.*;
import org.booklore.model.enums.BookFileType;
import org.mapstruct.*;
@@ -16,7 +16,7 @@ import java.util.Set;
import java.util.stream.Collectors;
@Mapper(componentModel = "spring", unmappedTargetPolicy = ReportingPolicy.IGNORE)
public interface MobileBookMapper {
public interface AppBookMapper {
@Mapping(target = "id", source = "book.id")
@Mapping(target = "title", source = "book.metadata.title")
@@ -33,7 +33,8 @@ public interface MobileBookMapper {
@Mapping(target = "primaryFileType", source = "book", qualifiedByName = "mapPrimaryFileType")
@Mapping(target = "coverUpdatedOn", source = "book.metadata.coverUpdatedOn")
@Mapping(target = "audiobookCoverUpdatedOn", source = "book.metadata.audiobookCoverUpdatedOn")
MobileBookSummary toSummary(BookEntity book, UserBookProgressEntity progress);
@Mapping(target = "isPhysical", source = "book.isPhysical")
AppBookSummary toSummary(BookEntity book, UserBookProgressEntity progress);
@Mapping(target = "id", source = "book.id")
@Mapping(target = "title", source = "book.metadata.title")
@@ -62,13 +63,15 @@ public interface MobileBookMapper {
@Mapping(target = "primaryFileType", source = "book", qualifiedByName = "mapPrimaryFileType")
@Mapping(target = "coverUpdatedOn", source = "book.metadata.coverUpdatedOn")
@Mapping(target = "audiobookCoverUpdatedOn", source = "book.metadata.audiobookCoverUpdatedOn")
@Mapping(target = "isPhysical", source = "book.isPhysical")
@Mapping(target = "fileTypes", source = "book", qualifiedByName = "mapFileTypes")
@Mapping(target = "files", source = "book", qualifiedByName = "mapFiles")
@Mapping(target = "epubProgress", source = "progress", qualifiedByName = "mapEpubProgress")
@Mapping(target = "pdfProgress", source = "progress", qualifiedByName = "mapPdfProgress")
@Mapping(target = "cbxProgress", source = "progress", qualifiedByName = "mapCbxProgress")
@Mapping(target = "audiobookProgress", source = "fileProgress", qualifiedByName = "mapAudiobookProgress")
MobileBookDetail toDetail(BookEntity book, UserBookProgressEntity progress, UserBookFileProgressEntity fileProgress);
@Mapping(target = "koreaderProgress", source = "progress", qualifiedByName = "mapKoreaderProgress")
AppBookDetail toDetail(BookEntity book, UserBookProgressEntity progress, UserBookFileProgressEntity fileProgress);
@Named("mapAuthors")
default List<String> mapAuthors(List<AuthorEntity> authors) {
@@ -99,7 +102,7 @@ public interface MobileBookMapper {
}
@Named("mapShelves")
default List<MobileShelfSummary> mapShelves(Set<ShelfEntity> shelves) {
default List<AppShelfSummary> mapShelves(Set<ShelfEntity> shelves) {
if (shelves == null || shelves.isEmpty()) {
return Collections.emptyList();
}
@@ -108,11 +111,11 @@ public interface MobileBookMapper {
.collect(Collectors.toList());
}
default MobileShelfSummary toShelfSummary(ShelfEntity shelf) {
default AppShelfSummary toShelfSummary(ShelfEntity shelf) {
if (shelf == null) {
return null;
}
return MobileShelfSummary.builder()
return AppShelfSummary.builder()
.id(shelf.getId())
.name(shelf.getName())
.icon(shelf.getIcon())
@@ -145,11 +148,11 @@ public interface MobileBookMapper {
}
@Named("mapEpubProgress")
default MobileBookDetail.EpubProgress mapEpubProgress(UserBookProgressEntity progress) {
default AppBookDetail.EpubProgress mapEpubProgress(UserBookProgressEntity progress) {
if (progress == null || progress.getEpubProgress() == null) {
return null;
}
return MobileBookDetail.EpubProgress.builder()
return AppBookDetail.EpubProgress.builder()
.cfi(progress.getEpubProgress())
.href(progress.getEpubProgressHref())
.percentage(progress.getEpubProgressPercent())
@@ -158,11 +161,11 @@ public interface MobileBookMapper {
}
@Named("mapPdfProgress")
default MobileBookDetail.PdfProgress mapPdfProgress(UserBookProgressEntity progress) {
default AppBookDetail.PdfProgress mapPdfProgress(UserBookProgressEntity progress) {
if (progress == null || progress.getPdfProgress() == null) {
return null;
}
return MobileBookDetail.PdfProgress.builder()
return AppBookDetail.PdfProgress.builder()
.page(progress.getPdfProgress())
.percentage(progress.getPdfProgressPercent())
.updatedAt(progress.getLastReadTime())
@@ -170,26 +173,39 @@ public interface MobileBookMapper {
}
@Named("mapCbxProgress")
default MobileBookDetail.CbxProgress mapCbxProgress(UserBookProgressEntity progress) {
default AppBookDetail.CbxProgress mapCbxProgress(UserBookProgressEntity progress) {
if (progress == null || progress.getCbxProgress() == null) {
return null;
}
return MobileBookDetail.CbxProgress.builder()
return AppBookDetail.CbxProgress.builder()
.page(progress.getCbxProgress())
.percentage(progress.getCbxProgressPercent())
.updatedAt(progress.getLastReadTime())
.build();
}
@Named("mapKoreaderProgress")
default AppBookDetail.KoreaderProgress mapKoreaderProgress(UserBookProgressEntity progress) {
if (progress == null || progress.getKoreaderProgressPercent() == null) {
return null;
}
return AppBookDetail.KoreaderProgress.builder()
.percentage(progress.getKoreaderProgressPercent())
.device(progress.getKoreaderDevice())
.deviceId(progress.getKoreaderDeviceId())
.lastSyncTime(progress.getKoreaderLastSyncTime())
.build();
}
@Named("mapAudiobookProgress")
default MobileBookDetail.AudiobookProgress mapAudiobookProgress(UserBookFileProgressEntity fileProgress) {
default AppBookDetail.AudiobookProgress mapAudiobookProgress(UserBookFileProgressEntity fileProgress) {
if (fileProgress == null) return null;
if (fileProgress.getBookFile() == null ||
fileProgress.getBookFile().getBookType() != BookFileType.AUDIOBOOK) {
return null;
}
return MobileBookDetail.AudiobookProgress.builder()
return AppBookDetail.AudiobookProgress.builder()
.positionMs(parseLongOrNull(fileProgress.getPositionData()))
.trackIndex(parseIntOrNull(fileProgress.getPositionHref()))
.percentage(fileProgress.getProgressPercent())
@@ -240,7 +256,7 @@ public interface MobileBookMapper {
}
@Named("mapFiles")
default List<MobileBookFile> mapFiles(BookEntity book) {
default List<AppBookFile> mapFiles(BookEntity book) {
if (book == null || book.getBookFiles() == null || book.getBookFiles().isEmpty()) {
return Collections.emptyList();
}
@@ -261,7 +277,7 @@ public interface MobileBookMapper {
// Handle case where extension cannot be extracted
}
return MobileBookFile.builder()
return AppBookFile.builder()
.id(bf.getId())
.bookId(bf.getBook() != null ? bf.getBook().getId() : null)
.fileName(bf.getFileName())
@@ -278,24 +294,34 @@ public interface MobileBookMapper {
.collect(Collectors.toList());
}
default MobileLibrarySummary toLibrarySummary(LibraryEntity library, long bookCount) {
default AppLibrarySummary toLibrarySummary(LibraryEntity library, long bookCount) {
if (library == null) {
return null;
}
return MobileLibrarySummary.builder()
List<AppLibrarySummary.PathSummary> paths = Collections.emptyList();
if (library.getLibraryPaths() != null && !library.getLibraryPaths().isEmpty()) {
paths = library.getLibraryPaths().stream()
.map(lp -> AppLibrarySummary.PathSummary.builder()
.id(lp.getId())
.path(lp.getPath())
.build())
.collect(Collectors.toList());
}
return AppLibrarySummary.builder()
.id(library.getId())
.name(library.getName())
.icon(library.getIcon())
.bookCount(bookCount)
.allowedFormats(library.getAllowedFormats())
.paths(paths)
.build();
}
default MobileShelfSummary toShelfSummaryFromEntity(ShelfEntity shelf) {
default AppShelfSummary toShelfSummaryFromEntity(ShelfEntity shelf) {
if (shelf == null) {
return null;
}
return MobileShelfSummary.builder()
return AppShelfSummary.builder()
.id(shelf.getId())
.name(shelf.getName())
.icon(shelf.getIcon())
@@ -304,11 +330,11 @@ public interface MobileBookMapper {
.build();
}
default MobileMagicShelfSummary toMagicShelfSummary(MagicShelfEntity magicShelf) {
default AppMagicShelfSummary toMagicShelfSummary(MagicShelfEntity magicShelf) {
if (magicShelf == null) {
return null;
}
return MobileMagicShelfSummary.builder()
return AppMagicShelfSummary.builder()
.id(magicShelf.getId())
.name(magicShelf.getName())
.icon(magicShelf.getIcon())
@@ -1,11 +1,11 @@
package org.booklore.mobile.service;
package org.booklore.app.service;
import lombok.AllArgsConstructor;
import org.booklore.config.security.service.AuthenticationService;
import org.booklore.exception.ApiError;
import org.booklore.mobile.dto.MobileAuthorDetail;
import org.booklore.mobile.dto.MobileAuthorSummary;
import org.booklore.mobile.dto.MobilePageResponse;
import org.booklore.app.dto.AppAuthorDetail;
import org.booklore.app.dto.AppAuthorSummary;
import org.booklore.app.dto.AppPageResponse;
import org.booklore.model.dto.BookLoreUser;
import org.booklore.model.dto.Library;
import org.booklore.model.entity.AuthorEntity;
@@ -25,7 +25,7 @@ import java.util.stream.Collectors;
@Service
@AllArgsConstructor
public class MobileAuthorService {
public class AppAuthorService {
private static final int DEFAULT_PAGE_SIZE = 30;
private static final int MAX_PAGE_SIZE = 50;
@@ -36,7 +36,7 @@ public class MobileAuthorService {
private final EntityManager entityManager;
@Transactional(readOnly = true)
public MobilePageResponse<MobileAuthorSummary> getAuthors(
public AppPageResponse<AppAuthorSummary> getAuthors(
Integer page,
Integer size,
String sortBy,
@@ -64,7 +64,7 @@ public class MobileAuthorService {
long totalElements = countQuery.getSingleResult();
if (totalElements == 0) {
return MobilePageResponse.of(Collections.emptyList(), pageNum, pageSize, 0L);
return AppPageResponse.of(Collections.emptyList(), pageNum, pageSize, 0L);
}
// Data query with book count
@@ -78,12 +78,12 @@ public class MobileAuthorService {
List<Object[]> results = dataQuery.getResultList();
List<MobileAuthorSummary> summaries = results.stream()
List<AppAuthorSummary> summaries = results.stream()
.map(row -> {
AuthorEntity author = (AuthorEntity) row[0];
long bookCount = (Long) row[1];
boolean authorHasPhoto = Files.exists(Paths.get(fileService.getAuthorThumbnailFile(author.getId())));
return MobileAuthorSummary.builder()
return AppAuthorSummary.builder()
.id(author.getId())
.name(author.getName())
.asin(author.getAsin())
@@ -100,14 +100,14 @@ public class MobileAuthorService {
.collect(Collectors.toList());
// Adjust total count for hasPhoto filter — requires a separate count
long filteredTotal = countAuthorsWithPhotoFilter(accessibleLibraryIds, libraryId, search, hasPhoto);
return MobilePageResponse.of(summaries, pageNum, pageSize, filteredTotal);
return AppPageResponse.of(summaries, pageNum, pageSize, filteredTotal);
}
return MobilePageResponse.of(summaries, pageNum, pageSize, totalElements);
return AppPageResponse.of(summaries, pageNum, pageSize, totalElements);
}
@Transactional(readOnly = true)
public MobileAuthorDetail getAuthorDetail(Long authorId) {
public AppAuthorDetail getAuthorDetail(Long authorId) {
BookLoreUser user = authenticationService.getAuthenticatedUser();
Set<Long> accessibleLibraryIds = getAccessibleLibraryIds(user);
@@ -125,7 +125,7 @@ public class MobileAuthorService {
int bookCount = countAccessibleBooks(authorId, accessibleLibraryIds);
boolean authorHasPhoto = Files.exists(Paths.get(fileService.getAuthorThumbnailFile(author.getId())));
return MobileAuthorDetail.builder()
return AppAuthorDetail.builder()
.id(author.getId())
.name(author.getName())
.description(author.getDescription())
@@ -1,13 +1,13 @@
package org.booklore.mobile.service;
package org.booklore.app.service;
import org.booklore.config.security.service.AuthenticationService;
import org.booklore.exception.ApiError;
import org.booklore.mobile.dto.MobileBookDetail;
import org.booklore.mobile.dto.MobileBookSummary;
import org.booklore.mobile.dto.MobileFilterOptions;
import org.booklore.mobile.dto.MobilePageResponse;
import org.booklore.mobile.mapper.MobileBookMapper;
import org.booklore.mobile.specification.MobileBookSpecification;
import org.booklore.app.dto.AppBookDetail;
import org.booklore.app.dto.AppBookSummary;
import org.booklore.app.dto.AppFilterOptions;
import org.booklore.app.dto.AppPageResponse;
import org.booklore.app.mapper.AppBookMapper;
import org.booklore.app.specification.AppBookSpecification;
import org.booklore.model.dto.Book;
import org.booklore.model.dto.BookLoreUser;
import org.booklore.model.dto.Library;
@@ -38,7 +38,7 @@ import java.util.stream.Collectors;
@Service
@AllArgsConstructor
public class MobileBookService {
public class AppBookService {
private static final int DEFAULT_PAGE_SIZE = 20;
private static final int MAX_PAGE_SIZE = 50;
@@ -48,12 +48,12 @@ public class MobileBookService {
private final UserBookFileProgressRepository userBookFileProgressRepository;
private final ShelfRepository shelfRepository;
private final AuthenticationService authenticationService;
private final MobileBookMapper mobileBookMapper;
private final AppBookMapper mobileBookMapper;
private final MagicShelfBookService magicShelfBookService;
private final EntityManager entityManager;
@Transactional(readOnly = true)
public MobilePageResponse<MobileBookSummary> getBooks(
public AppPageResponse<AppBookSummary> getBooks(
Integer page,
Integer size,
String sortBy,
@@ -89,15 +89,15 @@ public class MobileBookService {
.collect(Collectors.toSet());
Map<Long, UserBookProgressEntity> progressMap = getProgressMap(userId, bookIds);
List<MobileBookSummary> summaries = bookPage.getContent().stream()
List<AppBookSummary> summaries = bookPage.getContent().stream()
.map(book -> mobileBookMapper.toSummary(book, progressMap.get(book.getId())))
.collect(Collectors.toList());
return MobilePageResponse.of(summaries, pageNum, pageSize, bookPage.getTotalElements());
return AppPageResponse.of(summaries, pageNum, pageSize, bookPage.getTotalElements());
}
@Transactional(readOnly = true)
public MobileBookDetail getBookDetail(Long bookId) {
public AppBookDetail getBookDetail(Long bookId) {
BookLoreUser user = authenticationService.getAuthenticatedUser();
Long userId = user.getId();
Set<Long> accessibleLibraryIds = getAccessibleLibraryIds(user);
@@ -121,7 +121,7 @@ public class MobileBookService {
}
@Transactional(readOnly = true)
public MobilePageResponse<MobileBookSummary> searchBooks(
public AppPageResponse<AppBookSummary> searchBooks(
String query,
Integer page,
Integer size) {
@@ -139,11 +139,11 @@ public class MobileBookService {
Pageable pageable = PageRequest.of(pageNum, pageSize, Sort.by(Sort.Direction.DESC, "addedOn"));
Specification<BookEntity> spec = MobileBookSpecification.combine(
MobileBookSpecification.notDeleted(),
MobileBookSpecification.hasDigitalFile(),
MobileBookSpecification.inLibraries(accessibleLibraryIds),
MobileBookSpecification.searchText(query)
Specification<BookEntity> spec = AppBookSpecification.combine(
AppBookSpecification.notDeleted(),
AppBookSpecification.hasDigitalFile(),
AppBookSpecification.inLibraries(accessibleLibraryIds),
AppBookSpecification.searchText(query)
);
Page<BookEntity> bookPage = bookRepository.findAll(spec, pageable);
@@ -151,19 +151,19 @@ public class MobileBookService {
}
@Transactional(readOnly = true)
public List<MobileBookSummary> getContinueReading(Integer limit) {
public List<AppBookSummary> getContinueReading(Integer limit) {
BookLoreUser user = authenticationService.getAuthenticatedUser();
Long userId = user.getId();
Set<Long> accessibleLibraryIds = getAccessibleLibraryIds(user);
int maxItems = validateLimit(limit, 10);
Specification<BookEntity> spec = MobileBookSpecification.combine(
MobileBookSpecification.notDeleted(),
MobileBookSpecification.hasDigitalFile(),
MobileBookSpecification.inLibraries(accessibleLibraryIds),
MobileBookSpecification.inProgress(userId),
MobileBookSpecification.hasNonAudiobookFile()
Specification<BookEntity> spec = AppBookSpecification.combine(
AppBookSpecification.notDeleted(),
AppBookSpecification.hasDigitalFile(),
AppBookSpecification.inLibraries(accessibleLibraryIds),
AppBookSpecification.inProgress(userId),
AppBookSpecification.hasNonAudiobookFile()
);
List<BookEntity> books = bookRepository.findAll(spec);
@@ -185,19 +185,19 @@ public class MobileBookService {
}
@Transactional(readOnly = true)
public List<MobileBookSummary> getContinueListening(Integer limit) {
public List<AppBookSummary> getContinueListening(Integer limit) {
BookLoreUser user = authenticationService.getAuthenticatedUser();
Long userId = user.getId();
Set<Long> accessibleLibraryIds = getAccessibleLibraryIds(user);
int maxItems = validateLimit(limit, 10);
Specification<BookEntity> spec = MobileBookSpecification.combine(
MobileBookSpecification.notDeleted(),
MobileBookSpecification.hasDigitalFile(),
MobileBookSpecification.inLibraries(accessibleLibraryIds),
MobileBookSpecification.inProgress(userId),
MobileBookSpecification.hasAudiobookFile()
Specification<BookEntity> spec = AppBookSpecification.combine(
AppBookSpecification.notDeleted(),
AppBookSpecification.hasDigitalFile(),
AppBookSpecification.inLibraries(accessibleLibraryIds),
AppBookSpecification.inProgress(userId),
AppBookSpecification.hasAudiobookFile()
);
List<BookEntity> books = bookRepository.findAll(spec);
@@ -219,18 +219,18 @@ public class MobileBookService {
}
@Transactional(readOnly = true)
public List<MobileBookSummary> getRecentlyAdded(Integer limit) {
public List<AppBookSummary> getRecentlyAdded(Integer limit) {
BookLoreUser user = authenticationService.getAuthenticatedUser();
Long userId = user.getId();
Set<Long> accessibleLibraryIds = getAccessibleLibraryIds(user);
int maxItems = validateLimit(limit, 10);
Specification<BookEntity> spec = MobileBookSpecification.combine(
MobileBookSpecification.notDeleted(),
MobileBookSpecification.hasDigitalFile(),
MobileBookSpecification.inLibraries(accessibleLibraryIds),
MobileBookSpecification.addedWithinDays(30)
Specification<BookEntity> spec = AppBookSpecification.combine(
AppBookSpecification.notDeleted(),
AppBookSpecification.hasDigitalFile(),
AppBookSpecification.inLibraries(accessibleLibraryIds),
AppBookSpecification.addedWithinDays(30)
);
Pageable pageable = PageRequest.of(0, maxItems, Sort.by(Sort.Direction.DESC, "addedOn"));
@@ -243,7 +243,30 @@ public class MobileBookService {
}
@Transactional(readOnly = true)
public MobilePageResponse<MobileBookSummary> getRandomBooks(
public List<AppBookSummary> getRecentlyScanned(Integer limit) {
BookLoreUser user = authenticationService.getAuthenticatedUser();
Long userId = user.getId();
Set<Long> accessibleLibraryIds = getAccessibleLibraryIds(user);
int maxItems = validateLimit(limit, 10);
Specification<BookEntity> spec = AppBookSpecification.combine(
AppBookSpecification.notDeleted(),
AppBookSpecification.hasScannedOn(),
AppBookSpecification.inLibraries(accessibleLibraryIds)
);
Pageable pageable = PageRequest.of(0, maxItems, Sort.by(Sort.Direction.DESC, "scannedOn"));
Page<BookEntity> bookPage = bookRepository.findAll(spec, pageable);
Map<Long, UserBookProgressEntity> progressMap = getProgressMapForBooks(userId, bookPage.getContent());
return bookPage.getContent().stream()
.map(book -> mobileBookMapper.toSummary(book, progressMap.get(book.getId())))
.collect(Collectors.toList());
}
@Transactional(readOnly = true)
public AppPageResponse<AppBookSummary> getRandomBooks(
Integer page,
Integer size,
Long libraryId) {
@@ -260,7 +283,7 @@ public class MobileBookService {
long totalElements = bookRepository.count(spec);
if (totalElements == 0) {
return MobilePageResponse.of(Collections.emptyList(), pageNum, pageSize, 0L);
return AppPageResponse.of(Collections.emptyList(), pageNum, pageSize, 0L);
}
long maxOffset = Math.max(0, totalElements - pageSize);
@@ -273,7 +296,7 @@ public class MobileBookService {
}
@Transactional(readOnly = true)
public MobilePageResponse<MobileBookSummary> getBooksByMagicShelf(
public AppPageResponse<AppBookSummary> getBooksByMagicShelf(
Long magicShelfId,
Integer page,
Integer size) {
@@ -291,22 +314,22 @@ public class MobileBookService {
.collect(Collectors.toSet());
if (bookIds.isEmpty()) {
return MobilePageResponse.of(Collections.emptyList(), pageNum, pageSize, 0L);
return AppPageResponse.of(Collections.emptyList(), pageNum, pageSize, 0L);
}
List<BookEntity> bookEntities = bookRepository.findAllById(bookIds);
Map<Long, UserBookProgressEntity> progressMap = getProgressMapForBooks(userId, bookEntities);
List<MobileBookSummary> summaries = bookEntities.stream()
List<AppBookSummary> summaries = bookEntities.stream()
.filter(BookEntity::hasFiles)
.map(bookEntity -> mobileBookMapper.toSummary(bookEntity, progressMap.get(bookEntity.getId())))
.collect(Collectors.toList());
return MobilePageResponse.of(summaries, pageNum, pageSize, booksPage.getTotalElements());
return AppPageResponse.of(summaries, pageNum, pageSize, booksPage.getTotalElements());
}
@Transactional(readOnly = true)
public MobileFilterOptions getFilterOptions(Long libraryId, Long shelfId, Long magicShelfId) {
public AppFilterOptions getFilterOptions(Long libraryId, Long shelfId, Long magicShelfId) {
BookLoreUser user = authenticationService.getAuthenticatedUser();
Long userId = user.getId();
Set<Long> accessibleLibraryIds = getAccessibleLibraryIds(user);
@@ -316,7 +339,7 @@ public class MobileBookService {
if (magicShelfId != null) {
magicBookIds = resolveMagicShelfBookIds(magicShelfId, userId);
if (magicBookIds.isEmpty()) {
return MobileFilterOptions.builder()
return AppFilterOptions.builder()
.authors(Collections.emptyList())
.languages(Collections.emptyList())
.fileTypes(Collections.emptyList())
@@ -347,7 +370,7 @@ public class MobileBookService {
if (magicBookIds != null) {
magicBookClause = "AND b.id IN :magicBookIds";
} else if (shelfId != null) {
shelfClause = "AND b.id IN (SELECT sb.id FROM ShelfEntity s JOIN s.books sb WHERE s.id = :shelfId)";
shelfClause = "AND b.id IN (SELECT sb.id FROM ShelfEntity s JOIN s.bookEntities sb WHERE s.id = :shelfId)";
}
if (libraryId != null) {
@@ -370,8 +393,8 @@ public class MobileBookService {
setFilterQueryParams(authorQ, accessibleLibraryIds, libraryId, shelfId, magicBookIds);
authorQ.setMaxResults(200);
List<MobileFilterOptions.AuthorOption> authors = authorQ.getResultList().stream()
.map(t -> MobileFilterOptions.AuthorOption.builder()
List<AppFilterOptions.AuthorOption> authors = authorQ.getResultList().stream()
.map(t -> AppFilterOptions.AuthorOption.builder()
.name(t.get(0, String.class))
.count(t.get(1, Long.class))
.build())
@@ -388,8 +411,8 @@ public class MobileBookService {
var langQ = entityManager.createQuery(langQuery, Tuple.class);
setFilterQueryParams(langQ, accessibleLibraryIds, libraryId, shelfId, magicBookIds);
List<MobileFilterOptions.LanguageOption> languages = langQ.getResultList().stream()
.map(t -> MobileFilterOptions.LanguageOption.builder()
List<AppFilterOptions.LanguageOption> languages = langQ.getResultList().stream()
.map(t -> AppFilterOptions.LanguageOption.builder()
.code(t.get(0, String.class))
.label(Locale.forLanguageTag(t.get(0, String.class)).getDisplayLanguage(Locale.ENGLISH))
.count(t.get(1, Long.class))
@@ -414,7 +437,7 @@ public class MobileBookService {
// Read statuses — return all meaningful values
List<String> readStatuses = getReadStatusOptions();
return MobileFilterOptions.builder()
return AppFilterOptions.builder()
.authors(authors)
.languages(languages)
.fileTypes(fileTypes)
@@ -547,19 +570,19 @@ public class MobileBookService {
String language) {
List<Specification<BookEntity>> specs = new ArrayList<>();
specs.add(MobileBookSpecification.notDeleted());
specs.add(MobileBookSpecification.hasDigitalFile());
specs.add(AppBookSpecification.notDeleted());
specs.add(AppBookSpecification.hasDigitalFile());
if (accessibleLibraryIds != null) {
if (libraryId != null && accessibleLibraryIds.contains(libraryId)) {
specs.add(MobileBookSpecification.inLibrary(libraryId));
specs.add(AppBookSpecification.inLibrary(libraryId));
} else if (libraryId != null) {
throw ApiError.FORBIDDEN.createException("Access denied to library " + libraryId);
} else {
specs.add(MobileBookSpecification.inLibraries(accessibleLibraryIds));
specs.add(AppBookSpecification.inLibraries(accessibleLibraryIds));
}
} else if (libraryId != null) {
specs.add(MobileBookSpecification.inLibrary(libraryId));
specs.add(AppBookSpecification.inLibrary(libraryId));
}
if (shelfId != null) {
@@ -568,38 +591,38 @@ public class MobileBookService {
if (!shelf.isPublic() && !shelf.getUser().getId().equals(userId)) {
throw ApiError.FORBIDDEN.createException("Access denied to shelf " + shelfId);
}
specs.add(MobileBookSpecification.inShelf(shelfId));
specs.add(AppBookSpecification.inShelf(shelfId));
}
if (status != null) {
specs.add(MobileBookSpecification.withReadStatus(status, userId));
specs.add(AppBookSpecification.withReadStatus(status, userId));
}
if (search != null && !search.trim().isEmpty()) {
specs.add(MobileBookSpecification.searchText(search));
specs.add(AppBookSpecification.searchText(search));
}
if (fileType != null) {
specs.add(MobileBookSpecification.withFileType(fileType));
specs.add(AppBookSpecification.withFileType(fileType));
}
if (minRating != null) {
specs.add(MobileBookSpecification.withMinRating(minRating, userId));
specs.add(AppBookSpecification.withMinRating(minRating, userId));
}
if (maxRating != null) {
specs.add(MobileBookSpecification.withMaxRating(maxRating, userId));
specs.add(AppBookSpecification.withMaxRating(maxRating, userId));
}
if (authors != null && !authors.trim().isEmpty()) {
specs.add(MobileBookSpecification.withAuthor(authors.trim()));
specs.add(AppBookSpecification.withAuthor(authors.trim()));
}
if (language != null && !language.trim().isEmpty()) {
specs.add(MobileBookSpecification.withLanguage(language.trim()));
specs.add(AppBookSpecification.withLanguage(language.trim()));
}
return MobileBookSpecification.combine(specs.toArray(new Specification[0]));
return AppBookSpecification.combine(specs.toArray(new Specification[0]));
}
private Sort buildSort(String sortBy, String sortDir) {
@@ -631,24 +654,24 @@ public class MobileBookService {
private Specification<BookEntity> buildBaseSpecification(Set<Long> accessibleLibraryIds, Long libraryId) {
List<Specification<BookEntity>> specs = new ArrayList<>();
specs.add(MobileBookSpecification.notDeleted());
specs.add(MobileBookSpecification.hasDigitalFile());
specs.add(AppBookSpecification.notDeleted());
specs.add(AppBookSpecification.hasDigitalFile());
if (accessibleLibraryIds != null) {
if (libraryId != null && !accessibleLibraryIds.contains(libraryId)) {
throw ApiError.FORBIDDEN.createException("Access denied to library " + libraryId);
}
specs.add(libraryId != null
? MobileBookSpecification.inLibrary(libraryId)
: MobileBookSpecification.inLibraries(accessibleLibraryIds));
? AppBookSpecification.inLibrary(libraryId)
: AppBookSpecification.inLibraries(accessibleLibraryIds));
} else if (libraryId != null) {
specs.add(MobileBookSpecification.inLibrary(libraryId));
specs.add(AppBookSpecification.inLibrary(libraryId));
}
return MobileBookSpecification.combine(specs.toArray(new Specification[0]));
return AppBookSpecification.combine(specs.toArray(new Specification[0]));
}
private MobilePageResponse<MobileBookSummary> buildPageResponse(
private AppPageResponse<AppBookSummary> buildPageResponse(
Page<BookEntity> bookPage,
Long userId,
int pageNum,
@@ -656,11 +679,11 @@ public class MobileBookService {
Map<Long, UserBookProgressEntity> progressMap = getProgressMapForBooks(userId, bookPage.getContent());
List<MobileBookSummary> summaries = bookPage.getContent().stream()
List<AppBookSummary> summaries = bookPage.getContent().stream()
.map(book -> mobileBookMapper.toSummary(book, progressMap.get(book.getId())))
.collect(Collectors.toList());
return MobilePageResponse.of(summaries, pageNum, pageSize, bookPage.getTotalElements());
return AppPageResponse.of(summaries, pageNum, pageSize, bookPage.getTotalElements());
}
private Map<Long, UserBookProgressEntity> getProgressMapForBooks(Long userId, List<BookEntity> books) {
@@ -0,0 +1,197 @@
package org.booklore.app.service;
import org.booklore.config.security.service.AuthenticationService;
import org.booklore.app.dto.AppNotebookBookSummary;
import org.booklore.app.dto.AppNotebookEntry;
import org.booklore.app.dto.AppNotebookUpdateRequest;
import org.booklore.app.dto.AppPageResponse;
import org.booklore.model.dto.UpdateAnnotationRequest;
import org.booklore.model.dto.UpdateBookMarkRequest;
import org.booklore.model.dto.UpdateBookNoteV2Request;
import org.booklore.repository.AuthorRepository;
import org.booklore.repository.NotebookEntryRepository;
import org.booklore.service.book.AnnotationService;
import org.booklore.service.book.BookMarkService;
import org.booklore.service.book.BookNoteV2Service;
import lombok.AllArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.*;
import java.util.stream.Collectors;
@Service
@AllArgsConstructor
public class AppNotebookService {
private final NotebookEntryRepository notebookEntryRepository;
private final AuthorRepository authorRepository;
private final AuthenticationService authenticationService;
private final AnnotationService annotationService;
private final BookNoteV2Service bookNoteV2Service;
private final BookMarkService bookMarkService;
@Transactional(readOnly = true)
public AppPageResponse<AppNotebookBookSummary> getBooksWithAnnotations(int page, int size, String search) {
Long userId = authenticationService.getAuthenticatedUser().getId();
Pageable pageable = PageRequest.of(page, size);
Page<NotebookEntryRepository.BookWithCountProjection> booksPage =
notebookEntryRepository.findBooksWithAnnotationsPaginated(userId, wrapSearch(search), pageable);
List<NotebookEntryRepository.BookWithCountProjection> content = booksPage.getContent();
if (content.isEmpty()) {
return AppPageResponse.of(List.of(), page, size, 0);
}
Set<Long> bookIds = content.stream()
.map(NotebookEntryRepository.BookWithCountProjection::getBookId)
.collect(Collectors.toSet());
Map<Long, List<String>> authorsByBook = authorRepository.findAuthorNamesByBookIds(bookIds)
.stream()
.collect(Collectors.groupingBy(
AuthorRepository.AuthorBookProjection::getBookId,
Collectors.mapping(AuthorRepository.AuthorBookProjection::getAuthorName, Collectors.toList())));
List<AppNotebookBookSummary> summaries = content.stream()
.map(p -> AppNotebookBookSummary.builder()
.bookId(p.getBookId())
.bookTitle(p.getBookTitle())
.noteCount(p.getNoteCount())
.authors(authorsByBook.getOrDefault(p.getBookId(), List.of()))
.coverUpdatedOn(p.getCoverUpdatedOn())
.build())
.toList();
return AppPageResponse.of(summaries, page, size, booksPage.getTotalElements());
}
@Transactional(readOnly = true)
public AppPageResponse<AppNotebookEntry> getEntriesForBook(Long bookId, int page, int size,
Set<String> types, String search, String sort) {
Long userId = authenticationService.getAuthenticatedUser().getId();
Set<String> entryTypes = (types == null || types.isEmpty())
? Set.of("HIGHLIGHT", "NOTE", "BOOKMARK")
: types;
Pageable pageable = PageRequest.of(page, size, toSort(sort));
Page<NotebookEntryRepository.EntryProjection> entriesPage =
notebookEntryRepository.findEntries(userId, entryTypes, bookId, wrapSearch(search), pageable);
List<AppNotebookEntry> entries = entriesPage.getContent().stream()
.map(AppNotebookService::toMobileEntry)
.toList();
return AppPageResponse.of(entries, page, size, entriesPage.getTotalElements());
}
@Transactional
public AppNotebookEntry updateEntry(Long entryId, String type, AppNotebookUpdateRequest request) {
return switch (type.toUpperCase()) {
case "HIGHLIGHT" -> {
var updateReq = new UpdateAnnotationRequest();
if (request.getNote() != null) updateReq.setNote(request.getNote());
if (request.getColor() != null) updateReq.setColor(request.getColor());
var result = annotationService.updateAnnotation(entryId, updateReq);
yield AppNotebookEntry.builder()
.id(result.getId())
.type("HIGHLIGHT")
.bookId(result.getBookId())
.text(result.getText())
.note(result.getNote())
.color(result.getColor())
.style(result.getStyle())
.chapterTitle(result.getChapterTitle())
.createdAt(result.getCreatedAt())
.updatedAt(result.getUpdatedAt())
.build();
}
case "NOTE" -> {
var updateReq = new UpdateBookNoteV2Request();
if (request.getNote() != null) updateReq.setNoteContent(request.getNote());
if (request.getColor() != null) updateReq.setColor(request.getColor());
var result = bookNoteV2Service.updateNote(entryId, updateReq);
yield AppNotebookEntry.builder()
.id(result.getId())
.type("NOTE")
.bookId(result.getBookId())
.text(result.getSelectedText())
.note(result.getNoteContent())
.color(result.getColor())
.chapterTitle(result.getChapterTitle())
.createdAt(result.getCreatedAt())
.updatedAt(result.getUpdatedAt())
.build();
}
case "BOOKMARK" -> {
var updateReq = new UpdateBookMarkRequest();
if (request.getNote() != null) updateReq.setNotes(request.getNote());
if (request.getColor() != null) updateReq.setColor(request.getColor());
var result = bookMarkService.updateBookmark(entryId, updateReq);
yield AppNotebookEntry.builder()
.id(result.getId())
.type("BOOKMARK")
.bookId(result.getBookId())
.text(result.getTitle())
.note(result.getNotes())
.color(result.getColor())
.createdAt(result.getCreatedAt())
.updatedAt(result.getUpdatedAt())
.build();
}
default -> throw new IllegalArgumentException("Unknown entry type: " + type);
};
}
@Transactional
public void deleteEntry(Long entryId, String type) {
switch (type.toUpperCase()) {
case "HIGHLIGHT" -> annotationService.deleteAnnotation(entryId);
case "NOTE" -> bookNoteV2Service.deleteNote(entryId);
case "BOOKMARK" -> bookMarkService.deleteBookmark(entryId);
default -> throw new IllegalArgumentException("Unknown entry type: " + type);
}
}
private String wrapSearch(String search) {
if (search == null || search.isBlank()) return null;
return "%" + escapeLike(search) + "%";
}
private static String escapeLike(String input) {
return input.trim()
.replace("\\", "\\\\")
.replace("%", "\\%")
.replace("_", "\\_");
}
private static Sort toSort(String sort) {
if ("chapter".equalsIgnoreCase(sort)) {
return Sort.by(Sort.Order.asc("chapterTitle"), Sort.Order.asc("createdAt"));
}
if ("date_asc".equalsIgnoreCase(sort)) {
return Sort.by("createdAt").ascending();
}
return Sort.by("createdAt").descending();
}
private static AppNotebookEntry toMobileEntry(NotebookEntryRepository.EntryProjection p) {
return AppNotebookEntry.builder()
.id(p.getId())
.type(p.getType())
.bookId(p.getBookId())
.text(p.getText())
.note(p.getNote())
.color(p.getColor())
.style(p.getStyle())
.chapterTitle(p.getChapterTitle())
.createdAt(p.getCreatedAt())
.updatedAt(p.getUpdatedAt())
.build();
}
}
@@ -1,13 +1,13 @@
package org.booklore.mobile.service;
package org.booklore.app.service;
import jakarta.persistence.EntityManager;
import jakarta.persistence.Tuple;
import lombok.AllArgsConstructor;
import org.booklore.config.security.service.AuthenticationService;
import org.booklore.exception.ApiError;
import org.booklore.mobile.dto.*;
import org.booklore.mobile.mapper.MobileBookMapper;
import org.booklore.mobile.specification.MobileBookSpecification;
import org.booklore.app.dto.*;
import org.booklore.app.mapper.AppBookMapper;
import org.booklore.app.specification.AppBookSpecification;
import org.booklore.model.dto.BookLoreUser;
import org.booklore.model.dto.Library;
import org.booklore.model.entity.*;
@@ -29,7 +29,7 @@ import java.util.stream.Collectors;
@Service
@AllArgsConstructor
public class MobileSeriesService {
public class AppSeriesService {
private static final int DEFAULT_PAGE_SIZE = 20;
private static final int MAX_PAGE_SIZE = 50;
@@ -38,10 +38,10 @@ public class MobileSeriesService {
private final AuthenticationService authenticationService;
private final BookRepository bookRepository;
private final UserBookProgressRepository userBookProgressRepository;
private final MobileBookMapper mobileBookMapper;
private final AppBookMapper mobileBookMapper;
@Transactional(readOnly = true)
public MobilePageResponse<MobileSeriesSummary> getSeries(
public AppPageResponse<AppSeriesSummary> getSeries(
Integer page,
Integer size,
String sortBy,
@@ -154,7 +154,7 @@ public class MobileSeriesService {
return buildSeriesPage(aggregateResults, userId, accessibleLibraryIds, libraryId, inProgressOnly, pageNum, pageSize, totalElements);
}
private MobilePageResponse<MobileSeriesSummary> buildSeriesPage(
private AppPageResponse<AppSeriesSummary> buildSeriesPage(
List<Tuple> aggregateResults,
Long userId,
Set<Long> accessibleLibraryIds,
@@ -165,7 +165,7 @@ public class MobileSeriesService {
long totalElements) {
if (aggregateResults.isEmpty()) {
return MobilePageResponse.of(Collections.emptyList(), pageNum, pageSize, totalElements);
return AppPageResponse.of(Collections.emptyList(), pageNum, pageSize, totalElements);
}
List<String> seriesNames = aggregateResults.stream()
@@ -199,7 +199,7 @@ public class MobileSeriesService {
}
// Merge into summaries, preserving Phase 1 order
List<MobileSeriesSummary> summaries = new ArrayList<>();
List<AppSeriesSummary> summaries = new ArrayList<>();
for (String seriesName : seriesNames) {
Tuple agg = aggregateMap.get(seriesName);
List<BookEntity> seriesBooks = booksBySeries.getOrDefault(seriesName, Collections.emptyList());
@@ -234,7 +234,7 @@ public class MobileSeriesService {
Long booksReadLong = agg.get(4, Long.class);
int booksRead = booksReadLong != null ? booksReadLong.intValue() : 0;
summaries.add(MobileSeriesSummary.builder()
summaries.add(AppSeriesSummary.builder()
.seriesName(agg.get(0, String.class))
.bookCount(agg.get(1, Long.class).intValue())
.seriesTotal(agg.get(2, Integer.class))
@@ -245,11 +245,11 @@ public class MobileSeriesService {
.build());
}
return MobilePageResponse.of(summaries, pageNum, pageSize, totalElements);
return AppPageResponse.of(summaries, pageNum, pageSize, totalElements);
}
@Transactional(readOnly = true)
public MobilePageResponse<MobileBookSummary> getSeriesBooks(
public AppPageResponse<AppBookSummary> getSeriesBooks(
String seriesName,
Integer page,
Integer size,
@@ -280,14 +280,14 @@ public class MobileSeriesService {
.collect(Collectors.toSet());
Map<Long, UserBookProgressEntity> progressMap = getProgressMap(userId, bookIds);
List<MobileBookSummary> summaries = bookPage.getContent().stream()
List<AppBookSummary> summaries = bookPage.getContent().stream()
.map(book -> mobileBookMapper.toSummary(book, progressMap.get(book.getId())))
.toList();
return MobilePageResponse.of(summaries, pageNum, pageSize, bookPage.getTotalElements());
return AppPageResponse.of(summaries, pageNum, pageSize, bookPage.getTotalElements());
}
// --- Access control helpers (duplicated from MobileBookService to minimize blast radius) ---
// --- Access control helpers (duplicated from AppBookService to minimize blast radius) ---
private Set<Long> getAccessibleLibraryIds(BookLoreUser user) {
if (user.getPermissions().isAdmin()) {
@@ -362,19 +362,19 @@ public class MobileSeriesService {
private Specification<BookEntity> buildSeriesBooksSpec(Set<Long> accessibleLibraryIds, Long libraryId, String seriesName) {
List<Specification<BookEntity>> specs = new ArrayList<>();
specs.add(MobileBookSpecification.notDeleted());
specs.add(MobileBookSpecification.hasDigitalFile());
specs.add(MobileBookSpecification.inSeries(seriesName));
specs.add(AppBookSpecification.notDeleted());
specs.add(AppBookSpecification.hasDigitalFile());
specs.add(AppBookSpecification.inSeries(seriesName));
if (accessibleLibraryIds != null) {
specs.add(libraryId != null
? MobileBookSpecification.inLibrary(libraryId)
: MobileBookSpecification.inLibraries(accessibleLibraryIds));
? AppBookSpecification.inLibrary(libraryId)
: AppBookSpecification.inLibraries(accessibleLibraryIds));
} else if (libraryId != null) {
specs.add(MobileBookSpecification.inLibrary(libraryId));
specs.add(AppBookSpecification.inLibrary(libraryId));
}
return MobileBookSpecification.combine(specs.toArray(new Specification[0]));
return AppBookSpecification.combine(specs.toArray(new Specification[0]));
}
private Map<Long, UserBookProgressEntity> getProgressMap(Long userId, Set<Long> bookIds) {
@@ -1,4 +1,4 @@
package org.booklore.mobile.specification;
package org.booklore.app.specification;
import org.booklore.model.entity.*;
import org.booklore.model.enums.BookFileType;
@@ -12,9 +12,9 @@ import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
public class MobileBookSpecification {
public class AppBookSpecification {
private MobileBookSpecification() {
private AppBookSpecification() {
}
public static Specification<BookEntity> inLibraries(Collection<Long> libraryIds) {
@@ -112,6 +112,10 @@ public class MobileBookSpecification {
);
}
public static Specification<BookEntity> hasScannedOn() {
return (root, query, cb) -> cb.isNotNull(root.get("scannedOn"));
}
public static Specification<BookEntity> hasDigitalFile() {
return (root, query, cb) -> cb.isNotEmpty(root.get("bookFiles"));
}
@@ -17,8 +17,8 @@ public class CacheConfig {
public CacheManager cacheManager() {
CaffeineCacheManager cacheManager = new CaffeineCacheManager("publicSettings");
cacheManager.setCaffeine(Caffeine.newBuilder()
.expireAfterWrite(Duration.ofMinutes(5))
.maximumSize(10));
.expireAfterWrite(Duration.ofHours(24))
.maximumSize(100));
return cacheManager;
}
}
@@ -189,7 +189,7 @@ public class SecurityConfig {
@Order(7)
public SecurityFilterChain audiobookStreamingSecurityChain(HttpSecurity http, AudiobookStreamingJwtFilter audiobookStreamingJwtFilter) throws Exception {
http
.securityMatcher("/api/v1/audiobook/*/stream/**", "/api/v1/audiobook/*/track/*/stream/**", "/api/v1/audiobook/*/cover")
.securityMatcher("/api/v1/audiobooks/*/stream/**", "/api/v1/audiobooks/*/track/*/stream/**", "/api/v1/audiobooks/*/cover")
.cors(cors -> cors.configurationSource(corsConfigurationSource()))
.csrf(AbstractHttpConfigurer::disable)
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
@@ -25,7 +25,7 @@ import java.util.regex.Pattern;
public class AudiobookStreamingJwtFilter extends OncePerRequestFilter {
private static final Pattern AUDIOBOOK_STREAMING_ENDPOINT_PATTERN =
Pattern.compile("/api/v1/audiobook/\\d+/(stream|track/\\d+/stream|cover).*");
Pattern.compile("/api/v1/audiobooks/\\d+/(stream|track/\\d+/stream|cover).*");
private final JwtUtils jwtUtils;
private final UserRepository userRepository;
@@ -22,7 +22,7 @@ import java.nio.file.Path;
@Slf4j
@RestController
@RequestMapping("/api/v1/audiobook")
@RequestMapping("/api/v1/audiobooks")
@RequiredArgsConstructor
@Tag(name = "Audiobook Reader", description = "Endpoints for streaming audiobooks with HTTP Range support")
public class AudiobookReaderController {
@@ -17,7 +17,7 @@ import java.util.List;
@AllArgsConstructor
@RestController
@RequestMapping("/api/v2/email/providers")
@RequestMapping("/api/v1/email/providers")
@Tag(name = "Email Providers", description = "Endpoints for managing email providers for book delivery")
public class EmailProviderV2Controller {
@@ -17,7 +17,7 @@ import java.util.List;
@AllArgsConstructor
@RestController
@RequestMapping("/api/v2/email/recipients")
@RequestMapping("/api/v1/email/recipients")
@Tag(name = "Email Recipients", description = "Endpoints for managing email recipients for book delivery")
public class EmailRecipientV2Controller {
@@ -14,7 +14,7 @@ import org.springframework.web.bind.annotation.*;
@AllArgsConstructor
@RestController
@RequestMapping("/api/v2/email")
@RequestMapping("/api/v1/email")
@Tag(name = "Send Email", description = "Endpoints for sending books via email")
public class SendEmailV2Controller {
@@ -24,7 +24,7 @@ public class UserStatsController {
@ApiResponse(responseCode = "200", description = "Heatmap data retrieved successfully"),
@ApiResponse(responseCode = "401", description = "Unauthorized")
})
@GetMapping("/heatmap")
@GetMapping("/reading/heatmap")
@PreAuthorize("@securityUtil.canAccessUserStats() or @securityUtil.isAdmin()")
public ResponseEntity<List<ReadingSessionHeatmapResponse>> getHeatmapForYear(@RequestParam int year) {
List<ReadingSessionHeatmapResponse> heatmapData = readingSessionService.getSessionHeatmapForYear(year);
@@ -36,7 +36,7 @@ public class UserStatsController {
@ApiResponse(responseCode = "200", description = "Heatmap data retrieved successfully"),
@ApiResponse(responseCode = "401", description = "Unauthorized")
})
@GetMapping("/heatmap/monthly")
@GetMapping("/reading/heatmap/monthly")
@PreAuthorize("@securityUtil.canAccessUserStats() or @securityUtil.isAdmin()")
public ResponseEntity<List<ReadingSessionHeatmapResponse>> getHeatmapForMonth(
@RequestParam int year,
@@ -51,7 +51,7 @@ public class UserStatsController {
@ApiResponse(responseCode = "400", description = "Invalid week or year"),
@ApiResponse(responseCode = "401", description = "Unauthorized")
})
@GetMapping("/timeline")
@GetMapping("/reading/timeline")
@PreAuthorize("@securityUtil.canAccessUserStats() or @securityUtil.isAdmin()")
public ResponseEntity<List<ReadingSessionTimelineResponse>> getTimelineForWeek(
@RequestParam int year,
@@ -65,7 +65,7 @@ public class UserStatsController {
@ApiResponse(responseCode = "200", description = "Reading speed data retrieved successfully"),
@ApiResponse(responseCode = "401", description = "Unauthorized")
})
@GetMapping("/speed")
@GetMapping("/reading/speed")
@PreAuthorize("@securityUtil.canAccessUserStats() or @securityUtil.isAdmin()")
public ResponseEntity<List<ReadingSpeedResponse>> getReadingSpeedForYear(@RequestParam int year) {
List<ReadingSpeedResponse> speedData = readingSessionService.getReadingSpeedForYear(year);
@@ -77,12 +77,12 @@ public class UserStatsController {
@ApiResponse(responseCode = "200", description = "Peak reading hours retrieved successfully"),
@ApiResponse(responseCode = "401", description = "Unauthorized")
})
@GetMapping("/peak-hours")
@GetMapping("/reading/peak-hours")
@PreAuthorize("@securityUtil.canAccessUserStats() or @securityUtil.isAdmin()")
public ResponseEntity<List<PeakReadingHoursResponse>> getPeakReadingHours(
public ResponseEntity<List<PeakHoursResponse>> getPeakReadingHours(
@RequestParam(required = false) Integer year,
@RequestParam(required = false) Integer month) {
List<PeakReadingHoursResponse> peakHours = readingSessionService.getPeakReadingHours(year, month);
List<PeakHoursResponse> peakHours = readingSessionService.getPeakReadingHours(year, month);
return ResponseEntity.ok(peakHours);
}
@@ -91,7 +91,7 @@ public class UserStatsController {
@ApiResponse(responseCode = "200", description = "Favorite reading days retrieved successfully"),
@ApiResponse(responseCode = "401", description = "Unauthorized")
})
@GetMapping("/favorite-days")
@GetMapping("/reading/favorite-days")
@PreAuthorize("@securityUtil.canAccessUserStats() or @securityUtil.isAdmin()")
public ResponseEntity<List<FavoriteReadingDaysResponse>> getFavoriteReadingDays(
@RequestParam(required = false) Integer year,
@@ -105,7 +105,7 @@ public class UserStatsController {
@ApiResponse(responseCode = "200", description = "Genre statistics retrieved successfully"),
@ApiResponse(responseCode = "401", description = "Unauthorized")
})
@GetMapping("/genres")
@GetMapping("/reading/genres")
@PreAuthorize("@securityUtil.canAccessUserStats() or @securityUtil.isAdmin()")
public ResponseEntity<List<GenreStatisticsResponse>> getGenreStatistics() {
List<GenreStatisticsResponse> genreStats = readingSessionService.getGenreStatistics();
@@ -117,7 +117,7 @@ public class UserStatsController {
@ApiResponse(responseCode = "200", description = "Completion timeline retrieved successfully"),
@ApiResponse(responseCode = "401", description = "Unauthorized")
})
@GetMapping("/completion-timeline")
@GetMapping("/reading/completion-timeline")
@PreAuthorize("@securityUtil.canAccessUserStats() or @securityUtil.isAdmin()")
public ResponseEntity<List<CompletionTimelineResponse>> getCompletionTimeline(@RequestParam int year) {
List<CompletionTimelineResponse> timeline = readingSessionService.getCompletionTimeline(year);
@@ -129,7 +129,7 @@ public class UserStatsController {
@ApiResponse(responseCode = "200", description = "Book completion heatmap data retrieved successfully"),
@ApiResponse(responseCode = "401", description = "Unauthorized")
})
@GetMapping("/book-completion-heatmap")
@GetMapping("/reading/book-completion-heatmap")
@PreAuthorize("@securityUtil.canAccessUserStats() or @securityUtil.isAdmin()")
public ResponseEntity<List<BookCompletionHeatmapResponse>> getBookCompletionHeatmap() {
List<BookCompletionHeatmapResponse> heatmapData = readingSessionService.getBookCompletionHeatmap();
@@ -141,7 +141,7 @@ public class UserStatsController {
@ApiResponse(responseCode = "200", description = "Page turner scores retrieved successfully"),
@ApiResponse(responseCode = "401", description = "Unauthorized")
})
@GetMapping("/page-turner-scores")
@GetMapping("/reading/page-turner-scores")
@PreAuthorize("@securityUtil.canAccessUserStats() or @securityUtil.isAdmin()")
public ResponseEntity<List<PageTurnerScoreResponse>> getPageTurnerScores() {
List<PageTurnerScoreResponse> scores = readingSessionService.getPageTurnerScores();
@@ -153,7 +153,7 @@ public class UserStatsController {
@ApiResponse(responseCode = "200", description = "Completion race data retrieved successfully"),
@ApiResponse(responseCode = "401", description = "Unauthorized")
})
@GetMapping("/completion-race")
@GetMapping("/reading/completion-race")
@PreAuthorize("@securityUtil.canAccessUserStats() or @securityUtil.isAdmin()")
public ResponseEntity<List<CompletionRaceResponse>> getCompletionRace(@RequestParam int year) {
List<CompletionRaceResponse> data = readingSessionService.getCompletionRace(year);
@@ -165,7 +165,7 @@ public class UserStatsController {
@ApiResponse(responseCode = "200", description = "Book distributions retrieved successfully"),
@ApiResponse(responseCode = "401", description = "Unauthorized")
})
@GetMapping("/book-distributions")
@GetMapping("/reading/book-distributions")
@PreAuthorize("@securityUtil.canAccessUserStats() or @securityUtil.isAdmin()")
public ResponseEntity<BookDistributionsResponse> getBookDistributions() {
BookDistributionsResponse data = readingSessionService.getBookDistributions();
@@ -177,7 +177,7 @@ public class UserStatsController {
@ApiResponse(responseCode = "200", description = "Reading dates retrieved successfully"),
@ApiResponse(responseCode = "401", description = "Unauthorized")
})
@GetMapping("/reading-dates")
@GetMapping("/reading/dates")
@PreAuthorize("@securityUtil.canAccessUserStats() or @securityUtil.isAdmin()")
public ResponseEntity<List<ReadingSessionHeatmapResponse>> getReadingDates() {
List<ReadingSessionHeatmapResponse> data = readingSessionService.getReadingDates();
@@ -189,10 +189,127 @@ public class UserStatsController {
@ApiResponse(responseCode = "200", description = "Session scatter data retrieved successfully"),
@ApiResponse(responseCode = "401", description = "Unauthorized")
})
@GetMapping("/session-scatter")
@GetMapping("/reading/session-scatter")
@PreAuthorize("@securityUtil.canAccessUserStats() or @securityUtil.isAdmin()")
public ResponseEntity<List<SessionScatterResponse>> getSessionScatter(@RequestParam int year) {
List<SessionScatterResponse> data = readingSessionService.getSessionScatter(year);
return ResponseEntity.ok(data);
}
@Operation(summary = "Get reading streak", description = "Returns current streak, longest streak, total reading days, and last 52 weeks of daily reading activity")
@ApiResponses({
@ApiResponse(responseCode = "200", description = "Reading streak data retrieved successfully"),
@ApiResponse(responseCode = "401", description = "Unauthorized")
})
@GetMapping("/reading/streak")
@PreAuthorize("@securityUtil.canAccessUserStats() or @securityUtil.isAdmin()")
public ResponseEntity<ReadingStreakResponse> getReadingStreak() {
return ResponseEntity.ok(readingSessionService.getReadingStreak());
}
@Operation(summary = "Get book timeline for a year", description = "Returns the reading lifespan of each book the user read in a given year")
@ApiResponses({
@ApiResponse(responseCode = "200", description = "Book timeline data retrieved successfully"),
@ApiResponse(responseCode = "401", description = "Unauthorized")
})
@GetMapping("/reading/book-timeline")
@PreAuthorize("@securityUtil.canAccessUserStats() or @securityUtil.isAdmin()")
public ResponseEntity<List<BookTimelineResponse>> getBookTimeline(@RequestParam int year) {
return ResponseEntity.ok(readingSessionService.getBookTimeline(year));
}
// ========================================================================
// Listening (audiobook) stats
// ========================================================================
@Operation(summary = "Get listening heatmap for a month", description = "Returns daily listening session counts and duration for the authenticated user for a specific month")
@ApiResponses({
@ApiResponse(responseCode = "200", description = "Listening heatmap data retrieved successfully"),
@ApiResponse(responseCode = "401", description = "Unauthorized")
})
@GetMapping("/listening/heatmap/monthly")
@PreAuthorize("@securityUtil.canAccessUserStats() or @securityUtil.isAdmin()")
public ResponseEntity<List<ListeningHeatmapResponse>> getListeningHeatmapForMonth(
@RequestParam int year,
@RequestParam int month) {
return ResponseEntity.ok(readingSessionService.getListeningHeatmapForMonth(year, month));
}
@Operation(summary = "Get weekly listening trend", description = "Returns weekly listening hours over a number of past weeks")
@ApiResponses({
@ApiResponse(responseCode = "200", description = "Weekly listening trend retrieved successfully"),
@ApiResponse(responseCode = "401", description = "Unauthorized")
})
@GetMapping("/listening/weekly-trend")
@PreAuthorize("@securityUtil.canAccessUserStats() or @securityUtil.isAdmin()")
public ResponseEntity<List<WeeklyListeningTrendResponse>> getWeeklyListeningTrend(
@RequestParam(defaultValue = "26") int weeks) {
return ResponseEntity.ok(readingSessionService.getWeeklyListeningTrend(weeks));
}
@Operation(summary = "Get audiobook completion progress", description = "Returns in-progress audiobooks with completion percentages and overall library stats")
@ApiResponses({
@ApiResponse(responseCode = "200", description = "Listening completion data retrieved successfully"),
@ApiResponse(responseCode = "401", description = "Unauthorized")
})
@GetMapping("/listening/completion")
@PreAuthorize("@securityUtil.canAccessUserStats() or @securityUtil.isAdmin()")
public ResponseEntity<ListeningCompletionResponse> getListeningCompletion() {
return ResponseEntity.ok(readingSessionService.getListeningCompletion());
}
@Operation(summary = "Get monthly audiobook pace", description = "Returns audiobooks completed per month with listening duration")
@ApiResponses({
@ApiResponse(responseCode = "200", description = "Monthly pace data retrieved successfully"),
@ApiResponse(responseCode = "401", description = "Unauthorized")
})
@GetMapping("/listening/monthly-pace")
@PreAuthorize("@securityUtil.canAccessUserStats() or @securityUtil.isAdmin()")
public ResponseEntity<List<MonthlyPaceResponse>> getMonthlyListeningPace(
@RequestParam(defaultValue = "12") int months) {
return ResponseEntity.ok(readingSessionService.getMonthlyListeningPace(months));
}
@Operation(summary = "Get audiobook finish rate funnel", description = "Returns how many audiobooks reached each progress milestone (25%, 50%, 75%, finished)")
@ApiResponses({
@ApiResponse(responseCode = "200", description = "Finish funnel data retrieved successfully"),
@ApiResponse(responseCode = "401", description = "Unauthorized")
})
@GetMapping("/listening/finish-funnel")
@PreAuthorize("@securityUtil.canAccessUserStats() or @securityUtil.isAdmin()")
public ResponseEntity<ListeningFinishFunnelResponse> getListeningFinishFunnel() {
return ResponseEntity.ok(readingSessionService.getListeningFinishFunnel());
}
@GetMapping("/listening/peak-hours")
@PreAuthorize("@securityUtil.canAccessUserStats() or @securityUtil.isAdmin()")
public ResponseEntity<List<PeakHoursResponse>> getListeningPeakHours(
@RequestParam(required = false) Integer year,
@RequestParam(required = false) Integer month) {
return ResponseEntity.ok(readingSessionService.getListeningPeakHours(year, month));
}
@GetMapping("/listening/genres")
@PreAuthorize("@securityUtil.canAccessUserStats() or @securityUtil.isAdmin()")
public ResponseEntity<List<GenreStatisticsResponse>> getListeningGenreStatistics() {
return ResponseEntity.ok(readingSessionService.getListeningGenreStatistics());
}
@GetMapping("/listening/authors")
@PreAuthorize("@securityUtil.canAccessUserStats() or @securityUtil.isAdmin()")
public ResponseEntity<List<ListeningAuthorResponse>> getListeningAuthorStats() {
return ResponseEntity.ok(readingSessionService.getListeningAuthorStats());
}
@GetMapping("/listening/session-scatter")
@PreAuthorize("@securityUtil.canAccessUserStats() or @securityUtil.isAdmin()")
public ResponseEntity<List<SessionScatterResponse>> getListeningSessionScatter() {
return ResponseEntity.ok(readingSessionService.getListeningSessionScatter());
}
@GetMapping("/listening/longest-books")
@PreAuthorize("@securityUtil.canAccessUserStats() or @securityUtil.isAdmin()")
public ResponseEntity<List<LongestAudiobookResponse>> getListeningLongestBooks() {
return ResponseEntity.ok(readingSessionService.getListeningLongestBooks());
}
}
@@ -1,56 +0,0 @@
package org.booklore.mobile.controller;
import org.booklore.mobile.dto.MobileAuthorDetail;
import org.booklore.mobile.dto.MobileAuthorSummary;
import org.booklore.mobile.dto.MobilePageResponse;
import org.booklore.mobile.service.MobileAuthorService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.AllArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
@AllArgsConstructor
@RestController
@RequestMapping("/api/mobile/v1/authors")
@Tag(name = "Mobile Authors", description = "Mobile-optimized endpoints for browsing authors")
public class MobileAuthorController {
private final MobileAuthorService mobileAuthorService;
@Operation(summary = "Get paginated author list",
description = "Retrieve a paginated list of authors with optional filtering by library, search text, and photo availability.")
@ApiResponses({
@ApiResponse(responseCode = "200", description = "Authors retrieved successfully"),
@ApiResponse(responseCode = "403", description = "Access denied")
})
@GetMapping
public ResponseEntity<MobilePageResponse<MobileAuthorSummary>> getAuthors(
@Parameter(description = "Page number (0-indexed)") @RequestParam(required = false, defaultValue = "0") Integer page,
@Parameter(description = "Page size (max 50)") @RequestParam(required = false, defaultValue = "30") Integer size,
@Parameter(description = "Sort field (name, bookCount, recent)") @RequestParam(required = false, defaultValue = "name") String sort,
@Parameter(description = "Sort direction (asc, desc)") @RequestParam(required = false, defaultValue = "asc") String dir,
@Parameter(description = "Filter by library ID") @RequestParam(required = false) Long libraryId,
@Parameter(description = "Search by author name") @RequestParam(required = false) String search,
@Parameter(description = "Filter by photo availability") @RequestParam(required = false) Boolean hasPhoto) {
return ResponseEntity.ok(mobileAuthorService.getAuthors(page, size, sort, dir, libraryId, search, hasPhoto));
}
@Operation(summary = "Get author details",
description = "Retrieve full details for a specific author including description and book count.")
@ApiResponses({
@ApiResponse(responseCode = "200", description = "Author details retrieved successfully"),
@ApiResponse(responseCode = "403", description = "Access denied"),
@ApiResponse(responseCode = "404", description = "Author not found")
})
@GetMapping("/{authorId}")
public ResponseEntity<MobileAuthorDetail> getAuthorDetail(
@Parameter(description = "Author ID") @PathVariable Long authorId) {
return ResponseEntity.ok(mobileAuthorService.getAuthorDetail(authorId));
}
}
@@ -1,175 +0,0 @@
package org.booklore.mobile.controller;
import org.booklore.mobile.dto.*;
import org.booklore.mobile.service.MobileBookService;
import org.booklore.model.enums.BookFileType;
import org.booklore.model.enums.ReadStatus;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.AllArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@AllArgsConstructor
@RestController
@RequestMapping("/api/mobile/v1/books")
@Tag(name = "Mobile Books", description = "Mobile-optimized endpoints for book operations")
public class MobileBookController {
private final MobileBookService mobileBookService;
@Operation(summary = "Get paginated book list",
description = "Retrieve a paginated list of books with optional filtering by library, shelf, status, and search text.")
@ApiResponses({
@ApiResponse(responseCode = "200", description = "Books retrieved successfully"),
@ApiResponse(responseCode = "403", description = "Access denied")
})
@GetMapping
public ResponseEntity<MobilePageResponse<MobileBookSummary>> getBooks(
@Parameter(description = "Page number (0-indexed)") @RequestParam(required = false, defaultValue = "0") Integer page,
@Parameter(description = "Page size (max 50)") @RequestParam(required = false, defaultValue = "50") Integer size,
@Parameter(description = "Sort field (title, addedOn, lastReadTime, seriesName)") @RequestParam(required = false, defaultValue = "addedOn") String sort,
@Parameter(description = "Sort direction (asc, desc)") @RequestParam(required = false, defaultValue = "desc") String dir,
@Parameter(description = "Filter by library ID") @RequestParam(required = false) Long libraryId,
@Parameter(description = "Filter by shelf ID") @RequestParam(required = false) Long shelfId,
@Parameter(description = "Filter by read status") @RequestParam(required = false) ReadStatus status,
@Parameter(description = "Search in title, author, series") @RequestParam(required = false) String search,
@Parameter(description = "Filter by file type (EBOOK, AUDIOBOOK, PDF, CBX, etc.)") @RequestParam(required = false) BookFileType fileType,
@Parameter(description = "Minimum personal rating (1-5)") @RequestParam(required = false) Integer minRating,
@Parameter(description = "Maximum personal rating (1-5, 0 for unrated)") @RequestParam(required = false) Integer maxRating,
@Parameter(description = "Filter by author name") @RequestParam(required = false) String authors,
@Parameter(description = "Filter by language code (e.g. en, fr)") @RequestParam(required = false) String language) {
return ResponseEntity.ok(mobileBookService.getBooks(
page, size, sort, dir, libraryId, shelfId, status, search,
fileType, minRating, maxRating, authors, language));
}
@Operation(summary = "Get book details",
description = "Retrieve full details for a specific book.")
@ApiResponses({
@ApiResponse(responseCode = "200", description = "Book details retrieved successfully"),
@ApiResponse(responseCode = "403", description = "Access denied"),
@ApiResponse(responseCode = "404", description = "Book not found")
})
@GetMapping("/{bookId}")
public ResponseEntity<MobileBookDetail> getBookDetail(
@Parameter(description = "Book ID") @PathVariable Long bookId) {
return ResponseEntity.ok(mobileBookService.getBookDetail(bookId));
}
@Operation(summary = "Search books",
description = "Search books by query text in title, author, and series name.")
@ApiResponses({
@ApiResponse(responseCode = "200", description = "Search results retrieved successfully"),
@ApiResponse(responseCode = "400", description = "Query parameter required")
})
@GetMapping("/search")
public ResponseEntity<MobilePageResponse<MobileBookSummary>> searchBooks(
@Parameter(description = "Search query", required = true) @RequestParam String q,
@Parameter(description = "Page number (0-indexed)") @RequestParam(required = false, defaultValue = "0") Integer page,
@Parameter(description = "Page size (max 50)") @RequestParam(required = false, defaultValue = "20") Integer size) {
return ResponseEntity.ok(mobileBookService.searchBooks(q, page, size));
}
@Operation(summary = "Get continue reading list",
description = "Get books currently in progress, sorted by last read time (most recent first).")
@ApiResponse(responseCode = "200", description = "Continue reading list retrieved successfully")
@GetMapping("/continue-reading")
public ResponseEntity<List<MobileBookSummary>> getContinueReading(
@Parameter(description = "Maximum number of books to return") @RequestParam(required = false, defaultValue = "10") Integer limit) {
return ResponseEntity.ok(mobileBookService.getContinueReading(limit));
}
@Operation(summary = "Get continue listening list",
description = "Get audiobooks currently in progress, sorted by last listened time (most recent first).")
@ApiResponse(responseCode = "200", description = "Continue listening list retrieved successfully")
@GetMapping("/continue-listening")
public ResponseEntity<List<MobileBookSummary>> getContinueListening(
@Parameter(description = "Maximum number of audiobooks to return") @RequestParam(required = false, defaultValue = "10") Integer limit) {
return ResponseEntity.ok(mobileBookService.getContinueListening(limit));
}
@Operation(summary = "Get recently added books",
description = "Get books added in the last 30 days, sorted by added date (most recent first).")
@ApiResponse(responseCode = "200", description = "Recently added books retrieved successfully")
@GetMapping("/recently-added")
public ResponseEntity<List<MobileBookSummary>> getRecentlyAdded(
@Parameter(description = "Maximum number of books to return") @RequestParam(required = false, defaultValue = "10") Integer limit) {
return ResponseEntity.ok(mobileBookService.getRecentlyAdded(limit));
}
@Operation(summary = "Update book read status",
description = "Update the read status for a book.")
@ApiResponses({
@ApiResponse(responseCode = "200", description = "Status updated successfully"),
@ApiResponse(responseCode = "403", description = "Access denied"),
@ApiResponse(responseCode = "404", description = "Book not found")
})
@PutMapping("/{bookId}/status")
public ResponseEntity<Void> updateStatus(
@Parameter(description = "Book ID") @PathVariable Long bookId,
@Valid @RequestBody UpdateStatusRequest request) {
mobileBookService.updateReadStatus(bookId, request.getStatus());
return ResponseEntity.ok().build();
}
@Operation(summary = "Update book personal rating",
description = "Update the personal rating for a book (1-5).")
@ApiResponses({
@ApiResponse(responseCode = "200", description = "Rating updated successfully"),
@ApiResponse(responseCode = "403", description = "Access denied"),
@ApiResponse(responseCode = "404", description = "Book not found")
})
@PutMapping("/{bookId}/rating")
public ResponseEntity<Void> updateRating(
@Parameter(description = "Book ID") @PathVariable Long bookId,
@Valid @RequestBody UpdateRatingRequest request) {
mobileBookService.updatePersonalRating(bookId, request.getRating());
return ResponseEntity.ok().build();
}
@Operation(summary = "Get books by magic shelf",
description = "Retrieve a paginated list of books matching a magic shelf's rules.")
@ApiResponses({
@ApiResponse(responseCode = "200", description = "Books retrieved successfully"),
@ApiResponse(responseCode = "403", description = "Access denied"),
@ApiResponse(responseCode = "404", description = "Magic shelf not found")
})
@GetMapping("/magic-shelf/{magicShelfId}")
public ResponseEntity<MobilePageResponse<MobileBookSummary>> getBooksByMagicShelf(
@Parameter(description = "Magic shelf ID") @PathVariable Long magicShelfId,
@Parameter(description = "Page number (0-indexed)") @RequestParam(required = false, defaultValue = "0") Integer page,
@Parameter(description = "Page size (max 50)") @RequestParam(required = false, defaultValue = "20") Integer size) {
return ResponseEntity.ok(mobileBookService.getBooksByMagicShelf(magicShelfId, page, size));
}
@Operation(summary = "Get random books",
description = "Retrieve a paginated list of random books from accessible libraries.")
@ApiResponses({
@ApiResponse(responseCode = "200", description = "Random books retrieved successfully"),
@ApiResponse(responseCode = "403", description = "Access denied")
})
@GetMapping("/random")
public ResponseEntity<MobilePageResponse<MobileBookSummary>> getRandomBooks(
@Parameter(description = "Page number (0-indexed)") @RequestParam(required = false, defaultValue = "0") Integer page,
@Parameter(description = "Page size (max 50)") @RequestParam(required = false, defaultValue = "20") Integer size,
@Parameter(description = "Filter by library ID") @RequestParam(required = false) Long libraryId) {
return ResponseEntity.ok(mobileBookService.getRandomBooks(page, size, libraryId));
}
}
@@ -1,33 +0,0 @@
package org.booklore.mobile.controller;
import org.booklore.mobile.dto.MobileFilterOptions;
import org.booklore.mobile.service.MobileBookService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.AllArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@AllArgsConstructor
@RestController
@RequestMapping("/api/mobile/v1")
@Tag(name = "Mobile Filters", description = "Filter options for mobile book browsing")
public class MobileFilterController {
private final MobileBookService mobileBookService;
@Operation(summary = "Get available filter options",
description = "Returns available authors, languages, file types, and read statuses for filtering books.")
@ApiResponse(responseCode = "200", description = "Filter options retrieved successfully")
@GetMapping("/filter-options")
public ResponseEntity<MobileFilterOptions> getFilterOptions(
@RequestParam(required = false) Long libraryId,
@RequestParam(required = false) Long shelfId,
@RequestParam(required = false) Long magicShelfId) {
return ResponseEntity.ok(mobileBookService.getFilterOptions(libraryId, shelfId, magicShelfId));
}
}
@@ -0,0 +1,9 @@
package org.booklore.model.dto;
public interface AudiobookProgressDto {
Long getBookId();
String getTitle();
Float getMaxProgress();
Long getTotalDurationSeconds();
Long getListenedDurationSeconds();
}
@@ -0,0 +1,15 @@
package org.booklore.model.dto;
import java.time.LocalDateTime;
public interface BookTimelineDto {
Long getBookId();
String getTitle();
Integer getPageCount();
LocalDateTime getFirstSessionDate();
LocalDateTime getLastSessionDate();
Integer getTotalSessions();
Long getTotalDurationSeconds();
Double getMaxProgress();
String getReadStatus();
}
@@ -0,0 +1,8 @@
package org.booklore.model.dto;
public interface ListeningAuthorDto {
String getAuthorName();
Long getBookCount();
Long getTotalSessions();
Long getTotalDurationSeconds();
}
@@ -0,0 +1,9 @@
package org.booklore.model.dto;
import java.time.LocalDate;
public interface ListeningHeatmapDto {
LocalDate getDate();
Long getSessions();
Long getDurationMinutes();
}
@@ -0,0 +1,7 @@
package org.booklore.model.dto;
public interface MonthlyCompletedAudiobookDto {
Integer getYear();
Integer getMonth();
Long getBooksCompleted();
}
@@ -0,0 +1,7 @@
package org.booklore.model.dto;
public interface MonthlyListeningDurationDto {
Integer getYear();
Integer getMonth();
Long getTotalDurationSeconds();
}
@@ -0,0 +1,8 @@
package org.booklore.model.dto;
public interface WeeklyListeningTrendDto {
Integer getYear();
Integer getWeek();
Long getTotalDurationSeconds();
Long getSessions();
}
@@ -16,4 +16,5 @@ public class EpubProgress {
String href;
@NotNull
Float percentage;
String ttsPositionCfi;
}
@@ -6,5 +6,6 @@ public record BookFileProgress(
@NotNull Long bookFileId,
String positionData,
String positionHref,
@NotNull Float progressPercent) {
@NotNull Float progressPercent,
String ttsPositionCfi) {
}
@@ -22,6 +22,7 @@ public class AudiobookInfo {
private String codec;
private Integer sampleRate;
private Integer channels;
private Long totalSizeBytes;
private boolean folderBased;
private List<AudiobookChapter> chapters;
private List<AudiobookTrack> tracks;
@@ -0,0 +1,24 @@
package org.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 BookTimelineResponse {
private Long bookId;
private String title;
private Integer pageCount;
private LocalDate firstSessionDate;
private LocalDate lastSessionDate;
private Integer totalSessions;
private Long totalDurationSeconds;
private Double maxProgress;
private String readStatus;
}
@@ -0,0 +1,17 @@
package org.booklore.model.dto.response;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class ListeningAuthorResponse {
private String author;
private Long bookCount;
private Long totalSessions;
private Long totalDurationSeconds;
}
@@ -0,0 +1,31 @@
package org.booklore.model.dto.response;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.List;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class ListeningCompletionResponse {
private Integer totalAudiobooks;
private Integer completed;
private Integer inProgressCount;
private List<AudiobookCompletionEntry> inProgress;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public static class AudiobookCompletionEntry {
private Long bookId;
private String title;
private Double progressPercent;
private Long totalDurationSeconds;
private Long listenedDurationSeconds;
}
}
@@ -0,0 +1,18 @@
package org.booklore.model.dto.response;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class ListeningFinishFunnelResponse {
private Long totalStarted;
private Long reached25;
private Long reached50;
private Long reached75;
private Long completed;
}
@@ -0,0 +1,18 @@
package org.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 ListeningHeatmapResponse {
private LocalDate date;
private Long sessions;
private Long durationMinutes;
}
@@ -0,0 +1,18 @@
package org.booklore.model.dto.response;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class LongestAudiobookResponse {
private Long bookId;
private String title;
private Long totalDurationSeconds;
private Long listenedDurationSeconds;
private Double progressPercent;
}
@@ -0,0 +1,17 @@
package org.booklore.model.dto.response;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class MonthlyPaceResponse {
private Integer year;
private Integer month;
private Long booksCompleted;
private Long totalListeningSeconds;
}
@@ -9,7 +9,7 @@ import lombok.NoArgsConstructor;
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class PeakReadingHoursResponse {
public class PeakHoursResponse {
private Integer hourOfDay;
private Long sessionCount;
private Long totalDurationSeconds;
@@ -0,0 +1,29 @@
package org.booklore.model.dto.response;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.time.LocalDate;
import java.util.List;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class ReadingStreakResponse {
private int currentStreak;
private int longestStreak;
private int totalReadingDays;
private List<ReadingStreakDay> last52Weeks;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public static class ReadingStreakDay {
private LocalDate date;
private boolean active;
}
}
@@ -0,0 +1,17 @@
package org.booklore.model.dto.response;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class WeeklyListeningTrendResponse {
private Integer year;
private Integer week;
private Long totalDurationSeconds;
private Long sessions;
}
@@ -53,6 +53,9 @@ public class BookEntity {
@Column(name = "added_on")
private Instant addedOn;
@Column(name = "scanned_on")
private Instant scannedOn;
@Column(name = "book_cover_hash", length = 20)
private String bookCoverHash;
@@ -36,6 +36,9 @@ public class UserBookFileProgressEntity {
@Column(name = "progress_percent")
private Float progressPercent;
@Column(name = "tts_position_cfi", length = 1000)
private String ttsPositionCfi;
@Column(name = "last_read_time")
private Instant lastReadTime;
}
@@ -30,4 +30,16 @@ public interface AuthorRepository extends JpaRepository<AuthorEntity, Long> {
@Query("SELECT COUNT(b) > 0 FROM AuthorEntity a JOIN a.bookMetadataEntityList bm JOIN bm.book b WHERE a.id = :authorId AND b.library.id IN :libraryIds")
boolean existsByIdAndLibraryIds(@Param("authorId") Long authorId, @Param("libraryIds") Set<Long> libraryIds);
@Query(value = "SELECT m.book_id AS bookId, a.name AS authorName " +
"FROM book_metadata_author_mapping m " +
"JOIN author a ON a.id = m.author_id " +
"WHERE m.book_id IN :bookIds ORDER BY a.name",
nativeQuery = true)
List<AuthorBookProjection> findAuthorNamesByBookIds(@Param("bookIds") Set<Long> bookIds);
interface AuthorBookProjection {
Long getBookId();
String getAuthorName();
}
}
@@ -7,6 +7,7 @@ import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.Repository;
import org.springframework.data.repository.query.Param;
import java.time.Instant;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Set;
@@ -55,6 +56,13 @@ public interface NotebookEntryRepository extends Repository<AnnotationEntity, Lo
String getBookTitle();
}
interface BookWithCountProjection {
Long getBookId();
String getBookTitle();
int getNoteCount();
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, " +
@@ -83,4 +91,37 @@ public interface NotebookEntryRepository extends Repository<AnnotationEntity, Lo
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)
Page<BookWithCountProjection> findBooksWithAnnotationsPaginated(@Param("userId") Long userId,
@Param("search") String search,
Pageable pageable);
}
@@ -213,4 +213,182 @@ public interface ReadingSessionRepository extends JpaRepository<ReadingSessionEn
@Param("userId") Long userId,
@Param("year") int year,
@Param("tzOffset") String tzOffset);
// ========================================================================
// 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(
@Param("userId") Long userId,
@Param("year") int year,
@Param("month") int month,
@Param("tzOffset") String tzOffset);
@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(
@Param("userId") Long userId,
@Param("weeks") int weeks,
@Param("tzOffset") String tzOffset);
@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)
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
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'
)
GROUP BY year, month
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
FROM ReadingSessionEntity rs
JOIN rs.book b
JOIN b.metadata.categories c
WHERE rs.user.id = :userId
AND rs.bookType = org.booklore.model.enums.BookFileType.AUDIOBOOK
GROUP BY c.name
ORDER BY totalDurationSeconds DESC
""")
List<GenreStatisticsDto> findListeningGenreStatisticsByUser(@Param("userId") Long userId);
@Query(value = """
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'
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) as maxProgress,
ubp.read_status as readStatus
FROM reading_sessions rs
JOIN book b ON rs.book_id = b.id
LEFT JOIN book_metadata bm ON bm.book_id = b.id
LEFT JOIN user_book_progress ubp ON ubp.book_id = rs.book_id AND ubp.user_id = rs.user_id
WHERE rs.user_id = :userId
AND YEAR(CONVERT_TZ(rs.start_time, '+00:00', :tzOffset)) = :year
GROUP BY rs.book_id, bm.title, bm.page_count, ubp.read_status
ORDER BY firstSessionDate
""", nativeQuery = true)
List<BookTimelineDto> findBookTimelineByUserAndYear(
@Param("userId") Long userId,
@Param("year") int year,
@Param("tzOffset") String tzOffset);
}
@@ -6,7 +6,9 @@ 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.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;
@@ -150,13 +152,13 @@ public class ReadingSessionService {
}
@Transactional(readOnly = true)
public List<PeakReadingHoursResponse> getPeakReadingHours(Integer year, Integer month) {
public List<PeakHoursResponse> getPeakReadingHours(Integer year, Integer month) {
BookLoreUser authenticatedUser = authenticationService.getAuthenticatedUser();
Long userId = authenticatedUser.getId();
return readingSessionRepository.findPeakReadingHoursByUser(userId, year, month, getTimezoneOffset())
.stream()
.map(dto -> PeakReadingHoursResponse.builder()
.map(dto -> PeakHoursResponse.builder()
.hourOfDay(dto.getHourOfDay())
.sessionCount(dto.getSessionCount())
.totalDurationSeconds(dto.getTotalDurationSeconds())
@@ -508,6 +510,92 @@ public class ReadingSessionService {
.collect(Collectors.toList());
}
@Transactional(readOnly = true)
public ReadingStreakResponse getReadingStreak() {
BookLoreUser authenticatedUser = authenticationService.getAuthenticatedUser();
Long userId = authenticatedUser.getId();
List<ReadingSessionCountDto> allDates = readingSessionRepository.findAllSessionCountsByUser(userId, getTimezoneOffset());
Set<LocalDate> readingDays = allDates.stream()
.map(ReadingSessionCountDto::getDate)
.collect(Collectors.toCollection(TreeSet::new));
LocalDate today = LocalDate.now();
// Current streak: consecutive days backwards from today (allow yesterday as last active day)
int currentStreak = 0;
LocalDate checkDate = today;
if (!readingDays.contains(today)) {
// If user hasn't read today, start checking from yesterday
checkDate = today.minusDays(1);
}
while (readingDays.contains(checkDate)) {
currentStreak++;
checkDate = checkDate.minusDays(1);
}
// Longest streak: find the longest consecutive run in the date set
int longestStreak = 0;
int streak = 0;
LocalDate prevDate = null;
for (LocalDate date : readingDays) {
if (prevDate != null && date.equals(prevDate.plusDays(1))) {
streak++;
} else {
streak = 1;
}
longestStreak = Math.max(longestStreak, streak);
prevDate = date;
}
int totalReadingDays = readingDays.size();
// Last 52 weeks: generate all dates from (today - 364 days) to today
LocalDate startDate = today.minusDays(364);
List<ReadingStreakResponse.ReadingStreakDay> last52Weeks = new ArrayList<>();
for (LocalDate date = startDate; !date.isAfter(today); date = date.plusDays(1)) {
last52Weeks.add(ReadingStreakResponse.ReadingStreakDay.builder()
.date(date)
.active(readingDays.contains(date))
.build());
}
return ReadingStreakResponse.builder()
.currentStreak(currentStreak)
.longestStreak(longestStreak)
.totalReadingDays(totalReadingDays)
.last52Weeks(last52Weeks)
.build();
}
@Transactional(readOnly = true)
public List<BookTimelineResponse> getBookTimeline(int year) {
BookLoreUser authenticatedUser = authenticationService.getAuthenticatedUser();
Long userId = authenticatedUser.getId();
String tzOffset = getTimezoneOffset();
ZoneId zone = ZoneId.systemDefault();
return readingSessionRepository.findBookTimelineByUserAndYear(userId, year, tzOffset)
.stream()
.map(dto -> BookTimelineResponse.builder()
.bookId(dto.getBookId())
.title(dto.getTitle())
.pageCount(dto.getPageCount())
.firstSessionDate(dto.getFirstSessionDate() != null
? dto.getFirstSessionDate().toLocalDate()
: null)
.lastSessionDate(dto.getLastSessionDate() != null
? dto.getLastSessionDate().toLocalDate()
: null)
.totalSessions(dto.getTotalSessions())
.totalDurationSeconds(dto.getTotalDurationSeconds())
.maxProgress(dto.getMaxProgress())
.readStatus(dto.getReadStatus())
.build())
.collect(Collectors.toList());
}
private double linearRegressionSlope(List<Double> values) {
int n = values.size();
if (n < 2) return 0.0;
@@ -525,4 +613,216 @@ public class ReadingSessionService {
return (n * sumXY - sumX * sumY) / denominator;
}
// ========================================================================
// Listening (audiobook) stats
// ========================================================================
@Transactional(readOnly = true)
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())
.build())
.collect(Collectors.toList());
}
@Transactional(readOnly = true)
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())
.collect(Collectors.toList());
}
@Transactional(readOnly = true)
public ListeningCompletionResponse getListeningCompletion() {
Long userId = authenticationService.getAuthenticatedUser().getId();
var progressList = readingSessionRepository.findAudiobookProgressByUser(userId);
int totalAudiobooks = progressList.size();
int completed = 0;
List<ListeningCompletionResponse.AudiobookCompletionEntry> inProgress = new ArrayList<>();
for (var dto : progressList) {
float maxProg = dto.getMaxProgress() != null ? dto.getMaxProgress() : 0f;
if (maxProg >= 0.98f) {
completed++;
} else if (maxProg > 0f) {
inProgress.add(ListeningCompletionResponse.AudiobookCompletionEntry.builder()
.bookId(dto.getBookId())
.title(dto.getTitle())
.progressPercent(Math.round(maxProg * 1000.0) / 10.0)
.totalDurationSeconds(dto.getTotalDurationSeconds() != null ? dto.getTotalDurationSeconds() : 0L)
.listenedDurationSeconds(dto.getListenedDurationSeconds() != null ? dto.getListenedDurationSeconds() : 0L)
.build());
}
}
// Sort in-progress by most recently listened (highest listened duration as proxy)
inProgress.sort((a, b) -> Long.compare(b.getListenedDurationSeconds(), a.getListenedDurationSeconds()));
int inProgressCount = inProgress.size();
return ListeningCompletionResponse.builder()
.totalAudiobooks(totalAudiobooks)
.completed(completed)
.inProgressCount(inProgressCount)
.inProgress(inProgress.stream().limit(10).collect(Collectors.toList()))
.build();
}
@Transactional(readOnly = true)
public List<MonthlyPaceResponse> getMonthlyListeningPace(int months) {
Long userId = authenticationService.getAuthenticatedUser().getId();
// Get completed audiobooks by month
var completedByMonth = readingSessionRepository.findMonthlyCompletedAudiobooks(userId);
// Get listening durations by month
var durationsByMonth = readingSessionRepository.findMonthlyListeningDurations(userId, getTimezoneOffset());
Map<String, Long> durationMap = new HashMap<>();
for (var durDto : durationsByMonth) {
durationMap.put(durDto.getYear() + "-" + durDto.getMonth(), durDto.getTotalDurationSeconds());
}
// Merge and limit to N months
return completedByMonth.stream()
.limit(months)
.map(dto -> {
String key = dto.getYear() + "-" + dto.getMonth();
Long listeningSeconds = durationMap.getOrDefault(key, 0L);
return MonthlyPaceResponse.builder()
.year(dto.getYear())
.month(dto.getMonth())
.booksCompleted(dto.getBooksCompleted())
.totalListeningSeconds(listeningSeconds)
.build();
})
.collect(Collectors.toList());
}
@Transactional(readOnly = true)
public ListeningFinishFunnelResponse getListeningFinishFunnel() {
Long userId = authenticationService.getAuthenticatedUser().getId();
var progressList = readingSessionRepository.findAudiobookProgressByUser(userId);
long totalStarted = 0;
long reached25 = 0;
long reached50 = 0;
long reached75 = 0;
long completed = 0;
for (var dto : progressList) {
float maxProg = dto.getMaxProgress() != null ? dto.getMaxProgress() : 0f;
if (maxProg > 0f) {
totalStarted++;
if (maxProg >= 0.25f) reached25++;
if (maxProg >= 0.50f) reached50++;
if (maxProg >= 0.75f) reached75++;
if (maxProg >= 0.98f) completed++;
}
}
return ListeningFinishFunnelResponse.builder()
.totalStarted(totalStarted)
.reached25(reached25)
.reached50(reached50)
.reached75(reached75)
.completed(completed)
.build();
}
@Transactional(readOnly = true)
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())
.build())
.collect(Collectors.toList());
}
@Transactional(readOnly = true)
public List<GenreStatisticsResponse> getListeningGenreStatistics() {
Long userId = authenticationService.getAuthenticatedUser().getId();
return readingSessionRepository.findListeningGenreStatisticsByUser(userId)
.stream()
.map(dto -> {
double avgSessionsPerBook = dto.getBookCount() > 0
? (double) dto.getTotalSessions() / dto.getBookCount()
: 0.0;
return GenreStatisticsResponse.builder()
.genre(dto.getGenre())
.bookCount(dto.getBookCount())
.totalSessions(dto.getTotalSessions())
.totalDurationSeconds(dto.getTotalDurationSeconds())
.averageSessionsPerBook(Math.round(avgSessionsPerBook * 100.0) / 100.0)
.build();
})
.collect(Collectors.toList());
}
@Transactional(readOnly = true)
public List<ListeningAuthorResponse> getListeningAuthorStats() {
Long userId = authenticationService.getAuthenticatedUser().getId();
return readingSessionRepository.findListeningAuthorStatsByUser(userId)
.stream()
.map(dto -> ListeningAuthorResponse.builder()
.author(dto.getAuthorName())
.bookCount(dto.getBookCount())
.totalSessions(dto.getTotalSessions())
.totalDurationSeconds(dto.getTotalDurationSeconds())
.build())
.collect(Collectors.toList());
}
@Transactional(readOnly = true)
public List<SessionScatterResponse> getListeningSessionScatter() {
Long userId = authenticationService.getAuthenticatedUser().getId();
return readingSessionRepository.findListeningSessionScatterByUser(userId, getTimezoneOffset())
.stream()
.map(dto -> SessionScatterResponse.builder()
.hourOfDay(dto.getHourOfDay())
.durationMinutes(dto.getDurationMinutes())
.dayOfWeek(dto.getDayOfWeek())
.build())
.collect(Collectors.toList());
}
@Transactional(readOnly = true)
public List<LongestAudiobookResponse> getListeningLongestBooks() {
Long userId = authenticationService.getAuthenticatedUser().getId();
return readingSessionRepository.findAudiobookProgressByUser(userId)
.stream()
.sorted((a, b) -> Long.compare(
b.getTotalDurationSeconds() != null ? b.getTotalDurationSeconds() : 0L,
a.getTotalDurationSeconds() != null ? a.getTotalDurationSeconds() : 0L))
.limit(10)
.map(dto -> {
float maxProg = dto.getMaxProgress() != null ? dto.getMaxProgress() : 0f;
return LongestAudiobookResponse.builder()
.bookId(dto.getBookId())
.title(dto.getTitle())
.totalDurationSeconds(dto.getTotalDurationSeconds() != null ? dto.getTotalDurationSeconds() : 0L)
.listenedDurationSeconds(dto.getListenedDurationSeconds() != null ? dto.getListenedDurationSeconds() : 0L)
.progressPercent(Math.round(maxProg * 1000.0) / 10.0)
.build();
})
.collect(Collectors.toList());
}
}
@@ -53,6 +53,7 @@ public class PhysicalBookService {
.libraryPath(null)
.isPhysical(true)
.addedOn(Instant.now())
.scannedOn(Instant.now())
.bookFiles(new ArrayList<>())
.build();
@@ -152,6 +152,7 @@ public class ReadingProgressService {
.cfi(fileProgress.getPositionData())
.href(fileProgress.getPositionHref())
.percentage(roundToOneDecimal(fileProgress.getProgressPercent()))
.ttsPositionCfi(fileProgress.getTtsPositionCfi())
.build());
case PDF -> book.setPdfProgress(PdfProgress.builder()
.page(parseIntOrNull(fileProgress.getPositionData()))
@@ -287,6 +288,7 @@ public class ReadingProgressService {
entity.setPositionData(fileProgress.positionData());
entity.setPositionHref(fileProgress.positionHref());
entity.setProgressPercent(fileProgress.progressPercent());
entity.setTtsPositionCfi(fileProgress.ttsPositionCfi());
entity.setLastReadTime(now);
userBookFileProgressRepository.save(entity);
@@ -46,7 +46,8 @@ public class AudioMetadataService {
AudiobookInfo.AudiobookInfoBuilder builder = AudiobookInfo.builder()
.bookId(bookFile.getBook().getId())
.bookFileId(bookFile.getId())
.folderBased(false);
.folderBased(false)
.totalSizeBytes(bookFile.getFileSizeKb() != null ? bookFile.getFileSizeKb() * 1024 : Files.size(audioPath));
if (bookFile.getDurationSeconds() != null) {
BookMetadataEntity metadata = bookFile.getBook().getMetadata();
@@ -203,10 +204,15 @@ public class AudioMetadataService {
}
}
long totalSizeBytes = tracks.stream()
.mapToLong(t -> t.getFileSizeBytes() != null ? t.getFileSizeBytes() : 0)
.sum();
return builder
.title(title)
.author(author)
.durationMs(totalDurationMs)
.totalSizeBytes(totalSizeBytes > 0 ? totalSizeBytes : null)
.tracks(tracks)
.build();
}
@@ -0,0 +1 @@
ALTER TABLE user_book_file_progress ADD COLUMN IF NOT EXISTS tts_position_cfi VARCHAR(1000) NULL;
@@ -0,0 +1 @@
ALTER TABLE book ADD COLUMN IF NOT EXISTS scanned_on TIMESTAMP NULL;
@@ -1,7 +1,7 @@
package org.booklore.mobile.controller;
package org.booklore.app.controller;
import org.booklore.mobile.dto.MobileFilterOptions;
import org.booklore.mobile.service.MobileBookService;
import org.booklore.app.dto.AppFilterOptions;
import org.booklore.app.service.AppBookService;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
@@ -15,20 +15,20 @@ import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
@ExtendWith(MockitoExtension.class)
class MobileFilterControllerTest {
class AppFilterControllerTest {
@Mock
private MobileBookService mobileBookService;
private AppBookService mobileBookService;
@InjectMocks
private MobileFilterController controller;
private AppFilterController controller;
@Test
void getFilterOptions_noParams_delegatesWithNulls() {
MobileFilterOptions expected = buildOptions(List.of("Author A"), List.of("EPUB"), List.of("en"));
AppFilterOptions expected = buildOptions(List.of("Author A"), List.of("EPUB"), List.of("en"));
when(mobileBookService.getFilterOptions(null, null, null)).thenReturn(expected);
ResponseEntity<MobileFilterOptions> response = controller.getFilterOptions(null, null, null);
ResponseEntity<AppFilterOptions> response = controller.getFilterOptions(null, null, null);
assertEquals(200, response.getStatusCode().value());
assertSame(expected, response.getBody());
@@ -37,10 +37,10 @@ class MobileFilterControllerTest {
@Test
void getFilterOptions_withLibraryId_passesLibraryId() {
MobileFilterOptions expected = buildOptions(List.of("Author B"), List.of("PDF"), List.of("fr"));
AppFilterOptions expected = buildOptions(List.of("Author B"), List.of("PDF"), List.of("fr"));
when(mobileBookService.getFilterOptions(5L, null, null)).thenReturn(expected);
ResponseEntity<MobileFilterOptions> response = controller.getFilterOptions(5L, null, null);
ResponseEntity<AppFilterOptions> response = controller.getFilterOptions(5L, null, null);
assertEquals(200, response.getStatusCode().value());
assertEquals(1, response.getBody().getAuthors().size());
@@ -50,10 +50,10 @@ class MobileFilterControllerTest {
@Test
void getFilterOptions_withShelfId_passesShelfId() {
MobileFilterOptions expected = buildOptions(List.of(), List.of("EPUB"), List.of());
AppFilterOptions expected = buildOptions(List.of(), List.of("EPUB"), List.of());
when(mobileBookService.getFilterOptions(null, 10L, null)).thenReturn(expected);
ResponseEntity<MobileFilterOptions> response = controller.getFilterOptions(null, 10L, null);
ResponseEntity<AppFilterOptions> response = controller.getFilterOptions(null, 10L, null);
assertEquals(200, response.getStatusCode().value());
assertTrue(response.getBody().getAuthors().isEmpty());
@@ -62,24 +62,24 @@ class MobileFilterControllerTest {
@Test
void getFilterOptions_withMagicShelfId_passesMagicShelfId() {
MobileFilterOptions expected = buildOptions(List.of("Author C"), List.of("MOBI"), List.of("de"));
AppFilterOptions expected = buildOptions(List.of("Author C"), List.of("MOBI"), List.of("de"));
when(mobileBookService.getFilterOptions(null, null, 7L)).thenReturn(expected);
ResponseEntity<MobileFilterOptions> response = controller.getFilterOptions(null, null, 7L);
ResponseEntity<AppFilterOptions> response = controller.getFilterOptions(null, null, 7L);
assertEquals(200, response.getStatusCode().value());
assertEquals("Author C", response.getBody().getAuthors().getFirst().getName());
verify(mobileBookService).getFilterOptions(null, null, 7L);
}
private MobileFilterOptions buildOptions(List<String> authorNames, List<String> fileTypes, List<String> langCodes) {
List<MobileFilterOptions.AuthorOption> authors = authorNames.stream()
.map(name -> MobileFilterOptions.AuthorOption.builder().name(name).count(1L).build())
private AppFilterOptions buildOptions(List<String> authorNames, List<String> fileTypes, List<String> langCodes) {
List<AppFilterOptions.AuthorOption> authors = authorNames.stream()
.map(name -> AppFilterOptions.AuthorOption.builder().name(name).count(1L).build())
.toList();
List<MobileFilterOptions.LanguageOption> languages = langCodes.stream()
.map(code -> MobileFilterOptions.LanguageOption.builder().code(code).label(code).count(1L).build())
List<AppFilterOptions.LanguageOption> languages = langCodes.stream()
.map(code -> AppFilterOptions.LanguageOption.builder().code(code).label(code).count(1L).build())
.toList();
return MobileFilterOptions.builder()
return AppFilterOptions.builder()
.authors(authors)
.languages(languages)
.fileTypes(fileTypes)
@@ -1,7 +1,7 @@
package org.booklore.mobile.controller;
package org.booklore.app.controller;
import org.booklore.mobile.dto.*;
import org.booklore.mobile.service.MobileSeriesService;
import org.booklore.app.dto.*;
import org.booklore.app.service.AppSeriesService;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
@@ -16,21 +16,21 @@ import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
@ExtendWith(MockitoExtension.class)
class MobileSeriesControllerTest {
class AppSeriesControllerTest {
@Mock
private MobileSeriesService mobileSeriesService;
private AppSeriesService mobileSeriesService;
@InjectMocks
private MobileSeriesController controller;
private AppSeriesController controller;
@Test
void getSeries_defaultParams_delegatesCorrectly() {
MobilePageResponse<MobileSeriesSummary> expected = buildSeriesPage();
AppPageResponse<AppSeriesSummary> expected = buildSeriesPage();
when(mobileSeriesService.getSeries(0, 20, "recentlyAdded", "desc", null, null, false))
.thenReturn(expected);
ResponseEntity<MobilePageResponse<MobileSeriesSummary>> response =
ResponseEntity<AppPageResponse<AppSeriesSummary>> response =
controller.getSeries(0, 20, "recentlyAdded", "desc", null, null, null);
assertEquals(200, response.getStatusCode().value());
@@ -40,11 +40,11 @@ class MobileSeriesControllerTest {
@Test
void getSeries_withLibraryId_passesLibraryId() {
MobilePageResponse<MobileSeriesSummary> expected = buildSeriesPage();
AppPageResponse<AppSeriesSummary> expected = buildSeriesPage();
when(mobileSeriesService.getSeries(0, 20, "recentlyAdded", "desc", 5L, null, false))
.thenReturn(expected);
ResponseEntity<MobilePageResponse<MobileSeriesSummary>> response =
ResponseEntity<AppPageResponse<AppSeriesSummary>> response =
controller.getSeries(0, 20, "recentlyAdded", "desc", 5L, null, null);
assertEquals(200, response.getStatusCode().value());
@@ -53,11 +53,11 @@ class MobileSeriesControllerTest {
@Test
void getSeries_withSearch_passesSearch() {
MobilePageResponse<MobileSeriesSummary> expected = buildSeriesPage();
AppPageResponse<AppSeriesSummary> expected = buildSeriesPage();
when(mobileSeriesService.getSeries(0, 20, "recentlyAdded", "desc", null, "harry", false))
.thenReturn(expected);
ResponseEntity<MobilePageResponse<MobileSeriesSummary>> response =
ResponseEntity<AppPageResponse<AppSeriesSummary>> response =
controller.getSeries(0, 20, "recentlyAdded", "desc", null, "harry", null);
assertEquals(200, response.getStatusCode().value());
@@ -66,11 +66,11 @@ class MobileSeriesControllerTest {
@Test
void getSeries_withInProgressStatus_setsInProgressTrue() {
MobilePageResponse<MobileSeriesSummary> expected = buildSeriesPage();
AppPageResponse<AppSeriesSummary> expected = buildSeriesPage();
when(mobileSeriesService.getSeries(0, 20, "recentlyAdded", "desc", null, null, true))
.thenReturn(expected);
ResponseEntity<MobilePageResponse<MobileSeriesSummary>> response =
ResponseEntity<AppPageResponse<AppSeriesSummary>> response =
controller.getSeries(0, 20, "recentlyAdded", "desc", null, null, "in-progress");
assertEquals(200, response.getStatusCode().value());
@@ -79,11 +79,11 @@ class MobileSeriesControllerTest {
@Test
void getSeries_withUnknownStatus_treatedAsNotInProgress() {
MobilePageResponse<MobileSeriesSummary> expected = buildSeriesPage();
AppPageResponse<AppSeriesSummary> expected = buildSeriesPage();
when(mobileSeriesService.getSeries(0, 20, "recentlyAdded", "desc", null, null, false))
.thenReturn(expected);
ResponseEntity<MobilePageResponse<MobileSeriesSummary>> response =
ResponseEntity<AppPageResponse<AppSeriesSummary>> response =
controller.getSeries(0, 20, "recentlyAdded", "desc", null, null, "completed");
assertEquals(200, response.getStatusCode().value());
@@ -92,11 +92,11 @@ class MobileSeriesControllerTest {
@Test
void getSeriesBooks_defaultParams_delegatesCorrectly() {
MobilePageResponse<MobileBookSummary> expected = buildBookPage();
AppPageResponse<AppBookSummary> expected = buildBookPage();
when(mobileSeriesService.getSeriesBooks("Dune", 0, 20, "seriesNumber", "asc", null))
.thenReturn(expected);
ResponseEntity<MobilePageResponse<MobileBookSummary>> response =
ResponseEntity<AppPageResponse<AppBookSummary>> response =
controller.getSeriesBooks("Dune", 0, 20, "seriesNumber", "asc", null);
assertEquals(200, response.getStatusCode().value());
@@ -106,11 +106,11 @@ class MobileSeriesControllerTest {
@Test
void getSeriesBooks_withLibraryId_passesLibraryId() {
MobilePageResponse<MobileBookSummary> expected = buildBookPage();
AppPageResponse<AppBookSummary> expected = buildBookPage();
when(mobileSeriesService.getSeriesBooks("Dune", 0, 20, "seriesNumber", "asc", 5L))
.thenReturn(expected);
ResponseEntity<MobilePageResponse<MobileBookSummary>> response =
ResponseEntity<AppPageResponse<AppBookSummary>> response =
controller.getSeriesBooks("Dune", 0, 20, "seriesNumber", "asc", 5L);
assertEquals(200, response.getStatusCode().value());
@@ -119,11 +119,11 @@ class MobileSeriesControllerTest {
@Test
void getSeriesBooks_encodedSeriesName_passedAsIs() {
MobilePageResponse<MobileBookSummary> expected = buildBookPage();
AppPageResponse<AppBookSummary> expected = buildBookPage();
when(mobileSeriesService.getSeriesBooks("A Song of Ice and Fire", 0, 20, "seriesNumber", "asc", null))
.thenReturn(expected);
ResponseEntity<MobilePageResponse<MobileBookSummary>> response =
ResponseEntity<AppPageResponse<AppBookSummary>> response =
controller.getSeriesBooks("A Song of Ice and Fire", 0, 20, "seriesNumber", "asc", null);
assertEquals(200, response.getStatusCode().value());
@@ -132,8 +132,8 @@ class MobileSeriesControllerTest {
// ---- Helpers ----
private MobilePageResponse<MobileSeriesSummary> buildSeriesPage() {
MobileSeriesSummary summary = MobileSeriesSummary.builder()
private AppPageResponse<AppSeriesSummary> buildSeriesPage() {
AppSeriesSummary summary = AppSeriesSummary.builder()
.seriesName("Test Series")
.bookCount(5)
.seriesTotal(5)
@@ -142,17 +142,17 @@ class MobileSeriesControllerTest {
.latestAddedOn(Instant.now())
.coverBooks(List.of())
.build();
return MobilePageResponse.of(List.of(summary), 0, 20, 1);
return AppPageResponse.of(List.of(summary), 0, 20, 1);
}
private MobilePageResponse<MobileBookSummary> buildBookPage() {
MobileBookSummary summary = MobileBookSummary.builder()
private AppPageResponse<AppBookSummary> buildBookPage() {
AppBookSummary summary = AppBookSummary.builder()
.id(1L)
.title("Test Book")
.authors(List.of("Author A"))
.seriesName("Dune")
.seriesNumber(1.0f)
.build();
return MobilePageResponse.of(List.of(summary), 0, 20, 1);
return AppPageResponse.of(List.of(summary), 0, 20, 1);
}
}
@@ -1,12 +1,12 @@
package org.booklore.mobile.service;
package org.booklore.app.service;
import jakarta.persistence.EntityManager;
import jakarta.persistence.TypedQuery;
import org.booklore.config.security.service.AuthenticationService;
import org.booklore.exception.APIException;
import org.booklore.mobile.dto.MobileAuthorDetail;
import org.booklore.mobile.dto.MobileAuthorSummary;
import org.booklore.mobile.dto.MobilePageResponse;
import org.booklore.app.dto.AppAuthorDetail;
import org.booklore.app.dto.AppAuthorSummary;
import org.booklore.app.dto.AppPageResponse;
import org.booklore.model.dto.BookLoreUser;
import org.booklore.model.dto.Library;
import org.booklore.model.entity.AuthorEntity;
@@ -29,20 +29,20 @@ import static org.mockito.Mockito.*;
@ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.LENIENT)
class MobileAuthorServiceTest {
class AppAuthorServiceTest {
@Mock private EntityManager entityManager;
@Mock private AuthenticationService authenticationService;
@Mock private AuthorRepository authorRepository;
@Mock private FileService fileService;
private MobileAuthorService service;
private AppAuthorService service;
private final Long userId = 1L;
@BeforeEach
void setUp() {
service = new MobileAuthorService(authorRepository, authenticationService, fileService, entityManager);
service = new AppAuthorService(authorRepository, authenticationService, fileService, entityManager);
}
// ---- getAuthors tests ----
@@ -61,7 +61,7 @@ class MobileAuthorServiceTest {
mockAuthorThumbnailExists(1L, true);
mockAuthorThumbnailExists(2L, false);
MobilePageResponse<MobileAuthorSummary> result = service.getAuthors(0, 30, "name", "asc", null, null, null);
AppPageResponse<AppAuthorSummary> result = service.getAuthors(0, 30, "name", "asc", null, null, null);
assertNotNull(result);
assertEquals(2, result.getContent().size());
@@ -79,7 +79,7 @@ class MobileAuthorServiceTest {
mockAdminUser();
mockCountQuery(0L);
MobilePageResponse<MobileAuthorSummary> result = service.getAuthors(0, 30, null, null, null, null, null);
AppPageResponse<AppAuthorSummary> result = service.getAuthors(0, 30, null, null, null, null, null);
assertNotNull(result);
assertTrue(result.getContent().isEmpty());
@@ -95,7 +95,7 @@ class MobileAuthorServiceTest {
));
mockAuthorThumbnailExists(3L, false);
MobilePageResponse<MobileAuthorSummary> result = service.getAuthors(0, 30, null, null, 5L, null, null);
AppPageResponse<AppAuthorSummary> result = service.getAuthors(0, 30, null, null, 5L, null, null);
assertNotNull(result);
assertEquals(1, result.getContent().size());
@@ -111,7 +111,7 @@ class MobileAuthorServiceTest {
));
mockAuthorThumbnailExists(4L, true);
MobilePageResponse<MobileAuthorSummary> result = service.getAuthors(0, 30, null, null, null, null, null);
AppPageResponse<AppAuthorSummary> result = service.getAuthors(0, 30, null, null, null, null, null);
assertNotNull(result);
assertEquals(1, result.getContent().size());
@@ -126,7 +126,7 @@ class MobileAuthorServiceTest {
));
mockAuthorThumbnailExists(5L, true);
MobilePageResponse<MobileAuthorSummary> result = service.getAuthors(0, 30, null, null, null, "brandon", null);
AppPageResponse<AppAuthorSummary> result = service.getAuthors(0, 30, null, null, null, "brandon", null);
assertNotNull(result);
assertEquals(1, result.getContent().size());
@@ -146,7 +146,7 @@ class MobileAuthorServiceTest {
// Mock the hasPhoto count query
mockAuthorEntityQuery(List.of(buildAuthor(6L, "Author E"), buildAuthor(7L, "Author F")));
MobilePageResponse<MobileAuthorSummary> result = service.getAuthors(0, 30, null, null, null, null, true);
AppPageResponse<AppAuthorSummary> result = service.getAuthors(0, 30, null, null, null, null, true);
assertNotNull(result);
assertEquals(1, result.getContent().size());
@@ -166,7 +166,7 @@ class MobileAuthorServiceTest {
mockAuthorThumbnailExists(9L, false);
mockAuthorEntityQuery(List.of(buildAuthor(8L, "Author G"), buildAuthor(9L, "Author H")));
MobilePageResponse<MobileAuthorSummary> result = service.getAuthors(0, 30, null, null, null, null, false);
AppPageResponse<AppAuthorSummary> result = service.getAuthors(0, 30, null, null, null, null, false);
assertNotNull(result);
assertEquals(1, result.getContent().size());
@@ -179,7 +179,7 @@ class MobileAuthorServiceTest {
mockAdminUser();
mockCountQuery(0L);
MobilePageResponse<MobileAuthorSummary> result = service.getAuthors(null, null, null, null, null, null, null);
AppPageResponse<AppAuthorSummary> result = service.getAuthors(null, null, null, null, null, null, null);
assertEquals(0, result.getPage());
assertEquals(30, result.getSize());
@@ -190,7 +190,7 @@ class MobileAuthorServiceTest {
mockAdminUser();
mockCountQuery(0L);
MobilePageResponse<MobileAuthorSummary> result = service.getAuthors(0, 100, null, null, null, null, null);
AppPageResponse<AppAuthorSummary> result = service.getAuthors(0, 100, null, null, null, null, null);
assertEquals(50, result.getSize());
}
@@ -200,7 +200,7 @@ class MobileAuthorServiceTest {
mockAdminUser();
mockCountQuery(0L);
MobilePageResponse<MobileAuthorSummary> result = service.getAuthors(0, 30, "name", "asc", null, null, null);
AppPageResponse<AppAuthorSummary> result = service.getAuthors(0, 30, "name", "asc", null, null, null);
assertNotNull(result);
}
@@ -210,7 +210,7 @@ class MobileAuthorServiceTest {
mockAdminUser();
mockCountQuery(0L);
MobilePageResponse<MobileAuthorSummary> result = service.getAuthors(0, 30, "bookCount", "desc", null, null, null);
AppPageResponse<AppAuthorSummary> result = service.getAuthors(0, 30, "bookCount", "desc", null, null, null);
assertNotNull(result);
}
@@ -220,7 +220,7 @@ class MobileAuthorServiceTest {
mockAdminUser();
mockCountQuery(0L);
MobilePageResponse<MobileAuthorSummary> result = service.getAuthors(0, 30, "recent", "desc", null, null, null);
AppPageResponse<AppAuthorSummary> result = service.getAuthors(0, 30, "recent", "desc", null, null, null);
assertNotNull(result);
}
@@ -241,7 +241,7 @@ class MobileAuthorServiceTest {
mockAuthorThumbnailExists(1L, true);
mockBookCountQuery(3);
MobileAuthorDetail result = service.getAuthorDetail(1L);
AppAuthorDetail result = service.getAuthorDetail(1L);
assertNotNull(result);
assertEquals(1L, result.getId());
@@ -261,7 +261,7 @@ class MobileAuthorServiceTest {
mockAuthorThumbnailExists(2L, false);
mockBookCountQuery(6);
MobileAuthorDetail result = service.getAuthorDetail(2L);
AppAuthorDetail result = service.getAuthorDetail(2L);
assertNotNull(result);
assertEquals("Frank Herbert", result.getName());
@@ -1,12 +1,12 @@
package org.booklore.mobile.service;
package org.booklore.app.service;
import jakarta.persistence.EntityManager;
import jakarta.persistence.Tuple;
import jakarta.persistence.TypedQuery;
import org.booklore.config.security.service.AuthenticationService;
import org.booklore.exception.APIException;
import org.booklore.mobile.dto.MobileFilterOptions;
import org.booklore.mobile.mapper.MobileBookMapper;
import org.booklore.app.dto.AppFilterOptions;
import org.booklore.app.mapper.AppBookMapper;
import org.booklore.model.dto.Book;
import org.booklore.model.dto.BookLoreUser;
import org.booklore.model.dto.Library;
@@ -39,24 +39,24 @@ import static org.mockito.Mockito.*;
@ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.LENIENT)
class MobileBookServiceFilterOptionsTest {
class AppBookServiceFilterOptionsTest {
@Mock private BookRepository bookRepository;
@Mock private UserBookProgressRepository userBookProgressRepository;
@Mock private UserBookFileProgressRepository userBookFileProgressRepository;
@Mock private ShelfRepository shelfRepository;
@Mock private AuthenticationService authenticationService;
@Mock private MobileBookMapper mobileBookMapper;
@Mock private AppBookMapper mobileBookMapper;
@Mock private MagicShelfBookService magicShelfBookService;
@Mock private EntityManager entityManager;
private MobileBookService service;
private AppBookService service;
private final Long userId = 1L;
@BeforeEach
void setUp() {
service = new MobileBookService(
service = new AppBookService(
bookRepository, userBookProgressRepository, userBookFileProgressRepository,
shelfRepository, authenticationService, mobileBookMapper,
magicShelfBookService, entityManager
@@ -72,7 +72,7 @@ class MobileBookServiceFilterOptionsTest {
mockAdminUser();
mockJpqlQueries();
MobileFilterOptions result = service.getFilterOptions(null, null, null);
AppFilterOptions result = service.getFilterOptions(null, null, null);
assertNotNull(result);
assertNotNull(result.getAuthors());
@@ -90,7 +90,7 @@ class MobileBookServiceFilterOptionsTest {
mockAdminUser();
mockJpqlQueries();
MobileFilterOptions result = service.getFilterOptions(5L, null, null);
AppFilterOptions result = service.getFilterOptions(5L, null, null);
assertNotNull(result);
verify(entityManager, times(3)).createQuery(anyString(), any(Class.class));
@@ -101,7 +101,7 @@ class MobileBookServiceFilterOptionsTest {
mockNonAdminUser(Set.of(5L, 10L));
mockJpqlQueries();
MobileFilterOptions result = service.getFilterOptions(5L, null, null);
AppFilterOptions result = service.getFilterOptions(5L, null, null);
assertNotNull(result);
}
@@ -125,7 +125,7 @@ class MobileBookServiceFilterOptionsTest {
when(shelfRepository.findById(10L)).thenReturn(Optional.of(shelf));
mockJpqlQueries();
MobileFilterOptions result = service.getFilterOptions(null, 10L, null);
AppFilterOptions result = service.getFilterOptions(null, 10L, null);
assertNotNull(result);
}
@@ -138,7 +138,7 @@ class MobileBookServiceFilterOptionsTest {
when(shelfRepository.findById(10L)).thenReturn(Optional.of(shelf));
mockJpqlQueries();
MobileFilterOptions result = service.getFilterOptions(null, 10L, null);
AppFilterOptions result = service.getFilterOptions(null, 10L, null);
assertNotNull(result);
}
@@ -170,7 +170,7 @@ class MobileBookServiceFilterOptionsTest {
mockAdminUser();
mockMagicShelfBooks(7L, Collections.emptyList());
MobileFilterOptions result = service.getFilterOptions(null, null, 7L);
AppFilterOptions result = service.getFilterOptions(null, null, 7L);
assertNotNull(result);
assertTrue(result.getAuthors().isEmpty());
@@ -187,7 +187,7 @@ class MobileBookServiceFilterOptionsTest {
mockMagicShelfBooks(7L, List.of(book1, book2));
mockJpqlQueries();
MobileFilterOptions result = service.getFilterOptions(null, null, 7L);
AppFilterOptions result = service.getFilterOptions(null, null, 7L);
assertNotNull(result);
verify(magicShelfBookService).getBooksByMagicShelfId(eq(userId), eq(7L), eq(0), anyInt());
@@ -1,14 +1,14 @@
package org.booklore.mobile.service;
package org.booklore.app.service;
import jakarta.persistence.EntityManager;
import jakarta.persistence.Tuple;
import jakarta.persistence.TypedQuery;
import org.booklore.config.security.service.AuthenticationService;
import org.booklore.exception.APIException;
import org.booklore.mobile.dto.MobileBookSummary;
import org.booklore.mobile.dto.MobilePageResponse;
import org.booklore.mobile.dto.MobileSeriesSummary;
import org.booklore.mobile.mapper.MobileBookMapper;
import org.booklore.app.dto.AppBookSummary;
import org.booklore.app.dto.AppPageResponse;
import org.booklore.app.dto.AppSeriesSummary;
import org.booklore.app.mapper.AppBookMapper;
import org.booklore.model.dto.BookLoreUser;
import org.booklore.model.dto.Library;
import org.booklore.model.entity.*;
@@ -36,21 +36,21 @@ import static org.mockito.Mockito.*;
@ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.LENIENT)
class MobileSeriesServiceTest {
class AppSeriesServiceTest {
@Mock private EntityManager entityManager;
@Mock private AuthenticationService authenticationService;
@Mock private BookRepository bookRepository;
@Mock private UserBookProgressRepository userBookProgressRepository;
@Mock private MobileBookMapper mobileBookMapper;
@Mock private AppBookMapper mobileBookMapper;
private MobileSeriesService service;
private AppSeriesService service;
private final Long userId = 1L;
@BeforeEach
void setUp() {
service = new MobileSeriesService(
service = new AppSeriesService(
entityManager, authenticationService, bookRepository,
userBookProgressRepository, mobileBookMapper
);
@@ -70,7 +70,7 @@ class MobileSeriesServiceTest {
mockCountQuery(1L);
mockBooksQuery(List.of(buildBook(1L, "The Expanse", 1.0f, "Author A")));
MobilePageResponse<MobileSeriesSummary> result = service.getSeries(0, 20, null, null, null, null, false);
AppPageResponse<AppSeriesSummary> result = service.getSeries(0, 20, null, null, null, null, false);
assertNotNull(result);
assertEquals(1, result.getContent().size());
@@ -85,7 +85,7 @@ class MobileSeriesServiceTest {
mockAggregateQuery(Collections.emptyList());
mockCountQuery(0L);
MobilePageResponse<MobileSeriesSummary> result = service.getSeries(0, 20, null, null, null, null, false);
AppPageResponse<AppSeriesSummary> result = service.getSeries(0, 20, null, null, null, null, false);
assertNotNull(result);
assertTrue(result.getContent().isEmpty());
@@ -101,7 +101,7 @@ class MobileSeriesServiceTest {
mockCountQuery(1L);
mockBooksQuery(List.of(buildBook(2L, "Dune", 1.0f, "Frank Herbert")));
MobilePageResponse<MobileSeriesSummary> result = service.getSeries(0, 20, null, null, 5L, null, false);
AppPageResponse<AppSeriesSummary> result = service.getSeries(0, 20, null, null, 5L, null, false);
assertNotNull(result);
assertEquals(1, result.getContent().size());
@@ -124,7 +124,7 @@ class MobileSeriesServiceTest {
mockCountQuery(1L);
mockBooksQuery(List.of(buildBook(3L, "Harry Potter", 1.0f, "J.K. Rowling")));
MobilePageResponse<MobileSeriesSummary> result = service.getSeries(0, 20, null, null, null, "harry", false);
AppPageResponse<AppSeriesSummary> result = service.getSeries(0, 20, null, null, null, "harry", false);
assertNotNull(result);
assertEquals(1, result.getContent().size());
@@ -139,7 +139,7 @@ class MobileSeriesServiceTest {
mockCountQueryInProgress(1L);
mockBooksQuery(List.of(buildBook(1L, "The Expanse", 1.0f, "Author A")));
MobilePageResponse<MobileSeriesSummary> result = service.getSeries(0, 20, null, null, null, null, true);
AppPageResponse<AppSeriesSummary> result = service.getSeries(0, 20, null, null, null, null, true);
assertNotNull(result);
assertEquals(1, result.getContent().size());
@@ -151,7 +151,7 @@ class MobileSeriesServiceTest {
mockAggregateQuery(Collections.emptyList());
mockCountQuery(0L);
MobilePageResponse<MobileSeriesSummary> result = service.getSeries(null, null, null, null, null, null, false);
AppPageResponse<AppSeriesSummary> result = service.getSeries(null, null, null, null, null, null, false);
assertEquals(0, result.getPage());
assertEquals(20, result.getSize());
@@ -163,7 +163,7 @@ class MobileSeriesServiceTest {
mockAggregateQuery(Collections.emptyList());
mockCountQuery(0L);
MobilePageResponse<MobileSeriesSummary> result = service.getSeries(0, 100, null, null, null, null, false);
AppPageResponse<AppSeriesSummary> result = service.getSeries(0, 100, null, null, null, null, false);
assertEquals(50, result.getSize());
}
@@ -180,9 +180,9 @@ class MobileSeriesServiceTest {
mockCountQuery(1L);
mockBooksQuery(List.of(book1, book2));
MobilePageResponse<MobileSeriesSummary> result = service.getSeries(0, 20, null, null, null, null, false);
AppPageResponse<AppSeriesSummary> result = service.getSeries(0, 20, null, null, null, null, false);
MobileSeriesSummary series = result.getContent().getFirst();
AppSeriesSummary series = result.getContent().getFirst();
assertEquals(2, series.getCoverBooks().size());
assertEquals(2, series.getAuthors().size());
// Cover books should be ordered by seriesNumber ASC
@@ -196,7 +196,7 @@ class MobileSeriesServiceTest {
mockAggregateQuery(Collections.emptyList());
mockCountQuery(0L);
MobilePageResponse<MobileSeriesSummary> result = service.getSeries(0, 20, "name", "asc", null, null, false);
AppPageResponse<AppSeriesSummary> result = service.getSeries(0, 20, "name", "asc", null, null, false);
assertNotNull(result);
}
@@ -207,7 +207,7 @@ class MobileSeriesServiceTest {
mockAggregateQuery(Collections.emptyList());
mockCountQuery(0L);
MobilePageResponse<MobileSeriesSummary> result = service.getSeries(0, 20, "bookCount", "desc", null, null, false);
AppPageResponse<AppSeriesSummary> result = service.getSeries(0, 20, "bookCount", "desc", null, null, false);
assertNotNull(result);
}
@@ -226,7 +226,7 @@ class MobileSeriesServiceTest {
mockProgress(Collections.emptyList());
mockMapperSummary();
MobilePageResponse<MobileBookSummary> result = service.getSeriesBooks("Dune", 0, 20, null, null, null);
AppPageResponse<AppBookSummary> result = service.getSeriesBooks("Dune", 0, 20, null, null, null);
assertNotNull(result);
assertEquals(1, result.getContent().size());
@@ -241,7 +241,7 @@ class MobileSeriesServiceTest {
mockProgress(Collections.emptyList());
mockMapperSummary();
MobilePageResponse<MobileBookSummary> result = service.getSeriesBooks("Dune", 0, 20, null, null, 5L);
AppPageResponse<AppBookSummary> result = service.getSeriesBooks("Dune", 0, 20, null, null, 5L);
assertNotNull(result);
assertEquals(1, result.getContent().size());
@@ -260,7 +260,7 @@ class MobileSeriesServiceTest {
mockAdminUser();
mockBookPage(Collections.emptyList(), 0L);
MobilePageResponse<MobileBookSummary> result = service.getSeriesBooks("Nonexistent", 0, 20, null, null, null);
AppPageResponse<AppBookSummary> result = service.getSeriesBooks("Nonexistent", 0, 20, null, null, null);
assertNotNull(result);
assertTrue(result.getContent().isEmpty());
@@ -272,7 +272,7 @@ class MobileSeriesServiceTest {
mockAdminUser();
mockBookPage(Collections.emptyList(), 0L);
MobilePageResponse<MobileBookSummary> result = service.getSeriesBooks("Dune", 0, 20, "title", "desc", null);
AppPageResponse<AppBookSummary> result = service.getSeriesBooks("Dune", 0, 20, "title", "desc", null);
assertNotNull(result);
}
@@ -282,7 +282,7 @@ class MobileSeriesServiceTest {
mockAdminUser();
mockBookPage(Collections.emptyList(), 0L);
MobilePageResponse<MobileBookSummary> result = service.getSeriesBooks("Dune", 0, 20, "recentlyAdded", "asc", null);
AppPageResponse<AppBookSummary> result = service.getSeriesBooks("Dune", 0, 20, "recentlyAdded", "asc", null);
assertNotNull(result);
}
@@ -292,7 +292,7 @@ class MobileSeriesServiceTest {
mockAdminUser();
mockBookPage(Collections.emptyList(), 0L);
MobilePageResponse<MobileBookSummary> result = service.getSeriesBooks("Dune", 0, 20, null, null, null);
AppPageResponse<AppBookSummary> result = service.getSeriesBooks("Dune", 0, 20, null, null, null);
assertNotNull(result);
}
@@ -302,7 +302,7 @@ class MobileSeriesServiceTest {
mockAdminUser();
mockBookPage(Collections.emptyList(), 0L);
MobilePageResponse<MobileBookSummary> result = service.getSeriesBooks("Dune", null, null, null, null, null);
AppPageResponse<AppBookSummary> result = service.getSeriesBooks("Dune", null, null, null, null, null);
assertEquals(0, result.getPage());
assertEquals(20, result.getSize());
@@ -313,7 +313,7 @@ class MobileSeriesServiceTest {
mockAdminUser();
mockBookPage(Collections.emptyList(), 0L);
MobilePageResponse<MobileBookSummary> result = service.getSeriesBooks("Dune", 0, 200, null, null, null);
AppPageResponse<AppBookSummary> result = service.getSeriesBooks("Dune", 0, 200, null, null, null);
assertEquals(50, result.getSize());
}
@@ -446,7 +446,7 @@ class MobileSeriesServiceTest {
when(mobileBookMapper.toSummary(any(BookEntity.class), any()))
.thenAnswer(inv -> {
BookEntity b = inv.getArgument(0);
return MobileBookSummary.builder()
return AppBookSummary.builder()
.id(b.getId())
.title(b.getMetadata() != null ? b.getMetadata().getTitle() : null)
.build();
@@ -10,7 +10,7 @@ import { BookFileProgress } from '../../book/model/book.model';
providedIn: 'root'
})
export class AudiobookService {
private readonly baseUrl = `${API_CONFIG.BASE_URL}/api/v1/audiobook`;
private readonly baseUrl = `${API_CONFIG.BASE_URL}/api/v1/audiobooks`;
private readonly booksUrl = `${API_CONFIG.BASE_URL}/api/v1/books`;
private http = inject(HttpClient);
@@ -8,7 +8,7 @@ import {EmailProvider} from '../email-provider.model';
providedIn: 'root'
})
export class EmailV2ProviderService {
private readonly url = `${API_CONFIG.BASE_URL}/api/v2/email/providers`;
private readonly url = `${API_CONFIG.BASE_URL}/api/v1/email/providers`;
private http = inject(HttpClient);
@@ -8,7 +8,7 @@ import {EmailRecipient} from '../email-recipient.model';
providedIn: 'root'
})
export class EmailV2RecipientService {
private readonly url = `${API_CONFIG.BASE_URL}/api/v2/email/recipients`;
private readonly url = `${API_CONFIG.BASE_URL}/api/v1/email/recipients`;
private http = inject(HttpClient);
@@ -8,7 +8,7 @@ import {Observable} from 'rxjs';
})
export class EmailService {
private readonly apiUrl = `${API_CONFIG.BASE_URL}/api/v2/email`;
private readonly apiUrl = `${API_CONFIG.BASE_URL}/api/v1/email`;
private http = inject(HttpClient);
@@ -85,27 +85,27 @@ export class UserStatsService {
getHeatmapForYear(year: number): Observable<ReadingSessionHeatmapResponse[]> {
return this.http.get<ReadingSessionHeatmapResponse[]>(
`${this.readingSessionsUrl}/heatmap`,
`${this.readingSessionsUrl}/reading/heatmap`,
{params: {year: year.toString()}}
);
}
getTimelineForWeek(year: number, week: number): Observable<ReadingSessionTimelineResponse[]> {
return this.http.get<ReadingSessionTimelineResponse[]>(
`${this.readingSessionsUrl}/timeline`,
`${this.readingSessionsUrl}/reading/timeline`,
{params: {year: year.toString(), week: week.toString()}}
);
}
getGenreStats(): Observable<GenreStatsResponse[]> {
return this.http.get<GenreStatsResponse[]>(
`${this.readingSessionsUrl}/genres`
`${this.readingSessionsUrl}/reading/genres`
);
}
getCompletionTimelineForYear(year: number): Observable<CompletionTimelineResponse[]> {
return this.http.get<CompletionTimelineResponse[]>(
`${this.readingSessionsUrl}/completion-timeline`,
`${this.readingSessionsUrl}/reading/completion-timeline`,
{params: {year: year.toString()}}
);
}
@@ -120,7 +120,7 @@ export class UserStatsService {
}
return this.http.get<FavoriteDaysResponse[]>(
`${this.readingSessionsUrl}/favorite-days`,
`${this.readingSessionsUrl}/reading/favorite-days`,
{params}
);
}
@@ -135,33 +135,33 @@ export class UserStatsService {
}
return this.http.get<PeakHoursResponse[]>(
`${this.readingSessionsUrl}/peak-hours`,
`${this.readingSessionsUrl}/reading/peak-hours`,
{params}
);
}
getPageTurnerScores(): Observable<PageTurnerScoreResponse[]> {
return this.http.get<PageTurnerScoreResponse[]>(
`${this.readingSessionsUrl}/page-turner-scores`
`${this.readingSessionsUrl}/reading/page-turner-scores`
);
}
getCompletionRace(year: number): Observable<CompletionRaceResponse[]> {
return this.http.get<CompletionRaceResponse[]>(
`${this.readingSessionsUrl}/completion-race`,
`${this.readingSessionsUrl}/reading/completion-race`,
{params: {year: year.toString()}}
);
}
getReadingDates(): Observable<ReadingSessionHeatmapResponse[]> {
return this.http.get<ReadingSessionHeatmapResponse[]>(
`${this.readingSessionsUrl}/reading-dates`
`${this.readingSessionsUrl}/reading/dates`
);
}
getSessionScatter(year: number): Observable<SessionScatterResponse[]> {
return this.http.get<SessionScatterResponse[]>(
`${this.readingSessionsUrl}/session-scatter`,
`${this.readingSessionsUrl}/reading/session-scatter`,
{params: {year: year.toString()}}
);
}