Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 52 additions & 0 deletions server/constants/contentRatings.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import {
shouldFilterMovie,
shouldFilterTv,
} from '@server/constants/contentRatings';
import assert from 'node:assert/strict';
import { describe, it } from 'node:test';

describe('shouldFilterMovie', () => {
it('allows a rating within the cap', () => {
assert.equal(shouldFilterMovie('PG', 'PG-13'), false);
});

it('blocks a rating above the cap', () => {
assert.equal(shouldFilterMovie('R', 'PG-13'), true);
});

it('allows unrated content when blockUnrated is false', () => {
assert.equal(shouldFilterMovie('NR', 'PG-13', false), false);
});

it('blocks unrated content when blockUnrated is true', () => {
assert.equal(shouldFilterMovie('NR', 'PG-13', true), true);
assert.equal(shouldFilterMovie(undefined, 'PG-13', true), true);
});

it('fails closed on an invalid maxRating', () => {
assert.equal(shouldFilterMovie('G', 'NOT-A-RATING', false), true);
});
});

describe('shouldFilterTv', () => {
it('allows a rating within the cap', () => {
assert.equal(shouldFilterTv('TV-PG', 'TV-14'), false);
});

it('blocks a rating above the cap', () => {
assert.equal(shouldFilterTv('TV-MA', 'TV-14'), true);
});

it('allows unrated content when blockUnrated is false', () => {
assert.equal(shouldFilterTv('Unrated', 'TV-14', false), false);
});

it('blocks unrated content when blockUnrated is true', () => {
assert.equal(shouldFilterTv('Unrated', 'TV-14', true), true);
assert.equal(shouldFilterTv(null, 'TV-14', true), true);
});

it('fails closed on an invalid maxRating', () => {
assert.equal(shouldFilterTv('TV-G', 'NOT-A-RATING', false), true);
});
});
55 changes: 55 additions & 0 deletions server/constants/contentRatings.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
export const RATING_COUNTRY = 'US';

export const MOVIE_RATINGS = ['G', 'PG', 'PG-13', 'R', 'NC-17'] as const;
export type MovieRating = (typeof MOVIE_RATINGS)[number];

export const TV_RATINGS = [
'TV-Y',
'TV-Y7',
'TV-G',
'TV-PG',
'TV-14',
'TV-MA',
] as const;
export type TvRating = (typeof TV_RATINGS)[number];

export const UNRATED_VALUES = ['NR', 'UR', 'Unrated', 'Not Rated', ''];

export interface UserContentRatingLimits {
maxMovieRating?: string;
maxTvRating?: string;
blockUnrated?: boolean;
}

function shouldFilter(
ratings: readonly string[],
rating: string | undefined | null,
maxRating: string | undefined,
blockUnrated: boolean
): boolean {
if (!rating || UNRATED_VALUES.includes(rating)) {
return blockUnrated;
}

if (!maxRating) return false;

const ratingIndex = ratings.indexOf(rating);
const maxIndex = ratings.indexOf(maxRating);

if (ratingIndex === -1) return blockUnrated;
if (maxIndex === -1) return true;

return ratingIndex > maxIndex;
}

export const shouldFilterMovie = (
rating: string | undefined | null,
maxRating: string | undefined,
blockUnrated = false
) => shouldFilter(MOVIE_RATINGS, rating, maxRating, blockUnrated);

