From 9f9c762180ea2bcf1821f5c7b0f5dc9357a9f05d Mon Sep 17 00:00:00 2001 From: ACX <8075870+acx10@users.noreply.github.com> Date: Thu, 5 Feb 2026 17:10:44 -0700 Subject: [PATCH] feat(content-restrictions): add age rating and content rating support (#2619) --- .../security/aspect/BookAccessAspect.java | 12 +- .../ContentRestrictionController.java | 97 +++++++ .../mapper/MetadataClearFlagsMapper.java | 2 + .../booklore/model/MetadataClearFlags.java | 2 + .../org/booklore/model/dto/BookMetadata.java | 5 + .../model/dto/ContentRestriction.java | 23 ++ .../org/booklore/model/dto/RuleField.java | 6 +- .../request/BulkMetadataUpdateRequest.java | 6 + .../model/entity/BookLoreUserEntity.java | 4 + .../model/entity/BookMetadataEntity.java | 18 ++ .../entity/UserContentRestrictionEntity.java | 46 +++ .../booklore/model/enums/ContentRating.java | 9 + .../model/enums/ContentRestrictionMode.java | 6 + .../model/enums/ContentRestrictionType.java | 9 + .../UserContentRestrictionRepository.java | 35 +++ .../service/BookRuleEvaluatorService.java | 2 + .../service/book/BookQueryService.java | 3 + .../service/metadata/BookMetadataService.java | 2 + .../service/metadata/BookMetadataUpdater.java | 6 +- .../ContentRestrictionService.java | 272 ++++++++++++++++++ .../booklore/util/MetadataChangeDetector.java | 10 +- .../V110__Add_age_rating_to_book_metadata.sql | 5 + ..._Create_user_content_restriction_table.sql | 13 + .../service/KoboEntitlementServiceTest.java | 13 +- .../book-browser/book-browser.component.ts | 2 +- .../book-filter-orchestration.service.ts | 2 +- .../book-filter/book-filter.config.ts | 47 ++- .../book-browser/filters/sidebar-filter.ts | 149 ++++++++++ .../src/app/features/book/model/book.model.ts | 10 + .../book/service/book-menu.service.ts | 178 +++++++++++- .../metadata-editor.component.html | 44 +++ .../metadata-editor.component.ts | 39 +++ .../metadata-viewer.component.html | 22 ++ .../metadata-viewer.component.ts | 21 +- .../content-restriction.model.ts | 41 +++ .../content-restriction.service.ts | 33 +++ ...content-restrictions-editor.component.html | 113 ++++++++ ...content-restrictions-editor.component.scss | 187 ++++++++++++ .../content-restrictions-editor.component.ts | 232 +++++++++++++++ .../user-management.component.html | 14 + .../user-management.component.scss | 28 ++ .../user-management.component.ts | 4 +- 42 files changed, 1755 insertions(+), 17 deletions(-) create mode 100644 booklore-api/src/main/java/org/booklore/controller/ContentRestrictionController.java create mode 100644 booklore-api/src/main/java/org/booklore/model/dto/ContentRestriction.java create mode 100644 booklore-api/src/main/java/org/booklore/model/entity/UserContentRestrictionEntity.java create mode 100644 booklore-api/src/main/java/org/booklore/model/enums/ContentRating.java create mode 100644 booklore-api/src/main/java/org/booklore/model/enums/ContentRestrictionMode.java create mode 100644 booklore-api/src/main/java/org/booklore/model/enums/ContentRestrictionType.java create mode 100644 booklore-api/src/main/java/org/booklore/repository/UserContentRestrictionRepository.java create mode 100644 booklore-api/src/main/java/org/booklore/service/restriction/ContentRestrictionService.java create mode 100644 booklore-api/src/main/resources/db/migration/V110__Add_age_rating_to_book_metadata.sql create mode 100644 booklore-api/src/main/resources/db/migration/V111__Create_user_content_restriction_table.sql create mode 100644 booklore-ui/src/app/features/book/components/book-browser/filters/sidebar-filter.ts create mode 100644 booklore-ui/src/app/features/settings/user-management/content-restriction.model.ts create mode 100644 booklore-ui/src/app/features/settings/user-management/content-restriction.service.ts create mode 100644 booklore-ui/src/app/features/settings/user-management/content-restrictions-editor/content-restrictions-editor.component.html create mode 100644 booklore-ui/src/app/features/settings/user-management/content-restrictions-editor/content-restrictions-editor.component.scss create mode 100644 booklore-ui/src/app/features/settings/user-management/content-restrictions-editor/content-restrictions-editor.component.ts diff --git a/booklore-api/src/main/java/org/booklore/config/security/aspect/BookAccessAspect.java b/booklore-api/src/main/java/org/booklore/config/security/aspect/BookAccessAspect.java index ecdc3d29f..cc9a62f34 100644 --- a/booklore-api/src/main/java/org/booklore/config/security/aspect/BookAccessAspect.java +++ b/booklore-api/src/main/java/org/booklore/config/security/aspect/BookAccessAspect.java @@ -6,6 +6,7 @@ import org.booklore.exception.ApiError; import org.booklore.model.dto.BookLoreUser; import org.booklore.model.entity.BookEntity; import org.booklore.repository.BookRepository; +import org.booklore.service.restriction.ContentRestrictionService; import lombok.RequiredArgsConstructor; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.annotation.Aspect; @@ -14,6 +15,7 @@ import org.aspectj.lang.reflect.MethodSignature; import org.springframework.stereotype.Component; import java.lang.reflect.Method; +import java.util.List; import java.util.Objects; import java.util.regex.Pattern; @@ -25,6 +27,7 @@ public class BookAccessAspect { private static final Pattern NUMERIC_PATTERN = Pattern.compile("\\d+"); private final AuthenticationService authenticationService; private final BookRepository bookRepository; + private final ContentRestrictionService contentRestrictionService; @Before("@annotation(org.booklore.config.security.annotation.CheckBookAccess)") public void checkBookAccess(JoinPoint joinPoint) { @@ -49,9 +52,14 @@ public class BookAccessAspect { return; } - boolean hasAccess = user.getAssignedLibraries().stream().anyMatch(library -> library.getId().equals(bookEntity.getLibrary().getId())); + boolean hasLibraryAccess = user.getAssignedLibraries().stream().anyMatch(library -> library.getId().equals(bookEntity.getLibrary().getId())); - if (!hasAccess) { + if (!hasLibraryAccess) { + throw ApiError.FORBIDDEN.createException("You are not authorized to access this book."); + } + + List filteredBooks = contentRestrictionService.applyRestrictions(List.of(bookEntity), user.getId()); + if (filteredBooks.isEmpty()) { throw ApiError.FORBIDDEN.createException("You are not authorized to access this book."); } } diff --git a/booklore-api/src/main/java/org/booklore/controller/ContentRestrictionController.java b/booklore-api/src/main/java/org/booklore/controller/ContentRestrictionController.java new file mode 100644 index 000000000..67c72c682 --- /dev/null +++ b/booklore-api/src/main/java/org/booklore/controller/ContentRestrictionController.java @@ -0,0 +1,97 @@ +package org.booklore.controller; + +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.RequiredArgsConstructor; +import org.booklore.model.dto.ContentRestriction; +import org.booklore.service.restriction.ContentRestrictionService; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.web.bind.annotation.*; + +import java.util.List; + +@Tag(name = "Content Restrictions", description = "Endpoints for managing user content restrictions") +@RestController +@RequestMapping("/api/v1/users/{userId}/content-restrictions") +@RequiredArgsConstructor +public class ContentRestrictionController { + + private final ContentRestrictionService contentRestrictionService; + + @Operation(summary = "Get user content restrictions", description = "Retrieve all content restrictions for a specific user") + @ApiResponses({ + @ApiResponse(responseCode = "200", description = "Content restrictions retrieved successfully"), + @ApiResponse(responseCode = "403", description = "Forbidden - requires admin or own user"), + @ApiResponse(responseCode = "404", description = "User not found") + }) + @GetMapping + @PreAuthorize("@securityUtil.isAdmin() or @securityUtil.isSelf(#userId)") + public ResponseEntity> getUserRestrictions( + @Parameter(description = "ID of the user") @PathVariable Long userId) { + return ResponseEntity.ok(contentRestrictionService.getUserRestrictions(userId)); + } + + @Operation(summary = "Add content restriction", description = "Add a new content restriction for a user") + @ApiResponses({ + @ApiResponse(responseCode = "201", description = "Content restriction created successfully"), + @ApiResponse(responseCode = "400", description = "Invalid request or restriction already exists"), + @ApiResponse(responseCode = "403", description = "Forbidden - requires admin"), + @ApiResponse(responseCode = "404", description = "User not found") + }) + @PostMapping + @PreAuthorize("@securityUtil.isAdmin()") + public ResponseEntity addRestriction( + @Parameter(description = "ID of the user") @PathVariable Long userId, + @Parameter(description = "Content restriction to add") @RequestBody @Valid ContentRestriction restriction) { + return ResponseEntity.status(HttpStatus.CREATED) + .body(contentRestrictionService.addRestriction(userId, restriction)); + } + + @Operation(summary = "Update all content restrictions", description = "Replace all content restrictions for a user") + @ApiResponses({ + @ApiResponse(responseCode = "200", description = "Content restrictions updated successfully"), + @ApiResponse(responseCode = "403", description = "Forbidden - requires admin"), + @ApiResponse(responseCode = "404", description = "User not found") + }) + @PutMapping + @PreAuthorize("@securityUtil.isAdmin()") + public ResponseEntity> updateRestrictions( + @Parameter(description = "ID of the user") @PathVariable Long userId, + @Parameter(description = "List of content restrictions") @RequestBody @Valid List restrictions) { + return ResponseEntity.ok(contentRestrictionService.updateRestrictions(userId, restrictions)); + } + + @Operation(summary = "Delete content restriction", description = "Delete a specific content restriction") + @ApiResponses({ + @ApiResponse(responseCode = "204", description = "Content restriction deleted successfully"), + @ApiResponse(responseCode = "403", description = "Forbidden - requires admin"), + @ApiResponse(responseCode = "404", description = "Content restriction not found") + }) + @DeleteMapping("/{restrictionId}") + @PreAuthorize("@securityUtil.isAdmin()") + public ResponseEntity deleteRestriction( + @Parameter(description = "ID of the user") @PathVariable Long userId, + @Parameter(description = "ID of the restriction to delete") @PathVariable Long restrictionId) { + contentRestrictionService.deleteRestriction(restrictionId); + return ResponseEntity.noContent().build(); + } + + @Operation(summary = "Delete all user content restrictions", description = "Delete all content restrictions for a user") + @ApiResponses({ + @ApiResponse(responseCode = "204", description = "All content restrictions deleted successfully"), + @ApiResponse(responseCode = "403", description = "Forbidden - requires admin") + }) + @DeleteMapping + @PreAuthorize("@securityUtil.isAdmin()") + public ResponseEntity deleteAllRestrictions( + @Parameter(description = "ID of the user") @PathVariable Long userId) { + contentRestrictionService.deleteAllUserRestrictions(userId); + return ResponseEntity.noContent().build(); + } +} diff --git a/booklore-api/src/main/java/org/booklore/mapper/MetadataClearFlagsMapper.java b/booklore-api/src/main/java/org/booklore/mapper/MetadataClearFlagsMapper.java index 03cf65e6e..9f67fd724 100644 --- a/booklore-api/src/main/java/org/booklore/mapper/MetadataClearFlagsMapper.java +++ b/booklore-api/src/main/java/org/booklore/mapper/MetadataClearFlagsMapper.java @@ -18,5 +18,7 @@ public interface MetadataClearFlagsMapper { @Mapping(target = "categories", source = "clearGenres") @Mapping(target = "moods", source = "clearMoods") @Mapping(target = "tags", source = "clearTags") + @Mapping(target = "ageRating", source = "clearAgeRating") + @Mapping(target = "contentRating", source = "clearContentRating") MetadataClearFlags toClearFlags(BulkMetadataUpdateRequest request); } diff --git a/booklore-api/src/main/java/org/booklore/model/MetadataClearFlags.java b/booklore-api/src/main/java/org/booklore/model/MetadataClearFlags.java index 6f06749b8..faeb5d421 100644 --- a/booklore-api/src/main/java/org/booklore/model/MetadataClearFlags.java +++ b/booklore-api/src/main/java/org/booklore/model/MetadataClearFlags.java @@ -42,4 +42,6 @@ public class MetadataClearFlags { private boolean reviews; private boolean narrator; private boolean abridged; + private boolean ageRating; + private boolean contentRating; } diff --git a/booklore-api/src/main/java/org/booklore/model/dto/BookMetadata.java b/booklore-api/src/main/java/org/booklore/model/dto/BookMetadata.java index 9398f63c4..61ab339cc 100644 --- a/booklore-api/src/main/java/org/booklore/model/dto/BookMetadata.java +++ b/booklore-api/src/main/java/org/booklore/model/dto/BookMetadata.java @@ -112,4 +112,9 @@ public class BookMetadata { private Boolean reviewsLocked; private Boolean narratorLocked; private Boolean abridgedLocked; + + private Integer ageRating; + private String contentRating; + private Boolean ageRatingLocked; + private Boolean contentRatingLocked; } diff --git a/booklore-api/src/main/java/org/booklore/model/dto/ContentRestriction.java b/booklore-api/src/main/java/org/booklore/model/dto/ContentRestriction.java new file mode 100644 index 000000000..7fac23ddb --- /dev/null +++ b/booklore-api/src/main/java/org/booklore/model/dto/ContentRestriction.java @@ -0,0 +1,23 @@ +package org.booklore.model.dto; + +import com.fasterxml.jackson.annotation.JsonInclude; +import lombok.*; +import org.booklore.model.enums.ContentRestrictionMode; +import org.booklore.model.enums.ContentRestrictionType; + +import java.time.LocalDateTime; + +@Getter +@Setter +@Builder +@AllArgsConstructor +@NoArgsConstructor +@JsonInclude(JsonInclude.Include.NON_NULL) +public class ContentRestriction { + private Long id; + private Long userId; + private ContentRestrictionType restrictionType; + private ContentRestrictionMode mode; + private String value; + private LocalDateTime createdAt; +} diff --git a/booklore-api/src/main/java/org/booklore/model/dto/RuleField.java b/booklore-api/src/main/java/org/booklore/model/dto/RuleField.java index e70097f8f..11c484523 100644 --- a/booklore-api/src/main/java/org/booklore/model/dto/RuleField.java +++ b/booklore-api/src/main/java/org/booklore/model/dto/RuleField.java @@ -66,6 +66,10 @@ public enum RuleField { @JsonProperty("tags") TAGS, @JsonProperty("genre") - GENRE + GENRE, + @JsonProperty("ageRating") + AGE_RATING, + @JsonProperty("contentRating") + CONTENT_RATING } diff --git a/booklore-api/src/main/java/org/booklore/model/dto/request/BulkMetadataUpdateRequest.java b/booklore-api/src/main/java/org/booklore/model/dto/request/BulkMetadataUpdateRequest.java index 2daa2f7cc..c00b3eabd 100644 --- a/booklore-api/src/main/java/org/booklore/model/dto/request/BulkMetadataUpdateRequest.java +++ b/booklore-api/src/main/java/org/booklore/model/dto/request/BulkMetadataUpdateRequest.java @@ -39,4 +39,10 @@ public class BulkMetadataUpdateRequest { private boolean mergeCategories; private boolean mergeMoods; private boolean mergeTags; + + private Integer ageRating; + private boolean clearAgeRating; + + private String contentRating; + private boolean clearContentRating; } diff --git a/booklore-api/src/main/java/org/booklore/model/entity/BookLoreUserEntity.java b/booklore-api/src/main/java/org/booklore/model/entity/BookLoreUserEntity.java index 1ed64617e..921c0518e 100644 --- a/booklore-api/src/main/java/org/booklore/model/entity/BookLoreUserEntity.java +++ b/booklore-api/src/main/java/org/booklore/model/entity/BookLoreUserEntity.java @@ -70,6 +70,10 @@ public class BookLoreUserEntity { @Builder.Default private Set readingSessions = new HashSet<>(); + @OneToMany(mappedBy = "user", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY) + @Builder.Default + private Set contentRestrictions = new HashSet<>(); + @PrePersist public void prePersist() { this.createdAt = LocalDateTime.now(); diff --git a/booklore-api/src/main/java/org/booklore/model/entity/BookMetadataEntity.java b/booklore-api/src/main/java/org/booklore/model/entity/BookMetadataEntity.java index eaaedde3b..c7726d595 100644 --- a/booklore-api/src/main/java/org/booklore/model/entity/BookMetadataEntity.java +++ b/booklore-api/src/main/java/org/booklore/model/entity/BookMetadataEntity.java @@ -305,6 +305,20 @@ public class BookMetadataEntity { @Column(name = "search_text", columnDefinition = "TEXT") private String searchText; + @Column(name = "age_rating") + private Integer ageRating; + + @Column(name = "content_rating", length = 20) + private String contentRating; + + @Column(name = "age_rating_locked") + @Builder.Default + private Boolean ageRatingLocked = Boolean.FALSE; + + @Column(name = "content_rating_locked") + @Builder.Default + private Boolean contentRatingLocked = Boolean.FALSE; + @PrePersist @PreUpdate public void updateSearchText() { @@ -398,6 +412,8 @@ public class BookMetadataEntity { this.reviewsLocked = lock; this.narratorLocked = lock; this.abridgedLocked = lock; + this.ageRatingLocked = lock; + this.contentRatingLocked = lock; } public boolean areAllFieldsLocked() { @@ -441,6 +457,8 @@ public class BookMetadataEntity { && Boolean.TRUE.equals(this.reviewsLocked) && Boolean.TRUE.equals(this.narratorLocked) && Boolean.TRUE.equals(this.abridgedLocked) + && Boolean.TRUE.equals(this.ageRatingLocked) + && Boolean.TRUE.equals(this.contentRatingLocked) ; } } diff --git a/booklore-api/src/main/java/org/booklore/model/entity/UserContentRestrictionEntity.java b/booklore-api/src/main/java/org/booklore/model/entity/UserContentRestrictionEntity.java new file mode 100644 index 000000000..35fec23d9 --- /dev/null +++ b/booklore-api/src/main/java/org/booklore/model/entity/UserContentRestrictionEntity.java @@ -0,0 +1,46 @@ +package org.booklore.model.entity; + +import jakarta.persistence.*; +import lombok.*; +import org.booklore.model.enums.ContentRestrictionMode; +import org.booklore.model.enums.ContentRestrictionType; + +import java.time.LocalDateTime; + +@Entity +@Getter +@Setter +@Builder +@NoArgsConstructor +@AllArgsConstructor +@Table(name = "user_content_restriction", + uniqueConstraints = @UniqueConstraint(columnNames = {"user_id", "restriction_type", "value"})) +public class UserContentRestrictionEntity { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "user_id", nullable = false) + private BookLoreUserEntity user; + + @Column(name = "restriction_type", nullable = false, length = 20) + @Enumerated(EnumType.STRING) + private ContentRestrictionType restrictionType; + + @Column(name = "mode", nullable = false, length = 15) + @Enumerated(EnumType.STRING) + private ContentRestrictionMode mode; + + @Column(name = "value", nullable = false) + private String value; + + @Column(name = "created_at", nullable = false, updatable = false) + private LocalDateTime createdAt; + + @PrePersist + public void prePersist() { + this.createdAt = LocalDateTime.now(); + } +} diff --git a/booklore-api/src/main/java/org/booklore/model/enums/ContentRating.java b/booklore-api/src/main/java/org/booklore/model/enums/ContentRating.java new file mode 100644 index 000000000..dc49c533c --- /dev/null +++ b/booklore-api/src/main/java/org/booklore/model/enums/ContentRating.java @@ -0,0 +1,9 @@ +package org.booklore.model.enums; + +public enum ContentRating { + EVERYONE, + TEEN, + MATURE, + ADULT, + EXPLICIT +} diff --git a/booklore-api/src/main/java/org/booklore/model/enums/ContentRestrictionMode.java b/booklore-api/src/main/java/org/booklore/model/enums/ContentRestrictionMode.java new file mode 100644 index 000000000..059158ce3 --- /dev/null +++ b/booklore-api/src/main/java/org/booklore/model/enums/ContentRestrictionMode.java @@ -0,0 +1,6 @@ +package org.booklore.model.enums; + +public enum ContentRestrictionMode { + EXCLUDE, + ALLOW_ONLY +} diff --git a/booklore-api/src/main/java/org/booklore/model/enums/ContentRestrictionType.java b/booklore-api/src/main/java/org/booklore/model/enums/ContentRestrictionType.java new file mode 100644 index 000000000..eb99b2f19 --- /dev/null +++ b/booklore-api/src/main/java/org/booklore/model/enums/ContentRestrictionType.java @@ -0,0 +1,9 @@ +package org.booklore.model.enums; + +public enum ContentRestrictionType { + CATEGORY, + TAG, + MOOD, + AGE_RATING, + CONTENT_RATING +} diff --git a/booklore-api/src/main/java/org/booklore/repository/UserContentRestrictionRepository.java b/booklore-api/src/main/java/org/booklore/repository/UserContentRestrictionRepository.java new file mode 100644 index 000000000..595ea2ff9 --- /dev/null +++ b/booklore-api/src/main/java/org/booklore/repository/UserContentRestrictionRepository.java @@ -0,0 +1,35 @@ +package org.booklore.repository; + +import org.booklore.model.entity.UserContentRestrictionEntity; +import org.booklore.model.enums.ContentRestrictionMode; +import org.booklore.model.enums.ContentRestrictionType; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; + +import java.util.List; +import java.util.Optional; + +public interface UserContentRestrictionRepository extends JpaRepository { + + List findByUserId(Long userId); + + List findByUserIdAndRestrictionType(Long userId, ContentRestrictionType type); + + List findByUserIdAndMode(Long userId, ContentRestrictionMode mode); + + Optional findByUserIdAndRestrictionTypeAndValue( + Long userId, ContentRestrictionType restrictionType, String value); + + void deleteByUserId(Long userId); + + void deleteByUserIdAndRestrictionType(Long userId, ContentRestrictionType type); + + @Query("SELECT r FROM UserContentRestrictionEntity r WHERE r.user.id = :userId AND r.restrictionType = :type AND r.mode = :mode") + List findByUserIdAndTypeAndMode( + @Param("userId") Long userId, + @Param("type") ContentRestrictionType type, + @Param("mode") ContentRestrictionMode mode); + + boolean existsByUserIdAndRestrictionTypeAndValue(Long userId, ContentRestrictionType type, String value); +} diff --git a/booklore-api/src/main/java/org/booklore/service/BookRuleEvaluatorService.java b/booklore-api/src/main/java/org/booklore/service/BookRuleEvaluatorService.java index 6bfa8e136..183a8ef55 100644 --- a/booklore-api/src/main/java/org/booklore/service/BookRuleEvaluatorService.java +++ b/booklore-api/src/main/java/org/booklore/service/BookRuleEvaluatorService.java @@ -338,6 +338,8 @@ public class BookRuleEvaluatorService { case HARDCOVER_RATING -> root.get("metadata").get("hardcoverRating"); case HARDCOVER_REVIEW_COUNT -> root.get("metadata").get("hardcoverReviewCount"); case RANOBEDB_RATING -> root.get("metadata").get("ranobedbRating"); + case AGE_RATING -> root.get("metadata").get("ageRating"); + case CONTENT_RATING -> root.get("metadata").get("contentRating"); case FILE_TYPE -> cb.function("SUBSTRING_INDEX", String.class, root.get("fileName"), cb.literal("."), cb.literal(-1)); default -> null; diff --git a/booklore-api/src/main/java/org/booklore/service/book/BookQueryService.java b/booklore-api/src/main/java/org/booklore/service/book/BookQueryService.java index c0f306086..0268b2880 100644 --- a/booklore-api/src/main/java/org/booklore/service/book/BookQueryService.java +++ b/booklore-api/src/main/java/org/booklore/service/book/BookQueryService.java @@ -4,6 +4,7 @@ import org.booklore.mapper.v2.BookMapperV2; import org.booklore.model.dto.Book; import org.booklore.model.entity.BookEntity; import org.booklore.repository.BookRepository; +import org.booklore.service.restriction.ContentRestrictionService; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Service; @@ -17,6 +18,7 @@ public class BookQueryService { private final BookRepository bookRepository; private final BookMapperV2 bookMapperV2; + private final ContentRestrictionService contentRestrictionService; public List getAllBooks(boolean includeDescription) { List books = bookRepository.findAllWithMetadata(); @@ -25,6 +27,7 @@ public class BookQueryService { public List getAllBooksByLibraryIds(Set libraryIds, boolean includeDescription, Long userId) { List books = bookRepository.findAllWithMetadataByLibraryIds(libraryIds); + books = contentRestrictionService.applyRestrictions(books, userId); return mapBooksToDto(books, includeDescription, userId); } diff --git a/booklore-api/src/main/java/org/booklore/service/metadata/BookMetadataService.java b/booklore-api/src/main/java/org/booklore/service/metadata/BookMetadataService.java index 7f7796a03..f74703b81 100644 --- a/booklore-api/src/main/java/org/booklore/service/metadata/BookMetadataService.java +++ b/booklore-api/src/main/java/org/booklore/service/metadata/BookMetadataService.java @@ -152,6 +152,8 @@ public class BookMetadataService { .categories(request.getGenres() != null ? request.getGenres() : Collections.emptySet()) .moods(request.getMoods() != null ? request.getMoods() : Collections.emptySet()) .tags(request.getTags() != null ? request.getTags() : Collections.emptySet()) + .ageRating(request.getAgeRating()) + .contentRating(request.getContentRating()) .build(); for (Long bookId : request.getBookIds()) { diff --git a/booklore-api/src/main/java/org/booklore/service/metadata/BookMetadataUpdater.java b/booklore-api/src/main/java/org/booklore/service/metadata/BookMetadataUpdater.java index abfc8d0e1..42c0613c8 100644 --- a/booklore-api/src/main/java/org/booklore/service/metadata/BookMetadataUpdater.java +++ b/booklore-api/src/main/java/org/booklore/service/metadata/BookMetadataUpdater.java @@ -180,6 +180,8 @@ public class BookMetadataUpdater { handleFieldUpdate(e.getLubimyczytacRatingLocked(), clear.isLubimyczytacRating(), m.getLubimyczytacRating(), v -> e.setLubimyczytacRating(v), () -> e.getLubimyczytacRating(), replaceMode); handleFieldUpdate(e.getRanobedbIdLocked(), clear.isRanobedbId(), m.getRanobedbId(), v -> e.setRanobedbId(nullIfBlank(v)), e::getRanobedbId, replaceMode); handleFieldUpdate(e.getRanobedbRatingLocked(), clear.isRanobedbRating(), m.getRanobedbRating(), e::setRanobedbRating, e::getRanobedbRating, replaceMode); + handleFieldUpdate(e.getAgeRatingLocked(), clear.isAgeRating(), m.getAgeRating(), e::setAgeRating, e::getAgeRating, replaceMode); + handleFieldUpdate(e.getContentRatingLocked(), clear.isContentRating(), m.getContentRating(), v -> e.setContentRating(nullIfBlank(v)), e::getContentRating, replaceMode); } private void handleFieldUpdate(Boolean locked, boolean shouldClear, T newValue, Consumer setter, Supplier getter, MetadataReplaceMode mode) { @@ -416,7 +418,9 @@ public class BookMetadataUpdater { Pair.of(m.getTagsLocked(), e::setTagsLocked), Pair.of(m.getReviewsLocked(), e::setReviewsLocked), Pair.of(m.getNarratorLocked(), e::setNarratorLocked), - Pair.of(m.getAbridgedLocked(), e::setAbridgedLocked) + Pair.of(m.getAbridgedLocked(), e::setAbridgedLocked), + Pair.of(m.getAgeRatingLocked(), e::setAgeRatingLocked), + Pair.of(m.getContentRatingLocked(), e::setContentRatingLocked) ); lockMappings.forEach(pair -> { if (pair.getLeft() != null) pair.getRight().accept(pair.getLeft()); diff --git a/booklore-api/src/main/java/org/booklore/service/restriction/ContentRestrictionService.java b/booklore-api/src/main/java/org/booklore/service/restriction/ContentRestrictionService.java new file mode 100644 index 000000000..b65ad093d --- /dev/null +++ b/booklore-api/src/main/java/org/booklore/service/restriction/ContentRestrictionService.java @@ -0,0 +1,272 @@ +package org.booklore.service.restriction; + +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.booklore.exception.ApiError; +import org.booklore.model.dto.ContentRestriction; +import org.booklore.model.entity.BookEntity; +import org.booklore.model.entity.BookLoreUserEntity; +import org.booklore.model.entity.BookMetadataEntity; +import org.booklore.model.entity.UserContentRestrictionEntity; +import org.booklore.model.enums.ContentRestrictionMode; +import org.booklore.model.enums.ContentRestrictionType; +import org.booklore.repository.UserContentRestrictionRepository; +import org.booklore.repository.UserRepository; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.*; +import java.util.stream.Collectors; + +@Slf4j +@Service +@RequiredArgsConstructor +public class ContentRestrictionService { + + private final UserContentRestrictionRepository restrictionRepository; + private final UserRepository userRepository; + + public List getUserRestrictions(Long userId) { + return restrictionRepository.findByUserId(userId).stream() + .map(this::toDto) + .collect(Collectors.toList()); + } + + public ContentRestriction getRestriction(Long restrictionId) { + return restrictionRepository.findById(restrictionId) + .map(this::toDto) + .orElseThrow(() -> ApiError.GENERIC_NOT_FOUND.createException("Content restriction not found")); + } + + @Transactional + public ContentRestriction addRestriction(Long userId, ContentRestriction restriction) { + BookLoreUserEntity user = userRepository.findById(userId) + .orElseThrow(() -> ApiError.USER_NOT_FOUND.createException(userId)); + + if (restrictionRepository.existsByUserIdAndRestrictionTypeAndValue( + userId, restriction.getRestrictionType(), restriction.getValue())) { + throw ApiError.GENERIC_BAD_REQUEST.createException("Restriction already exists"); + } + + UserContentRestrictionEntity entity = UserContentRestrictionEntity.builder() + .user(user) + .restrictionType(restriction.getRestrictionType()) + .mode(restriction.getMode()) + .value(restriction.getValue()) + .build(); + + return toDto(restrictionRepository.save(entity)); + } + + @Transactional + public List updateRestrictions(Long userId, List restrictions) { + BookLoreUserEntity user = userRepository.findById(userId) + .orElseThrow(() -> ApiError.USER_NOT_FOUND.createException(userId)); + + restrictionRepository.deleteByUserId(userId); + + List entities = restrictions.stream() + .map(r -> UserContentRestrictionEntity.builder() + .user(user) + .restrictionType(r.getRestrictionType()) + .mode(r.getMode()) + .value(r.getValue()) + .build()) + .collect(Collectors.toList()); + + return restrictionRepository.saveAll(entities).stream() + .map(this::toDto) + .collect(Collectors.toList()); + } + + @Transactional + public void deleteRestriction(Long restrictionId) { + if (!restrictionRepository.existsById(restrictionId)) { + throw ApiError.GENERIC_NOT_FOUND.createException("Content restriction not found"); + } + restrictionRepository.deleteById(restrictionId); + } + + @Transactional + public void deleteAllUserRestrictions(Long userId) { + restrictionRepository.deleteByUserId(userId); + } + + public List applyRestrictions(List books, Long userId) { + List restrictions = restrictionRepository.findByUserId(userId); + + if (restrictions.isEmpty()) { + return books; + } + + Set excludedCategories = getValuesForTypeAndMode(restrictions, ContentRestrictionType.CATEGORY, ContentRestrictionMode.EXCLUDE); + Set excludedTags = getValuesForTypeAndMode(restrictions, ContentRestrictionType.TAG, ContentRestrictionMode.EXCLUDE); + Set excludedMoods = getValuesForTypeAndMode(restrictions, ContentRestrictionType.MOOD, ContentRestrictionMode.EXCLUDE); + Set excludedContentRatings = getValuesForTypeAndMode(restrictions, ContentRestrictionType.CONTENT_RATING, ContentRestrictionMode.EXCLUDE); + + Set allowedCategories = getValuesForTypeAndMode(restrictions, ContentRestrictionType.CATEGORY, ContentRestrictionMode.ALLOW_ONLY); + Set allowedTags = getValuesForTypeAndMode(restrictions, ContentRestrictionType.TAG, ContentRestrictionMode.ALLOW_ONLY); + Set allowedMoods = getValuesForTypeAndMode(restrictions, ContentRestrictionType.MOOD, ContentRestrictionMode.ALLOW_ONLY); + Set allowedContentRatings = getValuesForTypeAndMode(restrictions, ContentRestrictionType.CONTENT_RATING, ContentRestrictionMode.ALLOW_ONLY); + + Integer maxAgeRating = getMaxAgeRating(restrictions); + + return books.stream() + .filter(book -> !hasExcludedContent(book, excludedCategories, excludedTags, excludedMoods, excludedContentRatings)) + .filter(book -> matchesAllowList(book, allowedCategories, allowedTags, allowedMoods, allowedContentRatings)) + .filter(book -> isWithinAgeRating(book, maxAgeRating)) + .collect(Collectors.toList()); + } + + private Set getValuesForTypeAndMode(List restrictions, + ContentRestrictionType type, + ContentRestrictionMode mode) { + return restrictions.stream() + .filter(r -> r.getRestrictionType() == type && r.getMode() == mode) + .map(r -> r.getValue().toLowerCase()) + .collect(Collectors.toSet()); + } + + private Integer getMaxAgeRating(List restrictions) { + return restrictions.stream() + .filter(r -> r.getRestrictionType() == ContentRestrictionType.AGE_RATING) + .filter(r -> r.getMode() == ContentRestrictionMode.EXCLUDE) + .map(r -> { + try { + return Integer.parseInt(r.getValue()); + } catch (NumberFormatException e) { + return null; + } + }) + .filter(Objects::nonNull) + .min(Integer::compareTo) + .orElse(null); + } + + private boolean hasExcludedContent(BookEntity book, + Set excludedCategories, + Set excludedTags, + Set excludedMoods, + Set excludedContentRatings) { + BookMetadataEntity metadata = book.getMetadata(); + if (metadata == null) { + return false; + } + + if (!excludedCategories.isEmpty() && metadata.getCategories() != null) { + boolean hasExcludedCategory = metadata.getCategories().stream() + .anyMatch(c -> excludedCategories.contains(c.getName().toLowerCase())); + if (hasExcludedCategory) { + return true; + } + } + + if (!excludedTags.isEmpty() && metadata.getTags() != null) { + boolean hasExcludedTag = metadata.getTags().stream() + .anyMatch(t -> excludedTags.contains(t.getName().toLowerCase())); + if (hasExcludedTag) { + return true; + } + } + + if (!excludedMoods.isEmpty() && metadata.getMoods() != null) { + boolean hasExcludedMood = metadata.getMoods().stream() + .anyMatch(m -> excludedMoods.contains(m.getName().toLowerCase())); + if (hasExcludedMood) { + return true; + } + } + + if (!excludedContentRatings.isEmpty() && metadata.getContentRating() != null) { + if (excludedContentRatings.contains(metadata.getContentRating().toLowerCase())) { + return true; + } + } + + return false; + } + + private boolean matchesAllowList(BookEntity book, + Set allowedCategories, + Set allowedTags, + Set allowedMoods, + Set allowedContentRatings) { + BookMetadataEntity metadata = book.getMetadata(); + + if (allowedCategories.isEmpty() && allowedTags.isEmpty() && allowedMoods.isEmpty() && allowedContentRatings.isEmpty()) { + return true; + } + + if (metadata == null) { + return false; + } + + if (!allowedCategories.isEmpty()) { + if (metadata.getCategories() == null || metadata.getCategories().isEmpty()) { + return false; + } + boolean hasAllowedCategory = metadata.getCategories().stream() + .anyMatch(c -> allowedCategories.contains(c.getName().toLowerCase())); + if (!hasAllowedCategory) { + return false; + } + } + + if (!allowedTags.isEmpty()) { + if (metadata.getTags() == null || metadata.getTags().isEmpty()) { + return false; + } + boolean hasAllowedTag = metadata.getTags().stream() + .anyMatch(t -> allowedTags.contains(t.getName().toLowerCase())); + if (!hasAllowedTag) { + return false; + } + } + + if (!allowedMoods.isEmpty()) { + if (metadata.getMoods() == null || metadata.getMoods().isEmpty()) { + return false; + } + boolean hasAllowedMood = metadata.getMoods().stream() + .anyMatch(m -> allowedMoods.contains(m.getName().toLowerCase())); + if (!hasAllowedMood) { + return false; + } + } + + if (!allowedContentRatings.isEmpty()) { + if (metadata.getContentRating() == null) { + return false; + } + if (!allowedContentRatings.contains(metadata.getContentRating().toLowerCase())) { + return false; + } + } + + return true; + } + + private boolean isWithinAgeRating(BookEntity book, Integer maxAgeRating) { + if (maxAgeRating == null) { + return true; + } + + BookMetadataEntity metadata = book.getMetadata(); + if (metadata == null || metadata.getAgeRating() == null) { + return true; + } + + return metadata.getAgeRating() < maxAgeRating; + } + + private ContentRestriction toDto(UserContentRestrictionEntity entity) { + return ContentRestriction.builder() + .id(entity.getId()) + .userId(entity.getUser().getId()) + .restrictionType(entity.getRestrictionType()) + .mode(entity.getMode()) + .value(entity.getValue()) + .createdAt(entity.getCreatedAt()) + .build(); + } +} diff --git a/booklore-api/src/main/java/org/booklore/util/MetadataChangeDetector.java b/booklore-api/src/main/java/org/booklore/util/MetadataChangeDetector.java index c2aac11a4..bd6c6ab83 100644 --- a/booklore-api/src/main/java/org/booklore/util/MetadataChangeDetector.java +++ b/booklore-api/src/main/java/org/booklore/util/MetadataChangeDetector.java @@ -203,7 +203,15 @@ public class MetadataChangeDetector { new FieldDescriptor<>("abridged", BookMetadata::getAbridged, BookMetadataEntity::getAbridged, BookMetadata::getAbridgedLocked, BookMetadataEntity::getAbridgedLocked, - MetadataClearFlags::isAbridged, false) + MetadataClearFlags::isAbridged, false), + new FieldDescriptor<>("ageRating", + BookMetadata::getAgeRating, BookMetadataEntity::getAgeRating, + BookMetadata::getAgeRatingLocked, BookMetadataEntity::getAgeRatingLocked, + MetadataClearFlags::isAgeRating, false), + new FieldDescriptor<>("contentRating", + BookMetadata::getContentRating, BookMetadataEntity::getContentRating, + BookMetadata::getContentRatingLocked, BookMetadataEntity::getContentRatingLocked, + MetadataClearFlags::isContentRating, false) ); private static final List COLLECTION_FIELDS = List.of( diff --git a/booklore-api/src/main/resources/db/migration/V110__Add_age_rating_to_book_metadata.sql b/booklore-api/src/main/resources/db/migration/V110__Add_age_rating_to_book_metadata.sql new file mode 100644 index 000000000..ecd02ef5c --- /dev/null +++ b/booklore-api/src/main/resources/db/migration/V110__Add_age_rating_to_book_metadata.sql @@ -0,0 +1,5 @@ +-- Add age rating fields to book_metadata table for content restriction filtering +ALTER TABLE book_metadata ADD COLUMN age_rating INT DEFAULT NULL; +ALTER TABLE book_metadata ADD COLUMN content_rating VARCHAR(20) DEFAULT NULL; +ALTER TABLE book_metadata ADD COLUMN age_rating_locked BOOLEAN NOT NULL DEFAULT FALSE; +ALTER TABLE book_metadata ADD COLUMN content_rating_locked BOOLEAN NOT NULL DEFAULT FALSE; diff --git a/booklore-api/src/main/resources/db/migration/V111__Create_user_content_restriction_table.sql b/booklore-api/src/main/resources/db/migration/V111__Create_user_content_restriction_table.sql new file mode 100644 index 000000000..f6b7ab219 --- /dev/null +++ b/booklore-api/src/main/resources/db/migration/V111__Create_user_content_restriction_table.sql @@ -0,0 +1,13 @@ +-- Create user_content_restriction table for per-user content filtering +CREATE TABLE user_content_restriction ( + id BIGINT AUTO_INCREMENT PRIMARY KEY, + user_id BIGINT NOT NULL, + restriction_type VARCHAR(20) NOT NULL, + mode VARCHAR(15) NOT NULL, + value VARCHAR(255) NOT NULL, + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT fk_ucr_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE, + CONSTRAINT uk_user_restriction UNIQUE (user_id, restriction_type, value) +); + +CREATE INDEX idx_ucr_user_id ON user_content_restriction(user_id); diff --git a/booklore-api/src/test/java/org/booklore/service/KoboEntitlementServiceTest.java b/booklore-api/src/test/java/org/booklore/service/KoboEntitlementServiceTest.java index b9e32ca19..f4d99752b 100644 --- a/booklore-api/src/test/java/org/booklore/service/KoboEntitlementServiceTest.java +++ b/booklore-api/src/test/java/org/booklore/service/KoboEntitlementServiceTest.java @@ -384,8 +384,17 @@ class KoboEntitlementServiceTest { private BookEntity createEpubBookEntity(Long id) { BookEntity book = new BookEntity(); book.setId(id); - book.setBookType(BookFileType.EPUB); - book.setFileSizeKb(1024L); + book.setBookFiles(new java.util.ArrayList<>()); + + BookFileEntity bookFile = BookFileEntity.builder() + .book(book) + .fileName("test-book-" + id + ".epub") + .fileSubPath("") + .isBookFormat(true) + .bookType(BookFileType.EPUB) + .fileSizeKb(1024L) + .build(); + book.getBookFiles().add(bookFile); BookMetadataEntity metadata = new BookMetadataEntity(); metadata.setTitle("Test EPUB Book " + id); diff --git a/booklore-ui/src/app/features/book/components/book-browser/book-browser.component.ts b/booklore-ui/src/app/features/book/components/book-browser/book-browser.component.ts index d6872ca47..8b7a81a3b 100644 --- a/booklore-ui/src/app/features/book/components/book-browser/book-browser.component.ts +++ b/booklore-ui/src/app/features/book/components/book-browser/book-browser.component.ts @@ -26,7 +26,7 @@ import {BookFilterComponent} from './book-filter/book-filter.component'; import {Tooltip} from 'primeng/tooltip'; import {BookFilterMode, EntityViewPreferences, UserService} from '../../../settings/user-management/user.service'; import {SeriesCollapseFilter} from './filters/SeriesCollapseFilter'; -import {SideBarFilter} from './filters/SidebarFilter'; +import {SideBarFilter} from './filters/sidebar-filter'; import {HeaderFilter} from './filters/HeaderFilter'; import {CoverScalePreferenceService} from './cover-scale-preference.service'; import {BookSorter} from './sorting/BookSorter'; diff --git a/booklore-ui/src/app/features/book/components/book-browser/book-filter-orchestration.service.ts b/booklore-ui/src/app/features/book/components/book-browser/book-filter-orchestration.service.ts index b168aec65..5e3f3f6df 100644 --- a/booklore-ui/src/app/features/book/components/book-browser/book-filter-orchestration.service.ts +++ b/booklore-ui/src/app/features/book/components/book-browser/book-filter-orchestration.service.ts @@ -5,7 +5,7 @@ import {BookState} from '../../model/state/book-state.model'; import {SortOption} from '../../model/sort.model'; import {SortService} from '../../service/sort.service'; import {HeaderFilter} from './filters/HeaderFilter'; -import {SideBarFilter} from './filters/SidebarFilter'; +import {SideBarFilter} from './filters/sidebar-filter'; import {SeriesCollapseFilter} from './filters/SeriesCollapseFilter'; import {ParamMap} from '@angular/router'; import {QUERY_PARAMS} from './book-browser-query-params.service'; diff --git a/booklore-ui/src/app/features/book/components/book-browser/book-filter/book-filter.config.ts b/booklore-ui/src/app/features/book/components/book-browser/book-filter/book-filter.config.ts index c2ba95963..b647d72c8 100644 --- a/booklore-ui/src/app/features/book/components/book-browser/book-filter/book-filter.config.ts +++ b/booklore-ui/src/app/features/book/components/book-browser/book-filter/book-filter.config.ts @@ -19,7 +19,8 @@ export type FilterType = | 'author' | 'category' | 'series' | 'bookType' | 'readStatus' | 'personalRating' | 'publisher' | 'matchScore' | 'library' | 'shelf' | 'shelfStatus' | 'tag' | 'publishedDate' | 'fileSize' | 'amazonRating' - | 'goodreadsRating' | 'hardcoverRating' | 'language' | 'pageCount' | 'mood'; + | 'goodreadsRating' | 'hardcoverRating' | 'language' | 'pageCount' | 'mood' + | 'ageRating' | 'contentRating'; export type SortMode = 'count' | 'sortIndex'; @@ -102,6 +103,24 @@ export const MATCH_SCORE_RANGES: readonly RangeConfig[] = [ {id: 6, min: 0.00, max: 0.30, label: 'Poor (0–29%)', sortIndex: 6} ]; +export const AGE_RATING_OPTIONS: readonly RangeConfig[] = [ + {id: 0, min: 0, max: 1, label: 'All Ages', sortIndex: 0}, + {id: 6, min: 6, max: 7, label: '6+', sortIndex: 1}, + {id: 10, min: 10, max: 11, label: '10+', sortIndex: 2}, + {id: 13, min: 13, max: 14, label: '13+', sortIndex: 3}, + {id: 16, min: 16, max: 17, label: '16+', sortIndex: 4}, + {id: 18, min: 18, max: 19, label: '18+', sortIndex: 5}, + {id: 21, min: 21, max: 22, label: '21+', sortIndex: 6} +]; + +export const CONTENT_RATING_LABELS: Readonly> = { + 'EVERYONE': 'Everyone', + 'TEEN': 'Teen', + 'MATURE': 'Mature', + 'ADULT': 'Adult', + 'EXPLICIT': 'Explicit' +}; + export const readStatusLabels = READ_STATUS_LABELS; export const ratingRanges = RATING_RANGES_5; export const ratingOptions10 = RATING_OPTIONS_10; @@ -111,7 +130,8 @@ export const matchScoreRanges = MATCH_SCORE_RANGES; export const NUMERIC_ID_FILTER_TYPES = new Set([ 'personalRating', 'matchScore', 'fileSize', 'amazonRating', - 'goodreadsRating', 'hardcoverRating', 'pageCount', 'library', 'shelf' + 'goodreadsRating', 'hardcoverRating', 'pageCount', 'library', 'shelf', + 'ageRating' ]); export const FILTER_LABELS: Readonly> = { @@ -134,7 +154,9 @@ export const FILTER_LABELS: Readonly> = { hardcoverRating: 'Hardcover Rating', language: 'Language', pageCount: 'Page Count', - mood: 'Mood' + mood: 'Mood', + ageRating: 'Age Rating', + contentRating: 'Content Rating' }; // ============================================================================ @@ -164,6 +186,12 @@ const extractStringsAsFilters = (values: string[] | undefined): FilterValue[] => const extractSingleString = (value: string | undefined | null): FilterValue[] => value ? [{id: value, name: value}] : []; +const findExactAgeRating = (ageRating: number | null | undefined): FilterValue[] => { + if (ageRating == null) return []; + const match = AGE_RATING_OPTIONS.find(r => r.id === ageRating); + return match ? [{id: match.id, name: match.label, sortIndex: match.sortIndex}] : []; +}; + export const FILTER_EXTRACTORS: Readonly, (book: Book) => FilterValue[]>> = { author: (book) => extractStringsAsFilters(book.metadata?.authors), category: (book) => extractStringsAsFilters(book.metadata?.categories), @@ -195,7 +223,14 @@ export const FILTER_EXTRACTORS: Readonly, hardcoverRating: (book) => findInRange(book.metadata?.hardcoverRating, RATING_RANGES_5), language: (book) => extractSingleString(book.metadata?.language), pageCount: (book) => findInRange(book.metadata?.pageCount, PAGE_COUNT_RANGES), - mood: (book) => extractStringsAsFilters(book.metadata?.moods) + mood: (book) => extractStringsAsFilters(book.metadata?.moods), + ageRating: (book) => findExactAgeRating(book.metadata?.ageRating), + contentRating: (book) => { + const rating = book.metadata?.contentRating; + if (!rating) return []; + const label = CONTENT_RATING_LABELS[rating] ?? rating; + return [{id: rating, name: label}]; + } }; export const FILTER_CONFIGS: Readonly, Omit>> = { @@ -217,5 +252,7 @@ export const FILTER_CONFIGS: Readonly, Omi hardcoverRating: {label: 'Hardcover Rating', sortMode: 'sortIndex', isNumericId: true}, language: {label: 'Language', sortMode: 'count'}, pageCount: {label: 'Page Count', sortMode: 'sortIndex', isNumericId: true}, - mood: {label: 'Mood', sortMode: 'count'} + mood: {label: 'Mood', sortMode: 'count'}, + ageRating: {label: 'Age Rating', sortMode: 'sortIndex', isNumericId: true}, + contentRating: {label: 'Content Rating', sortMode: 'count'} }; diff --git a/booklore-ui/src/app/features/book/components/book-browser/filters/sidebar-filter.ts b/booklore-ui/src/app/features/book/components/book-browser/filters/sidebar-filter.ts new file mode 100644 index 000000000..d44687c21 --- /dev/null +++ b/booklore-ui/src/app/features/book/components/book-browser/filters/sidebar-filter.ts @@ -0,0 +1,149 @@ +import {combineLatest, Observable} from 'rxjs'; +import {map} from 'rxjs/operators'; +import {BookFilter} from './BookFilter'; +import {BookState} from '../../../model/state/book-state.model'; +import {AGE_RATING_OPTIONS, fileSizeRanges, matchScoreRanges, pageCountRanges, ratingRanges, RangeConfig} from '../book-filter/book-filter.config'; +import {Book, ReadStatus} from '../../../model/book.model'; +import {BookFilterMode} from '../../../../settings/user-management/user.service'; + +export function isRatingInRange(rating: number | undefined | null, rangeId: string | number): boolean { + if (rating == null) return false; + const numericId = typeof rangeId === 'string' ? Number(rangeId) : rangeId; + const range = ratingRanges.find(r => r.id === numericId); + if (!range) return false; + return rating >= range.min && rating < range.max; +} + +export function isRatingInRange10(rating: number | undefined | null, rangeId: string | number): boolean { + if (rating == null) return false; + const numericId = typeof rangeId === 'string' ? Number(rangeId) : rangeId; + return Math.round(rating) === numericId; +} + +export function isFileSizeInRange(fileSizeKb: number | undefined, rangeId: string | number): boolean { + if (fileSizeKb == null) return false; + const numericId = typeof rangeId === 'string' ? Number(rangeId) : rangeId; + const range = fileSizeRanges.find(r => r.id === numericId); + if (!range) return false; + return fileSizeKb >= range.min && fileSizeKb < range.max; +} + +export function isPageCountInRange(pageCount: number | undefined, rangeId: string | number): boolean { + if (pageCount == null) return false; + const numericId = typeof rangeId === 'string' ? Number(rangeId) : rangeId; + const range = pageCountRanges.find(r => r.id === numericId); + if (!range) return false; + return pageCount >= range.min && pageCount < range.max; +} + +export function isMatchScoreInRange(score: number | undefined | null, rangeId: string | number): boolean { + if (score == null) return false; + const normalizedScore = score > 1 ? score / 100 : score; + const numericId = typeof rangeId === 'string' ? Number(rangeId) : rangeId; + const range = matchScoreRanges.find(r => r.id === numericId); + if (!range) return false; + return normalizedScore >= range.min && normalizedScore < range.max; +} + +export function doesBookMatchReadStatus(book: Book, selected: string[]): boolean { + const status = book.readStatus ?? ReadStatus.UNSET; + return selected.includes(status); +} + +export function isAgeRatingMatch(ageRating: number | undefined | null, rangeId: string | number): boolean { + if (ageRating == null) return false; + const numericId = typeof rangeId === 'string' ? Number(rangeId) : rangeId; + return ageRating === numericId; +} + +export class SideBarFilter implements BookFilter { + + constructor(private selectedFilter$: Observable, private selectedFilterMode$: Observable) { + } + + filter(bookState: BookState): Observable { + return combineLatest([this.selectedFilter$, this.selectedFilterMode$]).pipe( + map(([activeFilters, mode]) => { + if (bookState.books == null) return bookState; + if (!activeFilters) return bookState; + const filteredBooks = (bookState.books || []).filter(book => { + const matches = Object.entries(activeFilters).map(([filterType, filterValues]) => { + if (!Array.isArray(filterValues) || filterValues.length === 0) { + return mode === 'or'; + } + switch (filterType) { + case 'author': + return mode === 'or' + ? filterValues.some(val => book.metadata?.authors?.includes(val)) + : filterValues.every(val => book.metadata?.authors?.includes(val)); + case 'category': + return mode === 'or' + ? filterValues.some(val => book.metadata?.categories?.includes(val)) + : filterValues.every(val => book.metadata?.categories?.includes(val)); + case 'series': + return mode === 'or' + ? filterValues.some(val => book.metadata?.seriesName === val) + : filterValues.every(val => book.metadata?.seriesName === val); + case 'bookType': + return filterValues.includes(book.primaryFile?.bookType); + case 'readStatus': + return doesBookMatchReadStatus(book, filterValues); + case 'personalRating': + return filterValues.some(range => isRatingInRange10(book.personalRating, range)); + case 'publisher': + return mode === 'or' + ? filterValues.some(val => book.metadata?.publisher === val) + : filterValues.every(val => book.metadata?.publisher === val); + case 'matchScore': + return filterValues.some(range => isMatchScoreInRange(book.metadataMatchScore, range)); + case 'library': + return mode === 'or' + ? filterValues.some(val => val == book.libraryId) + : filterValues.every(val => val == book.libraryId); + case 'shelf': + return mode === 'or' + ? filterValues.some(val => book.shelves?.some(s => s.id == val)) + : filterValues.every(val => book.shelves?.some(s => s.id == val)); + case 'shelfStatus': + const shelved = book.shelves && book.shelves.length > 0 ? 'shelved' : 'unshelved'; + return filterValues.includes(shelved); + case 'tag': + return mode === 'or' + ? filterValues.some(val => book.metadata?.tags?.includes(val)) + : filterValues.every(val => book.metadata?.tags?.includes(val)); + case 'publishedDate': + const bookYear = book.metadata?.publishedDate + ? new Date(book.metadata.publishedDate).getFullYear() + : null; + return bookYear ? filterValues.some(val => val == bookYear || val == bookYear.toString()) : false; + case 'fileSize': + return filterValues.some(range => isFileSizeInRange(book.fileSizeKb, range)); + case 'amazonRating': + return filterValues.some(range => isRatingInRange(book.metadata?.amazonRating, range)); + case 'goodreadsRating': + return filterValues.some(range => isRatingInRange(book.metadata?.goodreadsRating, range)); + case 'hardcoverRating': + return filterValues.some(range => isRatingInRange(book.metadata?.hardcoverRating, range)); + case 'language': + return filterValues.includes(book.metadata?.language); + case 'pageCount': + return filterValues.some(range => isPageCountInRange(book.metadata?.pageCount!, range)); + case 'mood': + return mode === 'or' + ? filterValues.some(val => book.metadata?.moods?.includes(val)) + : filterValues.every(val => book.metadata?.moods?.includes(val)); + case 'ageRating': + return filterValues.some(val => isAgeRatingMatch(book.metadata?.ageRating, val)); + case 'contentRating': + return filterValues.includes(book.metadata?.contentRating); + default: + return false; + } + }); + return mode === 'or' ? matches.some(m => m) : matches.every(m => m); + }); + return {...bookState, books: filteredBooks}; + }) + ); + } +} diff --git a/booklore-ui/src/app/features/book/model/book.model.ts b/booklore-ui/src/app/features/book/model/book.model.ts index 580c62b45..364563797 100644 --- a/booklore-ui/src/app/features/book/model/book.model.ts +++ b/booklore-ui/src/app/features/book/model/book.model.ts @@ -199,6 +199,10 @@ export interface BookMetadata { coverLocked?: boolean; audiobookCoverLocked?: boolean; reviewsLocked?: boolean; + ageRating?: number | null; + contentRating?: string | null; + ageRatingLocked?: boolean; + contentRatingLocked?: boolean; [key: string]: unknown; } @@ -243,6 +247,8 @@ export interface MetadataClearFlags { tags?: boolean; cover?: boolean; audiobookCover?: boolean; + ageRating?: boolean; + contentRating?: boolean; } export interface MetadataUpdateWrapper { @@ -327,6 +333,10 @@ export interface BulkMetadataUpdateRequest { mergeCategories?: boolean; mergeMoods?: boolean; mergeTags?: boolean; + ageRating?: number | null; + clearAgeRating?: boolean; + contentRating?: string | null; + clearContentRating?: boolean; } export interface BookDeletionResponse { diff --git a/booklore-ui/src/app/features/book/service/book-menu.service.ts b/booklore-ui/src/app/features/book/service/book-menu.service.ts index ef2ef567d..b8318b5e4 100644 --- a/booklore-ui/src/app/features/book/service/book-menu.service.ts +++ b/booklore-ui/src/app/features/book/service/book-menu.service.ts @@ -1,7 +1,7 @@ import {inject, Injectable} from '@angular/core'; import {ConfirmationService, MenuItem, MessageService} from 'primeng/api'; import {BookService} from './book.service'; -import {readStatusLabels} from '../components/book-browser/book-filter/book-filter.config'; +import {AGE_RATING_OPTIONS, CONTENT_RATING_LABELS, readStatusLabels} from '../components/book-browser/book-filter/book-filter.config'; import {ReadStatus} from '../model/book.model'; import {ResetProgressTypes} from '../../../shared/constants/reset-progress-type'; import {finalize} from 'rxjs'; @@ -134,6 +134,182 @@ export class BookMenuService { }); } + if (permissions?.canBulkEditMetadata) { + items.push({ + label: 'Set Age Rating', + icon: 'pi pi-user', + items: [ + ...AGE_RATING_OPTIONS.map(option => ({ + label: option.label, + command: () => { + this.confirmationService.confirm({ + message: `Are you sure you want to set the age rating to "${option.label}" for ${count} book(s)?`, + header: 'Confirm Age Rating Update', + icon: 'pi pi-exclamation-triangle', + acceptLabel: 'Yes', + rejectLabel: 'No', + accept: () => { + const loader = this.loadingService.show(`Setting age rating for ${count} book(s)...`); + this.bookService.updateBooksMetadata({ + bookIds: Array.from(selectedBooks), + ageRating: option.id + }).pipe(finalize(() => this.loadingService.hide(loader))) + .subscribe({ + next: () => { + this.messageService.add({ + severity: 'success', + summary: 'Age Rating Updated', + detail: `Set to "${option.label}"`, + life: 2000 + }); + }, + error: (err: HttpErrorResponse) => { + const apiError = err.error as APIException; + this.messageService.add({ + severity: 'error', + summary: 'Update Failed', + detail: apiError?.message || 'Could not update age rating.', + life: 3000 + }); + } + }); + } + }); + } + })), + { + separator: true + }, + { + label: 'Clear Age Rating', + icon: 'pi pi-times', + command: () => { + this.confirmationService.confirm({ + message: `Are you sure you want to clear the age rating for ${count} book(s)?`, + header: 'Confirm Clear Age Rating', + icon: 'pi pi-exclamation-triangle', + acceptLabel: 'Yes', + rejectLabel: 'No', + accept: () => { + const loader = this.loadingService.show(`Clearing age rating for ${count} book(s)...`); + this.bookService.updateBooksMetadata({ + bookIds: Array.from(selectedBooks), + clearAgeRating: true + }).pipe(finalize(() => this.loadingService.hide(loader))) + .subscribe({ + next: () => { + this.messageService.add({ + severity: 'success', + summary: 'Age Rating Cleared', + detail: 'Age rating has been cleared.', + life: 2000 + }); + }, + error: (err: HttpErrorResponse) => { + const apiError = err.error as APIException; + this.messageService.add({ + severity: 'error', + summary: 'Update Failed', + detail: apiError?.message || 'Could not clear age rating.', + life: 3000 + }); + } + }); + } + }); + } + } + ] + }); + + items.push({ + label: 'Set Content Rating', + icon: 'pi pi-shield', + items: [ + ...Object.entries(CONTENT_RATING_LABELS).map(([value, label]) => ({ + label: label, + command: () => { + this.confirmationService.confirm({ + message: `Are you sure you want to set the content rating to "${label}" for ${count} book(s)?`, + header: 'Confirm Content Rating Update', + icon: 'pi pi-exclamation-triangle', + acceptLabel: 'Yes', + rejectLabel: 'No', + accept: () => { + const loader = this.loadingService.show(`Setting content rating for ${count} book(s)...`); + this.bookService.updateBooksMetadata({ + bookIds: Array.from(selectedBooks), + contentRating: value + }).pipe(finalize(() => this.loadingService.hide(loader))) + .subscribe({ + next: () => { + this.messageService.add({ + severity: 'success', + summary: 'Content Rating Updated', + detail: `Set to "${label}"`, + life: 2000 + }); + }, + error: (err: HttpErrorResponse) => { + const apiError = err.error as APIException; + this.messageService.add({ + severity: 'error', + summary: 'Update Failed', + detail: apiError?.message || 'Could not update content rating.', + life: 3000 + }); + } + }); + } + }); + } + })), + { + separator: true + }, + { + label: 'Clear Content Rating', + icon: 'pi pi-times', + command: () => { + this.confirmationService.confirm({ + message: `Are you sure you want to clear the content rating for ${count} book(s)?`, + header: 'Confirm Clear Content Rating', + icon: 'pi pi-exclamation-triangle', + acceptLabel: 'Yes', + rejectLabel: 'No', + accept: () => { + const loader = this.loadingService.show(`Clearing content rating for ${count} book(s)...`); + this.bookService.updateBooksMetadata({ + bookIds: Array.from(selectedBooks), + clearContentRating: true + }).pipe(finalize(() => this.loadingService.hide(loader))) + .subscribe({ + next: () => { + this.messageService.add({ + severity: 'success', + summary: 'Content Rating Cleared', + detail: 'Content rating has been cleared.', + life: 2000 + }); + }, + error: (err: HttpErrorResponse) => { + const apiError = err.error as APIException; + this.messageService.add({ + severity: 'error', + summary: 'Update Failed', + detail: apiError?.message || 'Could not clear content rating.', + life: 3000 + }); + } + }); + } + }); + } + } + ] + }); + } + // Shelf Actions if (permissions?.canManageLibrary || permissions?.admin) { // Assuming these permissions cover shelf management for books items.push({ diff --git a/booklore-ui/src/app/features/metadata/component/book-metadata-center/metadata-editor/metadata-editor.component.html b/booklore-ui/src/app/features/metadata/component/book-metadata-center/metadata-editor/metadata-editor.component.html index 7db5987f8..6bada4a1a 100644 --- a/booklore-ui/src/app/features/metadata/component/book-metadata-center/metadata-editor/metadata-editor.component.html +++ b/booklore-ui/src/app/features/metadata/component/book-metadata-center/metadata-editor/metadata-editor.component.html @@ -419,6 +419,50 @@ } + +
+ +
+ + + @if (!book.metadata!['ageRatingLocked']) { + + } + @if (book.metadata!['ageRatingLocked']) { + + } +
+
+ +
+ +
+ + + @if (!book.metadata!['contentRatingLocked']) { + + } + @if (book.metadata!['contentRatingLocked']) { + + } +
+
diff --git a/booklore-ui/src/app/features/metadata/component/book-metadata-center/metadata-editor/metadata-editor.component.ts b/booklore-ui/src/app/features/metadata/component/book-metadata-center/metadata-editor/metadata-editor.component.ts index 6783867de..02d2ee922 100644 --- a/booklore-ui/src/app/features/metadata/component/book-metadata-center/metadata-editor/metadata-editor.component.ts +++ b/booklore-ui/src/app/features/metadata/component/book-metadata-center/metadata-editor/metadata-editor.component.ts @@ -21,6 +21,7 @@ import {DatePicker} from "primeng/datepicker"; import {Textarea} from "primeng/textarea"; import {Image} from "primeng/image"; import {LazyLoadImageModule} from "ng-lazyload-image"; +import {Select} from "primeng/select"; import {TaskHelperService} from '../../../../settings/task-management/task-helper.service'; import {BookDialogHelperService} from "../../../../book/components/book-browser/book-dialog-helper.service"; import {BookNavigationService} from '../../../../book/service/book-navigation.service'; @@ -50,6 +51,7 @@ import {MetadataProviderSpecificFields} from '../../../../../shared/model/app-se Textarea, Image, LazyLoadImageModule, + Select, ], }) export class MetadataEditorComponent implements OnInit { @@ -102,6 +104,9 @@ export class MetadataEditorComponent implements OnInit { filteredSeries: string[] = []; private metadataCenterViewMode: 'route' | 'dialog' = 'route'; + contentRatingOptions: {label: string, value: string}[] = []; + ageRatingOptions: {label: string, value: number}[] = []; + providerSpecificFields: MetadataProviderSpecificFields = { asin: true, amazonRating: true, @@ -246,7 +251,29 @@ export class MetadataEditorComponent implements OnInit { coverLocked: new FormControl(false), audiobookCoverLocked: new FormControl(false), reviewsLocked: new FormControl(false), + ageRating: new FormControl(""), + contentRating: new FormControl(""), + ageRatingLocked: new FormControl(false), + contentRatingLocked: new FormControl(false), }); + + this.contentRatingOptions = [ + {label: 'Everyone', value: 'EVERYONE'}, + {label: 'Teen', value: 'TEEN'}, + {label: 'Mature', value: 'MATURE'}, + {label: 'Adult', value: 'ADULT'}, + {label: 'Explicit', value: 'EXPLICIT'} + ]; + + this.ageRatingOptions = [ + {label: 'All Ages', value: 0}, + {label: '6+', value: 6}, + {label: '10+', value: 10}, + {label: '13+', value: 13}, + {label: '16+', value: 16}, + {label: '18+', value: 18}, + {label: '21+', value: 21} + ]; } ngOnInit(): void { @@ -401,6 +428,10 @@ export class MetadataEditorComponent implements OnInit { coverLocked: metadata.coverLocked ?? false, audiobookCoverLocked: metadata.audiobookCoverLocked ?? false, reviewsLocked: metadata.reviewsLocked ?? false, + ageRating: metadata.ageRating ?? null, + contentRating: metadata.contentRating ?? null, + ageRatingLocked: metadata.ageRatingLocked ?? false, + contentRatingLocked: metadata.contentRatingLocked ?? false, }); const lockableFields: { key: keyof BookMetadata; control: string }[] = [ @@ -443,6 +474,8 @@ export class MetadataEditorComponent implements OnInit { {key: "coverLocked", control: "thumbnailUrl"}, {key: "audiobookCoverLocked", control: "audiobookCover"}, {key: "reviewsLocked", control: "reviews"}, + {key: "ageRatingLocked", control: "ageRating"}, + {key: "contentRatingLocked", control: "contentRating"}, ]; for (const {key, control} of lockableFields) { @@ -634,6 +667,10 @@ export class MetadataEditorComponent implements OnInit { coverLocked: form.get("coverLocked")?.value, audiobookCoverLocked: form.get("audiobookCoverLocked")?.value, reviewsLocked: form.get("reviewsLocked")?.value, + ageRating: form.get("ageRating")?.value, + contentRating: form.get("contentRating")?.value, + ageRatingLocked: form.get("ageRatingLocked")?.value, + contentRatingLocked: form.get("contentRatingLocked")?.value, ...(shouldLockAllFields !== undefined && { allFieldsLocked: shouldLockAllFields, @@ -690,6 +727,8 @@ export class MetadataEditorComponent implements OnInit { seriesTotal: wasCleared("seriesTotal"), audiobookCover: wasCleared("audiobookCover"), cover: false, + ageRating: wasCleared("ageRating"), + contentRating: wasCleared("contentRating"), }; return {metadata, clearFlags}; diff --git a/booklore-ui/src/app/features/metadata/component/book-metadata-center/metadata-viewer/metadata-viewer.component.html b/booklore-ui/src/app/features/metadata/component/book-metadata-center/metadata-viewer/metadata-viewer.component.html index 9c342ae95..eca98457c 100644 --- a/booklore-ui/src/app/features/metadata/component/book-metadata-center/metadata-viewer/metadata-viewer.component.html +++ b/booklore-ui/src/app/features/metadata/component/book-metadata-center/metadata-viewer/metadata-viewer.component.html @@ -524,6 +524,28 @@ } + + + + @if (hasDigitalFile(book)) { + +
+

+ + Content Restrictions +

+

+ Configure which content this user can see based on categories, tags, moods, or age ratings. +

+ + +
} diff --git a/booklore-ui/src/app/features/settings/user-management/user-management.component.scss b/booklore-ui/src/app/features/settings/user-management/user-management.component.scss index 399038d22..80888f83a 100644 --- a/booklore-ui/src/app/features/settings/user-management/user-management.component.scss +++ b/booklore-ui/src/app/features/settings/user-management/user-management.component.scss @@ -347,6 +347,34 @@ gap: 1rem; } +.content-restrictions-section { + display: flex; + flex-direction: column; + gap: 0.75rem; + margin-top: 0.5rem; + padding-top: 1rem; + border-top: 1px solid var(--p-content-border-color); + + .section-description { + font-size: settings.$settings-description-size; + color: var(--p-text-muted-color); + margin: 0 0 0.5rem 0; + padding-left: 1.5rem; + + @media (max-width: 600px) { + padding-left: 0; + } + } + + app-content-restrictions-editor { + padding-left: 1.5rem; + + @media (max-width: 600px) { + padding-left: 0; + } + } +} + .details-title { display: flex; align-items: center; diff --git a/booklore-ui/src/app/features/settings/user-management/user-management.component.ts b/booklore-ui/src/app/features/settings/user-management/user-management.component.ts index 5342065e8..b374ee62f 100644 --- a/booklore-ui/src/app/features/settings/user-management/user-management.component.ts +++ b/booklore-ui/src/app/features/settings/user-management/user-management.component.ts @@ -17,6 +17,7 @@ import {filter, take, takeUntil} from 'rxjs/operators'; import {Subject} from 'rxjs'; import {Tooltip} from 'primeng/tooltip'; import {DialogLauncherService} from '../../../shared/services/dialog-launcher.service'; +import {ContentRestrictionsEditorComponent} from './content-restrictions-editor/content-restrictions-editor.component'; interface UserWithEditing extends User { isEditing?: boolean; @@ -37,7 +38,8 @@ interface UserWithEditing extends User { InputText, LowerCasePipe, TitleCasePipe, - Tooltip + Tooltip, + ContentRestrictionsEditorComponent ], templateUrl: './user-management.component.html', styleUrls: ['./user-management.component.scss'],