feat(content-restrictions): add age rating and content rating support (#2619)
This commit is contained in:
+10
-2
@@ -6,6 +6,7 @@ import org.booklore.exception.ApiError;
|
|||||||
import org.booklore.model.dto.BookLoreUser;
|
import org.booklore.model.dto.BookLoreUser;
|
||||||
import org.booklore.model.entity.BookEntity;
|
import org.booklore.model.entity.BookEntity;
|
||||||
import org.booklore.repository.BookRepository;
|
import org.booklore.repository.BookRepository;
|
||||||
|
import org.booklore.service.restriction.ContentRestrictionService;
|
||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
import org.aspectj.lang.JoinPoint;
|
import org.aspectj.lang.JoinPoint;
|
||||||
import org.aspectj.lang.annotation.Aspect;
|
import org.aspectj.lang.annotation.Aspect;
|
||||||
@@ -14,6 +15,7 @@ import org.aspectj.lang.reflect.MethodSignature;
|
|||||||
import org.springframework.stereotype.Component;
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
import java.lang.reflect.Method;
|
import java.lang.reflect.Method;
|
||||||
|
import java.util.List;
|
||||||
import java.util.Objects;
|
import java.util.Objects;
|
||||||
import java.util.regex.Pattern;
|
import java.util.regex.Pattern;
|
||||||
|
|
||||||
@@ -25,6 +27,7 @@ public class BookAccessAspect {
|
|||||||
private static final Pattern NUMERIC_PATTERN = Pattern.compile("\\d+");
|
private static final Pattern NUMERIC_PATTERN = Pattern.compile("\\d+");
|
||||||
private final AuthenticationService authenticationService;
|
private final AuthenticationService authenticationService;
|
||||||
private final BookRepository bookRepository;
|
private final BookRepository bookRepository;
|
||||||
|
private final ContentRestrictionService contentRestrictionService;
|
||||||
|
|
||||||
@Before("@annotation(org.booklore.config.security.annotation.CheckBookAccess)")
|
@Before("@annotation(org.booklore.config.security.annotation.CheckBookAccess)")
|
||||||
public void checkBookAccess(JoinPoint joinPoint) {
|
public void checkBookAccess(JoinPoint joinPoint) {
|
||||||
@@ -49,9 +52,14 @@ public class BookAccessAspect {
|
|||||||
return;
|
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<BookEntity> filteredBooks = contentRestrictionService.applyRestrictions(List.of(bookEntity), user.getId());
|
||||||
|
if (filteredBooks.isEmpty()) {
|
||||||
throw ApiError.FORBIDDEN.createException("You are not authorized to access this book.");
|
throw ApiError.FORBIDDEN.createException("You are not authorized to access this book.");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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<List<ContentRestriction>> 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<ContentRestriction> 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<List<ContentRestriction>> updateRestrictions(
|
||||||
|
@Parameter(description = "ID of the user") @PathVariable Long userId,
|
||||||
|
@Parameter(description = "List of content restrictions") @RequestBody @Valid List<ContentRestriction> 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<Void> 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<Void> deleteAllRestrictions(
|
||||||
|
@Parameter(description = "ID of the user") @PathVariable Long userId) {
|
||||||
|
contentRestrictionService.deleteAllUserRestrictions(userId);
|
||||||
|
return ResponseEntity.noContent().build();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -18,5 +18,7 @@ public interface MetadataClearFlagsMapper {
|
|||||||
@Mapping(target = "categories", source = "clearGenres")
|
@Mapping(target = "categories", source = "clearGenres")
|
||||||
@Mapping(target = "moods", source = "clearMoods")
|
@Mapping(target = "moods", source = "clearMoods")
|
||||||
@Mapping(target = "tags", source = "clearTags")
|
@Mapping(target = "tags", source = "clearTags")
|
||||||
|
@Mapping(target = "ageRating", source = "clearAgeRating")
|
||||||
|
@Mapping(target = "contentRating", source = "clearContentRating")
|
||||||
MetadataClearFlags toClearFlags(BulkMetadataUpdateRequest request);
|
MetadataClearFlags toClearFlags(BulkMetadataUpdateRequest request);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -42,4 +42,6 @@ public class MetadataClearFlags {
|
|||||||
private boolean reviews;
|
private boolean reviews;
|
||||||
private boolean narrator;
|
private boolean narrator;
|
||||||
private boolean abridged;
|
private boolean abridged;
|
||||||
|
private boolean ageRating;
|
||||||
|
private boolean contentRating;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -112,4 +112,9 @@ public class BookMetadata {
|
|||||||
private Boolean reviewsLocked;
|
private Boolean reviewsLocked;
|
||||||
private Boolean narratorLocked;
|
private Boolean narratorLocked;
|
||||||
private Boolean abridgedLocked;
|
private Boolean abridgedLocked;
|
||||||
|
|
||||||
|
private Integer ageRating;
|
||||||
|
private String contentRating;
|
||||||
|
private Boolean ageRatingLocked;
|
||||||
|
private Boolean contentRatingLocked;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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;
|
||||||
|
}
|
||||||
@@ -66,6 +66,10 @@ public enum RuleField {
|
|||||||
@JsonProperty("tags")
|
@JsonProperty("tags")
|
||||||
TAGS,
|
TAGS,
|
||||||
@JsonProperty("genre")
|
@JsonProperty("genre")
|
||||||
GENRE
|
GENRE,
|
||||||
|
@JsonProperty("ageRating")
|
||||||
|
AGE_RATING,
|
||||||
|
@JsonProperty("contentRating")
|
||||||
|
CONTENT_RATING
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+6
@@ -39,4 +39,10 @@ public class BulkMetadataUpdateRequest {
|
|||||||
private boolean mergeCategories;
|
private boolean mergeCategories;
|
||||||
private boolean mergeMoods;
|
private boolean mergeMoods;
|
||||||
private boolean mergeTags;
|
private boolean mergeTags;
|
||||||
|
|
||||||
|
private Integer ageRating;
|
||||||
|
private boolean clearAgeRating;
|
||||||
|
|
||||||
|
private String contentRating;
|
||||||
|
private boolean clearContentRating;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -70,6 +70,10 @@ public class BookLoreUserEntity {
|
|||||||
@Builder.Default
|
@Builder.Default
|
||||||
private Set<ReadingSessionEntity> readingSessions = new HashSet<>();
|
private Set<ReadingSessionEntity> readingSessions = new HashSet<>();
|
||||||
|
|
||||||
|
@OneToMany(mappedBy = "user", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY)
|
||||||
|
@Builder.Default
|
||||||
|
private Set<UserContentRestrictionEntity> contentRestrictions = new HashSet<>();
|
||||||
|
|
||||||
@PrePersist
|
@PrePersist
|
||||||
public void prePersist() {
|
public void prePersist() {
|
||||||
this.createdAt = LocalDateTime.now();
|
this.createdAt = LocalDateTime.now();
|
||||||
|
|||||||
@@ -305,6 +305,20 @@ public class BookMetadataEntity {
|
|||||||
@Column(name = "search_text", columnDefinition = "TEXT")
|
@Column(name = "search_text", columnDefinition = "TEXT")
|
||||||
private String searchText;
|
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
|
@PrePersist
|
||||||
@PreUpdate
|
@PreUpdate
|
||||||
public void updateSearchText() {
|
public void updateSearchText() {
|
||||||
@@ -398,6 +412,8 @@ public class BookMetadataEntity {
|
|||||||
this.reviewsLocked = lock;
|
this.reviewsLocked = lock;
|
||||||
this.narratorLocked = lock;
|
this.narratorLocked = lock;
|
||||||
this.abridgedLocked = lock;
|
this.abridgedLocked = lock;
|
||||||
|
this.ageRatingLocked = lock;
|
||||||
|
this.contentRatingLocked = lock;
|
||||||
}
|
}
|
||||||
|
|
||||||
public boolean areAllFieldsLocked() {
|
public boolean areAllFieldsLocked() {
|
||||||
@@ -441,6 +457,8 @@ public class BookMetadataEntity {
|
|||||||
&& Boolean.TRUE.equals(this.reviewsLocked)
|
&& Boolean.TRUE.equals(this.reviewsLocked)
|
||||||
&& Boolean.TRUE.equals(this.narratorLocked)
|
&& Boolean.TRUE.equals(this.narratorLocked)
|
||||||
&& Boolean.TRUE.equals(this.abridgedLocked)
|
&& Boolean.TRUE.equals(this.abridgedLocked)
|
||||||
|
&& Boolean.TRUE.equals(this.ageRatingLocked)
|
||||||
|
&& Boolean.TRUE.equals(this.contentRatingLocked)
|
||||||
;
|
;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+46
@@ -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();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
package org.booklore.model.enums;
|
||||||
|
|
||||||
|
public enum ContentRating {
|
||||||
|
EVERYONE,
|
||||||
|
TEEN,
|
||||||
|
MATURE,
|
||||||
|
ADULT,
|
||||||
|
EXPLICIT
|
||||||
|
}
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
package org.booklore.model.enums;
|
||||||
|
|
||||||
|
public enum ContentRestrictionMode {
|
||||||
|
EXCLUDE,
|
||||||
|
ALLOW_ONLY
|
||||||
|
}
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
package org.booklore.model.enums;
|
||||||
|
|
||||||
|
public enum ContentRestrictionType {
|
||||||
|
CATEGORY,
|
||||||
|
TAG,
|
||||||
|
MOOD,
|
||||||
|
AGE_RATING,
|
||||||
|
CONTENT_RATING
|
||||||
|
}
|
||||||
+35
@@ -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<UserContentRestrictionEntity, Long> {
|
||||||
|
|
||||||
|
List<UserContentRestrictionEntity> findByUserId(Long userId);
|
||||||
|
|
||||||
|
List<UserContentRestrictionEntity> findByUserIdAndRestrictionType(Long userId, ContentRestrictionType type);
|
||||||
|
|
||||||
|
List<UserContentRestrictionEntity> findByUserIdAndMode(Long userId, ContentRestrictionMode mode);
|
||||||
|
|
||||||
|
Optional<UserContentRestrictionEntity> 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<UserContentRestrictionEntity> findByUserIdAndTypeAndMode(
|
||||||
|
@Param("userId") Long userId,
|
||||||
|
@Param("type") ContentRestrictionType type,
|
||||||
|
@Param("mode") ContentRestrictionMode mode);
|
||||||
|
|
||||||
|
boolean existsByUserIdAndRestrictionTypeAndValue(Long userId, ContentRestrictionType type, String value);
|
||||||
|
}
|
||||||
@@ -338,6 +338,8 @@ public class BookRuleEvaluatorService {
|
|||||||
case HARDCOVER_RATING -> root.get("metadata").get("hardcoverRating");
|
case HARDCOVER_RATING -> root.get("metadata").get("hardcoverRating");
|
||||||
case HARDCOVER_REVIEW_COUNT -> root.get("metadata").get("hardcoverReviewCount");
|
case HARDCOVER_REVIEW_COUNT -> root.get("metadata").get("hardcoverReviewCount");
|
||||||
case RANOBEDB_RATING -> root.get("metadata").get("ranobedbRating");
|
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,
|
case FILE_TYPE -> cb.function("SUBSTRING_INDEX", String.class,
|
||||||
root.get("fileName"), cb.literal("."), cb.literal(-1));
|
root.get("fileName"), cb.literal("."), cb.literal(-1));
|
||||||
default -> null;
|
default -> null;
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import org.booklore.mapper.v2.BookMapperV2;
|
|||||||
import org.booklore.model.dto.Book;
|
import org.booklore.model.dto.Book;
|
||||||
import org.booklore.model.entity.BookEntity;
|
import org.booklore.model.entity.BookEntity;
|
||||||
import org.booklore.repository.BookRepository;
|
import org.booklore.repository.BookRepository;
|
||||||
|
import org.booklore.service.restriction.ContentRestrictionService;
|
||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
@@ -17,6 +18,7 @@ public class BookQueryService {
|
|||||||
|
|
||||||
private final BookRepository bookRepository;
|
private final BookRepository bookRepository;
|
||||||
private final BookMapperV2 bookMapperV2;
|
private final BookMapperV2 bookMapperV2;
|
||||||
|
private final ContentRestrictionService contentRestrictionService;
|
||||||
|
|
||||||
public List<Book> getAllBooks(boolean includeDescription) {
|
public List<Book> getAllBooks(boolean includeDescription) {
|
||||||
List<BookEntity> books = bookRepository.findAllWithMetadata();
|
List<BookEntity> books = bookRepository.findAllWithMetadata();
|
||||||
@@ -25,6 +27,7 @@ public class BookQueryService {
|
|||||||
|
|
||||||
public List<Book> getAllBooksByLibraryIds(Set<Long> libraryIds, boolean includeDescription, Long userId) {
|
public List<Book> getAllBooksByLibraryIds(Set<Long> libraryIds, boolean includeDescription, Long userId) {
|
||||||
List<BookEntity> books = bookRepository.findAllWithMetadataByLibraryIds(libraryIds);
|
List<BookEntity> books = bookRepository.findAllWithMetadataByLibraryIds(libraryIds);
|
||||||
|
books = contentRestrictionService.applyRestrictions(books, userId);
|
||||||
return mapBooksToDto(books, includeDescription, userId);
|
return mapBooksToDto(books, includeDescription, userId);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -152,6 +152,8 @@ public class BookMetadataService {
|
|||||||
.categories(request.getGenres() != null ? request.getGenres() : Collections.emptySet())
|
.categories(request.getGenres() != null ? request.getGenres() : Collections.emptySet())
|
||||||
.moods(request.getMoods() != null ? request.getMoods() : Collections.emptySet())
|
.moods(request.getMoods() != null ? request.getMoods() : Collections.emptySet())
|
||||||
.tags(request.getTags() != null ? request.getTags() : Collections.emptySet())
|
.tags(request.getTags() != null ? request.getTags() : Collections.emptySet())
|
||||||
|
.ageRating(request.getAgeRating())
|
||||||
|
.contentRating(request.getContentRating())
|
||||||
.build();
|
.build();
|
||||||
|
|
||||||
for (Long bookId : request.getBookIds()) {
|
for (Long bookId : request.getBookIds()) {
|
||||||
|
|||||||
@@ -180,6 +180,8 @@ public class BookMetadataUpdater {
|
|||||||
handleFieldUpdate(e.getLubimyczytacRatingLocked(), clear.isLubimyczytacRating(), m.getLubimyczytacRating(), v -> e.setLubimyczytacRating(v), () -> e.getLubimyczytacRating(), replaceMode);
|
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.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.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 <T> void handleFieldUpdate(Boolean locked, boolean shouldClear, T newValue, Consumer<T> setter, Supplier<T> getter, MetadataReplaceMode mode) {
|
private <T> void handleFieldUpdate(Boolean locked, boolean shouldClear, T newValue, Consumer<T> setter, Supplier<T> getter, MetadataReplaceMode mode) {
|
||||||
@@ -416,7 +418,9 @@ public class BookMetadataUpdater {
|
|||||||
Pair.of(m.getTagsLocked(), e::setTagsLocked),
|
Pair.of(m.getTagsLocked(), e::setTagsLocked),
|
||||||
Pair.of(m.getReviewsLocked(), e::setReviewsLocked),
|
Pair.of(m.getReviewsLocked(), e::setReviewsLocked),
|
||||||
Pair.of(m.getNarratorLocked(), e::setNarratorLocked),
|
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 -> {
|
lockMappings.forEach(pair -> {
|
||||||
if (pair.getLeft() != null) pair.getRight().accept(pair.getLeft());
|
if (pair.getLeft() != null) pair.getRight().accept(pair.getLeft());
|
||||||
|
|||||||
+272
@@ -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<ContentRestriction> 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<ContentRestriction> updateRestrictions(Long userId, List<ContentRestriction> restrictions) {
|
||||||
|
BookLoreUserEntity user = userRepository.findById(userId)
|
||||||
|
.orElseThrow(() -> ApiError.USER_NOT_FOUND.createException(userId));
|
||||||
|
|
||||||
|
restrictionRepository.deleteByUserId(userId);
|
||||||
|
|
||||||
|
List<UserContentRestrictionEntity> 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<BookEntity> applyRestrictions(List<BookEntity> books, Long userId) {
|
||||||
|
List<UserContentRestrictionEntity> restrictions = restrictionRepository.findByUserId(userId);
|
||||||
|
|
||||||
|
if (restrictions.isEmpty()) {
|
||||||
|
return books;
|
||||||
|
}
|
||||||
|
|
||||||
|
Set<String> excludedCategories = getValuesForTypeAndMode(restrictions, ContentRestrictionType.CATEGORY, ContentRestrictionMode.EXCLUDE);
|
||||||
|
Set<String> excludedTags = getValuesForTypeAndMode(restrictions, ContentRestrictionType.TAG, ContentRestrictionMode.EXCLUDE);
|
||||||
|
Set<String> excludedMoods = getValuesForTypeAndMode(restrictions, ContentRestrictionType.MOOD, ContentRestrictionMode.EXCLUDE);
|
||||||
|
Set<String> excludedContentRatings = getValuesForTypeAndMode(restrictions, ContentRestrictionType.CONTENT_RATING, ContentRestrictionMode.EXCLUDE);
|
||||||
|
|
||||||
|
Set<String> allowedCategories = getValuesForTypeAndMode(restrictions, ContentRestrictionType.CATEGORY, ContentRestrictionMode.ALLOW_ONLY);
|
||||||
|
Set<String> allowedTags = getValuesForTypeAndMode(restrictions, ContentRestrictionType.TAG, ContentRestrictionMode.ALLOW_ONLY);
|
||||||
|
Set<String> allowedMoods = getValuesForTypeAndMode(restrictions, ContentRestrictionType.MOOD, ContentRestrictionMode.ALLOW_ONLY);
|
||||||
|
Set<String> 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<String> getValuesForTypeAndMode(List<UserContentRestrictionEntity> 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<UserContentRestrictionEntity> 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<String> excludedCategories,
|
||||||
|
Set<String> excludedTags,
|
||||||
|
Set<String> excludedMoods,
|
||||||
|
Set<String> 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<String> allowedCategories,
|
||||||
|
Set<String> allowedTags,
|
||||||
|
Set<String> allowedMoods,
|
||||||
|
Set<String> 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();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -203,7 +203,15 @@ public class MetadataChangeDetector {
|
|||||||
new FieldDescriptor<>("abridged",
|
new FieldDescriptor<>("abridged",
|
||||||
BookMetadata::getAbridged, BookMetadataEntity::getAbridged,
|
BookMetadata::getAbridged, BookMetadataEntity::getAbridged,
|
||||||
BookMetadata::getAbridgedLocked, BookMetadataEntity::getAbridgedLocked,
|
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<CollectionFieldDescriptor> COLLECTION_FIELDS = List.of(
|
private static final List<CollectionFieldDescriptor> COLLECTION_FIELDS = List.of(
|
||||||
|
|||||||
@@ -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;
|
||||||
+13
@@ -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);
|
||||||
@@ -384,8 +384,17 @@ class KoboEntitlementServiceTest {
|
|||||||
private BookEntity createEpubBookEntity(Long id) {
|
private BookEntity createEpubBookEntity(Long id) {
|
||||||
BookEntity book = new BookEntity();
|
BookEntity book = new BookEntity();
|
||||||
book.setId(id);
|
book.setId(id);
|
||||||
book.setBookType(BookFileType.EPUB);
|
book.setBookFiles(new java.util.ArrayList<>());
|
||||||
book.setFileSizeKb(1024L);
|
|
||||||
|
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();
|
BookMetadataEntity metadata = new BookMetadataEntity();
|
||||||
metadata.setTitle("Test EPUB Book " + id);
|
metadata.setTitle("Test EPUB Book " + id);
|
||||||
|
|||||||
@@ -26,7 +26,7 @@ import {BookFilterComponent} from './book-filter/book-filter.component';
|
|||||||
import {Tooltip} from 'primeng/tooltip';
|
import {Tooltip} from 'primeng/tooltip';
|
||||||
import {BookFilterMode, EntityViewPreferences, UserService} from '../../../settings/user-management/user.service';
|
import {BookFilterMode, EntityViewPreferences, UserService} from '../../../settings/user-management/user.service';
|
||||||
import {SeriesCollapseFilter} from './filters/SeriesCollapseFilter';
|
import {SeriesCollapseFilter} from './filters/SeriesCollapseFilter';
|
||||||
import {SideBarFilter} from './filters/SidebarFilter';
|
import {SideBarFilter} from './filters/sidebar-filter';
|
||||||
import {HeaderFilter} from './filters/HeaderFilter';
|
import {HeaderFilter} from './filters/HeaderFilter';
|
||||||
import {CoverScalePreferenceService} from './cover-scale-preference.service';
|
import {CoverScalePreferenceService} from './cover-scale-preference.service';
|
||||||
import {BookSorter} from './sorting/BookSorter';
|
import {BookSorter} from './sorting/BookSorter';
|
||||||
|
|||||||
+1
-1
@@ -5,7 +5,7 @@ import {BookState} from '../../model/state/book-state.model';
|
|||||||
import {SortOption} from '../../model/sort.model';
|
import {SortOption} from '../../model/sort.model';
|
||||||
import {SortService} from '../../service/sort.service';
|
import {SortService} from '../../service/sort.service';
|
||||||
import {HeaderFilter} from './filters/HeaderFilter';
|
import {HeaderFilter} from './filters/HeaderFilter';
|
||||||
import {SideBarFilter} from './filters/SidebarFilter';
|
import {SideBarFilter} from './filters/sidebar-filter';
|
||||||
import {SeriesCollapseFilter} from './filters/SeriesCollapseFilter';
|
import {SeriesCollapseFilter} from './filters/SeriesCollapseFilter';
|
||||||
import {ParamMap} from '@angular/router';
|
import {ParamMap} from '@angular/router';
|
||||||
import {QUERY_PARAMS} from './book-browser-query-params.service';
|
import {QUERY_PARAMS} from './book-browser-query-params.service';
|
||||||
|
|||||||
+42
-5
@@ -19,7 +19,8 @@ export type FilterType =
|
|||||||
| 'author' | 'category' | 'series' | 'bookType' | 'readStatus'
|
| 'author' | 'category' | 'series' | 'bookType' | 'readStatus'
|
||||||
| 'personalRating' | 'publisher' | 'matchScore' | 'library' | 'shelf'
|
| 'personalRating' | 'publisher' | 'matchScore' | 'library' | 'shelf'
|
||||||
| 'shelfStatus' | 'tag' | 'publishedDate' | 'fileSize' | 'amazonRating'
|
| 'shelfStatus' | 'tag' | 'publishedDate' | 'fileSize' | 'amazonRating'
|
||||||
| 'goodreadsRating' | 'hardcoverRating' | 'language' | 'pageCount' | 'mood';
|
| 'goodreadsRating' | 'hardcoverRating' | 'language' | 'pageCount' | 'mood'
|
||||||
|
| 'ageRating' | 'contentRating';
|
||||||
|
|
||||||
export type SortMode = 'count' | 'sortIndex';
|
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}
|
{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<Record<string, string>> = {
|
||||||
|
'EVERYONE': 'Everyone',
|
||||||
|
'TEEN': 'Teen',
|
||||||
|
'MATURE': 'Mature',
|
||||||
|
'ADULT': 'Adult',
|
||||||
|
'EXPLICIT': 'Explicit'
|
||||||
|
};
|
||||||
|
|
||||||
export const readStatusLabels = READ_STATUS_LABELS;
|
export const readStatusLabels = READ_STATUS_LABELS;
|
||||||
export const ratingRanges = RATING_RANGES_5;
|
export const ratingRanges = RATING_RANGES_5;
|
||||||
export const ratingOptions10 = RATING_OPTIONS_10;
|
export const ratingOptions10 = RATING_OPTIONS_10;
|
||||||
@@ -111,7 +130,8 @@ export const matchScoreRanges = MATCH_SCORE_RANGES;
|
|||||||
|
|
||||||
export const NUMERIC_ID_FILTER_TYPES = new Set<FilterType>([
|
export const NUMERIC_ID_FILTER_TYPES = new Set<FilterType>([
|
||||||
'personalRating', 'matchScore', 'fileSize', 'amazonRating',
|
'personalRating', 'matchScore', 'fileSize', 'amazonRating',
|
||||||
'goodreadsRating', 'hardcoverRating', 'pageCount', 'library', 'shelf'
|
'goodreadsRating', 'hardcoverRating', 'pageCount', 'library', 'shelf',
|
||||||
|
'ageRating'
|
||||||
]);
|
]);
|
||||||
|
|
||||||
export const FILTER_LABELS: Readonly<Record<FilterType, string>> = {
|
export const FILTER_LABELS: Readonly<Record<FilterType, string>> = {
|
||||||
@@ -134,7 +154,9 @@ export const FILTER_LABELS: Readonly<Record<FilterType, string>> = {
|
|||||||
hardcoverRating: 'Hardcover Rating',
|
hardcoverRating: 'Hardcover Rating',
|
||||||
language: 'Language',
|
language: 'Language',
|
||||||
pageCount: 'Page Count',
|
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[] =>
|
const extractSingleString = (value: string | undefined | null): FilterValue[] =>
|
||||||
value ? [{id: value, name: value}] : [];
|
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<Record<Exclude<FilterType, 'library'>, (book: Book) => FilterValue[]>> = {
|
export const FILTER_EXTRACTORS: Readonly<Record<Exclude<FilterType, 'library'>, (book: Book) => FilterValue[]>> = {
|
||||||
author: (book) => extractStringsAsFilters(book.metadata?.authors),
|
author: (book) => extractStringsAsFilters(book.metadata?.authors),
|
||||||
category: (book) => extractStringsAsFilters(book.metadata?.categories),
|
category: (book) => extractStringsAsFilters(book.metadata?.categories),
|
||||||
@@ -195,7 +223,14 @@ export const FILTER_EXTRACTORS: Readonly<Record<Exclude<FilterType, 'library'>,
|
|||||||
hardcoverRating: (book) => findInRange(book.metadata?.hardcoverRating, RATING_RANGES_5),
|
hardcoverRating: (book) => findInRange(book.metadata?.hardcoverRating, RATING_RANGES_5),
|
||||||
language: (book) => extractSingleString(book.metadata?.language),
|
language: (book) => extractSingleString(book.metadata?.language),
|
||||||
pageCount: (book) => findInRange(book.metadata?.pageCount, PAGE_COUNT_RANGES),
|
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<Record<Exclude<FilterType, 'library'>, Omit<FilterConfig, 'extractor'>>> = {
|
export const FILTER_CONFIGS: Readonly<Record<Exclude<FilterType, 'library'>, Omit<FilterConfig, 'extractor'>>> = {
|
||||||
@@ -217,5 +252,7 @@ export const FILTER_CONFIGS: Readonly<Record<Exclude<FilterType, 'library'>, Omi
|
|||||||
hardcoverRating: {label: 'Hardcover Rating', sortMode: 'sortIndex', isNumericId: true},
|
hardcoverRating: {label: 'Hardcover Rating', sortMode: 'sortIndex', isNumericId: true},
|
||||||
language: {label: 'Language', sortMode: 'count'},
|
language: {label: 'Language', sortMode: 'count'},
|
||||||
pageCount: {label: 'Page Count', sortMode: 'sortIndex', isNumericId: true},
|
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'}
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -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<unknown>, private selectedFilterMode$: Observable<BookFilterMode>) {
|
||||||
|
}
|
||||||
|
|
||||||
|
filter(bookState: BookState): Observable<BookState> {
|
||||||
|
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};
|
||||||
|
})
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -199,6 +199,10 @@ export interface BookMetadata {
|
|||||||
coverLocked?: boolean;
|
coverLocked?: boolean;
|
||||||
audiobookCoverLocked?: boolean;
|
audiobookCoverLocked?: boolean;
|
||||||
reviewsLocked?: boolean;
|
reviewsLocked?: boolean;
|
||||||
|
ageRating?: number | null;
|
||||||
|
contentRating?: string | null;
|
||||||
|
ageRatingLocked?: boolean;
|
||||||
|
contentRatingLocked?: boolean;
|
||||||
|
|
||||||
[key: string]: unknown;
|
[key: string]: unknown;
|
||||||
}
|
}
|
||||||
@@ -243,6 +247,8 @@ export interface MetadataClearFlags {
|
|||||||
tags?: boolean;
|
tags?: boolean;
|
||||||
cover?: boolean;
|
cover?: boolean;
|
||||||
audiobookCover?: boolean;
|
audiobookCover?: boolean;
|
||||||
|
ageRating?: boolean;
|
||||||
|
contentRating?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface MetadataUpdateWrapper {
|
export interface MetadataUpdateWrapper {
|
||||||
@@ -327,6 +333,10 @@ export interface BulkMetadataUpdateRequest {
|
|||||||
mergeCategories?: boolean;
|
mergeCategories?: boolean;
|
||||||
mergeMoods?: boolean;
|
mergeMoods?: boolean;
|
||||||
mergeTags?: boolean;
|
mergeTags?: boolean;
|
||||||
|
ageRating?: number | null;
|
||||||
|
clearAgeRating?: boolean;
|
||||||
|
contentRating?: string | null;
|
||||||
|
clearContentRating?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface BookDeletionResponse {
|
export interface BookDeletionResponse {
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import {inject, Injectable} from '@angular/core';
|
import {inject, Injectable} from '@angular/core';
|
||||||
import {ConfirmationService, MenuItem, MessageService} from 'primeng/api';
|
import {ConfirmationService, MenuItem, MessageService} from 'primeng/api';
|
||||||
import {BookService} from './book.service';
|
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 {ReadStatus} from '../model/book.model';
|
||||||
import {ResetProgressTypes} from '../../../shared/constants/reset-progress-type';
|
import {ResetProgressTypes} from '../../../shared/constants/reset-progress-type';
|
||||||
import {finalize} from 'rxjs';
|
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
|
// Shelf Actions
|
||||||
if (permissions?.canManageLibrary || permissions?.admin) { // Assuming these permissions cover shelf management for books
|
if (permissions?.canManageLibrary || permissions?.admin) { // Assuming these permissions cover shelf management for books
|
||||||
items.push({
|
items.push({
|
||||||
|
|||||||
+44
@@ -419,6 +419,50 @@
|
|||||||
}
|
}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<div class="field-group small-field">
|
||||||
|
<label for="ageRating">Age Rating</label>
|
||||||
|
<div class="field-with-lock">
|
||||||
|
<p-select
|
||||||
|
id="ageRating"
|
||||||
|
formControlName="ageRating"
|
||||||
|
[options]="ageRatingOptions"
|
||||||
|
optionLabel="label"
|
||||||
|
optionValue="value"
|
||||||
|
placeholder="Select"
|
||||||
|
[showClear]="true"
|
||||||
|
appendTo="body">
|
||||||
|
</p-select>
|
||||||
|
@if (!book.metadata!['ageRatingLocked']) {
|
||||||
|
<p-button icon="pi pi-lock-open" [outlined]="true" (onClick)="toggleLock('ageRating')" severity="success"></p-button>
|
||||||
|
}
|
||||||
|
@if (book.metadata!['ageRatingLocked']) {
|
||||||
|
<p-button icon="pi pi-lock" [outlined]="true" (onClick)="toggleLock('ageRating')" severity="warn"></p-button>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="field-group small-field">
|
||||||
|
<label for="contentRating">Content Rating</label>
|
||||||
|
<div class="field-with-lock">
|
||||||
|
<p-select
|
||||||
|
id="contentRating"
|
||||||
|
formControlName="contentRating"
|
||||||
|
[options]="contentRatingOptions"
|
||||||
|
optionLabel="label"
|
||||||
|
optionValue="value"
|
||||||
|
placeholder="Select"
|
||||||
|
[showClear]="true"
|
||||||
|
appendTo="body">
|
||||||
|
</p-select>
|
||||||
|
@if (!book.metadata!['contentRatingLocked']) {
|
||||||
|
<p-button icon="pi pi-lock-open" [outlined]="true" (onClick)="toggleLock('contentRating')" severity="success"></p-button>
|
||||||
|
}
|
||||||
|
@if (book.metadata!['contentRatingLocked']) {
|
||||||
|
<p-button icon="pi pi-lock" [outlined]="true" (onClick)="toggleLock('contentRating')" severity="warn"></p-button>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
+39
@@ -21,6 +21,7 @@ import {DatePicker} from "primeng/datepicker";
|
|||||||
import {Textarea} from "primeng/textarea";
|
import {Textarea} from "primeng/textarea";
|
||||||
import {Image} from "primeng/image";
|
import {Image} from "primeng/image";
|
||||||
import {LazyLoadImageModule} from "ng-lazyload-image";
|
import {LazyLoadImageModule} from "ng-lazyload-image";
|
||||||
|
import {Select} from "primeng/select";
|
||||||
import {TaskHelperService} from '../../../../settings/task-management/task-helper.service';
|
import {TaskHelperService} from '../../../../settings/task-management/task-helper.service';
|
||||||
import {BookDialogHelperService} from "../../../../book/components/book-browser/book-dialog-helper.service";
|
import {BookDialogHelperService} from "../../../../book/components/book-browser/book-dialog-helper.service";
|
||||||
import {BookNavigationService} from '../../../../book/service/book-navigation.service';
|
import {BookNavigationService} from '../../../../book/service/book-navigation.service';
|
||||||
@@ -50,6 +51,7 @@ import {MetadataProviderSpecificFields} from '../../../../../shared/model/app-se
|
|||||||
Textarea,
|
Textarea,
|
||||||
Image,
|
Image,
|
||||||
LazyLoadImageModule,
|
LazyLoadImageModule,
|
||||||
|
Select,
|
||||||
],
|
],
|
||||||
})
|
})
|
||||||
export class MetadataEditorComponent implements OnInit {
|
export class MetadataEditorComponent implements OnInit {
|
||||||
@@ -102,6 +104,9 @@ export class MetadataEditorComponent implements OnInit {
|
|||||||
filteredSeries: string[] = [];
|
filteredSeries: string[] = [];
|
||||||
private metadataCenterViewMode: 'route' | 'dialog' = 'route';
|
private metadataCenterViewMode: 'route' | 'dialog' = 'route';
|
||||||
|
|
||||||
|
contentRatingOptions: {label: string, value: string}[] = [];
|
||||||
|
ageRatingOptions: {label: string, value: number}[] = [];
|
||||||
|
|
||||||
providerSpecificFields: MetadataProviderSpecificFields = {
|
providerSpecificFields: MetadataProviderSpecificFields = {
|
||||||
asin: true,
|
asin: true,
|
||||||
amazonRating: true,
|
amazonRating: true,
|
||||||
@@ -246,7 +251,29 @@ export class MetadataEditorComponent implements OnInit {
|
|||||||
coverLocked: new FormControl(false),
|
coverLocked: new FormControl(false),
|
||||||
audiobookCoverLocked: new FormControl(false),
|
audiobookCoverLocked: new FormControl(false),
|
||||||
reviewsLocked: 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 {
|
ngOnInit(): void {
|
||||||
@@ -401,6 +428,10 @@ export class MetadataEditorComponent implements OnInit {
|
|||||||
coverLocked: metadata.coverLocked ?? false,
|
coverLocked: metadata.coverLocked ?? false,
|
||||||
audiobookCoverLocked: metadata.audiobookCoverLocked ?? false,
|
audiobookCoverLocked: metadata.audiobookCoverLocked ?? false,
|
||||||
reviewsLocked: metadata.reviewsLocked ?? 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 }[] = [
|
const lockableFields: { key: keyof BookMetadata; control: string }[] = [
|
||||||
@@ -443,6 +474,8 @@ export class MetadataEditorComponent implements OnInit {
|
|||||||
{key: "coverLocked", control: "thumbnailUrl"},
|
{key: "coverLocked", control: "thumbnailUrl"},
|
||||||
{key: "audiobookCoverLocked", control: "audiobookCover"},
|
{key: "audiobookCoverLocked", control: "audiobookCover"},
|
||||||
{key: "reviewsLocked", control: "reviews"},
|
{key: "reviewsLocked", control: "reviews"},
|
||||||
|
{key: "ageRatingLocked", control: "ageRating"},
|
||||||
|
{key: "contentRatingLocked", control: "contentRating"},
|
||||||
];
|
];
|
||||||
|
|
||||||
for (const {key, control} of lockableFields) {
|
for (const {key, control} of lockableFields) {
|
||||||
@@ -634,6 +667,10 @@ export class MetadataEditorComponent implements OnInit {
|
|||||||
coverLocked: form.get("coverLocked")?.value,
|
coverLocked: form.get("coverLocked")?.value,
|
||||||
audiobookCoverLocked: form.get("audiobookCoverLocked")?.value,
|
audiobookCoverLocked: form.get("audiobookCoverLocked")?.value,
|
||||||
reviewsLocked: form.get("reviewsLocked")?.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 && {
|
...(shouldLockAllFields !== undefined && {
|
||||||
allFieldsLocked: shouldLockAllFields,
|
allFieldsLocked: shouldLockAllFields,
|
||||||
@@ -690,6 +727,8 @@ export class MetadataEditorComponent implements OnInit {
|
|||||||
seriesTotal: wasCleared("seriesTotal"),
|
seriesTotal: wasCleared("seriesTotal"),
|
||||||
audiobookCover: wasCleared("audiobookCover"),
|
audiobookCover: wasCleared("audiobookCover"),
|
||||||
cover: false,
|
cover: false,
|
||||||
|
ageRating: wasCleared("ageRating"),
|
||||||
|
contentRating: wasCleared("contentRating"),
|
||||||
};
|
};
|
||||||
|
|
||||||
return {metadata, clearFlags};
|
return {metadata, clearFlags};
|
||||||
|
|||||||
+22
@@ -524,6 +524,28 @@
|
|||||||
}
|
}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<div class="metadata-item">
|
||||||
|
<span class="metadata-key">Age Rating:</span>
|
||||||
|
@if (book?.metadata?.ageRating != null) {
|
||||||
|
<span class="metadata-value metadata-link" (click)="goToAgeRating(book?.metadata?.ageRating!)">
|
||||||
|
{{ getAgeRatingLabel(book?.metadata?.ageRating) }}
|
||||||
|
</span>
|
||||||
|
} @else {
|
||||||
|
<span class="metadata-value">-</span>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="metadata-item">
|
||||||
|
<span class="metadata-key">Content Rating:</span>
|
||||||
|
@if (book?.metadata?.contentRating) {
|
||||||
|
<span class="metadata-value metadata-link" (click)="goToContentRating(book?.metadata?.contentRating!)">
|
||||||
|
{{ getContentRatingLabel(book?.metadata?.contentRating) }}
|
||||||
|
</span>
|
||||||
|
} @else {
|
||||||
|
<span class="metadata-value">-</span>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
|
||||||
@if (hasDigitalFile(book)) {
|
@if (hasDigitalFile(book)) {
|
||||||
<div class="metadata-item">
|
<div class="metadata-item">
|
||||||
<span class="metadata-key">File Size:</span>
|
<span class="metadata-key">File Size:</span>
|
||||||
|
|||||||
+20
-1
@@ -28,7 +28,7 @@ import {Image} from 'primeng/image';
|
|||||||
import {BookDialogHelperService} from '../../../../book/components/book-browser/book-dialog-helper.service';
|
import {BookDialogHelperService} from '../../../../book/components/book-browser/book-dialog-helper.service';
|
||||||
import {TagColor, TagComponent} from '../../../../../shared/components/tag/tag.component';
|
import {TagColor, TagComponent} from '../../../../../shared/components/tag/tag.component';
|
||||||
import {TaskHelperService} from '../../../../settings/task-management/task-helper.service';
|
import {TaskHelperService} from '../../../../settings/task-management/task-helper.service';
|
||||||
import {fileSizeRanges, matchScoreRanges, pageCountRanges} from '../../../../book/components/book-browser/book-filter/book-filter.config';
|
import {AGE_RATING_OPTIONS, CONTENT_RATING_LABELS, fileSizeRanges, matchScoreRanges, pageCountRanges} from '../../../../book/components/book-browser/book-filter/book-filter.config';
|
||||||
import {BookNavigationService} from '../../../../book/service/book-navigation.service';
|
import {BookNavigationService} from '../../../../book/service/book-navigation.service';
|
||||||
import {Divider} from 'primeng/divider';
|
import {Divider} from 'primeng/divider';
|
||||||
import {BookMetadataHostService} from '../../../../../shared/service/book-metadata-host.service';
|
import {BookMetadataHostService} from '../../../../../shared/service/book-metadata-host.service';
|
||||||
@@ -832,6 +832,25 @@ export class MetadataViewerComponent implements OnInit, OnChanges {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
goToAgeRating(ageRating: number): void {
|
||||||
|
this.handleMetadataClick('ageRating', ageRating.toString());
|
||||||
|
}
|
||||||
|
|
||||||
|
goToContentRating(contentRating: string): void {
|
||||||
|
this.handleMetadataClick('contentRating', contentRating);
|
||||||
|
}
|
||||||
|
|
||||||
|
getAgeRatingLabel(ageRating: number | null | undefined): string {
|
||||||
|
if (ageRating == null) return '-';
|
||||||
|
const match = AGE_RATING_OPTIONS.find(r => r.id === ageRating);
|
||||||
|
return match?.label ?? `${ageRating}+`;
|
||||||
|
}
|
||||||
|
|
||||||
|
getContentRatingLabel(contentRating: string | null | undefined): string {
|
||||||
|
if (!contentRating) return '-';
|
||||||
|
return CONTENT_RATING_LABELS[contentRating] ?? contentRating;
|
||||||
|
}
|
||||||
|
|
||||||
private extractYear(dateString: string | null | undefined): string | null {
|
private extractYear(dateString: string | null | undefined): string | null {
|
||||||
if (!dateString) return null;
|
if (!dateString) return null;
|
||||||
const yearMatch = dateString.match(/\d{4}/);
|
const yearMatch = dateString.match(/\d{4}/);
|
||||||
|
|||||||
@@ -0,0 +1,41 @@
|
|||||||
|
export enum ContentRestrictionType {
|
||||||
|
CATEGORY = 'CATEGORY',
|
||||||
|
TAG = 'TAG',
|
||||||
|
MOOD = 'MOOD',
|
||||||
|
AGE_RATING = 'AGE_RATING',
|
||||||
|
CONTENT_RATING = 'CONTENT_RATING'
|
||||||
|
}
|
||||||
|
|
||||||
|
export enum ContentRestrictionMode {
|
||||||
|
EXCLUDE = 'EXCLUDE',
|
||||||
|
ALLOW_ONLY = 'ALLOW_ONLY'
|
||||||
|
}
|
||||||
|
|
||||||
|
export enum ContentRating {
|
||||||
|
EVERYONE = 'EVERYONE',
|
||||||
|
TEEN = 'TEEN',
|
||||||
|
MATURE = 'MATURE',
|
||||||
|
ADULT = 'ADULT',
|
||||||
|
EXPLICIT = 'EXPLICIT'
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ContentRestriction {
|
||||||
|
id?: number;
|
||||||
|
userId: number;
|
||||||
|
restrictionType: ContentRestrictionType;
|
||||||
|
mode: ContentRestrictionMode;
|
||||||
|
value: string;
|
||||||
|
createdAt?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const CONTENT_RATINGS = Object.values(ContentRating);
|
||||||
|
|
||||||
|
export const AGE_RATING_OPTIONS = [
|
||||||
|
{ value: '0', label: 'All Ages' },
|
||||||
|
{ value: '6', label: '6+' },
|
||||||
|
{ value: '10', label: '10+' },
|
||||||
|
{ value: '13', label: '13+' },
|
||||||
|
{ value: '16', label: '16+' },
|
||||||
|
{ value: '18', label: '18+' },
|
||||||
|
{ value: '21', label: '21+' }
|
||||||
|
];
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
import {inject, Injectable} from '@angular/core';
|
||||||
|
import {HttpClient} from '@angular/common/http';
|
||||||
|
import {Observable} from 'rxjs';
|
||||||
|
import {API_CONFIG} from '../../../core/config/api-config';
|
||||||
|
import {ContentRestriction} from './content-restriction.model';
|
||||||
|
|
||||||
|
@Injectable({
|
||||||
|
providedIn: 'root'
|
||||||
|
})
|
||||||
|
export class ContentRestrictionService {
|
||||||
|
private readonly baseUrl = `${API_CONFIG.BASE_URL}/api/v1/users`;
|
||||||
|
private http = inject(HttpClient);
|
||||||
|
|
||||||
|
getUserRestrictions(userId: number): Observable<ContentRestriction[]> {
|
||||||
|
return this.http.get<ContentRestriction[]>(`${this.baseUrl}/${userId}/content-restrictions`);
|
||||||
|
}
|
||||||
|
|
||||||
|
addRestriction(userId: number, restriction: ContentRestriction): Observable<ContentRestriction> {
|
||||||
|
return this.http.post<ContentRestriction>(`${this.baseUrl}/${userId}/content-restrictions`, restriction);
|
||||||
|
}
|
||||||
|
|
||||||
|
updateRestrictions(userId: number, restrictions: ContentRestriction[]): Observable<ContentRestriction[]> {
|
||||||
|
return this.http.put<ContentRestriction[]>(`${this.baseUrl}/${userId}/content-restrictions`, restrictions);
|
||||||
|
}
|
||||||
|
|
||||||
|
deleteRestriction(userId: number, restrictionId: number): Observable<void> {
|
||||||
|
return this.http.delete<void>(`${this.baseUrl}/${userId}/content-restrictions/${restrictionId}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
deleteAllRestrictions(userId: number): Observable<void> {
|
||||||
|
return this.http.delete<void>(`${this.baseUrl}/${userId}/content-restrictions`);
|
||||||
|
}
|
||||||
|
}
|
||||||
+113
@@ -0,0 +1,113 @@
|
|||||||
|
<div class="content-restrictions-editor">
|
||||||
|
@if (isEditing) {
|
||||||
|
<div class="add-restriction-form">
|
||||||
|
<div class="form-row">
|
||||||
|
<div class="form-field">
|
||||||
|
<label>Type</label>
|
||||||
|
<p-select
|
||||||
|
[options]="restrictionTypes"
|
||||||
|
[(ngModel)]="newRestriction.restrictionType"
|
||||||
|
optionLabel="label"
|
||||||
|
optionValue="value"
|
||||||
|
placeholder="Select type"
|
||||||
|
appendTo="body">
|
||||||
|
</p-select>
|
||||||
|
</div>
|
||||||
|
<div class="form-field">
|
||||||
|
<label>Mode</label>
|
||||||
|
<p-select
|
||||||
|
[options]="restrictionModes"
|
||||||
|
[(ngModel)]="newRestriction.mode"
|
||||||
|
optionLabel="label"
|
||||||
|
optionValue="value"
|
||||||
|
placeholder="Select mode"
|
||||||
|
appendTo="body">
|
||||||
|
</p-select>
|
||||||
|
</div>
|
||||||
|
<div class="form-field form-field-wide">
|
||||||
|
<label>Value</label>
|
||||||
|
<p-select
|
||||||
|
[options]="getValueOptions()"
|
||||||
|
[(ngModel)]="newRestriction.value"
|
||||||
|
optionLabel="label"
|
||||||
|
optionValue="value"
|
||||||
|
placeholder="Select value"
|
||||||
|
[filter]="true"
|
||||||
|
filterPlaceholder="Search..."
|
||||||
|
appendTo="body">
|
||||||
|
</p-select>
|
||||||
|
</div>
|
||||||
|
<div class="form-field form-field-button">
|
||||||
|
<p-button
|
||||||
|
icon="pi pi-plus"
|
||||||
|
severity="success"
|
||||||
|
[outlined]="true"
|
||||||
|
(onClick)="addRestriction()"
|
||||||
|
pTooltip="Add restriction">
|
||||||
|
</p-button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
|
||||||
|
@if (restrictions.length === 0) {
|
||||||
|
<div class="empty-state">
|
||||||
|
<i class="pi pi-check-circle"></i>
|
||||||
|
<p>No content restrictions configured</p>
|
||||||
|
<span class="empty-hint">This user can access all content in their assigned libraries</span>
|
||||||
|
</div>
|
||||||
|
} @else {
|
||||||
|
<div class="restrictions-list">
|
||||||
|
@if (getExcludeRestrictions().length > 0) {
|
||||||
|
<div class="restrictions-group">
|
||||||
|
<h5 class="group-title">
|
||||||
|
<i class="pi pi-ban"></i>
|
||||||
|
Hidden Content (Exclude)
|
||||||
|
</h5>
|
||||||
|
<p class="group-description">Books matching these criteria will be hidden from this user</p>
|
||||||
|
<div class="restrictions-chips">
|
||||||
|
@for (restriction of getExcludeRestrictions(); track restriction.id) {
|
||||||
|
<div class="restriction-chip mode-exclude">
|
||||||
|
<span class="chip-type">{{ getRestrictionTypeLabel(restriction.restrictionType) }}</span>
|
||||||
|
<span class="chip-value">{{ restriction.value }}</span>
|
||||||
|
@if (isEditing) {
|
||||||
|
<button class="chip-remove" (click)="removeRestriction(restriction)">
|
||||||
|
<i class="pi pi-times"></i>
|
||||||
|
</button>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
|
||||||
|
@if (getAllowOnlyRestrictions().length > 0) {
|
||||||
|
<div class="restrictions-group">
|
||||||
|
<h5 class="group-title">
|
||||||
|
<i class="pi pi-check"></i>
|
||||||
|
Allowed Content Only
|
||||||
|
</h5>
|
||||||
|
<p class="group-description">Only books matching these criteria will be visible to this user</p>
|
||||||
|
<div class="restrictions-chips">
|
||||||
|
@for (restriction of getAllowOnlyRestrictions(); track restriction.id) {
|
||||||
|
<div class="restriction-chip mode-allow">
|
||||||
|
<span class="chip-type">{{ getRestrictionTypeLabel(restriction.restrictionType) }}</span>
|
||||||
|
<span class="chip-value">{{ restriction.value }}</span>
|
||||||
|
@if (isEditing) {
|
||||||
|
<button class="chip-remove" (click)="removeRestriction(restriction)">
|
||||||
|
<i class="pi pi-times"></i>
|
||||||
|
</button>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
|
||||||
|
<div class="restrictions-info">
|
||||||
|
<i class="pi pi-info-circle"></i>
|
||||||
|
<span>Exclude rules take priority over Allow Only rules for safety</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
+187
@@ -0,0 +1,187 @@
|
|||||||
|
.content-restrictions-editor {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.add-restriction-form {
|
||||||
|
background: var(--surface-ground);
|
||||||
|
border-radius: 8px;
|
||||||
|
padding: 1rem;
|
||||||
|
border: 1px solid var(--surface-border);
|
||||||
|
|
||||||
|
.form-row {
|
||||||
|
display: flex;
|
||||||
|
gap: 0.75rem;
|
||||||
|
align-items: flex-end;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
|
||||||
|
.form-field {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 0.25rem;
|
||||||
|
min-width: 140px;
|
||||||
|
|
||||||
|
label {
|
||||||
|
font-size: 0.75rem;
|
||||||
|
font-weight: 500;
|
||||||
|
color: var(--text-color-secondary);
|
||||||
|
text-transform: uppercase;
|
||||||
|
letter-spacing: 0.5px;
|
||||||
|
}
|
||||||
|
|
||||||
|
&.form-field-wide {
|
||||||
|
flex: 1;
|
||||||
|
min-width: 200px;
|
||||||
|
}
|
||||||
|
|
||||||
|
&.form-field-button {
|
||||||
|
min-width: auto;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.empty-state {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
padding: 2rem;
|
||||||
|
text-align: center;
|
||||||
|
color: var(--text-color-secondary);
|
||||||
|
|
||||||
|
i {
|
||||||
|
font-size: 2rem;
|
||||||
|
margin-bottom: 0.5rem;
|
||||||
|
color: var(--green-500);
|
||||||
|
}
|
||||||
|
|
||||||
|
p {
|
||||||
|
margin: 0;
|
||||||
|
font-weight: 500;
|
||||||
|
}
|
||||||
|
|
||||||
|
.empty-hint {
|
||||||
|
font-size: 0.85rem;
|
||||||
|
margin-top: 0.25rem;
|
||||||
|
opacity: 0.8;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.restrictions-list {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.restrictions-group {
|
||||||
|
background: var(--surface-ground);
|
||||||
|
border-radius: 8px;
|
||||||
|
padding: 1rem;
|
||||||
|
border: 1px solid var(--surface-border);
|
||||||
|
|
||||||
|
.group-title {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.5rem;
|
||||||
|
margin: 0 0 0.25rem 0;
|
||||||
|
font-size: 0.9rem;
|
||||||
|
font-weight: 600;
|
||||||
|
|
||||||
|
i {
|
||||||
|
font-size: 0.9rem;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.group-description {
|
||||||
|
margin: 0 0 0.75rem 0;
|
||||||
|
font-size: 0.8rem;
|
||||||
|
color: var(--text-color-secondary);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.restrictions-chips {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
gap: 0.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.restriction-chip {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.5rem;
|
||||||
|
padding: 0.35rem 0.75rem;
|
||||||
|
border-radius: 20px;
|
||||||
|
font-size: 0.85rem;
|
||||||
|
transition: all 0.2s ease;
|
||||||
|
|
||||||
|
&.mode-exclude {
|
||||||
|
background: rgba(239, 68, 68, 0.1);
|
||||||
|
border: 1px solid rgba(239, 68, 68, 0.3);
|
||||||
|
color: var(--red-500);
|
||||||
|
|
||||||
|
.chip-type {
|
||||||
|
color: var(--red-400);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
&.mode-allow {
|
||||||
|
background: rgba(34, 197, 94, 0.1);
|
||||||
|
border: 1px solid rgba(34, 197, 94, 0.3);
|
||||||
|
color: var(--green-500);
|
||||||
|
|
||||||
|
.chip-type {
|
||||||
|
color: var(--green-400);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.chip-type {
|
||||||
|
font-size: 0.7rem;
|
||||||
|
text-transform: uppercase;
|
||||||
|
font-weight: 600;
|
||||||
|
letter-spacing: 0.5px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.chip-value {
|
||||||
|
font-weight: 500;
|
||||||
|
}
|
||||||
|
|
||||||
|
.chip-remove {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
width: 18px;
|
||||||
|
height: 18px;
|
||||||
|
border: none;
|
||||||
|
background: transparent;
|
||||||
|
cursor: pointer;
|
||||||
|
border-radius: 50%;
|
||||||
|
padding: 0;
|
||||||
|
margin-left: 0.25rem;
|
||||||
|
transition: all 0.2s ease;
|
||||||
|
|
||||||
|
i {
|
||||||
|
font-size: 0.7rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
&:hover {
|
||||||
|
background: rgba(0, 0, 0, 0.1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.restrictions-info {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.5rem;
|
||||||
|
padding: 0.75rem;
|
||||||
|
background: rgba(59, 130, 246, 0.1);
|
||||||
|
border-radius: 6px;
|
||||||
|
font-size: 0.8rem;
|
||||||
|
color: var(--blue-500);
|
||||||
|
|
||||||
|
i {
|
||||||
|
font-size: 0.9rem;
|
||||||
|
}
|
||||||
|
}
|
||||||
+232
@@ -0,0 +1,232 @@
|
|||||||
|
import {Component, EventEmitter, inject, Input, OnChanges, OnInit, Output, SimpleChanges} from '@angular/core';
|
||||||
|
import {CommonModule} from '@angular/common';
|
||||||
|
import {FormsModule} from '@angular/forms';
|
||||||
|
import {Button} from 'primeng/button';
|
||||||
|
import {Select} from 'primeng/select';
|
||||||
|
import {MessageService} from 'primeng/api';
|
||||||
|
import {Tooltip} from 'primeng/tooltip';
|
||||||
|
import {
|
||||||
|
AGE_RATING_OPTIONS,
|
||||||
|
CONTENT_RATINGS,
|
||||||
|
ContentRestriction,
|
||||||
|
ContentRestrictionMode,
|
||||||
|
ContentRestrictionType
|
||||||
|
} from '../content-restriction.model';
|
||||||
|
import {ContentRestrictionService} from '../content-restriction.service';
|
||||||
|
import {BookService} from '../../../book/service/book.service';
|
||||||
|
import {filter, take} from 'rxjs/operators';
|
||||||
|
import {Book} from '../../../book/model/book.model';
|
||||||
|
|
||||||
|
@Component({
|
||||||
|
selector: 'app-content-restrictions-editor',
|
||||||
|
standalone: true,
|
||||||
|
imports: [
|
||||||
|
CommonModule,
|
||||||
|
FormsModule,
|
||||||
|
Button,
|
||||||
|
Select,
|
||||||
|
Tooltip
|
||||||
|
],
|
||||||
|
templateUrl: './content-restrictions-editor.component.html',
|
||||||
|
styleUrls: ['./content-restrictions-editor.component.scss']
|
||||||
|
})
|
||||||
|
export class ContentRestrictionsEditorComponent implements OnInit, OnChanges {
|
||||||
|
@Input() userId!: number;
|
||||||
|
@Input() isEditing = false;
|
||||||
|
@Output() restrictionsChanged = new EventEmitter<ContentRestriction[]>();
|
||||||
|
|
||||||
|
private contentRestrictionService = inject(ContentRestrictionService);
|
||||||
|
private bookService = inject(BookService);
|
||||||
|
private messageService = inject(MessageService);
|
||||||
|
|
||||||
|
restrictions: ContentRestriction[] = [];
|
||||||
|
availableCategories: string[] = [];
|
||||||
|
availableTags: string[] = [];
|
||||||
|
availableMoods: string[] = [];
|
||||||
|
|
||||||
|
newRestriction: Partial<ContentRestriction> = {
|
||||||
|
restrictionType: ContentRestrictionType.CATEGORY,
|
||||||
|
mode: ContentRestrictionMode.EXCLUDE,
|
||||||
|
value: ''
|
||||||
|
};
|
||||||
|
|
||||||
|
restrictionTypes = [
|
||||||
|
{label: 'Category/Genre', value: ContentRestrictionType.CATEGORY},
|
||||||
|
{label: 'Tag', value: ContentRestrictionType.TAG},
|
||||||
|
{label: 'Mood', value: ContentRestrictionType.MOOD},
|
||||||
|
{label: 'Age Rating', value: ContentRestrictionType.AGE_RATING},
|
||||||
|
{label: 'Content Rating', value: ContentRestrictionType.CONTENT_RATING}
|
||||||
|
];
|
||||||
|
|
||||||
|
restrictionModes = [
|
||||||
|
{label: 'Exclude (Hide matching)', value: ContentRestrictionMode.EXCLUDE},
|
||||||
|
{label: 'Allow Only (Show only matching)', value: ContentRestrictionMode.ALLOW_ONLY}
|
||||||
|
];
|
||||||
|
|
||||||
|
ageRatingOptions = AGE_RATING_OPTIONS;
|
||||||
|
contentRatingOptions = CONTENT_RATINGS.map(r => ({label: r, value: r}));
|
||||||
|
|
||||||
|
ngOnInit() {
|
||||||
|
this.loadRestrictions();
|
||||||
|
this.loadAvailableValues();
|
||||||
|
}
|
||||||
|
|
||||||
|
ngOnChanges(changes: SimpleChanges) {
|
||||||
|
if (changes['userId'] && !changes['userId'].firstChange) {
|
||||||
|
this.loadRestrictions();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
loadRestrictions() {
|
||||||
|
if (!this.userId) return;
|
||||||
|
|
||||||
|
this.contentRestrictionService.getUserRestrictions(this.userId).subscribe({
|
||||||
|
next: (restrictions) => {
|
||||||
|
this.restrictions = restrictions;
|
||||||
|
this.restrictionsChanged.emit(this.restrictions);
|
||||||
|
},
|
||||||
|
error: () => {
|
||||||
|
this.messageService.add({
|
||||||
|
severity: 'error',
|
||||||
|
summary: 'Error',
|
||||||
|
detail: 'Failed to load content restrictions'
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
loadAvailableValues() {
|
||||||
|
this.bookService.bookState$.pipe(
|
||||||
|
filter(state => !!state.books && state.books.length > 0),
|
||||||
|
take(1)
|
||||||
|
).subscribe(state => {
|
||||||
|
const books: Book[] = state.books || [];
|
||||||
|
const categories = new Set<string>();
|
||||||
|
const tags = new Set<string>();
|
||||||
|
const moods = new Set<string>();
|
||||||
|
|
||||||
|
books.forEach((book: Book) => {
|
||||||
|
book.metadata?.categories?.forEach((c: string) => categories.add(c));
|
||||||
|
book.metadata?.tags?.forEach((t: string) => tags.add(t));
|
||||||
|
book.metadata?.moods?.forEach((m: string) => moods.add(m));
|
||||||
|
});
|
||||||
|
|
||||||
|
this.availableCategories = Array.from(categories).sort();
|
||||||
|
this.availableTags = Array.from(tags).sort();
|
||||||
|
this.availableMoods = Array.from(moods).sort();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
getValueOptions(): {label: string, value: string}[] {
|
||||||
|
switch (this.newRestriction.restrictionType) {
|
||||||
|
case ContentRestrictionType.CATEGORY:
|
||||||
|
return this.availableCategories.map(c => ({label: c, value: c}));
|
||||||
|
case ContentRestrictionType.TAG:
|
||||||
|
return this.availableTags.map(t => ({label: t, value: t}));
|
||||||
|
case ContentRestrictionType.MOOD:
|
||||||
|
return this.availableMoods.map(m => ({label: m, value: m}));
|
||||||
|
case ContentRestrictionType.AGE_RATING:
|
||||||
|
return this.ageRatingOptions.map(o => ({label: o.label, value: o.value}));
|
||||||
|
case ContentRestrictionType.CONTENT_RATING:
|
||||||
|
return this.contentRatingOptions;
|
||||||
|
default:
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
addRestriction() {
|
||||||
|
if (!this.newRestriction.value || !this.newRestriction.restrictionType || !this.newRestriction.mode) {
|
||||||
|
this.messageService.add({
|
||||||
|
severity: 'warn',
|
||||||
|
summary: 'Warning',
|
||||||
|
detail: 'Please select all fields'
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const exists = this.restrictions.some(r =>
|
||||||
|
r.restrictionType === this.newRestriction.restrictionType &&
|
||||||
|
r.value === this.newRestriction.value
|
||||||
|
);
|
||||||
|
|
||||||
|
if (exists) {
|
||||||
|
this.messageService.add({
|
||||||
|
severity: 'warn',
|
||||||
|
summary: 'Warning',
|
||||||
|
detail: 'This restriction already exists'
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const restriction: ContentRestriction = {
|
||||||
|
userId: this.userId,
|
||||||
|
restrictionType: this.newRestriction.restrictionType!,
|
||||||
|
mode: this.newRestriction.mode!,
|
||||||
|
value: this.newRestriction.value!
|
||||||
|
};
|
||||||
|
|
||||||
|
this.contentRestrictionService.addRestriction(this.userId, restriction).subscribe({
|
||||||
|
next: (added) => {
|
||||||
|
this.restrictions.push(added);
|
||||||
|
this.restrictionsChanged.emit(this.restrictions);
|
||||||
|
this.newRestriction.value = '';
|
||||||
|
this.messageService.add({
|
||||||
|
severity: 'success',
|
||||||
|
summary: 'Success',
|
||||||
|
detail: 'Content restriction added'
|
||||||
|
});
|
||||||
|
},
|
||||||
|
error: () => {
|
||||||
|
this.messageService.add({
|
||||||
|
severity: 'error',
|
||||||
|
summary: 'Error',
|
||||||
|
detail: 'Failed to add content restriction'
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
removeRestriction(restriction: ContentRestriction) {
|
||||||
|
if (!restriction.id) return;
|
||||||
|
|
||||||
|
this.contentRestrictionService.deleteRestriction(this.userId, restriction.id).subscribe({
|
||||||
|
next: () => {
|
||||||
|
this.restrictions = this.restrictions.filter(r => r.id !== restriction.id);
|
||||||
|
this.restrictionsChanged.emit(this.restrictions);
|
||||||
|
this.messageService.add({
|
||||||
|
severity: 'success',
|
||||||
|
summary: 'Success',
|
||||||
|
detail: 'Content restriction removed'
|
||||||
|
});
|
||||||
|
},
|
||||||
|
error: () => {
|
||||||
|
this.messageService.add({
|
||||||
|
severity: 'error',
|
||||||
|
summary: 'Error',
|
||||||
|
detail: 'Failed to remove content restriction'
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
getRestrictionTypeLabel(type: ContentRestrictionType): string {
|
||||||
|
const found = this.restrictionTypes.find(t => t.value === type);
|
||||||
|
return found?.label || type;
|
||||||
|
}
|
||||||
|
|
||||||
|
getModeLabel(mode: ContentRestrictionMode): string {
|
||||||
|
return mode === ContentRestrictionMode.EXCLUDE ? 'Exclude' : 'Allow Only';
|
||||||
|
}
|
||||||
|
|
||||||
|
getModeClass(mode: ContentRestrictionMode): string {
|
||||||
|
return mode === ContentRestrictionMode.EXCLUDE ? 'mode-exclude' : 'mode-allow';
|
||||||
|
}
|
||||||
|
|
||||||
|
getExcludeRestrictions(): ContentRestriction[] {
|
||||||
|
return this.restrictions.filter(r => r.mode === ContentRestrictionMode.EXCLUDE);
|
||||||
|
}
|
||||||
|
|
||||||
|
getAllowOnlyRestrictions(): ContentRestriction[] {
|
||||||
|
return this.restrictions.filter(r => r.mode === ContentRestrictionMode.ALLOW_ONLY);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -397,6 +397,20 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<div class="content-restrictions-section">
|
||||||
|
<h4 class="details-title">
|
||||||
|
<i class="pi pi-eye-slash"></i>
|
||||||
|
Content Restrictions
|
||||||
|
</h4>
|
||||||
|
<p class="section-description">
|
||||||
|
Configure which content this user can see based on categories, tags, moods, or age ratings.
|
||||||
|
</p>
|
||||||
|
<app-content-restrictions-editor
|
||||||
|
[userId]="user.id"
|
||||||
|
[isEditing]="user.isEditing ?? false">
|
||||||
|
</app-content-restrictions-editor>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
}
|
}
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -347,6 +347,34 @@
|
|||||||
gap: 1rem;
|
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 {
|
.details-title {
|
||||||
display: flex;
|
display: flex;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
|
|||||||
@@ -17,6 +17,7 @@ import {filter, take, takeUntil} from 'rxjs/operators';
|
|||||||
import {Subject} from 'rxjs';
|
import {Subject} from 'rxjs';
|
||||||
import {Tooltip} from 'primeng/tooltip';
|
import {Tooltip} from 'primeng/tooltip';
|
||||||
import {DialogLauncherService} from '../../../shared/services/dialog-launcher.service';
|
import {DialogLauncherService} from '../../../shared/services/dialog-launcher.service';
|
||||||
|
import {ContentRestrictionsEditorComponent} from './content-restrictions-editor/content-restrictions-editor.component';
|
||||||
|
|
||||||
interface UserWithEditing extends User {
|
interface UserWithEditing extends User {
|
||||||
isEditing?: boolean;
|
isEditing?: boolean;
|
||||||
@@ -37,7 +38,8 @@ interface UserWithEditing extends User {
|
|||||||
InputText,
|
InputText,
|
||||||
LowerCasePipe,
|
LowerCasePipe,
|
||||||
TitleCasePipe,
|
TitleCasePipe,
|
||||||
Tooltip
|
Tooltip,
|
||||||
|
ContentRestrictionsEditorComponent
|
||||||
],
|
],
|
||||||
templateUrl: './user-management.component.html',
|
templateUrl: './user-management.component.html',
|
||||||
styleUrls: ['./user-management.component.scss'],
|
styleUrls: ['./user-management.component.scss'],
|
||||||
|
|||||||
Reference in New Issue
Block a user