export const shouldFilterTv = (
rating: string | undefined | null,
maxRating: string | undefined,
blockUnrated = false
) => shouldFilter(TV_RATINGS, rating, maxRating, blockUnrated);
16 changes: 16 additions & 0 deletions server/entity/MediaRequest.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,16 @@
import TheMovieDb from '@server/api/themoviedb';
import type {
TmdbMovieDetails,
TmdbTvDetails,
} from '@server/api/themoviedb/interfaces';
import {
MediaRequestStatus,
MediaStatus,
MediaType,
} from '@server/constants/media';
import { getRepository } from '@server/datasource';
import type { MediaRequestBody } from '@server/interfaces/api/requestInterfaces';
import { isMovieRestricted, isTvRestricted } from '@server/lib/contentRating';
import notificationManager, { Notification } from '@server/lib/notifications';
import overrideRules from '@server/lib/overrideRules';
import { Permission } from '@server/lib/permissions';
Expand Down Expand Up @@ -40,6 +45,7 @@ export class QuotaRestrictedError extends Error {}
export class DuplicateMediaRequestError extends Error {}
export class NoSeasonsAvailableError extends Error {}
export class BlocklistedMediaError extends Error {}
export class ContentRatingRestrictedError extends Error {}

type MediaRequestOptions = {
isAutoRequest?: boolean;
Expand Down Expand Up @@ -171,6 +177,16 @@ export class MediaRequest {
? await tmdb.getMovie({ movieId: requestBody.mediaId })
: await tmdb.getTvShow({ tvId: requestBody.mediaId });

if (
requestBody.mediaType === MediaType.MOVIE
? isMovieRestricted(requestUser, tmdbMedia as TmdbMovieDetails)
: isTvRestricted(requestUser, tmdbMedia as TmdbTvDetails)
) {
throw new ContentRatingRestrictedError(
'This content is restricted by your parental controls.'
);
}

let media = await mediaRepository.findOne({
where: {
tmdbId: requestBody.mediaId,
Expand Down
10 changes: 10 additions & 0 deletions server/entity/UserSettings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,16 @@ export class UserSettings {
@Column({ nullable: true })
public watchlistSyncTv?: boolean;

// Admin-set only; user cannot view or change their own limits.
@Column({ type: 'varchar', nullable: true })
public maxMovieRating?: string | null;

@Column({ type: 'varchar', nullable: true })
public maxTvRating?: string | null;

@Column({ default: false })
public blockUnrated?: boolean;

Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
@Column({
type: 'text',
nullable: true,
Expand Down
74 changes: 74 additions & 0 deletions server/lib/contentRating.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
import {
getMovieCertification,
getTvCertification,
} from '@server/lib/contentRating';
import assert from 'node:assert/strict';
import { describe, it } from 'node:test';

describe('getMovieCertification', () => {
const movie = (iso_3166_1: string, ...certifications: string[]) => ({
release_dates: {
results: [
{
iso_3166_1,
rating: '',
release_dates: certifications.map((certification) => ({
certification,
release_date: '',
type: 3,
})),
},
],
},
});

it('returns a single US certification', () => {
assert.equal(getMovieCertification(movie('US', 'PG-13')), 'PG-13');
});

it('picks the most restrictive of multiple US certifications', () => {
assert.equal(getMovieCertification(movie('US', 'PG-13', 'R')), 'R');
});

it('ignores an unrated release when a real certification also exists', () => {
assert.equal(getMovieCertification(movie('US', 'NR', 'PG')), 'PG');
});

it('returns undefined when there is no US entry', () => {
assert.equal(getMovieCertification(movie('GB', '15')), undefined);
});
});

describe('getTvCertification', () => {
const show = (...entries: [string, string][]) => ({
content_ratings: {
results: entries.map(([iso_3166_1, rating]) => ({ iso_3166_1, rating })),
},
});

it('returns the US content rating', () => {
assert.equal(getTvCertification(show(['US', 'TV-14'])), 'TV-14');
});

it('picks the most restrictive of multiple US entries', () => {
assert.equal(
getTvCertification(show(['US', 'TV-Y7'], ['US', 'TV-14'])),
'TV-14'
);
});

it('ignores an unrated entry when a real rating also exists', () => {
assert.equal(
getTvCertification(show(['US', 'NR'], ['US', 'TV-PG'])),
'TV-PG'
);
});

it('returns undefined for an unrated US entry', () => {
assert.equal(getTvCertification(show(['US', 'NR'])), undefined);
});

it('returns undefined when there is no US entry', () => {
assert.equal(getTvCertification(show(['GB', '12'])), undefined);
});
});
95 changes: 95 additions & 0 deletions server/lib/contentRating.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
import type {
TmdbMovieDetails,
TmdbTvDetails,
} from '@server/api/themoviedb/interfaces';
import {
MOVIE_RATINGS,
RATING_COUNTRY,
TV_RATINGS,
UNRATED_VALUES,
shouldFilterMovie,
shouldFilterTv,
type UserContentRatingLimits,
} from '@server/constants/contentRatings';
import type { User } from '@server/entity/User';

export function getUserContentRatingLimits(
user?: User
): UserContentRatingLimits | undefined {
const maxMovieRating = user?.settings?.maxMovieRating ?? undefined;
const maxTvRating = user?.settings?.maxTvRating ?? undefined;
const blockUnrated = user?.settings?.blockUnrated ?? false;

if (!maxMovieRating && !maxTvRating && !blockUnrated) {
return undefined;
}

return { maxMovieRating, maxTvRating, blockUnrated };
}

const mostRestrictive = (ratings: readonly string[], certs?: string[]) =>
certs?.reduce<string | undefined>(
(worst, cert) =>
worst === undefined || ratings.indexOf(cert) > ratings.indexOf(worst)
? cert
: worst,
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
undefined
);

// Most restrictive US certification. Unrated releases are ignored, so an
// unrated cut doesn't override the theatrical rating.
export function getMovieCertification(
details: Pick<TmdbMovieDetails, 'release_dates'>
): string | undefined {
return mostRestrictive(
MOVIE_RATINGS,
details.release_dates?.results
.filter((r) => r.iso_3166_1 === RATING_COUNTRY)
.flatMap((r) => r.release_dates.map((rd) => rd.certification))
.filter((cert) => !UNRATED_VALUES.includes(cert))
);
}

// A show can carry multiple US ratings (e.g. different seasons or networks);
// the most restrictive one wins.
export function getTvCertification(
details: Pick<TmdbTvDetails, 'content_ratings'>
): string | undefined {
return mostRestrictive(
TV_RATINGS,
details.content_ratings?.results
.filter((r) => r.iso_3166_1 === RATING_COUNTRY)
.map((r) => r.rating)
.filter((rating) => rating && !UNRATED_VALUES.includes(rating))
);
}

export function isMovieRestricted(
user: User | undefined,
details: Pick<TmdbMovieDetails, 'release_dates'>
): boolean {
const limits = getUserContentRatingLimits(user);
return (
!!limits &&
shouldFilterMovie(
getMovieCertification(details),
limits.maxMovieRating,
limits.blockUnrated
)
);
}

export function isTvRestricted(
user: User | undefined,
details: Pick<TmdbTvDetails, 'content_ratings'>
): boolean {
const limits = getUserContentRatingLimits(user);
return (
!!limits &&
shouldFilterTv(
getTvCertification(details),
limits.maxTvRating,
limits.blockUnrated
)
);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import type { MigrationInterface, QueryRunner } from 'typeorm';

export class AddParentalControlColumns1792267428951 implements MigrationInterface {
name = 'AddParentalControlColumns1792267428951';

public async up(queryRunner: QueryRunner): Promise<void> {
const table = await queryRunner.getTable('user_settings');
const columns = [
['maxMovieRating', 'character varying'],
['maxTvRating', 'character varying'],
['blockUnrated', 'boolean NOT NULL DEFAULT false'],
];
for (const [name, type] of columns) {
if (!table?.findColumnByName(name)) {
await queryRunner.query(
`ALTER TABLE "user_settings" ADD "${name}" ${type}`
);
}
}
}

public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(
`ALTER TABLE "user_settings" DROP COLUMN "blockUnrated"`
);
await queryRunner.query(
`ALTER TABLE "user_settings" DROP COLUMN "maxTvRating"`
);
await queryRunner.query(
`ALTER TABLE "user_settings" DROP COLUMN "maxMovieRating"`
);
}
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
Loading