feat(content-restrictions): add age rating and content rating support (#2619)

This commit is contained in:
ACX
2026-02-05 17:10:44 -07:00
committed by GitHub
parent 89b4319970
commit 9f9c762180
42 changed files with 1755 additions and 17 deletions
@@ -26,7 +26,7 @@ import {BookFilterComponent} from './book-filter/book-filter.component';
import {Tooltip} from 'primeng/tooltip';
import {BookFilterMode, EntityViewPreferences, UserService} from '../../../settings/user-management/user.service';
import {SeriesCollapseFilter} from './filters/SeriesCollapseFilter';
import {SideBarFilter} from './filters/SidebarFilter';
import {SideBarFilter} from './filters/sidebar-filter';
import {HeaderFilter} from './filters/HeaderFilter';
import {CoverScalePreferenceService} from './cover-scale-preference.service';
import {BookSorter} from './sorting/BookSorter';
@@ -5,7 +5,7 @@ import {BookState} from '../../model/state/book-state.model';
import {SortOption} from '../../model/sort.model';
import {SortService} from '../../service/sort.service';
import {HeaderFilter} from './filters/HeaderFilter';
import {SideBarFilter} from './filters/SidebarFilter';
import {SideBarFilter} from './filters/sidebar-filter';
import {SeriesCollapseFilter} from './filters/SeriesCollapseFilter';
import {ParamMap} from '@angular/router';
import {QUERY_PARAMS} from './book-browser-query-params.service';
@@ -19,7 +19,8 @@ export type FilterType =
| 'author' | 'category' | 'series' | 'bookType' | 'readStatus'
| 'personalRating' | 'publisher' | 'matchScore' | 'library' | 'shelf'
| 'shelfStatus' | 'tag' | 'publishedDate' | 'fileSize' | 'amazonRating'
| 'goodreadsRating' | 'hardcoverRating' | 'language' | 'pageCount' | 'mood';
| 'goodreadsRating' | 'hardcoverRating' | 'language' | 'pageCount' | 'mood'
| 'ageRating' | 'contentRating';
export type SortMode = 'count' | 'sortIndex';
@@ -102,6 +103,24 @@ export const MATCH_SCORE_RANGES: readonly RangeConfig[] = [
{id: 6, min: 0.00, max: 0.30, label: 'Poor (0–29%)', sortIndex: 6}
];
export const AGE_RATING_OPTIONS: readonly RangeConfig[] = [
{id: 0, min: 0, max: 1, label: 'All Ages', sortIndex: 0},
{id: 6, min: 6, max: 7, label: '6+', sortIndex: 1},
{id: 10, min: 10, max: 11, label: '10+', sortIndex: 2},
{id: 13, min: 13, max: 14, label: '13+', sortIndex: 3},
{id: 16, min: 16, max: 17, label: '16+', sortIndex: 4},
{id: 18, min: 18, max: 19, label: '18+', sortIndex: 5},
{id: 21, min: 21, max: 22, label: '21+', sortIndex: 6}
];
export const CONTENT_RATING_LABELS: Readonly<Record<string, string>> = {
'EVERYONE': 'Everyone',
'TEEN': 'Teen',
'MATURE': 'Mature',
'ADULT': 'Adult',
'EXPLICIT': 'Explicit'
};
export const readStatusLabels = READ_STATUS_LABELS;
export const ratingRanges = RATING_RANGES_5;
export const ratingOptions10 = RATING_OPTIONS_10;
@@ -111,7 +130,8 @@ export const matchScoreRanges = MATCH_SCORE_RANGES;
export const NUMERIC_ID_FILTER_TYPES = new Set<FilterType>([
'personalRating', 'matchScore', 'fileSize', 'amazonRating',
'goodreadsRating', 'hardcoverRating', 'pageCount', 'library', 'shelf'
'goodreadsRating', 'hardcoverRating', 'pageCount', 'library', 'shelf',
'ageRating'
]);
export const FILTER_LABELS: Readonly<Record<FilterType, string>> = {
@@ -134,7 +154,9 @@ export const FILTER_LABELS: Readonly<Record<FilterType, string>> = {
hardcoverRating: 'Hardcover Rating',
language: 'Language',
pageCount: 'Page Count',
mood: 'Mood'
mood: 'Mood',
ageRating: 'Age Rating',
contentRating: 'Content Rating'
};
// ============================================================================
@@ -164,6 +186,12 @@ const extractStringsAsFilters = (values: string[] | undefined): FilterValue[] =>
const extractSingleString = (value: string | undefined | null): FilterValue[] =>
value ? [{id: value, name: value}] : [];
const findExactAgeRating = (ageRating: number | null | undefined): FilterValue[] => {
if (ageRating == null) return [];
const match = AGE_RATING_OPTIONS.find(r => r.id === ageRating);
return match ? [{id: match.id, name: match.label, sortIndex: match.sortIndex}] : [];
};
export const FILTER_EXTRACTORS: Readonly<Record<Exclude<FilterType, 'library'>, (book: Book) => FilterValue[]>> = {
author: (book) => extractStringsAsFilters(book.metadata?.authors),
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),
language: (book) => extractSingleString(book.metadata?.language),
pageCount: (book) => findInRange(book.metadata?.pageCount, PAGE_COUNT_RANGES),
mood: (book) => extractStringsAsFilters(book.metadata?.moods)
mood: (book) => extractStringsAsFilters(book.metadata?.moods),
ageRating: (book) => findExactAgeRating(book.metadata?.ageRating),
contentRating: (book) => {
const rating = book.metadata?.contentRating;
if (!rating) return [];
const label = CONTENT_RATING_LABELS[rating] ?? rating;
return [{id: rating, name: label}];
}
};
export const FILTER_CONFIGS: Readonly<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},
language: {label: 'Language', sortMode: 'count'},
pageCount: {label: 'Page Count', sortMode: 'sortIndex', isNumericId: true},
mood: {label: 'Mood', sortMode: 'count'}
mood: {label: 'Mood', sortMode: 'count'},
ageRating: {label: 'Age Rating', sortMode: 'sortIndex', isNumericId: true},
contentRating: {label: 'Content Rating', sortMode: 'count'}
};
@@ -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;
audiobookCoverLocked?: boolean;
reviewsLocked?: boolean;
ageRating?: number | null;
contentRating?: string | null;
ageRatingLocked?: boolean;
contentRatingLocked?: boolean;
[key: string]: unknown;
}
@@ -243,6 +247,8 @@ export interface MetadataClearFlags {
tags?: boolean;
cover?: boolean;
audiobookCover?: boolean;
ageRating?: boolean;
contentRating?: boolean;
}
export interface MetadataUpdateWrapper {
@@ -327,6 +333,10 @@ export interface BulkMetadataUpdateRequest {
mergeCategories?: boolean;
mergeMoods?: boolean;
mergeTags?: boolean;
ageRating?: number | null;
clearAgeRating?: boolean;
contentRating?: string | null;
clearContentRating?: boolean;
}
export interface BookDeletionResponse {
@@ -1,7 +1,7 @@
import {inject, Injectable} from '@angular/core';
import {ConfirmationService, MenuItem, MessageService} from 'primeng/api';
import {BookService} from './book.service';
import {readStatusLabels} from '../components/book-browser/book-filter/book-filter.config';
import {AGE_RATING_OPTIONS, CONTENT_RATING_LABELS, readStatusLabels} from '../components/book-browser/book-filter/book-filter.config';
import {ReadStatus} from '../model/book.model';
import {ResetProgressTypes} from '../../../shared/constants/reset-progress-type';
import {finalize} from 'rxjs';
@@ -134,6 +134,182 @@ export class BookMenuService {
});
}
if (permissions?.canBulkEditMetadata) {
items.push({
label: 'Set Age Rating',
icon: 'pi pi-user',
items: [
...AGE_RATING_OPTIONS.map(option => ({
label: option.label,
command: () => {
this.confirmationService.confirm({
message: `Are you sure you want to set the age rating to "${option.label}" for ${count} book(s)?`,
header: 'Confirm Age Rating Update',
icon: 'pi pi-exclamation-triangle',
acceptLabel: 'Yes',
rejectLabel: 'No',
accept: () => {
const loader = this.loadingService.show(`Setting age rating for ${count} book(s)...`);
this.bookService.updateBooksMetadata({
bookIds: Array.from(selectedBooks),
ageRating: option.id
}).pipe(finalize(() => this.loadingService.hide(loader)))
.subscribe({
next: () => {
this.messageService.add({
severity: 'success',
summary: 'Age Rating Updated',
detail: `Set to "${option.label}"`,
life: 2000
});
},
error: (err: HttpErrorResponse) => {
const apiError = err.error as APIException;
this.messageService.add({
severity: 'error',
summary: 'Update Failed',
detail: apiError?.message || 'Could not update age rating.',
life: 3000
});
}
});
}
});
}
})),
{
separator: true
},
{
label: 'Clear Age Rating',
icon: 'pi pi-times',
command: () => {
this.confirmationService.confirm({
message: `Are you sure you want to clear the age rating for ${count} book(s)?`,
header: 'Confirm Clear Age Rating',
icon: 'pi pi-exclamation-triangle',
acceptLabel: 'Yes',
rejectLabel: 'No',
accept: () => {
const loader = this.loadingService.show(`Clearing age rating for ${count} book(s)...`);
this.bookService.updateBooksMetadata({
bookIds: Array.from(selectedBooks),
clearAgeRating: true
}).pipe(finalize(() => this.loadingService.hide(loader)))
.subscribe({
next: () => {
this.messageService.add({
severity: 'success',
summary: 'Age Rating Cleared',
detail: 'Age rating has been cleared.',
life: 2000
});
},
error: (err: HttpErrorResponse) => {
const apiError = err.error as APIException;
this.messageService.add({
severity: 'error',
summary: 'Update Failed',
detail: apiError?.message || 'Could not clear age rating.',
life: 3000
});
}
});
}
});
}
}
]
});
items.push({
label: 'Set Content Rating',
icon: 'pi pi-shield',
items: [
...Object.entries(CONTENT_RATING_LABELS).map(([value, label]) => ({
label: label,
command: () => {
this.confirmationService.confirm({
message: `Are you sure you want to set the content rating to "${label}" for ${count} book(s)?`,
header: 'Confirm Content Rating Update',
icon: 'pi pi-exclamation-triangle',
acceptLabel: 'Yes',
rejectLabel: 'No',
accept: () => {
const loader = this.loadingService.show(`Setting content rating for ${count} book(s)...`);
this.bookService.updateBooksMetadata({
bookIds: Array.from(selectedBooks),
contentRating: value
}).pipe(finalize(() => this.loadingService.hide(loader)))
.subscribe({
next: () => {
this.messageService.add({
severity: 'success',
summary: 'Content Rating Updated',
detail: `Set to "${label}"`,
life: 2000
});
},
error: (err: HttpErrorResponse) => {
const apiError = err.error as APIException;
this.messageService.add({
severity: 'error',
summary: 'Update Failed',
detail: apiError?.message || 'Could not update content rating.',
life: 3000
});
}
});
}
});
}
})),
{
separator: true
},
{
label: 'Clear Content Rating',
icon: 'pi pi-times',
command: () => {
this.confirmationService.confirm({
message: `Are you sure you want to clear the content rating for ${count} book(s)?`,
header: 'Confirm Clear Content Rating',
icon: 'pi pi-exclamation-triangle',
acceptLabel: 'Yes',
rejectLabel: 'No',
accept: () => {
const loader = this.loadingService.show(`Clearing content rating for ${count} book(s)...`);
this.bookService.updateBooksMetadata({
bookIds: Array.from(selectedBooks),
clearContentRating: true
}).pipe(finalize(() => this.loadingService.hide(loader)))
.subscribe({
next: () => {
this.messageService.add({
severity: 'success',
summary: 'Content Rating Cleared',
detail: 'Content rating has been cleared.',
life: 2000
});
},
error: (err: HttpErrorResponse) => {
const apiError = err.error as APIException;
this.messageService.add({
severity: 'error',
summary: 'Update Failed',
detail: apiError?.message || 'Could not clear content rating.',
life: 3000
});
}
});
}
});
}
}
]
});
}
// Shelf Actions
if (permissions?.canManageLibrary || permissions?.admin) { // Assuming these permissions cover shelf management for books
items.push({