Add setting/toggle to automatically download reviews (#1221)

This commit is contained in:
Aditya Chandel
2025-09-26 14:39:52 -06:00
committed by GitHub
parent a9c1be9854
commit 06523d4c24
10 changed files with 124 additions and 31 deletions
@@ -2,11 +2,13 @@ package com.adityachandel.booklore.controller;
import com.adityachandel.booklore.model.dto.BookReview; import com.adityachandel.booklore.model.dto.BookReview;
import com.adityachandel.booklore.service.BookReviewService; import com.adityachandel.booklore.service.BookReviewService;
import jakarta.validation.constraints.Positive;
import lombok.AllArgsConstructor; import lombok.AllArgsConstructor;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import java.util.List; import java.util.List;
@RestController @RestController
@@ -17,8 +19,12 @@ public class BookReviewController {
private final BookReviewService bookReviewService; private final BookReviewService bookReviewService;
@GetMapping("/book/{bookId}") @GetMapping("/book/{bookId}")
public List<BookReview> listByBook(@PathVariable Long bookId) { public ResponseEntity<List<BookReview>> listByBook(@PathVariable @Positive(message = "Book ID must be positive") Long bookId) {
return bookReviewService.getByBookId(bookId); List<BookReview> reviews = bookReviewService.getByBookId(bookId);
if (reviews.isEmpty()) {
return ResponseEntity.noContent().build();
}
return ResponseEntity.ok(reviews);
} }
@PostMapping("/book/{bookId}/refresh") @PostMapping("/book/{bookId}/refresh")
@@ -11,6 +11,7 @@ import java.util.Set;
public class MetadataPublicReviewsSettings { public class MetadataPublicReviewsSettings {
private boolean downloadEnabled; private boolean downloadEnabled;
private boolean autoDownloadEnabled;
private Set<ReviewProviderConfig> providers; private Set<ReviewProviderConfig> providers;
@Builder @Builder
@@ -37,25 +37,40 @@ public class BookReviewService {
private final AuthenticationService authenticationService; private final AuthenticationService authenticationService;
public List<BookReview> getByBookId(Long bookId) { public List<BookReview> getByBookId(Long bookId) {
List<BookReview> reviews = bookReviewRepository.findByBookMetadataBookId(bookId).stream()
.map(mapper::toDto)
.collect(Collectors.toList());
if (!appSettingService.getAppSettings().getMetadataPublicReviewsSettings().isDownloadEnabled() || !reviews.isEmpty()) {
return reviews;
}
BookLoreUser user = authenticationService.getAuthenticatedUser();
if (!(user.getPermissions().isAdmin() || user.getPermissions().isCanManipulateLibrary())) {
return reviews;
}
BookEntity bookEntity = bookRepository.findById(bookId).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId)); BookEntity bookEntity = bookRepository.findById(bookId).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId));
bookReviewUpdateService.addReviewsToBook(fetchBookReviews(bookEntity), bookEntity.getMetadata());
bookRepository.save(bookEntity); List<BookReview> existingReviews = bookReviewRepository.findByBookMetadataBookId(bookId).stream()
return bookReviewRepository.findByBookMetadataBookId(bookId).stream()
.map(mapper::toDto) .map(mapper::toDto)
.collect(Collectors.toList()); .collect(Collectors.toList());
MetadataPublicReviewsSettings reviewSettings = appSettingService.getAppSettings().getMetadataPublicReviewsSettings();
// Return existing reviews if download is disabled or reviews already exist
if (!reviewSettings.isDownloadEnabled() || !existingReviews.isEmpty()) {
return existingReviews;
}
// Check user permissions for auto-download
BookLoreUser currentUser = authenticationService.getAuthenticatedUser();
boolean hasPermission = currentUser.getPermissions().isAdmin() || currentUser.getPermissions().isCanManipulateLibrary();
if (!hasPermission || !reviewSettings.isAutoDownloadEnabled()) {
return existingReviews;
}
try {
List<BookReview> fetchedReviews = fetchBookReviews(bookEntity);
if (!fetchedReviews.isEmpty()) {
bookReviewUpdateService.addReviewsToBook(fetchedReviews, bookEntity.getMetadata());
bookRepository.save(bookEntity);
return bookReviewRepository.findByBookMetadataBookId(bookId).stream()
.map(mapper::toDto)
.collect(Collectors.toList());
}
} catch (Exception ignored) {
}
return existingReviews;
} }
public List<BookReview> fetchBookReviews(BookEntity bookEntity) { public List<BookReview> fetchBookReviews(BookEntity bookEntity) {
@@ -191,6 +191,7 @@ public class SettingPersistenceHelper {
public MetadataPublicReviewsSettings getDefaultMetadataPublicReviewsSettings() { public MetadataPublicReviewsSettings getDefaultMetadataPublicReviewsSettings() {
return MetadataPublicReviewsSettings.builder() return MetadataPublicReviewsSettings.builder()
.downloadEnabled(true) .downloadEnabled(true)
.autoDownloadEnabled(false)
.providers(Set.of( .providers(Set.of(
MetadataPublicReviewsSettings.ReviewProviderConfig.builder() MetadataPublicReviewsSettings.ReviewProviderConfig.builder()
.provider(MetadataProvider.Amazon) .provider(MetadataProvider.Amazon)
@@ -108,6 +108,7 @@ class BookReviewServiceTest {
return MetadataPublicReviewsSettings.builder() return MetadataPublicReviewsSettings.builder()
.downloadEnabled(enabled) .downloadEnabled(enabled)
.autoDownloadEnabled(enabled)
.providers(configs) .providers(configs)
.build(); .build();
} }
@@ -115,11 +116,13 @@ class BookReviewServiceTest {
@Test @Test
void getByBookId_returnsExistingReviews_whenReviewsExist() { void getByBookId_returnsExistingReviews_whenReviewsExist() {
Long bookId = 1L; Long bookId = 1L;
BookEntity bookEntity = new BookEntity();
BookReviewEntity entity = createBookReviewEntity(MetadataProvider.Amazon); BookReviewEntity entity = createBookReviewEntity(MetadataProvider.Amazon);
BookReview dto = createBookReview(MetadataProvider.Amazon); BookReview dto = createBookReview(MetadataProvider.Amazon);
AppSettings appSettings = new AppSettings(); AppSettings appSettings = new AppSettings();
appSettings.setMetadataPublicReviewsSettings(createReviewSettings(true)); appSettings.setMetadataPublicReviewsSettings(createReviewSettings(true));
when(bookRepository.findById(bookId)).thenReturn(Optional.of(bookEntity));
when(bookReviewRepository.findByBookMetadataBookId(bookId)) when(bookReviewRepository.findByBookMetadataBookId(bookId))
.thenReturn(Collections.singletonList(entity)); .thenReturn(Collections.singletonList(entity));
when(mapper.toDto(entity)).thenReturn(dto); when(mapper.toDto(entity)).thenReturn(dto);
@@ -135,9 +138,11 @@ class BookReviewServiceTest {
@Test @Test
void getByBookId_returnsEmptyList_whenDownloadDisabled() { void getByBookId_returnsEmptyList_whenDownloadDisabled() {
Long bookId = 1L; Long bookId = 1L;
BookEntity bookEntity = new BookEntity();
AppSettings appSettings = new AppSettings(); AppSettings appSettings = new AppSettings();
appSettings.setMetadataPublicReviewsSettings(createReviewSettings(false)); appSettings.setMetadataPublicReviewsSettings(createReviewSettings(false));
when(bookRepository.findById(bookId)).thenReturn(Optional.of(bookEntity));
when(bookReviewRepository.findByBookMetadataBookId(bookId)) when(bookReviewRepository.findByBookMetadataBookId(bookId))
.thenReturn(Collections.emptyList()); .thenReturn(Collections.emptyList());
when(appSettingService.getAppSettings()).thenReturn(appSettings); when(appSettingService.getAppSettings()).thenReturn(appSettings);
@@ -151,10 +156,12 @@ class BookReviewServiceTest {
@Test @Test
void getByBookId_returnsEmptyList_whenUserLacksPermissions() { void getByBookId_returnsEmptyList_whenUserLacksPermissions() {
Long bookId = 1L; Long bookId = 1L;
BookEntity bookEntity = new BookEntity();
AppSettings appSettings = new AppSettings(); AppSettings appSettings = new AppSettings();
appSettings.setMetadataPublicReviewsSettings(createReviewSettings(true, MetadataProvider.Amazon)); appSettings.setMetadataPublicReviewsSettings(createReviewSettings(true, MetadataProvider.Amazon));
BookLoreUser user = createUser(false, false); BookLoreUser user = createUser(false, false);
when(bookRepository.findById(bookId)).thenReturn(Optional.of(bookEntity));
when(bookReviewRepository.findByBookMetadataBookId(bookId)) when(bookReviewRepository.findByBookMetadataBookId(bookId))
.thenReturn(Collections.emptyList()); .thenReturn(Collections.emptyList());
when(appSettingService.getAppSettings()).thenReturn(appSettings); when(appSettingService.getAppSettings()).thenReturn(appSettings);
@@ -239,14 +246,7 @@ class BookReviewServiceTest {
@Test @Test
void getByBookId_throwsException_whenBookNotFound() { void getByBookId_throwsException_whenBookNotFound() {
Long bookId = 1L; Long bookId = 1L;
AppSettings appSettings = new AppSettings();
appSettings.setMetadataPublicReviewsSettings(createReviewSettings(true, MetadataProvider.Amazon));
BookLoreUser user = createUser(true, false);
when(bookReviewRepository.findByBookMetadataBookId(bookId))
.thenReturn(Collections.emptyList());
when(appSettingService.getAppSettings()).thenReturn(appSettings);
when(authenticationService.getAuthenticatedUser()).thenReturn(user);
when(bookRepository.findById(bookId)).thenReturn(Optional.empty()); when(bookRepository.findById(bookId)).thenReturn(Optional.empty());
RuntimeException exception = assertThrows(RuntimeException.class, RuntimeException exception = assertThrows(RuntimeException.class,
@@ -6,14 +6,32 @@
<span class="text-gray-400">Getting latest reviews...</span> <span class="text-gray-400">Getting latest reviews...</span>
</div> </div>
} @else if (reviews?.length === 0) { } @else if (reviews?.length === 0) {
<div class="text-center p-8 text-gray-400"> <div class="text-center p-8 text-gray-400 empty-state">
<i class="pi pi-comments text-4xl mb-4 block"></i> <div class="empty-state-icon">
<p class="text-gray-200">No reviews available for this book</p> @if (hasPermission && !reviewsLocked && reviewDownloadEnabled) {
<p-button
outlined
rounded
icon="pi pi-download"
severity="primary"
(click)="fetchNewReviews()"
pTooltip="Fetch Reviews"
tooltipPosition="top"
class="action-btn floating-btn">
</p-button>
}
</div>
<p class="text-gray-200 empty-state-title">No reviews available for this book</p>
@if (!reviewDownloadEnabled) { @if (!reviewDownloadEnabled) {
<p class="text-sm text-amber-400 mt-2"> <p class="text-sm text-amber-400 mt-2 empty-state-subtitle">
Book review downloads are currently disabled. Enable this in Metadata Settings to fetch reviews. Book review downloads are currently disabled. Enable this in Metadata Settings to fetch reviews.
</p> </p>
} @else if (hasPermission && !reviewsLocked) {
<p class="text-sm text-gray-400 mt-2 empty-state-subtitle">
Click "Fetch Reviews" to download reviews from configured providers
</p>
} }
<div class="empty-state-decoration"></div>
</div> </div>
} @else { } @else {
<div class="reviews-scroll-container"> <div class="reviews-scroll-container">
@@ -54,6 +54,35 @@
} }
} }
.empty-state {
position: relative;
padding: 3rem !important;
.empty-state-title {
font-size: 1.25rem;
font-weight: 600;
margin-top: 1rem;
margin-bottom: 0.5rem;
}
.empty-state-subtitle {
max-width: 400px;
margin: 0 auto;
line-height: 1.6;
}
.empty-state-decoration {
position: absolute;
top: 20%;
right: 15%;
width: 100px;
height: 100px;
border-radius: 50%;
filter: blur(40px);
animation: float 4s ease-in-out infinite;
}
}
.reviews-scroll-container { .reviews-scroll-container {
overflow-x: auto; overflow-x: auto;
overflow-y: hidden; overflow-y: hidden;
@@ -94,6 +94,7 @@ export interface ReviewProviderConfig {
export interface PublicReviewSettings { export interface PublicReviewSettings {
downloadEnabled: boolean; downloadEnabled: boolean;
autoDownloadEnabled: boolean;
providers: ReviewProviderConfig[]; providers: ReviewProviderConfig[];
} }
@@ -10,12 +10,28 @@
</div> </div>
<p class="setting-description"> <p class="setting-description">
<i class="pi pi-info-circle"></i> <i class="pi pi-info-circle"></i>
Automatically download user reviews from enabled platforms (Amazon, Goodreads, Hardcover) when fetching book metadata. Reviews will be stored with your books for offline access. Enable downloading user reviews from configured platforms (Amazon, Goodreads, Hardcover). Reviews will be stored with your books for offline access.
</p> </p>
</div> </div>
</div> </div>
@if (publicReviewSettings.downloadEnabled) { @if (publicReviewSettings.downloadEnabled) {
<div class="setting-item">
<div class="setting-info">
<div class="setting-label-row">
<label class="setting-label">Auto Download on Book Open</label>
<p-toggleswitch
[(ngModel)]="publicReviewSettings.autoDownloadEnabled"
(onChange)="onAutoDownloadToggle($event.checked)">
</p-toggleswitch>
</div>
<p class="setting-description">
<i class="pi pi-info-circle"></i>
Automatically fetch reviews when you open a book's details page. When disabled, reviews will only be downloaded manually or during metadata refresh, reducing background network activity and improving performance.
</p>
</div>
</div>
<div class="review-sources-section"> <div class="review-sources-section">
<div class="sources-header"> <div class="sources-header">
<h4 class="subsection-title">Review Sources</h4> <h4 class="subsection-title">Review Sources</h4>
@@ -25,6 +25,7 @@ export class PublicReviewsSettingsComponent implements OnInit {
publicReviewSettings: PublicReviewSettings = { publicReviewSettings: PublicReviewSettings = {
downloadEnabled: true, downloadEnabled: true,
autoDownloadEnabled: false,
providers: [...DEFAULT_PROVIDERS] providers: [...DEFAULT_PROVIDERS]
}; };
@@ -42,6 +43,11 @@ export class PublicReviewsSettingsComponent implements OnInit {
this.settingsHelper.saveSetting(AppSettingKey.METADATA_PUBLIC_REVIEWS_SETTINGS, this.publicReviewSettings); this.settingsHelper.saveSetting(AppSettingKey.METADATA_PUBLIC_REVIEWS_SETTINGS, this.publicReviewSettings);
} }
onAutoDownloadToggle(checked: boolean): void {
this.publicReviewSettings.autoDownloadEnabled = checked;
this.settingsHelper.saveSetting(AppSettingKey.METADATA_PUBLIC_REVIEWS_SETTINGS, this.publicReviewSettings);
}
onProviderToggle(providerName: string, enabled: boolean): void { onProviderToggle(providerName: string, enabled: boolean): void {
this.updateProviderProperty(providerName, 'enabled', enabled); this.updateProviderProperty(providerName, 'enabled', enabled);
} }