From e255cca02aeb64730a6af101636789e8e594c794 Mon Sep 17 00:00:00 2001 From: Progeny Alpha Date: Thu, 3 Sep 2026 15:52:09 -0400 Subject: [PATCH] feat(parental-controls): add per-user rating limits and block over-limit titles Add maxMovieRating, maxTvRating and blockUnrated to UserSettings with migrations for both databases, the US rating hierarchies and comparison helpers, and US certification extraction from TMDB details. Movie and TV detail and ratings routes return 403 for a user whose limits exclude the title, and requesting one is rejected with a ContentRatingRestrictedError. The detail pages surface that 403 instead of falling through to 404. --- server/constants/contentRatings.test.ts | 52 ++++++++++ server/constants/contentRatings.ts | 55 +++++++++++ server/entity/MediaRequest.ts | 16 ++++ server/entity/UserSettings.ts | 10 ++ server/lib/contentRating.test.ts | 74 +++++++++++++++ server/lib/contentRating.ts | 95 +++++++++++++++++++ ...1792267428951-AddParentalControlColumns.ts | 33 +++++++ ...1792267433596-AddParentalControlColumns.ts | 33 +++++++ server/routes/movie.ts | 22 +++++ server/routes/request.ts | 2 + server/routes/tv.ts | 24 +++++ src/components/MovieDetails/index.tsx | 3 +- src/components/TvDetails/index.tsx | 3 +- src/i18n/locale/en.json | 1 + src/pages/_error.tsx | 3 + src/pages/movie/[movieId]/index.tsx | 42 +++++--- src/pages/tv/[tvId]/index.tsx | 42 +++++--- 17 files changed, 480 insertions(+), 30 deletions(-) create mode 100644 server/constants/contentRatings.test.ts create mode 100644 server/constants/contentRatings.ts create mode 100644 server/lib/contentRating.test.ts create mode 100644 server/lib/contentRating.ts create mode 100644 server/migration/postgres/1792267428951-AddParentalControlColumns.ts create mode 100644 server/migration/sqlite/1792267433596-AddParentalControlColumns.ts diff --git a/server/constants/contentRatings.test.ts b/server/constants/contentRatings.test.ts new file mode 100644 index 0000000000..edf2ae4103 --- /dev/null +++ b/server/constants/contentRatings.test.ts @@ -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); + }); +}); diff --git a/server/constants/contentRatings.ts b/server/constants/contentRatings.ts new file mode 100644 index 0000000000..5b79432714 --- /dev/null +++ b/server/constants/contentRatings.ts @@ -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); diff --git a/server/entity/MediaRequest.ts b/server/entity/MediaRequest.ts index ec2d64aaab..8a508d9ce2 100644 --- a/server/entity/MediaRequest.ts +++ b/server/entity/MediaRequest.ts @@ -1,4 +1,8 @@ import TheMovieDb from '@server/api/themoviedb'; +import type { + TmdbMovieDetails, + TmdbTvDetails, +} from '@server/api/themoviedb/interfaces'; import { MediaRequestStatus, MediaStatus, @@ -6,6 +10,7 @@ import { } 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'; @@ -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; @@ -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, diff --git a/server/entity/UserSettings.ts b/server/entity/UserSettings.ts index d0f2ef1f7e..b7f0c86098 100644 --- a/server/entity/UserSettings.ts +++ b/server/entity/UserSettings.ts @@ -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; + @Column({ type: 'text', nullable: true, diff --git a/server/lib/contentRating.test.ts b/server/lib/contentRating.test.ts new file mode 100644 index 0000000000..4e42a4dc25 --- /dev/null +++ b/server/lib/contentRating.test.ts @@ -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); + }); +}); diff --git a/server/lib/contentRating.ts b/server/lib/contentRating.ts new file mode 100644 index 0000000000..569bd4a39a --- /dev/null +++ b/server/lib/contentRating.ts @@ -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( + (worst, cert) => + worst === undefined || ratings.indexOf(cert) > ratings.indexOf(worst) + ? cert + : worst, + undefined + ); + +// Most restrictive US certification. Unrated releases are ignored, so an +// unrated cut doesn't override the theatrical rating. +export function getMovieCertification( + details: Pick +): 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 +): 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 +): boolean { + const limits = getUserContentRatingLimits(user); + return ( + !!limits && + shouldFilterMovie( + getMovieCertification(details), + limits.maxMovieRating, + limits.blockUnrated + ) + ); +} + +export function isTvRestricted( + user: User | undefined, + details: Pick +): boolean { + const limits = getUserContentRatingLimits(user); + return ( + !!limits && + shouldFilterTv( + getTvCertification(details), + limits.maxTvRating, + limits.blockUnrated + ) + ); +} diff --git a/server/migration/postgres/1792267428951-AddParentalControlColumns.ts b/server/migration/postgres/1792267428951-AddParentalControlColumns.ts new file mode 100644 index 0000000000..deaf205e46 --- /dev/null +++ b/server/migration/postgres/1792267428951-AddParentalControlColumns.ts @@ -0,0 +1,33 @@ +import type { MigrationInterface, QueryRunner } from 'typeorm'; + +export class AddParentalControlColumns1792267428951 implements MigrationInterface { + name = 'AddParentalControlColumns1792267428951'; + + public async up(queryRunner: QueryRunner): Promise { + 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 { + 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"` + ); + } +} diff --git a/server/migration/sqlite/1792267433596-AddParentalControlColumns.ts b/server/migration/sqlite/1792267433596-AddParentalControlColumns.ts new file mode 100644 index 0000000000..05709128c5 --- /dev/null +++ b/server/migration/sqlite/1792267433596-AddParentalControlColumns.ts @@ -0,0 +1,33 @@ +import type { MigrationInterface, QueryRunner } from 'typeorm'; + +export class AddParentalControlColumns1792267433596 implements MigrationInterface { + name = 'AddParentalControlColumns1792267433596'; + + public async up(queryRunner: QueryRunner): Promise { + const table = await queryRunner.getTable('user_settings'); + const columns = [ + ['maxMovieRating', 'varchar'], + ['maxTvRating', 'varchar'], + ['blockUnrated', 'boolean NOT NULL DEFAULT (0)'], + ]; + 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 { + 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"` + ); + } +} diff --git a/server/routes/movie.ts b/server/routes/movie.ts index affd2d54e1..b6a476b67d 100644 --- a/server/routes/movie.ts +++ b/server/routes/movie.ts @@ -6,6 +6,7 @@ import { MediaType } from '@server/constants/media'; import { getRepository } from '@server/datasource'; import Media from '@server/entity/Media'; import { Watchlist } from '@server/entity/Watchlist'; +import { isMovieRestricted } from '@server/lib/contentRating'; import logger from '@server/logger'; import { mapMovieDetails } from '@server/models/Movie'; import { mapMovieResult } from '@server/models/Search'; @@ -22,6 +23,13 @@ movieRoutes.get('/:id', async (req, res, next) => { language: (req.query.language as string) ?? req.locale, }); + if (isMovieRestricted(req.user, tmdbMovie)) { + return res.status(403).json({ + status: 403, + message: 'Content restricted by parental controls.', + }); + } + const media = await Media.getMedia(tmdbMovie.id, MediaType.MOVIE); const onUserWatchlist = await getRepository(Watchlist).exist({ @@ -164,6 +172,13 @@ movieRoutes.get('/:id/ratings', async (req, res, next) => { movieId: Number(req.params.id), }); + if (isMovieRestricted(req.user, movie)) { + return res.status(403).json({ + status: 403, + message: 'Content restricted by parental controls.', + }); + } + const rtratings = await rtapi.getMovieRatings( movie.title, Number(movie.release_date.slice(0, 4)) @@ -203,6 +218,13 @@ movieRoutes.get('/:id/ratingscombined', async (req, res, next) => { movieId: Number(req.params.id), }); + if (isMovieRestricted(req.user, movie)) { + return res.status(403).json({ + status: 403, + message: 'Content restricted by parental controls.', + }); + } + const rtratings = await rtapi.getMovieRatings( movie.title, Number(movie.release_date.slice(0, 4)) diff --git a/server/routes/request.ts b/server/routes/request.ts index 2bfdb4bc6c..a984e5eb2c 100644 --- a/server/routes/request.ts +++ b/server/routes/request.ts @@ -9,6 +9,7 @@ import { getRepository } from '@server/datasource'; import Media from '@server/entity/Media'; import { BlocklistedMediaError, + ContentRatingRestrictedError, DuplicateMediaRequestError, MediaRequest, NoSeasonsAvailableError, @@ -337,6 +338,7 @@ requestRoutes.post( case NoSeasonsAvailableError: return next({ status: 202, message: error.message }); case BlocklistedMediaError: + case ContentRatingRestrictedError: return next({ status: 403, message: error.message }); default: return next({ status: 500, message: error.message }); diff --git a/server/routes/tv.ts b/server/routes/tv.ts index 865564ba66..f61cb743cd 100644 --- a/server/routes/tv.ts +++ b/server/routes/tv.ts @@ -7,6 +7,7 @@ import { MediaType } from '@server/constants/media'; import { getRepository } from '@server/datasource'; import Media from '@server/entity/Media'; import { Watchlist } from '@server/entity/Watchlist'; +import { isTvRestricted } from '@server/lib/contentRating'; import logger from '@server/logger'; import { mapTvResult } from '@server/models/Search'; import { mapSeasonWithEpisodes, mapTvDetails } from '@server/models/Tv'; @@ -21,6 +22,14 @@ tvRoutes.get('/:id', async (req, res, next) => { const tmdbTv = await tmdb.getTvShow({ tvId: Number(req.params.id), }); + + if (isTvRestricted(req.user, tmdbTv)) { + return res.status(403).json({ + status: 403, + message: 'Content restricted by parental controls.', + }); + } + const metadataProvider = tmdbTv.keywords.results.some( (keyword: TmdbKeyword) => keyword.id === ANIME_KEYWORD_ID ) @@ -72,6 +81,14 @@ tvRoutes.get('/:id/season/:seasonNumber', async (req, res, next) => { const tmdbTv = await tmdb.getTvShow({ tvId: Number(req.params.id), }); + + if (isTvRestricted(req.user, tmdbTv)) { + return res.status(403).json({ + status: 403, + message: 'Content restricted by parental controls.', + }); + } + const metadataProvider = tmdbTv.keywords.results.some( (keyword: TmdbKeyword) => keyword.id === ANIME_KEYWORD_ID ) @@ -198,6 +215,13 @@ tvRoutes.get('/:id/ratings', async (req, res, next) => { tvId: Number(req.params.id), }); + if (isTvRestricted(req.user, tv)) { + return res.status(403).json({ + status: 403, + message: 'Content restricted by parental controls.', + }); + } + const rtratings = await rtapi.getTVRatings( tv.name, tv.first_air_date ? Number(tv.first_air_date.slice(0, 4)) : undefined diff --git a/src/components/MovieDetails/index.tsx b/src/components/MovieDetails/index.tsx index e356110a0d..5a4c2266eb 100644 --- a/src/components/MovieDetails/index.tsx +++ b/src/components/MovieDetails/index.tsx @@ -189,7 +189,8 @@ const MovieDetails = ({ movie }: MovieDetailsProps) => { } if (!data) { - return ; + const statusCode = error?.response?.status === 403 ? 403 : 404; + return ; } const showAllStudios = data.productionCompanies.length <= minStudios + 1; diff --git a/src/components/TvDetails/index.tsx b/src/components/TvDetails/index.tsx index 41a890250f..f3d8df0cd7 100644 --- a/src/components/TvDetails/index.tsx +++ b/src/components/TvDetails/index.tsx @@ -192,7 +192,8 @@ const TvDetails = ({ tv }: TvDetailsProps) => { } if (!data) { - return ; + const statusCode = error?.response?.status === 403 ? 403 : 404; + return ; } const mediaLinks: PlayButtonLink[] = []; diff --git a/src/i18n/locale/en.json b/src/i18n/locale/en.json index 4a1a0eec9d..a6aee52469 100644 --- a/src/i18n/locale/en.json +++ b/src/i18n/locale/en.json @@ -1707,6 +1707,7 @@ "i18n.usersettings": "User Settings", "i18n.view": "View", "pages.errormessagewithcode": "{statusCode} - {error}", + "pages.forbidden": "Forbidden", "pages.internalservererror": "Internal Server Error", "pages.oops": "Oops", "pages.pagenotfound": "Page Not Found", diff --git a/src/pages/_error.tsx b/src/pages/_error.tsx index 4057eca0c1..e0189c3cc3 100644 --- a/src/pages/_error.tsx +++ b/src/pages/_error.tsx @@ -12,6 +12,7 @@ interface ErrorProps { const messages = defineMessages('pages', { errormessagewithcode: '{statusCode} - {error}', + forbidden: 'Forbidden', internalservererror: 'Internal Server Error', serviceunavailable: 'Service Unavailable', somethingwentwrong: 'Something Went Wrong', @@ -24,6 +25,8 @@ const ErrorPage: NextPage = ({ statusCode }) => { const getErrorMessage = (statusCode?: number) => { switch (statusCode) { + case 403: + return intl.formatMessage(messages.forbidden); case 500: return intl.formatMessage(messages.internalservererror); case 503: diff --git a/src/pages/movie/[movieId]/index.tsx b/src/pages/movie/[movieId]/index.tsx index 4f0d455c78..a92b38b3bf 100644 --- a/src/pages/movie/[movieId]/index.tsx +++ b/src/pages/movie/[movieId]/index.tsx @@ -1,4 +1,5 @@ import MovieDetails from '@app/components/MovieDetails'; +import ErrorPage from '@app/pages/_error'; import { getHostAndPort } from '@app/utils/urlHelper'; import type { MovieDetails as MovieDetailsType } from '@server/models/Movie'; import axios from 'axios'; @@ -6,29 +7,42 @@ import type { GetServerSideProps, NextPage } from 'next'; interface MoviePageProps { movie?: MovieDetailsType; + statusCode?: number; } -const MoviePage: NextPage = ({ movie }) => { +const MoviePage: NextPage = ({ movie, statusCode }) => { + if (statusCode) { + return ; + } + return ; }; export const getServerSideProps: GetServerSideProps = async ( ctx ) => { - const response = await axios.get( - `http://${getHostAndPort()}/api/v1/movie/${ctx.query.movieId}`, - { - headers: ctx.req?.headers?.cookie - ? { cookie: ctx.req.headers.cookie } - : undefined, - } - ); + try { + const response = await axios.get( + `http://${getHostAndPort()}/api/v1/movie/${ctx.query.movieId}`, + { + headers: ctx.req?.headers?.cookie + ? { cookie: ctx.req.headers.cookie } + : undefined, + } + ); - return { - props: { - movie: response.data, - }, - }; + return { + props: { + movie: response.data, + }, + }; + } catch (e) { + if (axios.isAxiosError(e) && e.response?.status === 403) { + ctx.res.statusCode = 403; + return { props: { statusCode: 403 } }; + } + throw e; + } }; export default MoviePage; diff --git a/src/pages/tv/[tvId]/index.tsx b/src/pages/tv/[tvId]/index.tsx index fae9218414..7b48a32c74 100644 --- a/src/pages/tv/[tvId]/index.tsx +++ b/src/pages/tv/[tvId]/index.tsx @@ -1,4 +1,5 @@ import TvDetails from '@app/components/TvDetails'; +import ErrorPage from '@app/pages/_error'; import { getHostAndPort } from '@app/utils/urlHelper'; import type { TvDetails as TvDetailsType } from '@server/models/Tv'; import axios from 'axios'; @@ -6,29 +7,42 @@ import type { GetServerSideProps, NextPage } from 'next'; interface TvPageProps { tv?: TvDetailsType; + statusCode?: number; } -const TvPage: NextPage = ({ tv }) => { +const TvPage: NextPage = ({ tv, statusCode }) => { + if (statusCode) { + return ; + } + return ; }; export const getServerSideProps: GetServerSideProps = async ( ctx ) => { - const response = await axios.get( - `http://${getHostAndPort()}/api/v1/tv/${ctx.query.tvId}`, - { - headers: ctx.req?.headers?.cookie - ? { cookie: ctx.req.headers.cookie } - : undefined, - } - ); + try { + const response = await axios.get( + `http://${getHostAndPort()}/api/v1/tv/${ctx.query.tvId}`, + { + headers: ctx.req?.headers?.cookie + ? { cookie: ctx.req.headers.cookie } + : undefined, + } + ); - return { - props: { - tv: response.data, - }, - }; + return { + props: { + tv: response.data, + }, + }; + } catch (e) { + if (axios.isAxiosError(e) && e.response?.status === 403) { + ctx.res.statusCode = 403; + return { props: { statusCode: 403 } }; + } + throw e; + } }; export default TvPage;