diff --git a/.all-contributorsrc b/.all-contributorsrc
index 113d0af47..b5166196f 100644
--- a/.all-contributorsrc
+++ b/.all-contributorsrc
@@ -809,6 +809,96 @@
"contributions": [
"code"
]
+ },
+ {
+ "login": "Alexays",
+ "name": "Alex",
+ "avatar_url": "https://avatars.githubusercontent.com/u/13947260?v=4",
+ "profile": "https://arouillard.fr",
+ "contributions": [
+ "code"
+ ]
+ },
+ {
+ "login": "Zebebles",
+ "name": "Zeb Muller",
+ "avatar_url": "https://avatars.githubusercontent.com/u/11425451?v=4",
+ "profile": "https://github.com/Zebebles",
+ "contributions": [
+ "code"
+ ]
+ },
+ {
+ "login": "SMores",
+ "name": "Shane Friedman",
+ "avatar_url": "https://avatars.githubusercontent.com/u/5354254?v=4",
+ "profile": "http://smoores.dev",
+ "contributions": [
+ "code"
+ ]
+ },
+ {
+ "login": "IzaacJ",
+ "name": "Izaac Brånn",
+ "avatar_url": "https://avatars.githubusercontent.com/u/711323?v=4",
+ "profile": "https://izaacj.me",
+ "contributions": [
+ "code"
+ ]
+ },
+ {
+ "login": "SalmanTariq",
+ "name": "Salman Tariq",
+ "avatar_url": "https://avatars.githubusercontent.com/u/13284494?v=4",
+ "profile": "https://github.com/SalmanTariq",
+ "contributions": [
+ "code"
+ ]
+ },
+ {
+ "login": "andrew-kennedy",
+ "name": "Andrew Kennedy",
+ "avatar_url": "https://avatars.githubusercontent.com/u/2387159?v=4",
+ "profile": "https://github.com/andrew-kennedy",
+ "contributions": [
+ "code"
+ ]
+ },
+ {
+ "login": "Fallenbagel",
+ "name": "Fallenbagel",
+ "avatar_url": "https://avatars.githubusercontent.com/u/98979876?v=4",
+ "profile": "https://github.com/Fallenbagel",
+ "contributions": [
+ "code"
+ ]
+ },
+ {
+ "login": "scorp200",
+ "name": "Anton K. (ai Doge)",
+ "avatar_url": "https://avatars.githubusercontent.com/u/9427639?v=4",
+ "profile": "http://aidoge.xyz",
+ "contributions": [
+ "code"
+ ]
+ },
+ {
+ "login": "marcofaggian",
+ "name": "Marco Faggian",
+ "avatar_url": "https://avatars.githubusercontent.com/u/19221001?v=4",
+ "profile": "https://marcofaggian.com",
+ "contributions": [
+ "code"
+ ]
+ },
+ {
+ "login": "nemchik",
+ "name": "Eric Nemchik",
+ "avatar_url": "https://avatars.githubusercontent.com/u/725456?v=4",
+ "profile": "http://nemchik.com/",
+ "contributions": [
+ "code"
+ ]
}
],
"badgeTemplate": "-orange.svg\"/>",
@@ -818,5 +908,6 @@
"repoType": "github",
"repoHost": "https://github.com",
"skipCi": false,
- "commitConvention": "angular"
+ "commitConvention": "angular",
+ "commitType": "docs"
}
diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS
index 6effae045..68a2d018e 100644
--- a/.github/CODEOWNERS
+++ b/.github/CODEOWNERS
@@ -1,10 +1,10 @@
# Global code ownership
-* @sct @TheCatLady @danshilm
+* @sct @TheCatLady @danshilm @OwsleyJr
# Documentation
-/.all-contributorsrc @TheCatLady @samwiseg0 @danshilm
-/*.md @TheCatLady @samwiseg0 @danshilm
-/docs/ @TheCatLady @samwiseg0 @danshilm
+/.all-contributorsrc @TheCatLady @samwiseg0 @danshilm @OwsleyJr
+/*.md @TheCatLady @samwiseg0 @danshilm @OwsleyJr
+/docs/ @TheCatLady @samwiseg0 @danshilm @OwsleyJr
# Snap-related files
/.github/workflows/snap.yaml @samwiseg0
@@ -12,4 +12,4 @@
# i18n locale files
/src/i18n/locale/ @sct @TheCatLady
-/src/i18n/locale/en.json @sct @TheCatLady @danshilm
+/src/i18n/locale/en.json @sct @TheCatLady @danshilm @OwsleyJr
diff --git a/README.md b/README.md
index 83fff5ea7..2369a0cda 100644
--- a/README.md
+++ b/README.md
@@ -11,7 +11,7 @@
-
+
@@ -187,6 +187,18 @@ Thanks goes to these wonderful people ([emoji key](https://allcontributors.org/d
Owen Voke 💻 |
Sebastian K 💻 |
jariz 💻 |
+ Alex 💻 |
+ Zeb Muller 💻 |
+ Shane Friedman 💻 |
+
+
+ Izaac Brånn 💻 |
+ Salman Tariq 💻 |
+ Andrew Kennedy 💻 |
+ Fallenbagel 💻 |
+ Anton K. (ai Doge) 💻 |
+ Marco Faggian 💻 |
+ Eric Nemchik 💻 |
diff --git a/cypress/e2e/pull-to-refresh.cy.ts b/cypress/e2e/pull-to-refresh.cy.ts
index d56c55897..732ee4137 100644
--- a/cypress/e2e/pull-to-refresh.cy.ts
+++ b/cypress/e2e/pull-to-refresh.cy.ts
@@ -13,7 +13,7 @@ describe('Pull To Refresh', () => {
url: '/api/v1/*',
}).as('apiCall');
- cy.get('.searchbar').swipe('bottom', [190, 400]);
+ cy.get('.searchbar').swipe('bottom', [190, 500]);
cy.wait('@apiCall').then((interception) => {
assert.isNotNull(
diff --git a/overseerr-api.yml b/overseerr-api.yml
index 11e6dd8bb..2ebff63db 100644
--- a/overseerr-api.yml
+++ b/overseerr-api.yml
@@ -4199,6 +4199,16 @@ paths:
schema:
type: number
example: 10
+ - in: query
+ name: voteCountGte
+ schema:
+ type: number
+ example: 7
+ - in: query
+ name: voteCountLte
+ schema:
+ type: number
+ example: 10
- in: query
name: watchRegion
schema:
@@ -4478,6 +4488,16 @@ paths:
schema:
type: number
example: 10
+ - in: query
+ name: voteCountGte
+ schema:
+ type: number
+ example: 7
+ - in: query
+ name: voteCountLte
+ schema:
+ type: number
+ example: 10
- in: query
name: watchRegion
schema:
@@ -5331,6 +5351,63 @@ paths:
audienceRating:
type: string
enum: ['Spilled', 'Upright']
+ /movie/{movieId}/ratingscombined:
+ get:
+ summary: Get RT and IMDB movie ratings combined
+ description: Returns ratings from RottenTomatoes and IMDB based on the provided movieId in a JSON object.
+ tags:
+ - movies
+ parameters:
+ - in: path
+ name: movieId
+ required: true
+ schema:
+ type: number
+ example: 337401
+ responses:
+ '200':
+ description: Ratings returned
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ rt:
+ type: object
+ properties:
+ title:
+ type: string
+ example: Mulan
+ year:
+ type: number
+ example: 2020
+ url:
+ type: string
+ example: 'http://www.rottentomatoes.com/m/mulan_2020/'
+ criticsScore:
+ type: number
+ example: 85
+ criticsRating:
+ type: string
+ enum: ['Rotten', 'Fresh', 'Certified Fresh']
+ audienceScore:
+ type: number
+ example: 65
+ audienceRating:
+ type: string
+ enum: ['Spilled', 'Upright']
+ imdb:
+ type: object
+ properties:
+ title:
+ type: string
+ example: I am Legend
+ url:
+ type: string
+ example: 'https://www.imdb.com/title/tt0480249'
+ criticsScore:
+ type: number
+ example: 6.5
/tv/{tvId}:
get:
summary: Get TV details
diff --git a/package.json b/package.json
index 5dff068ee..8b82e45d4 100644
--- a/package.json
+++ b/package.json
@@ -68,7 +68,6 @@
"openpgp": "5.7.0",
"plex-api": "5.3.2",
"pug": "3.0.2",
- "pulltorefreshjs": "0.1.22",
"react": "18.2.0",
"react-ace": "10.1.0",
"react-animate-height": "2.1.2",
@@ -121,7 +120,6 @@
"@types/node": "17.0.36",
"@types/node-schedule": "2.1.0",
"@types/nodemailer": "6.4.7",
- "@types/pulltorefreshjs": "0.1.5",
"@types/react": "18.0.28",
"@types/react-dom": "18.0.11",
"@types/react-transition-group": "4.4.5",
diff --git a/server/api/plextv.ts b/server/api/plextv.ts
index 76ee66188..704926895 100644
--- a/server/api/plextv.ts
+++ b/server/api/plextv.ts
@@ -82,21 +82,6 @@ interface ServerResponse {
};
}
-interface FriendResponse {
- MediaContainer: {
- User: {
- $: {
- id: string;
- title: string;
- username: string;
- email: string;
- thumb: string;
- };
- Server?: ServerResponse[];
- }[];
- };
-}
-
interface UsersResponse {
MediaContainer: {
User: {
@@ -234,19 +219,6 @@ class PlexTvAPI extends ExternalAPI {
}
}
- public async getFriends(): Promise {
- const response = await this.axios.get('/pms/friends/all', {
- transformResponse: [],
- responseType: 'text',
- });
-
- const parsedXml = (await xml2js.parseStringPromise(
- response.data
- )) as FriendResponse;
-
- return parsedXml;
- }
-
public async checkUserAccess(userId: number): Promise {
const settings = getSettings();
@@ -255,9 +227,9 @@ class PlexTvAPI extends ExternalAPI {
throw new Error('Plex is not configured!');
}
- const friends = await this.getFriends();
+ const usersResponse = await this.getUsers();
- const users = friends.MediaContainer.User;
+ const users = usersResponse.MediaContainer.User;
const user = users.find((u) => parseInt(u.$.id) === userId);
diff --git a/server/api/rating/imdbRadarrProxy.ts b/server/api/rating/imdbRadarrProxy.ts
new file mode 100644
index 000000000..0d8ec79fb
--- /dev/null
+++ b/server/api/rating/imdbRadarrProxy.ts
@@ -0,0 +1,195 @@
+import ExternalAPI from '@server/api/externalapi';
+import cacheManager from '@server/lib/cache';
+
+type IMDBRadarrProxyResponse = IMDBMovie[];
+
+interface IMDBMovie {
+ ImdbId: string;
+ Overview: string;
+ Title: string;
+ OriginalTitle: string;
+ TitleSlug: string;
+ Ratings: Rating[];
+ MovieRatings: MovieRatings;
+ Runtime: number;
+ Images: Image[];
+ Genres: string[];
+ Popularity: number;
+ Premier: string;
+ InCinema: string;
+ PhysicalRelease: any;
+ DigitalRelease: string;
+ Year: number;
+ AlternativeTitles: AlternativeTitle[];
+ Translations: Translation[];
+ Recommendations: Recommendation[];
+ Credits: Credits;
+ Studio: string;
+ YoutubeTrailerId: string;
+ Certifications: Certification[];
+ Status: any;
+ Collection: Collection;
+ OriginalLanguage: string;
+ Homepage: string;
+ TmdbId: number;
+}
+
+interface Rating {
+ Count: number;
+ Value: number;
+ Origin: string;
+ Type: string;
+}
+
+interface MovieRatings {
+ Tmdb: Tmdb;
+ Imdb: Imdb;
+ Metacritic: Metacritic;
+ RottenTomatoes: RottenTomatoes;
+}
+
+interface Tmdb {
+ Count: number;
+ Value: number;
+ Type: string;
+}
+
+interface Imdb {
+ Count: number;
+ Value: number;
+ Type: string;
+}
+
+interface Metacritic {
+ Count: number;
+ Value: number;
+ Type: string;
+}
+
+interface RottenTomatoes {
+ Count: number;
+ Value: number;
+ Type: string;
+}
+
+interface Image {
+ CoverType: string;
+ Url: string;
+}
+
+interface AlternativeTitle {
+ Title: string;
+ Type: string;
+ Language: string;
+}
+
+interface Translation {
+ Title: string;
+ Overview: string;
+ Language: string;
+}
+
+interface Recommendation {
+ TmdbId: number;
+ Title: string;
+}
+
+interface Credits {
+ Cast: Cast[];
+ Crew: Crew[];
+}
+
+interface Cast {
+ Name: string;
+ Order: number;
+ Character: string;
+ TmdbId: number;
+ CreditId: string;
+ Images: Image2[];
+}
+
+interface Image2 {
+ CoverType: string;
+ Url: string;
+}
+
+interface Crew {
+ Name: string;
+ Job: string;
+ Department: string;
+ TmdbId: number;
+ CreditId: string;
+ Images: Image3[];
+}
+
+interface Image3 {
+ CoverType: string;
+ Url: string;
+}
+
+interface Certification {
+ Country: string;
+ Certification: string;
+}
+
+interface Collection {
+ Name: string;
+ Images: any;
+ Overview: any;
+ Translations: any;
+ Parts: any;
+ TmdbId: number;
+}
+
+export interface IMDBRating {
+ title: string;
+ url: string;
+ criticsScore: number;
+}
+
+/**
+ * This is a best-effort API. The IMDB API is technically
+ * private and getting access costs money/requires approval.
+ *
+ * Radarr hosts a public proxy that's in use by all Radarr instances.
+ */
+class IMDBRadarrProxy extends ExternalAPI {
+ constructor() {
+ super('https://api.radarr.video/v1', {
+ headers: {
+ 'Content-Type': 'application/json',
+ Accept: 'application/json',
+ },
+ nodeCache: cacheManager.getCache('imdb').data,
+ });
+ }
+
+ /**
+ * Ask the Radarr IMDB Proxy for the movie
+ *
+ * @param IMDBid Id of IMDB movie
+ */
+ public async getMovieRatings(IMDBid: string): Promise {
+ try {
+ const data = await this.get(
+ `/movie/imdb/${IMDBid}`
+ );
+
+ if (!data?.length || data[0].ImdbId !== IMDBid) {
+ return null;
+ }
+
+ return {
+ title: data[0].Title,
+ url: `https://www.imdb.com/title/${data[0].ImdbId}`,
+ criticsScore: data[0].MovieRatings.Imdb.Value,
+ };
+ } catch (e) {
+ throw new Error(
+ `[IMDB RADARR PROXY API] Failed to retrieve movie ratings: ${e.message}`
+ );
+ }
+ }
+}
+
+export default IMDBRadarrProxy;
diff --git a/server/api/rottentomatoes.ts b/server/api/rating/rottentomatoes.ts
similarity index 88%
rename from server/api/rottentomatoes.ts
rename to server/api/rating/rottentomatoes.ts
index 7695e3987..1cf9d6d8e 100644
--- a/server/api/rottentomatoes.ts
+++ b/server/api/rating/rottentomatoes.ts
@@ -1,6 +1,6 @@
+import ExternalAPI from '@server/api/externalapi';
import cacheManager from '@server/lib/cache';
import { getSettings } from '@server/lib/settings';
-import ExternalAPI from './externalapi';
interface RTAlgoliaSearchResponse {
results: {
@@ -17,7 +17,7 @@ interface RTAlgoliaHit {
title: string;
titles: string[];
description: string;
- releaseYear: string;
+ releaseYear: number;
rating: string;
genres: string[];
updateDate: string;
@@ -111,22 +111,19 @@ class RottenTomatoes extends ExternalAPI {
// First, attempt to match exact name and year
let movie = contentResults.hits.find(
- (movie) => movie.releaseYear === year.toString() && movie.title === name
+ (movie) => movie.releaseYear === year && movie.title === name
);
// If we don't find a movie, try to match partial name and year
if (!movie) {
movie = contentResults.hits.find(
- (movie) =>
- movie.releaseYear === year.toString() && movie.title.includes(name)
+ (movie) => movie.releaseYear === year && movie.title.includes(name)
);
}
// If we still dont find a movie, try to match just on year
if (!movie) {
- movie = contentResults.hits.find(
- (movie) => movie.releaseYear === year.toString()
- );
+ movie = contentResults.hits.find((movie) => movie.releaseYear === year);
}
// One last try, try exact name match only
@@ -147,6 +144,9 @@ class RottenTomatoes extends ExternalAPI {
? 'Fresh'
: 'Rotten',
criticsScore: movie.rottenTomatoes.criticsScore,
+ audienceRating:
+ movie.rottenTomatoes.audienceScore >= 60 ? 'Upright' : 'Spilled',
+ audienceScore: movie.rottenTomatoes.audienceScore,
year: Number(movie.releaseYear),
};
} catch (e) {
@@ -181,7 +181,7 @@ class RottenTomatoes extends ExternalAPI {
if (year) {
tvshow = contentResults.hits.find(
- (series) => series.releaseYear === year.toString()
+ (series) => series.releaseYear === year
);
}
@@ -195,6 +195,9 @@ class RottenTomatoes extends ExternalAPI {
criticsRating:
tvshow.rottenTomatoes.criticsScore >= 60 ? 'Fresh' : 'Rotten',
criticsScore: tvshow.rottenTomatoes.criticsScore,
+ audienceRating:
+ tvshow.rottenTomatoes.audienceScore >= 60 ? 'Upright' : 'Spilled',
+ audienceScore: tvshow.rottenTomatoes.audienceScore,
year: Number(tvshow.releaseYear),
};
} catch (e) {
diff --git a/server/api/ratings.ts b/server/api/ratings.ts
new file mode 100644
index 000000000..1fe1354cf
--- /dev/null
+++ b/server/api/ratings.ts
@@ -0,0 +1,7 @@
+import { type IMDBRating } from '@server/api/rating/imdbRadarrProxy';
+import { type RTRating } from '@server/api/rating/rottentomatoes';
+
+export interface RatingResponse {
+ rt?: RTRating;
+ imdb?: IMDBRating;
+}
diff --git a/server/api/servarr/sonarr.ts b/server/api/servarr/sonarr.ts
index 2e423ef39..6cda2a49c 100644
--- a/server/api/servarr/sonarr.ts
+++ b/server/api/servarr/sonarr.ts
@@ -76,6 +76,15 @@ export interface SonarrSeries {
ignoreEpisodesWithoutFiles?: boolean;
searchForMissingEpisodes?: boolean;
};
+ statistics: {
+ seasonCount: number;
+ episodeFileCount: number;
+ episodeCount: number;
+ totalEpisodeCount: number;
+ sizeOnDisk: number;
+ releaseGroups: string[];
+ percentOfEpisodes: number;
+ };
}
export interface AddSeriesOptions {
@@ -116,6 +125,16 @@ class SonarrAPI extends ServarrBase<{
}
}
+ public async getSeriesById(id: number): Promise {
+ try {
+ const response = await this.axios.get(`/series/${id}`);
+
+ return response.data;
+ } catch (e) {
+ throw new Error(`[Sonarr] Failed to retrieve series by ID: ${e.message}`);
+ }
+ }
+
public async getSeriesByTitle(title: string): Promise {
try {
const response = await this.axios.get('/series/lookup', {
diff --git a/server/api/themoviedb/index.ts b/server/api/themoviedb/index.ts
index 4c931ff97..ef36fcd6d 100644
--- a/server/api/themoviedb/index.ts
+++ b/server/api/themoviedb/index.ts
@@ -65,6 +65,8 @@ interface DiscoverMovieOptions {
withRuntimeLte?: string;
voteAverageGte?: string;
voteAverageLte?: string;
+ voteCountGte?: string;
+ voteCountLte?: string;
originalLanguage?: string;
genre?: string;
studio?: string;
@@ -83,6 +85,8 @@ interface DiscoverTvOptions {
withRuntimeLte?: string;
voteAverageGte?: string;
voteAverageLte?: string;
+ voteCountGte?: string;
+ voteCountLte?: string;
includeEmptyReleaseDate?: boolean;
originalLanguage?: string;
genre?: string;
@@ -460,6 +464,8 @@ class TheMovieDb extends ExternalAPI {
withRuntimeLte,
voteAverageGte,
voteAverageLte,
+ voteCountGte,
+ voteCountLte,
watchProviders,
watchRegion,
}: DiscoverMovieOptions = {}): Promise => {
@@ -504,6 +510,8 @@ class TheMovieDb extends ExternalAPI {
'with_runtime.lte': withRuntimeLte,
'vote_average.gte': voteAverageGte,
'vote_average.lte': voteAverageLte,
+ 'vote_count.gte': voteCountGte,
+ 'vote_count.lte': voteCountLte,
watch_region: watchRegion,
with_watch_providers: watchProviders,
},
@@ -530,6 +538,8 @@ class TheMovieDb extends ExternalAPI {
withRuntimeLte,
voteAverageGte,
voteAverageLte,
+ voteCountGte,
+ voteCountLte,
watchProviders,
watchRegion,
}: DiscoverTvOptions = {}): Promise => {
@@ -574,6 +584,8 @@ class TheMovieDb extends ExternalAPI {
'with_runtime.lte': withRuntimeLte,
'vote_average.gte': voteAverageGte,
'vote_average.lte': voteAverageLte,
+ 'vote_count.gte': voteCountGte,
+ 'vote_count.lte': voteCountLte,
with_watch_providers: watchProviders,
watch_region: watchRegion,
},
diff --git a/server/api/themoviedb/interfaces.ts b/server/api/themoviedb/interfaces.ts
index 955e1b12e..775a89765 100644
--- a/server/api/themoviedb/interfaces.ts
+++ b/server/api/themoviedb/interfaces.ts
@@ -28,6 +28,18 @@ export interface TmdbTvResult extends TmdbMediaResult {
first_air_date: string;
}
+export interface TmdbCollectionResult {
+ id: number;
+ media_type: 'collection';
+ title: string;
+ original_title: string;
+ adult: boolean;
+ poster_path?: string;
+ backdrop_path?: string;
+ overview: string;
+ original_language: string;
+}
+
export interface TmdbPersonResult {
id: number;
name: string;
@@ -45,7 +57,12 @@ interface TmdbPaginatedResponse {
}
export interface TmdbSearchMultiResponse extends TmdbPaginatedResponse {
- results: (TmdbMovieResult | TmdbTvResult | TmdbPersonResult)[];
+ results: (
+ | TmdbMovieResult
+ | TmdbTvResult
+ | TmdbPersonResult
+ | TmdbCollectionResult
+ )[];
}
export interface TmdbSearchMovieResponse extends TmdbPaginatedResponse {
diff --git a/server/entity/MediaRequest.ts b/server/entity/MediaRequest.ts
index 61122afc3..e980860c6 100644
--- a/server/entity/MediaRequest.ts
+++ b/server/entity/MediaRequest.ts
@@ -704,7 +704,7 @@ export class MediaRequest {
let rootFolder = radarrSettings.activeDirectory;
let qualityProfile = radarrSettings.activeProfileId;
- let tags = radarrSettings.tags;
+ let tags = radarrSettings.tags ? [...radarrSettings.tags] : [];
if (
this.rootFolder &&
@@ -764,6 +764,38 @@ export class MediaRequest {
return;
}
+ if (radarrSettings.tagRequests) {
+ let userTag = (await radarr.getTags()).find((v) =>
+ v.label.startsWith(this.requestedBy.id + ' - ')
+ );
+ if (!userTag) {
+ logger.info(`Requester has no active tag. Creating new`, {
+ label: 'Media Request',
+ requestId: this.id,
+ mediaId: this.media.id,
+ userId: this.requestedBy.id,
+ newTag:
+ this.requestedBy.id + ' - ' + this.requestedBy.displayName,
+ });
+ userTag = await radarr.createTag({
+ label: this.requestedBy.id + ' - ' + this.requestedBy.displayName,
+ });
+ }
+ if (userTag.id) {
+ if (!tags?.find((v) => v === userTag?.id)) {
+ tags?.push(userTag.id);
+ }
+ } else {
+ logger.warn(`Requester has no tag and failed to add one`, {
+ label: 'Media Request',
+ requestId: this.id,
+ mediaId: this.media.id,
+ userId: this.requestedBy.id,
+ radarrServer: radarrSettings.hostname + ':' + radarrSettings.port,
+ });
+ }
+ }
+
if (
media[this.is4k ? 'status4k' : 'status'] === MediaStatus.AVAILABLE
) {
@@ -970,7 +1002,11 @@ export class MediaRequest {
let tags =
seriesType === 'anime'
? sonarrSettings.animeTags
- : sonarrSettings.tags;
+ ? [...sonarrSettings.animeTags]
+ : []
+ : sonarrSettings.tags
+ ? [...sonarrSettings.tags]
+ : [];
if (
this.rootFolder &&
@@ -1022,6 +1058,38 @@ export class MediaRequest {
});
}
+ if (sonarrSettings.tagRequests) {
+ let userTag = (await sonarr.getTags()).find((v) =>
+ v.label.startsWith(this.requestedBy.id + ' - ')
+ );
+ if (!userTag) {
+ logger.info(`Requester has no active tag. Creating new`, {
+ label: 'Media Request',
+ requestId: this.id,
+ mediaId: this.media.id,
+ userId: this.requestedBy.id,
+ newTag:
+ this.requestedBy.id + ' - ' + this.requestedBy.displayName,
+ });
+ userTag = await sonarr.createTag({
+ label: this.requestedBy.id + ' - ' + this.requestedBy.displayName,
+ });
+ }
+ if (userTag.id) {
+ if (!tags?.find((v) => v === userTag?.id)) {
+ tags?.push(userTag.id);
+ }
+ } else {
+ logger.warn(`Requester has no tag and failed to add one`, {
+ label: 'Media Request',
+ requestId: this.id,
+ mediaId: this.media.id,
+ userId: this.requestedBy.id,
+ sonarrServer: sonarrSettings.hostname + ':' + sonarrSettings.port,
+ });
+ }
+ }
+
const sonarrSeriesOptions: AddSeriesOptions = {
profileId: qualityProfile,
languageProfileId: languageProfile,
diff --git a/server/job/schedule.ts b/server/job/schedule.ts
index 998abf1f4..932d6107f 100644
--- a/server/job/schedule.ts
+++ b/server/job/schedule.ts
@@ -8,6 +8,7 @@ import type { JobId } from '@server/lib/settings';
import { getSettings } from '@server/lib/settings';
import watchlistSync from '@server/lib/watchlistsync';
import logger from '@server/logger';
+import random from 'lodash/random';
import schedule from 'node-schedule';
interface ScheduledJob {
@@ -60,21 +61,31 @@ export const startJobs = (): void => {
cancelFn: () => plexFullScanner.cancel(),
});
- // Run watchlist sync every 5 minutes
- scheduledJobs.push({
+ // Watchlist Sync
+ const watchlistSyncJob: ScheduledJob = {
id: 'plex-watchlist-sync',
name: 'Plex Watchlist Sync',
type: 'process',
- interval: 'minutes',
+ interval: 'fixed',
cronSchedule: jobs['plex-watchlist-sync'].schedule,
- job: schedule.scheduleJob(jobs['plex-watchlist-sync'].schedule, () => {
+ job: schedule.scheduleJob(new Date(Date.now() + 1000 * 60 * 20), () => {
logger.info('Starting scheduled job: Plex Watchlist Sync', {
label: 'Jobs',
});
watchlistSync.syncWatchlist();
}),
+ };
+
+ // To help alleviate load on Plex's servers, we will add some fuzziness to the next schedule
+ // after each run
+ watchlistSyncJob.job.on('run', () => {
+ watchlistSyncJob.job.schedule(
+ new Date(Math.floor(Date.now() + 1000 * 60 * random(14, 24, true)))
+ );
});
+ scheduledJobs.push(watchlistSyncJob);
+
// Run full radarr scan every 24 hours
scheduledJobs.push({
id: 'radarr-scan',
diff --git a/server/lib/availabilitySync.ts b/server/lib/availabilitySync.ts
index 93ccfe391..0a16302cc 100644
--- a/server/lib/availabilitySync.ts
+++ b/server/lib/availabilitySync.ts
@@ -1,13 +1,13 @@
import type { PlexMetadata } from '@server/api/plexapi';
import PlexAPI from '@server/api/plexapi';
-import RadarrAPI from '@server/api/servarr/radarr';
-import type { SonarrSeason } from '@server/api/servarr/sonarr';
+import RadarrAPI, { type RadarrMovie } from '@server/api/servarr/radarr';
+import type { SonarrSeason, SonarrSeries } from '@server/api/servarr/sonarr';
import SonarrAPI from '@server/api/servarr/sonarr';
-import { MediaStatus } from '@server/constants/media';
+import { MediaRequestStatus, MediaStatus } from '@server/constants/media';
import { getRepository } from '@server/datasource';
import Media from '@server/entity/Media';
import MediaRequest from '@server/entity/MediaRequest';
-import Season from '@server/entity/Season';
+import type Season from '@server/entity/Season';
import SeasonRequest from '@server/entity/SeasonRequest';
import { User } from '@server/entity/User';
import type { RadarrSettings, SonarrSettings } from '@server/lib/settings';
@@ -17,8 +17,8 @@ import logger from '@server/logger';
class AvailabilitySync {
public running = false;
private plexClient: PlexAPI;
- private plexSeasonsCache: Record = {};
- private sonarrSeasonsCache: Record = {};
+ private plexSeasonsCache: Record;
+ private sonarrSeasonsCache: Record;
private radarrServers: RadarrSettings[];
private sonarrServers: SonarrSettings[];
@@ -29,176 +29,179 @@ class AvailabilitySync {
this.sonarrSeasonsCache = {};
this.radarrServers = settings.radarr.filter((server) => server.syncEnabled);
this.sonarrServers = settings.sonarr.filter((server) => server.syncEnabled);
- await this.initPlexClient();
- if (!this.plexClient) {
- return;
- }
+ try {
+ logger.info(`Starting availability sync...`, {
+ label: 'AvailabilitySync',
+ });
+ const pageSize = 50;
- logger.info(`Starting availability sync...`, {
- label: 'AvailabilitySync',
- });
- const mediaRepository = getRepository(Media);
- const requestRepository = getRepository(MediaRequest);
- const seasonRepository = getRepository(Season);
- const seasonRequestRepository = getRepository(SeasonRequest);
+ const userRepository = getRepository(User);
+ const admin = await userRepository.findOne({
+ select: { id: true, plexToken: true },
+ where: { id: 1 },
+ });
- const pageSize = 50;
+ if (admin) {
+ this.plexClient = new PlexAPI({ plexToken: admin.plexToken });
+ } else {
+ logger.error('An admin is not configured.');
+ }
- try {
for await (const media of this.loadAvailableMediaPaginated(pageSize)) {
- try {
- if (!this.running) {
- throw new Error('Job aborted');
+ if (!this.running) {
+ throw new Error('Job aborted');
+ }
+
+ // Check plex, radarr, and sonarr for that specific media and
+ // if unavailable, then we change the status accordingly.
+ // If a non-4k or 4k version exists in at least one of the instances, we will only update that specific version
+ if (media.mediaType === 'movie') {
+ let movieExists = false;
+ let movieExists4k = false;
+
+ const { existsInPlex } = await this.mediaExistsInPlex(media, false);
+ const { existsInPlex: existsInPlex4k } = await this.mediaExistsInPlex(
+ media,
+ true
+ );
+
+ const existsInRadarr = await this.mediaExistsInRadarr(media, false);
+ const existsInRadarr4k = await this.mediaExistsInRadarr(media, true);
+
+ if (existsInPlex || existsInRadarr) {
+ movieExists = true;
+ logger.info(
+ `The non-4K movie [TMDB ID ${media.tmdbId}] still exists. Preventing removal.`,
+ {
+ label: 'AvailabilitySync',
+ }
+ );
}
- const mediaExists = await this.mediaExists(media);
-
- //We can not delete media so if both versions do not exist, we will change both columns to unknown or null
- if (!mediaExists) {
- if (
- media.status !== MediaStatus.UNKNOWN ||
- media.status4k !== MediaStatus.UNKNOWN
- ) {
- const request = await requestRepository.find({
- relations: {
- media: true,
- },
- where: { media: { id: media.id } },
- });
-
- logger.info(
- `${
- media.mediaType === 'tv' ? media.tvdbId : media.tmdbId
- } does not exist in any of your media instances. We will change its status to unknown.`,
- { label: 'AvailabilitySync' }
- );
-
- await mediaRepository.update(media.id, {
- status: MediaStatus.UNKNOWN,
- status4k: MediaStatus.UNKNOWN,
- serviceId: null,
- serviceId4k: null,
- externalServiceId: null,
- externalServiceId4k: null,
- externalServiceSlug: null,
- externalServiceSlug4k: null,
- ratingKey: null,
- ratingKey4k: null,
- });
-
- await requestRepository.remove(request);
- }
+ if (existsInPlex4k || existsInRadarr4k) {
+ movieExists4k = true;
+ logger.info(
+ `The 4K movie [TMDB ID ${media.tmdbId}] still exists. Preventing removal.`,
+ {
+ label: 'AvailabilitySync',
+ }
+ );
+ }
+
+ if (!movieExists && media.status === MediaStatus.AVAILABLE) {
+ await this.mediaUpdater(media, false);
+ }
+
+ if (!movieExists4k && media.status4k === MediaStatus.AVAILABLE) {
+ await this.mediaUpdater(media, true);
}
+ }
- if (media.mediaType === 'tv') {
- // ok, the show itself exists, but do all it's seasons?
- const seasons = await seasonRepository.find({
- where: [
- { status: MediaStatus.AVAILABLE, media: { id: media.id } },
- {
- status: MediaStatus.PARTIALLY_AVAILABLE,
- media: { id: media.id },
- },
- { status4k: MediaStatus.AVAILABLE, media: { id: media.id } },
- {
- status4k: MediaStatus.PARTIALLY_AVAILABLE,
- media: { id: media.id },
- },
- ],
- });
-
- let didDeleteSeasons = false;
- for (const season of seasons) {
- if (
- !mediaExists &&
- (season.status !== MediaStatus.UNKNOWN ||
- season.status4k !== MediaStatus.UNKNOWN)
- ) {
- await seasonRepository.update(
- { id: season.id },
- {
- status: MediaStatus.UNKNOWN,
- status4k: MediaStatus.UNKNOWN,
- }
- );
- } else {
- const seasonExists = await this.seasonExists(media, season);
-
- if (!seasonExists) {
- logger.info(
- `Removing season ${season.seasonNumber}, media id: ${media.tvdbId} because it does not exist in any of your media instances.`,
- { label: 'AvailabilitySync' }
- );
-
- if (
- season.status !== MediaStatus.UNKNOWN ||
- season.status4k !== MediaStatus.UNKNOWN
- ) {
- await seasonRepository.update(
- { id: season.id },
- {
- status: MediaStatus.UNKNOWN,
- status4k: MediaStatus.UNKNOWN,
- }
- );
- }
-
- const seasonToBeDeleted =
- await seasonRequestRepository.findOne({
- relations: {
- request: {
- media: true,
- },
- },
- where: {
- request: {
- media: {
- id: media.id,
- },
- },
- seasonNumber: season.seasonNumber,
- },
- });
-
- if (seasonToBeDeleted) {
- await seasonRequestRepository.remove(seasonToBeDeleted);
- }
-
- didDeleteSeasons = true;
- }
+ // If both versions still exist in plex, we still need
+ // to check through sonarr to verify season availability
+ if (media.mediaType === 'tv') {
+ let showExists = false;
+ let showExists4k = false;
+
+ const { existsInPlex, seasonsMap: plexSeasonsMap = new Map() } =
+ await this.mediaExistsInPlex(media, false);
+ const {
+ existsInPlex: existsInPlex4k,
+ seasonsMap: plexSeasonsMap4k = new Map(),
+ } = await this.mediaExistsInPlex(media, true);
+
+ const { existsInSonarr, seasonsMap: sonarrSeasonsMap } =
+ await this.mediaExistsInSonarr(media, false);
+ const {
+ existsInSonarr: existsInSonarr4k,
+ seasonsMap: sonarrSeasonsMap4k,
+ } = await this.mediaExistsInSonarr(media, true);
+
+ if (existsInPlex || existsInSonarr) {
+ showExists = true;
+ logger.info(
+ `The non-4K show [TMDB ID ${media.tmdbId}] still exists. Preventing removal.`,
+ {
+ label: 'AvailabilitySync',
}
+ );
+ }
- if (didDeleteSeasons) {
- if (
- media.status === MediaStatus.AVAILABLE ||
- media.status4k === MediaStatus.AVAILABLE
- ) {
- logger.info(
- `Marking media id: ${media.tvdbId} as PARTIALLY_AVAILABLE because we deleted some of its seasons.`,
- { label: 'AvailabilitySync' }
- );
-
- if (media.status === MediaStatus.AVAILABLE) {
- await mediaRepository.update(media.id, {
- status: MediaStatus.PARTIALLY_AVAILABLE,
- });
- }
-
- if (media.status4k === MediaStatus.AVAILABLE) {
- await mediaRepository.update(media.id, {
- status4k: MediaStatus.PARTIALLY_AVAILABLE,
- });
- }
- }
+ if (existsInPlex4k || existsInSonarr4k) {
+ showExists4k = true;
+ logger.info(
+ `The 4K show [TMDB ID ${media.tmdbId}] still exists. Preventing removal.`,
+ {
+ label: 'AvailabilitySync',
}
- }
+ );
+ }
+
+ // Here we will create a final map that will cross compare
+ // with plex and sonarr. Filtered seasons will go through
+ // each season and assume the season does not exist. If Plex or
+ // Sonarr finds that season, we will change the final seasons value
+ // to true.
+ const filteredSeasonsMap: Map = new Map();
+
+ media.seasons
+ .filter(
+ (season) =>
+ season.status === MediaStatus.AVAILABLE ||
+ season.status === MediaStatus.PARTIALLY_AVAILABLE
+ )
+ .forEach((season) =>
+ filteredSeasonsMap.set(season.seasonNumber, false)
+ );
+
+ const finalSeasons = new Map([
+ ...filteredSeasonsMap,
+ ...plexSeasonsMap,
+ ...sonarrSeasonsMap,
+ ]);
+
+ const filteredSeasonsMap4k: Map = new Map();
+
+ media.seasons
+ .filter(
+ (season) =>
+ season.status4k === MediaStatus.AVAILABLE ||
+ season.status4k === MediaStatus.PARTIALLY_AVAILABLE
+ )
+ .forEach((season) =>
+ filteredSeasonsMap4k.set(season.seasonNumber, false)
+ );
+
+ const finalSeasons4k = new Map([
+ ...filteredSeasonsMap4k,
+ ...plexSeasonsMap4k,
+ ...sonarrSeasonsMap4k,
+ ]);
+
+ if ([...finalSeasons.values()].includes(false)) {
+ await this.seasonUpdater(media, finalSeasons, false);
+ }
+
+ if ([...finalSeasons4k.values()].includes(false)) {
+ await this.seasonUpdater(media, finalSeasons4k, true);
+ }
+
+ if (
+ !showExists &&
+ (media.status === MediaStatus.AVAILABLE ||
+ media.status === MediaStatus.PARTIALLY_AVAILABLE)
+ ) {
+ await this.mediaUpdater(media, false);
+ }
+
+ if (
+ !showExists4k &&
+ (media.status4k === MediaStatus.AVAILABLE ||
+ media.status4k === MediaStatus.PARTIALLY_AVAILABLE)
+ ) {
+ await this.mediaUpdater(media, true);
}
- } catch (ex) {
- logger.error('Failure with media.', {
- errorMessage: ex.message,
- label: 'AvailabilitySync',
- });
}
}
} catch (ex) {
@@ -240,477 +243,481 @@ class AvailabilitySync {
} while (mediaPage.length > 0);
}
+ private findMediaStatus(
+ requests: MediaRequest[],
+ is4k: boolean
+ ): MediaStatus {
+ const filteredRequests = requests.filter(
+ (request) => request.is4k === is4k
+ );
+
+ let mediaStatus: MediaStatus;
+
+ if (
+ filteredRequests.some(
+ (request) => request.status === MediaRequestStatus.APPROVED
+ )
+ ) {
+ mediaStatus = MediaStatus.PROCESSING;
+ } else if (
+ filteredRequests.some(
+ (request) => request.status === MediaRequestStatus.PENDING
+ )
+ ) {
+ mediaStatus = MediaStatus.PENDING;
+ } else {
+ mediaStatus = MediaStatus.UNKNOWN;
+ }
+
+ return mediaStatus;
+ }
+
private async mediaUpdater(media: Media, is4k: boolean): Promise {
const mediaRepository = getRepository(Media);
const requestRepository = getRepository(MediaRequest);
- const isTVType = media.mediaType === 'tv';
+ try {
+ // Find all related requests only if
+ // the related media has an available status
+ const requests = await requestRepository
+ .createQueryBuilder('request')
+ .leftJoinAndSelect('request.media', 'media')
+ .where('(media.id = :id)', {
+ id: media.id,
+ })
+ .andWhere(
+ `(request.is4k = :is4k AND media.${
+ is4k ? 'status4k' : 'status'
+ } IN (:...mediaStatus))`,
+ {
+ mediaStatus: [
+ MediaStatus.AVAILABLE,
+ MediaStatus.PARTIALLY_AVAILABLE,
+ ],
+ is4k: is4k,
+ }
+ )
+ .getMany();
+
+ // Check if a season is processing or pending to
+ // make sure we set the media to the correct status
+ let mediaStatus = MediaStatus.UNKNOWN;
- const request = await requestRepository.findOne({
- relations: {
- media: true,
- },
- where: { media: { id: media.id }, is4k: is4k ? true : false },
- });
+ if (media.mediaType === 'tv') {
+ mediaStatus = this.findMediaStatus(requests, is4k);
+ }
+
+ media[is4k ? 'status4k' : 'status'] = mediaStatus;
+ media[is4k ? 'serviceId4k' : 'serviceId'] =
+ mediaStatus === MediaStatus.PROCESSING
+ ? media[is4k ? 'serviceId4k' : 'serviceId']
+ : null;
+ media[is4k ? 'externalServiceId4k' : 'externalServiceId'] =
+ mediaStatus === MediaStatus.PROCESSING
+ ? media[is4k ? 'externalServiceId4k' : 'externalServiceId']
+ : null;
+ media[is4k ? 'externalServiceSlug4k' : 'externalServiceSlug'] =
+ mediaStatus === MediaStatus.PROCESSING
+ ? media[is4k ? 'externalServiceSlug4k' : 'externalServiceSlug']
+ : null;
+ media[is4k ? 'ratingKey4k' : 'ratingKey'] =
+ mediaStatus === MediaStatus.PROCESSING
+ ? media[is4k ? 'ratingKey4k' : 'ratingKey']
+ : null;
+
+ logger.info(
+ `The ${is4k ? '4K' : 'non-4K'} ${
+ media.mediaType === 'movie' ? 'movie' : 'show'
+ } [TMDB ID ${media.tmdbId}] was not found in any ${
+ media.mediaType === 'movie' ? 'Radarr' : 'Sonarr'
+ } and Plex instance. Status will be changed to unknown.`,
+ { label: 'AvailabilitySync' }
+ );
+
+ await mediaRepository.save({ media, ...media });
- logger.info(
- `${media.tmdbId} does not exist in your ${is4k ? '4k' : 'non-4k'} ${
- isTVType ? 'sonarr' : 'radarr'
- } and plex instance. We will change its status to unknown.`,
- { label: 'AvailabilitySync' }
+ // Only delete media request if type is movie.
+ // Type tv request deletion is handled
+ // in the season request entity
+ if (requests.length > 0 && media.mediaType === 'movie') {
+ await requestRepository.remove(requests);
+ }
+ } catch (ex) {
+ logger.debug(
+ `Failure updating the ${is4k ? '4K' : 'non-4K'} ${
+ media.mediaType === 'tv' ? 'show' : 'movie'
+ } [TMDB ID ${media.tmdbId}].`,
+ {
+ errorMessage: ex.message,
+ label: 'AvailabilitySync',
+ }
+ );
+ }
+ }
+
+ private async seasonUpdater(
+ media: Media,
+ seasons: Map,
+ is4k: boolean
+ ): Promise {
+ const mediaRepository = getRepository(Media);
+ const seasonRequestRepository = getRepository(SeasonRequest);
+
+ const seasonsPendingRemoval = new Map(
+ // Disabled linter as only the value is needed from the filter
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
+ [...seasons].filter(([_, exists]) => !exists)
);
+ const seasonKeys = [...seasonsPendingRemoval.keys()];
- await mediaRepository.update(
- media.id,
- is4k
- ? {
- status4k: MediaStatus.UNKNOWN,
- serviceId4k: null,
- externalServiceId4k: null,
- externalServiceSlug4k: null,
- ratingKey4k: null,
- }
- : {
- status: MediaStatus.UNKNOWN,
- serviceId: null,
- externalServiceId: null,
- externalServiceSlug: null,
- ratingKey: null,
+ try {
+ // Need to check and see if there are any related season
+ // requests. If they are, we will need to delete them.
+ const seasonRequests = await seasonRequestRepository
+ .createQueryBuilder('seasonRequest')
+ .leftJoinAndSelect('seasonRequest.request', 'request')
+ .leftJoinAndSelect('request.media', 'media')
+ .where('(media.id = :id)', { id: media.id })
+ .andWhere(
+ '(request.is4k = :is4k AND seasonRequest.seasonNumber IN (:...seasonNumbers))',
+ {
+ seasonNumbers: seasonKeys,
+ is4k: is4k,
}
- );
+ )
+ .getMany();
+
+ for (const mediaSeason of media.seasons) {
+ if (seasonsPendingRemoval.has(mediaSeason.seasonNumber)) {
+ mediaSeason[is4k ? 'status4k' : 'status'] = MediaStatus.UNKNOWN;
+ }
+ }
+
+ if (media.status === MediaStatus.AVAILABLE) {
+ media.status = MediaStatus.PARTIALLY_AVAILABLE;
+ logger.info(
+ `Marking the non-4K show [TMDB ID ${media.tmdbId}] as PARTIALLY_AVAILABLE because season removal has occurred.`,
+ { label: 'AvailabilitySync' }
+ );
+ }
+
+ if (media.status4k === MediaStatus.AVAILABLE) {
+ media.status4k = MediaStatus.PARTIALLY_AVAILABLE;
+ logger.info(
+ `Marking the 4K show [TMDB ID ${media.tmdbId}] as PARTIALLY_AVAILABLE because season removal has occurred.`,
+ { label: 'AvailabilitySync' }
+ );
+ }
+
+ await mediaRepository.save({ media, ...media });
- if (isTVType) {
- const seasonRepository = getRepository(Season);
+ if (seasonRequests.length > 0) {
+ await seasonRequestRepository.remove(seasonRequests);
+ }
- await seasonRepository?.update(
- { media: { id: media.id } },
- is4k
- ? { status4k: MediaStatus.UNKNOWN }
- : { status: MediaStatus.UNKNOWN }
+ logger.info(
+ `The ${is4k ? '4K' : 'non-4K'} season(s) [${seasonKeys}] [TMDB ID ${
+ media.tmdbId
+ }] was not found in any ${
+ media.mediaType === 'tv' ? 'Sonarr' : 'Radarr'
+ } and Plex instance. Status will be changed to unknown.`,
+ { label: 'AvailabilitySync' }
+ );
+ } catch (ex) {
+ logger.debug(
+ `Failure updating the ${
+ is4k ? '4K' : 'non-4K'
+ } season(s) [${seasonKeys}], TMDB ID ${media.tmdbId}.`,
+ {
+ errorMessage: ex.message,
+ label: 'AvailabilitySync',
+ }
);
}
-
- await requestRepository.delete({ id: request?.id });
}
private async mediaExistsInRadarr(
media: Media,
- existsInPlex: boolean,
- existsInPlex4k: boolean
+ is4k: boolean
): Promise {
- let existsInRadarr = true;
- let existsInRadarr4k = true;
+ let existsInRadarr = false;
+ // Check for availability in all of the available radarr servers
+ // If any find the media, we will assume the media exists
for (const server of this.radarrServers) {
- const api = new RadarrAPI({
+ const radarrAPI = new RadarrAPI({
apiKey: server.apiKey,
url: RadarrAPI.buildUrl(server, '/api/v3'),
});
- const meta = await api.getMovieByTmdbId(media.tmdbId);
-
- //check if both exist or if a single non-4k or 4k exists
- //if both do not exist we will return false
- if (!server.is4k && !meta.id) {
- existsInRadarr = false;
- }
-
- if (server.is4k && !meta.id) {
- existsInRadarr4k = false;
- }
- }
-
- if (existsInRadarr && existsInRadarr4k) {
- return true;
- }
- if (!existsInRadarr && existsInPlex) {
- return true;
- }
+ try {
+ let radarr: RadarrMovie | undefined;
- if (!existsInRadarr4k && existsInPlex4k) {
- return true;
- }
+ if (!server.is4k && media.externalServiceId && !is4k) {
+ radarr = await radarrAPI.getMovie({
+ id: media.externalServiceId,
+ });
+ }
- //if only a single non-4k or 4k exists, then change entity columns accordingly
- //related media request will then be deleted
- if (!existsInRadarr && existsInRadarr4k && !existsInPlex) {
- if (media.status !== MediaStatus.UNKNOWN) {
- this.mediaUpdater(media, false);
- }
- }
+ if (server.is4k && media.externalServiceId4k && is4k) {
+ radarr = await radarrAPI.getMovie({
+ id: media.externalServiceId4k,
+ });
+ }
- if (existsInRadarr && !existsInRadarr4k && !existsInPlex4k) {
- if (media.status4k !== MediaStatus.UNKNOWN) {
- this.mediaUpdater(media, true);
+ if (radarr && radarr.hasFile) {
+ existsInRadarr = true;
+ }
+ } catch (ex) {
+ if (!ex.message.includes('404')) {
+ existsInRadarr = true;
+ logger.debug(
+ `Failure retrieving the ${is4k ? '4K' : 'non-4K'} movie [TMDB ID ${
+ media.tmdbId
+ }] from Radarr.`,
+ {
+ errorMessage: ex.message,
+ label: 'AvailabilitySync',
+ }
+ );
+ }
}
}
- if (existsInRadarr || existsInRadarr4k) {
- return true;
- }
-
- return false;
+ return existsInRadarr;
}
private async mediaExistsInSonarr(
media: Media,
- existsInPlex: boolean,
- existsInPlex4k: boolean
- ): Promise {
- if (!media.tvdbId) {
- return false;
- }
-
- let existsInSonarr = true;
- let existsInSonarr4k = true;
+ is4k: boolean
+ ): Promise<{ existsInSonarr: boolean; seasonsMap: Map }> {
+ let existsInSonarr = false;
+ let preventSeasonSearch = false;
+ // Check for availability in all of the available sonarr servers
+ // If any find the media, we will assume the media exists
for (const server of this.sonarrServers) {
- const api = new SonarrAPI({
+ const sonarrAPI = new SonarrAPI({
apiKey: server.apiKey,
url: SonarrAPI.buildUrl(server, '/api/v3'),
});
- const meta = await api.getSeriesByTvdbId(media.tvdbId);
+ try {
+ let sonarr: SonarrSeries | undefined;
- this.sonarrSeasonsCache[`${server.id}-${media.tvdbId}`] = meta.seasons;
+ if (!server.is4k && media.externalServiceId && !is4k) {
+ sonarr = await sonarrAPI.getSeriesById(media.externalServiceId);
+ this.sonarrSeasonsCache[`${server.id}-${media.externalServiceId}`] =
+ sonarr.seasons;
+ }
- //check if both exist or if a single non-4k or 4k exists
- //if both do not exist we will return false
- if (!server.is4k && !meta.id) {
- existsInSonarr = false;
- }
+ if (server.is4k && media.externalServiceId4k && is4k) {
+ sonarr = await sonarrAPI.getSeriesById(media.externalServiceId4k);
+ this.sonarrSeasonsCache[`${server.id}-${media.externalServiceId4k}`] =
+ sonarr.seasons;
+ }
- if (server.is4k && !meta.id) {
- existsInSonarr4k = false;
+ if (sonarr && sonarr.statistics.episodeFileCount > 0) {
+ existsInSonarr = true;
+ }
+ } catch (ex) {
+ if (!ex.message.includes('404')) {
+ existsInSonarr = true;
+ preventSeasonSearch = true;
+ logger.debug(
+ `Failure retrieving the ${is4k ? '4K' : 'non-4K'} show [TMDB ID ${
+ media.tmdbId
+ }] from Sonarr.`,
+ {
+ errorMessage: ex.message,
+ label: 'AvailabilitySync',
+ }
+ );
+ }
}
}
- if (existsInSonarr && existsInSonarr4k) {
- return true;
- }
+ // Here we check each season for availability
+ // If the API returns an error other than a 404,
+ // we will have to prevent the season check from happening
+ const seasonsMap: Map = new Map();
- if (!existsInSonarr && existsInPlex) {
- return true;
- }
-
- if (!existsInSonarr4k && existsInPlex4k) {
- return true;
- }
+ if (!preventSeasonSearch) {
+ const filteredSeasons = media.seasons.filter(
+ (season) =>
+ season[is4k ? 'status4k' : 'status'] === MediaStatus.AVAILABLE ||
+ season[is4k ? 'status4k' : 'status'] ===
+ MediaStatus.PARTIALLY_AVAILABLE
+ );
- //if only a single non-4k or 4k exists, then change entity columns accordingly
- //related media request will then be deleted
- if (!existsInSonarr && existsInSonarr4k && !existsInPlex) {
- if (media.status !== MediaStatus.UNKNOWN) {
- this.mediaUpdater(media, false);
- }
- }
+ for (const season of filteredSeasons) {
+ const seasonExists = await this.seasonExistsInSonarr(
+ media,
+ season,
+ is4k
+ );
- if (existsInSonarr && !existsInSonarr4k && !existsInPlex4k) {
- if (media.status4k !== MediaStatus.UNKNOWN) {
- this.mediaUpdater(media, true);
+ if (seasonExists) {
+ seasonsMap.set(season.seasonNumber, true);
+ }
}
}
- if (existsInSonarr || existsInSonarr4k) {
- return true;
- }
-
- return false;
+ return { existsInSonarr, seasonsMap };
}
private async seasonExistsInSonarr(
media: Media,
season: Season,
- seasonExistsInPlex: boolean,
- seasonExistsInPlex4k: boolean
+ is4k: boolean
): Promise {
- if (!media.tvdbId) {
- return false;
- }
-
- let seasonExistsInSonarr = true;
- let seasonExistsInSonarr4k = true;
-
- const mediaRepository = getRepository(Media);
- const seasonRepository = getRepository(Season);
- const seasonRequestRepository = getRepository(SeasonRequest);
+ let seasonExists = false;
+ // Check each sonarr instance to see if the media still exists
+ // If found, we will assume the media exists and prevent removal
+ // We can use the cache we built when we fetched the series with mediaExistsInSonarr
for (const server of this.sonarrServers) {
- const api = new SonarrAPI({
- apiKey: server.apiKey,
- url: SonarrAPI.buildUrl(server, '/api/v3'),
- });
-
- const seasons =
- this.sonarrSeasonsCache[`${server.id}-${media.tvdbId}`] ??
- (await api.getSeriesByTvdbId(media.tvdbId)).seasons;
- this.sonarrSeasonsCache[`${server.id}-${media.tvdbId}`] = seasons;
-
- const hasMonitoredSeason = seasons.find(
- ({ monitored, seasonNumber }) =>
- monitored && season.seasonNumber === seasonNumber
- );
+ let sonarrSeasons: SonarrSeason[] | undefined;
- if (!server.is4k && !hasMonitoredSeason) {
- seasonExistsInSonarr = false;
+ if (media.externalServiceId && !is4k) {
+ sonarrSeasons =
+ this.sonarrSeasonsCache[`${server.id}-${media.externalServiceId}`];
}
- if (server.is4k && !hasMonitoredSeason) {
- seasonExistsInSonarr4k = false;
- }
- }
-
- if (seasonExistsInSonarr && seasonExistsInSonarr4k) {
- return true;
- }
-
- if (!seasonExistsInSonarr && seasonExistsInPlex) {
- return true;
- }
-
- if (!seasonExistsInSonarr4k && seasonExistsInPlex4k) {
- return true;
- }
-
- const seasonToBeDeleted = await seasonRequestRepository.findOne({
- relations: {
- request: {
- media: true,
- },
- },
- where: {
- request: {
- is4k: seasonExistsInSonarr ? true : false,
- media: {
- id: media.id,
- },
- },
- seasonNumber: season.seasonNumber,
- },
- });
-
- //if season does not exist, we will change status to unknown and delete related season request
- //if parent media request is empty(all related seasons have been removed), parent is automatically deleted
- if (
- !seasonExistsInSonarr &&
- seasonExistsInSonarr4k &&
- !seasonExistsInPlex
- ) {
- if (season.status !== MediaStatus.UNKNOWN) {
- logger.info(
- `${media.tvdbId}, season: ${season.seasonNumber} does not exist in your non-4k sonarr and plex instance. We will change its status to unknown.`,
- { label: 'AvailabilitySync' }
- );
- await seasonRepository.update(season.id, {
- status: MediaStatus.UNKNOWN,
- });
-
- if (seasonToBeDeleted) {
- await seasonRequestRepository.remove(seasonToBeDeleted);
- }
-
- if (media.status === MediaStatus.AVAILABLE) {
- logger.info(
- `Marking media id: ${media.tvdbId} as PARTIALLY_AVAILABLE because we deleted one of its seasons.`,
- { label: 'AvailabilitySync' }
- );
- await mediaRepository.update(media.id, {
- status: MediaStatus.PARTIALLY_AVAILABLE,
- });
- }
+ if (media.externalServiceId4k && is4k) {
+ sonarrSeasons =
+ this.sonarrSeasonsCache[`${server.id}-${media.externalServiceId4k}`];
}
- }
-
- if (
- seasonExistsInSonarr &&
- !seasonExistsInSonarr4k &&
- !seasonExistsInPlex4k
- ) {
- if (season.status4k !== MediaStatus.UNKNOWN) {
- logger.info(
- `${media.tvdbId}, season: ${season.seasonNumber} does not exist in your 4k sonarr and plex instance. We will change its status to unknown.`,
- { label: 'AvailabilitySync' }
- );
- await seasonRepository.update(season.id, {
- status4k: MediaStatus.UNKNOWN,
- });
- if (seasonToBeDeleted) {
- await seasonRequestRepository.remove(seasonToBeDeleted);
- }
+ const seasonIsAvailable = sonarrSeasons?.find(
+ ({ seasonNumber, statistics }) =>
+ season.seasonNumber === seasonNumber &&
+ statistics?.episodeFileCount &&
+ statistics?.episodeFileCount > 0
+ );
- if (media.status4k === MediaStatus.AVAILABLE) {
- logger.info(
- `Marking media id: ${media.tvdbId} as PARTIALLY_AVAILABLE because we deleted one of its seasons.`,
- { label: 'AvailabilitySync' }
- );
- await mediaRepository.update(media.id, {
- status4k: MediaStatus.PARTIALLY_AVAILABLE,
- });
- }
+ if (seasonIsAvailable && sonarrSeasons) {
+ seasonExists = true;
}
}
- if (seasonExistsInSonarr || seasonExistsInSonarr4k) {
- return true;
- }
-
- return false;
+ return seasonExists;
}
- private async mediaExists(media: Media): Promise {
+ private async mediaExistsInPlex(
+ media: Media,
+ is4k: boolean
+ ): Promise<{ existsInPlex: boolean; seasonsMap?: Map }> {
const ratingKey = media.ratingKey;
const ratingKey4k = media.ratingKey4k;
-
let existsInPlex = false;
- let existsInPlex4k = false;
+ let preventSeasonSearch = false;
- //check each plex instance to see if media exists
+ // Check each plex instance to see if the media still exists
+ // If found, we will assume the media exists and prevent removal
+ // We can use the cache we built when we fetched the series with mediaExistsInPlex
try {
- if (ratingKey) {
- const meta = await this.plexClient?.getMetadata(ratingKey);
- if (meta) {
- existsInPlex = true;
+ let plexMedia: PlexMetadata | undefined;
+
+ if (ratingKey && !is4k) {
+ plexMedia = await this.plexClient?.getMetadata(ratingKey);
+
+ if (media.mediaType === 'tv') {
+ this.plexSeasonsCache[ratingKey] =
+ await this.plexClient?.getChildrenMetadata(ratingKey);
}
}
- if (ratingKey4k) {
- const meta4k = await this.plexClient?.getMetadata(ratingKey4k);
- if (meta4k) {
- existsInPlex4k = true;
+
+ if (ratingKey4k && is4k) {
+ plexMedia = await this.plexClient?.getMetadata(ratingKey4k);
+
+ if (media.mediaType === 'tv') {
+ this.plexSeasonsCache[ratingKey4k] =
+ await this.plexClient?.getChildrenMetadata(ratingKey4k);
}
}
- } catch (ex) {
- // TODO: oof, not the nicest way of handling this, but plex-api does not leave us with any other options...
- if (!ex.message.includes('response code: 404')) {
- throw ex;
- }
- }
- //base case for if both media versions exist in plex
- if (existsInPlex && existsInPlex4k) {
- return true;
- }
-
- //we then check radarr or sonarr has that specific media. If not, then we will move to delete
- //if a non-4k or 4k version exists in at least one of the instances, we will only update that specific version
- if (media.mediaType === 'movie') {
- const existsInRadarr = await this.mediaExistsInRadarr(
- media,
- existsInPlex,
- existsInPlex4k
- );
- //if true, media exists in at least one radarr or plex instance.
- if (existsInRadarr) {
- logger.warn(
- `${media.tmdbId} exists in at least one radarr or plex instance. Media will be updated if set to available.`,
+ if (plexMedia) {
+ existsInPlex = true;
+ }
+ } catch (ex) {
+ if (!ex.message.includes('404')) {
+ existsInPlex = true;
+ preventSeasonSearch = true;
+ logger.debug(
+ `Failure retrieving the ${is4k ? '4K' : 'non-4K'} ${
+ media.mediaType === 'tv' ? 'show' : 'movie'
+ } [TMDB ID ${media.tmdbId}] from Plex.`,
{
+ errorMessage: ex.message,
label: 'AvailabilitySync',
}
);
-
- return true;
}
}
+ // Here we check each season in plex for availability
+ // If the API returns an error other than a 404,
+ // we will have to prevent the season check from happening
if (media.mediaType === 'tv') {
- const existsInSonarr = await this.mediaExistsInSonarr(
- media,
- existsInPlex,
- existsInPlex4k
- );
-
- //if true, media exists in at least one sonarr or plex instance.
- if (existsInSonarr) {
- logger.warn(
- `${media.tvdbId} exists in at least one sonarr or plex instance. Media will be updated if set to available.`,
- {
- label: 'AvailabilitySync',
- }
+ const seasonsMap: Map = new Map();
+
+ if (!preventSeasonSearch) {
+ const filteredSeasons = media.seasons.filter(
+ (season) =>
+ season[is4k ? 'status4k' : 'status'] === MediaStatus.AVAILABLE ||
+ season[is4k ? 'status4k' : 'status'] ===
+ MediaStatus.PARTIALLY_AVAILABLE
);
- return true;
+ for (const season of filteredSeasons) {
+ const seasonExists = await this.seasonExistsInPlex(
+ media,
+ season,
+ is4k
+ );
+
+ if (seasonExists) {
+ seasonsMap.set(season.seasonNumber, true);
+ }
+ }
}
+
+ return { existsInPlex, seasonsMap };
}
- return false;
+ return { existsInPlex };
}
- private async seasonExists(media: Media, season: Season) {
+ private async seasonExistsInPlex(
+ media: Media,
+ season: Season,
+ is4k: boolean
+ ): Promise {
const ratingKey = media.ratingKey;
const ratingKey4k = media.ratingKey4k;
-
let seasonExistsInPlex = false;
- let seasonExistsInPlex4k = false;
-
- if (ratingKey) {
- const children =
- this.plexSeasonsCache[ratingKey] ??
- (await this.plexClient?.getChildrenMetadata(ratingKey)) ??
- [];
- this.plexSeasonsCache[ratingKey] = children;
- const seasonMeta = children?.find(
- (child) => child.index === season.seasonNumber
- );
-
- if (seasonMeta) {
- seasonExistsInPlex = true;
- }
- }
- if (ratingKey4k) {
- const children4k =
- this.plexSeasonsCache[ratingKey4k] ??
- (await this.plexClient?.getChildrenMetadata(ratingKey4k)) ??
- [];
- this.plexSeasonsCache[ratingKey4k] = children4k;
- const seasonMeta4k = children4k?.find(
- (child) => child.index === season.seasonNumber
- );
+ // Check each plex instance to see if the season exists
+ let plexSeasons: PlexMetadata[] | undefined;
- if (seasonMeta4k) {
- seasonExistsInPlex4k = true;
- }
+ if (ratingKey && !is4k) {
+ plexSeasons = this.plexSeasonsCache[ratingKey];
}
- //base case for if both season versions exist in plex
- if (seasonExistsInPlex && seasonExistsInPlex4k) {
- return true;
+ if (ratingKey4k && is4k) {
+ plexSeasons = this.plexSeasonsCache[ratingKey4k];
}
- const existsInSonarr = await this.seasonExistsInSonarr(
- media,
- season,
- seasonExistsInPlex,
- seasonExistsInPlex4k
+ const seasonIsAvailable = plexSeasons?.find(
+ (plexSeason) => plexSeason.index === season.seasonNumber
);
- if (existsInSonarr) {
- logger.warn(
- `${media.tvdbId}, season: ${season.seasonNumber} exists in at least one sonarr or plex instance. Media will be updated if set to available.`,
- {
- label: 'AvailabilitySync',
- }
- );
-
- return true;
- }
-
- return false;
- }
-
- private async initPlexClient() {
- const userRepository = getRepository(User);
- const admin = await userRepository.findOne({
- select: { id: true, plexToken: true },
- where: { id: 1 },
- });
-
- if (!admin) {
- logger.warning('No admin configured. Availability sync skipped.');
- return;
+ if (seasonIsAvailable) {
+ seasonExistsInPlex = true;
}
- this.plexClient = new PlexAPI({ plexToken: admin.plexToken });
+ return seasonExistsInPlex;
}
}
diff --git a/server/lib/cache.ts b/server/lib/cache.ts
index e81466629..011205e7f 100644
--- a/server/lib/cache.ts
+++ b/server/lib/cache.ts
@@ -5,6 +5,7 @@ export type AvailableCacheIds =
| 'radarr'
| 'sonarr'
| 'rt'
+ | 'imdb'
| 'github'
| 'plexguid'
| 'plextv';
@@ -51,6 +52,10 @@ class CacheManager {
stdTtl: 43200,
checkPeriod: 60 * 30,
}),
+ imdb: new Cache('imdb', 'IMDB Radarr Proxy', {
+ stdTtl: 43200,
+ checkPeriod: 60 * 30,
+ }),
github: new Cache('github', 'GitHub API', {
stdTtl: 21600,
checkPeriod: 60 * 30,
diff --git a/server/lib/settings.ts b/server/lib/settings.ts
index a6f3a76a0..88467f635 100644
--- a/server/lib/settings.ts
+++ b/server/lib/settings.ts
@@ -61,6 +61,7 @@ export interface DVRSettings {
externalUrl?: string;
syncEnabled: boolean;
preventSearch: boolean;
+ tagRequests: boolean;
}
export interface RadarrSettings extends DVRSettings {
@@ -378,7 +379,7 @@ class Settings {
options: {
webhookUrl: '',
jsonPayload:
- 'IntcbiAgICBcIm5vdGlmaWNhdGlvbl90eXBlXCI6IFwie3tub3RpZmljYXRpb25fdHlwZX19XCIsXG4gICAgXCJldmVudFwiOiBcInt7ZXZlbnR9fVwiLFxuICAgIFwic3ViamVjdFwiOiBcInt7c3ViamVjdH19XCIsXG4gICAgXCJtZXNzYWdlXCI6IFwie3ttZXNzYWdlfX1cIixcbiAgICBcImltYWdlXCI6IFwie3tpbWFnZX19XCIsXG4gICAgXCJ7e21lZGlhfX1cIjoge1xuICAgICAgICBcIm1lZGlhX3R5cGVcIjogXCJ7e21lZGlhX3R5cGV9fVwiLFxuICAgICAgICBcInRtZGJJZFwiOiBcInt7bWVkaWFfdG1kYmlkfX1cIixcbiAgICAgICAgXCJ0dmRiSWRcIjogXCJ7e21lZGlhX3R2ZGJpZH19XCIsXG4gICAgICAgIFwic3RhdHVzXCI6IFwie3ttZWRpYV9zdGF0dXN9fVwiLFxuICAgICAgICBcInN0YXR1czRrXCI6IFwie3ttZWRpYV9zdGF0dXM0a319XCJcbiAgICB9LFxuICAgIFwie3tyZXF1ZXN0fX1cIjoge1xuICAgICAgICBcInJlcXVlc3RfaWRcIjogXCJ7e3JlcXVlc3RfaWR9fVwiLFxuICAgICAgICBcInJlcXVlc3RlZEJ5X2VtYWlsXCI6IFwie3tyZXF1ZXN0ZWRCeV9lbWFpbH19XCIsXG4gICAgICAgIFwicmVxdWVzdGVkQnlfdXNlcm5hbWVcIjogXCJ7e3JlcXVlc3RlZEJ5X3VzZXJuYW1lfX1cIixcbiAgICAgICAgXCJyZXF1ZXN0ZWRCeV9hdmF0YXJcIjogXCJ7e3JlcXVlc3RlZEJ5X2F2YXRhcn19XCJcbiAgICB9LFxuICAgIFwie3tpc3N1ZX19XCI6IHtcbiAgICAgICAgXCJpc3N1ZV9pZFwiOiBcInt7aXNzdWVfaWR9fVwiLFxuICAgICAgICBcImlzc3VlX3R5cGVcIjogXCJ7e2lzc3VlX3R5cGV9fVwiLFxuICAgICAgICBcImlzc3VlX3N0YXR1c1wiOiBcInt7aXNzdWVfc3RhdHVzfX1cIixcbiAgICAgICAgXCJyZXBvcnRlZEJ5X2VtYWlsXCI6IFwie3tyZXBvcnRlZEJ5X2VtYWlsfX1cIixcbiAgICAgICAgXCJyZXBvcnRlZEJ5X3VzZXJuYW1lXCI6IFwie3tyZXBvcnRlZEJ5X3VzZXJuYW1lfX1cIixcbiAgICAgICAgXCJyZXBvcnRlZEJ5X2F2YXRhclwiOiBcInt7cmVwb3J0ZWRCeV9hdmF0YXJ9fVwiXG4gICAgfSxcbiAgICBcInt7Y29tbWVudH19XCI6IHtcbiAgICAgICAgXCJjb21tZW50X21lc3NhZ2VcIjogXCJ7e2NvbW1lbnRfbWVzc2FnZX19XCIsXG4gICAgICAgIFwiY29tbWVudGVkQnlfZW1haWxcIjogXCJ7e2NvbW1lbnRlZEJ5X2VtYWlsfX1cIixcbiAgICAgICAgXCJjb21tZW50ZWRCeV91c2VybmFtZVwiOiBcInt7Y29tbWVudGVkQnlfdXNlcm5hbWV9fVwiLFxuICAgICAgICBcImNvbW1lbnRlZEJ5X2F2YXRhclwiOiBcInt7Y29tbWVudGVkQnlfYXZhdGFyfX1cIlxuICAgIH0sXG4gICAgXCJ7e2V4dHJhfX1cIjogW11cbn0i',
+ 'IntcbiAgXCJub3RpZmljYXRpb25fdHlwZVwiOiBcInt7bm90aWZpY2F0aW9uX3R5cGV9fVwiLFxuICBcImV2ZW50XCI6IFwie3tldmVudH19XCIsXG4gIFwic3ViamVjdFwiOiBcInt7c3ViamVjdH19XCIsXG4gIFwibWVzc2FnZVwiOiBcInt7bWVzc2FnZX19XCIsXG4gIFwiaW1hZ2VcIjogXCJ7e2ltYWdlfX1cIixcbiAgXCJ7e21lZGlhfX1cIjoge1xuICAgIFwibWVkaWFfdHlwZVwiOiBcInt7bWVkaWFfdHlwZX19XCIsXG4gICAgXCJ0bWRiSWRcIjogXCJ7e21lZGlhX3RtZGJpZH19XCIsXG4gICAgXCJ0dmRiSWRcIjogXCJ7e21lZGlhX3R2ZGJpZH19XCIsXG4gICAgXCJzdGF0dXNcIjogXCJ7e21lZGlhX3N0YXR1c319XCIsXG4gICAgXCJzdGF0dXM0a1wiOiBcInt7bWVkaWFfc3RhdHVzNGt9fVwiXG4gIH0sXG4gIFwie3tyZXF1ZXN0fX1cIjoge1xuICAgIFwicmVxdWVzdF9pZFwiOiBcInt7cmVxdWVzdF9pZH19XCIsXG4gICAgXCJyZXF1ZXN0ZWRCeV9lbWFpbFwiOiBcInt7cmVxdWVzdGVkQnlfZW1haWx9fVwiLFxuICAgIFwicmVxdWVzdGVkQnlfdXNlcm5hbWVcIjogXCJ7e3JlcXVlc3RlZEJ5X3VzZXJuYW1lfX1cIixcbiAgICBcInJlcXVlc3RlZEJ5X2F2YXRhclwiOiBcInt7cmVxdWVzdGVkQnlfYXZhdGFyfX1cIixcbiAgICBcInJlcXVlc3RlZEJ5X3NldHRpbmdzX2Rpc2NvcmRJZFwiOiBcInt7cmVxdWVzdGVkQnlfc2V0dGluZ3NfZGlzY29yZElkfX1cIixcbiAgICBcInJlcXVlc3RlZEJ5X3NldHRpbmdzX3RlbGVncmFtQ2hhdElkXCI6IFwie3tyZXF1ZXN0ZWRCeV9zZXR0aW5nc190ZWxlZ3JhbUNoYXRJZH19XCJcbiAgfSxcbiAgXCJ7e2lzc3VlfX1cIjoge1xuICAgIFwiaXNzdWVfaWRcIjogXCJ7e2lzc3VlX2lkfX1cIixcbiAgICBcImlzc3VlX3R5cGVcIjogXCJ7e2lzc3VlX3R5cGV9fVwiLFxuICAgIFwiaXNzdWVfc3RhdHVzXCI6IFwie3tpc3N1ZV9zdGF0dXN9fVwiLFxuICAgIFwicmVwb3J0ZWRCeV9lbWFpbFwiOiBcInt7cmVwb3J0ZWRCeV9lbWFpbH19XCIsXG4gICAgXCJyZXBvcnRlZEJ5X3VzZXJuYW1lXCI6IFwie3tyZXBvcnRlZEJ5X3VzZXJuYW1lfX1cIixcbiAgICBcInJlcG9ydGVkQnlfYXZhdGFyXCI6IFwie3tyZXBvcnRlZEJ5X2F2YXRhcn19XCIsXG4gICAgXCJyZXBvcnRlZEJ5X3NldHRpbmdzX2Rpc2NvcmRJZFwiOiBcInt7cmVwb3J0ZWRCeV9zZXR0aW5nc19kaXNjb3JkSWR9fVwiLFxuICAgIFwicmVwb3J0ZWRCeV9zZXR0aW5nc190ZWxlZ3JhbUNoYXRJZFwiOiBcInt7cmVwb3J0ZWRCeV9zZXR0aW5nc190ZWxlZ3JhbUNoYXRJZH19XCJcbiAgfSxcbiAgXCJ7e2NvbW1lbnR9fVwiOiB7XG4gICAgXCJjb21tZW50X21lc3NhZ2VcIjogXCJ7e2NvbW1lbnRfbWVzc2FnZX19XCIsXG4gICAgXCJjb21tZW50ZWRCeV9lbWFpbFwiOiBcInt7Y29tbWVudGVkQnlfZW1haWx9fVwiLFxuICAgIFwiY29tbWVudGVkQnlfdXNlcm5hbWVcIjogXCJ7e2NvbW1lbnRlZEJ5X3VzZXJuYW1lfX1cIixcbiAgICBcImNvbW1lbnRlZEJ5X2F2YXRhclwiOiBcInt7Y29tbWVudGVkQnlfYXZhdGFyfX1cIixcbiAgICBcImNvbW1lbnRlZEJ5X3NldHRpbmdzX2Rpc2NvcmRJZFwiOiBcInt7Y29tbWVudGVkQnlfc2V0dGluZ3NfZGlzY29yZElkfX1cIixcbiAgICBcImNvbW1lbnRlZEJ5X3NldHRpbmdzX3RlbGVncmFtQ2hhdElkXCI6IFwie3tjb21tZW50ZWRCeV9zZXR0aW5nc190ZWxlZ3JhbUNoYXRJZH19XCJcbiAgfSxcbiAgXCJ7e2V4dHJhfX1cIjogW11cbn0i',
},
},
webpush: {
diff --git a/server/models/Search.ts b/server/models/Search.ts
index 6ab696fe3..2193bbe15 100644
--- a/server/models/Search.ts
+++ b/server/models/Search.ts
@@ -1,4 +1,5 @@
import type {
+ TmdbCollectionResult,
TmdbMovieDetails,
TmdbMovieResult,
TmdbPersonDetails,
@@ -9,7 +10,7 @@ import type {
import { MediaType as MainMediaType } from '@server/constants/media';
import type Media from '@server/entity/Media';
-export type MediaType = 'tv' | 'movie' | 'person';
+export type MediaType = 'tv' | 'movie' | 'person' | 'collection';
interface SearchResult {
id: number;
@@ -43,6 +44,18 @@ export interface TvResult extends SearchResult {
firstAirDate: string;
}
+export interface CollectionResult {
+ id: number;
+ mediaType: 'collection';
+ title: string;
+ originalTitle: string;
+ adult: boolean;
+ posterPath?: string;
+ backdropPath?: string;
+ overview: string;
+ originalLanguage: string;
+}
+
export interface PersonResult {
id: number;
name: string;
@@ -53,7 +66,7 @@ export interface PersonResult {
knownFor: (MovieResult | TvResult)[];
}
-export type Results = MovieResult | TvResult | PersonResult;
+export type Results = MovieResult | TvResult | PersonResult | CollectionResult;
export const mapMovieResult = (
movieResult: TmdbMovieResult,
@@ -99,6 +112,20 @@ export const mapTvResult = (
mediaInfo: media,
});
+export const mapCollectionResult = (
+ collectionResult: TmdbCollectionResult
+): CollectionResult => ({
+ id: collectionResult.id,
+ mediaType: collectionResult.media_type || 'collection',
+ adult: collectionResult.adult,
+ originalLanguage: collectionResult.original_language,
+ originalTitle: collectionResult.original_title,
+ title: collectionResult.title,
+ overview: collectionResult.overview,
+ backdropPath: collectionResult.backdrop_path,
+ posterPath: collectionResult.poster_path,
+});
+
export const mapPersonResult = (
personResult: TmdbPersonResult
): PersonResult => ({
@@ -118,7 +145,12 @@ export const mapPersonResult = (
});
export const mapSearchResults = (
- results: (TmdbMovieResult | TmdbTvResult | TmdbPersonResult)[],
+ results: (
+ | TmdbMovieResult
+ | TmdbTvResult
+ | TmdbPersonResult
+ | TmdbCollectionResult
+ )[],
media?: Media[]
): Results[] =>
results.map((result) => {
@@ -139,6 +171,8 @@ export const mapSearchResults = (
req.tmdbId === result.id && req.mediaType === MainMediaType.TV
)
);
+ case 'collection':
+ return mapCollectionResult(result);
default:
return mapPersonResult(result);
}
diff --git a/server/routes/discover.ts b/server/routes/discover.ts
index f032fa66b..487d1a329 100644
--- a/server/routes/discover.ts
+++ b/server/routes/discover.ts
@@ -14,12 +14,13 @@ import { getSettings } from '@server/lib/settings';
import logger from '@server/logger';
import { mapProductionCompany } from '@server/models/Movie';
import {
+ mapCollectionResult,
mapMovieResult,
mapPersonResult,
mapTvResult,
} from '@server/models/Search';
import { mapNetwork } from '@server/models/Tv';
-import { isMovie, isPerson } from '@server/utils/typeHelpers';
+import { isCollection, isMovie, isPerson } from '@server/utils/typeHelpers';
import { Router } from 'express';
import { sortBy } from 'lodash';
import { z } from 'zod';
@@ -64,6 +65,8 @@ const QueryFilterOptions = z.object({
withRuntimeLte: z.coerce.string().optional(),
voteAverageGte: z.coerce.string().optional(),
voteAverageLte: z.coerce.string().optional(),
+ voteCountGte: z.coerce.string().optional(),
+ voteCountLte: z.coerce.string().optional(),
network: z.coerce.string().optional(),
watchProviders: z.coerce.string().optional(),
watchRegion: z.coerce.string().optional(),
@@ -95,6 +98,8 @@ discoverRoutes.get('/movies', async (req, res, next) => {
withRuntimeLte: query.withRuntimeLte,
voteAverageGte: query.voteAverageGte,
voteAverageLte: query.voteAverageLte,
+ voteCountGte: query.voteCountGte,
+ voteCountLte: query.voteCountLte,
watchProviders: query.watchProviders,
watchRegion: query.watchRegion,
});
@@ -370,6 +375,8 @@ discoverRoutes.get('/tv', async (req, res, next) => {
withRuntimeLte: query.withRuntimeLte,
voteAverageGte: query.voteAverageGte,
voteAverageLte: query.voteAverageLte,
+ voteCountGte: query.voteCountGte,
+ voteCountLte: query.voteCountLte,
watchProviders: query.watchProviders,
watchRegion: query.watchRegion,
});
@@ -647,6 +654,8 @@ discoverRoutes.get('/trending', async (req, res, next) => {
)
: isPerson(result)
? mapPersonResult(result)
+ : isCollection(result)
+ ? mapCollectionResult(result)
: mapTvResult(
result,
media.find(
diff --git a/server/routes/movie.ts b/server/routes/movie.ts
index f11cead8c..e39e2e86e 100644
--- a/server/routes/movie.ts
+++ b/server/routes/movie.ts
@@ -1,4 +1,6 @@
-import RottenTomatoes from '@server/api/rottentomatoes';
+import IMDBRadarrProxy from '@server/api/rating/imdbRadarrProxy';
+import RottenTomatoes from '@server/api/rating/rottentomatoes';
+import { type RatingResponse } from '@server/api/ratings';
import TheMovieDb from '@server/api/themoviedb';
import { MediaType } from '@server/constants/media';
import Media from '@server/entity/Media';
@@ -116,6 +118,9 @@ movieRoutes.get('/:id/similar', async (req, res, next) => {
}
});
+/**
+ * Endpoint backed by RottenTomatoes
+ */
movieRoutes.get('/:id/ratings', async (req, res, next) => {
const tmdb = new TheMovieDb();
const rtapi = new RottenTomatoes();
@@ -151,4 +156,53 @@ movieRoutes.get('/:id/ratings', async (req, res, next) => {
}
});
+/**
+ * Endpoint combining RottenTomatoes and IMDB
+ */
+movieRoutes.get('/:id/ratingscombined', async (req, res, next) => {
+ const tmdb = new TheMovieDb();
+ const rtapi = new RottenTomatoes();
+ const imdbApi = new IMDBRadarrProxy();
+
+ try {
+ const movie = await tmdb.getMovie({
+ movieId: Number(req.params.id),
+ });
+
+ const rtratings = await rtapi.getMovieRatings(
+ movie.title,
+ Number(movie.release_date.slice(0, 4))
+ );
+
+ let imdbRatings;
+ if (movie.imdb_id) {
+ imdbRatings = await imdbApi.getMovieRatings(movie.imdb_id);
+ }
+
+ if (!rtratings && !imdbRatings) {
+ return next({
+ status: 404,
+ message: 'No ratings found.',
+ });
+ }
+
+ const ratings: RatingResponse = {
+ ...(rtratings ? { rt: rtratings } : {}),
+ ...(imdbRatings ? { imdb: imdbRatings } : {}),
+ };
+
+ return res.status(200).json(ratings);
+ } catch (e) {
+ logger.debug('Something went wrong retrieving movie ratings', {
+ label: 'API',
+ errorMessage: e.message,
+ movieId: req.params.id,
+ });
+ return next({
+ status: 500,
+ message: 'Unable to retrieve movie ratings.',
+ });
+ }
+});
+
export default movieRoutes;
diff --git a/server/routes/service.ts b/server/routes/service.ts
index b77d58c9d..083e1eb57 100644
--- a/server/routes/service.ts
+++ b/server/routes/service.ts
@@ -183,9 +183,7 @@ serviceRoutes.get<{ tmdbId: string }>(
const sonarr = new SonarrAPI({
apiKey: sonarrSettings.apiKey,
- url: `${sonarrSettings.useSsl ? 'https' : 'http'}://${
- sonarrSettings.hostname
- }:${sonarrSettings.port}${sonarrSettings.baseUrl ?? ''}/api`,
+ url: SonarrAPI.buildUrl(sonarrSettings, '/api/v3'),
});
try {
diff --git a/server/routes/settings/index.ts b/server/routes/settings/index.ts
index 53544e1d2..9c85313bf 100644
--- a/server/routes/settings/index.ts
+++ b/server/routes/settings/index.ts
@@ -286,25 +286,27 @@ settingsRoutes.post('/tautulli', async (req, res, next) => {
Object.assign(settings.tautulli, req.body);
- try {
- const tautulliClient = new TautulliAPI(settings.tautulli);
+ if (settings.tautulli.hostname) {
+ try {
+ const tautulliClient = new TautulliAPI(settings.tautulli);
- const result = await tautulliClient.getInfo();
+ const result = await tautulliClient.getInfo();
- if (!semver.gte(semver.coerce(result?.tautulli_version) ?? '', '2.9.0')) {
- throw new Error('Tautulli version not supported');
- }
+ if (!semver.gte(semver.coerce(result?.tautulli_version) ?? '', '2.9.0')) {
+ throw new Error('Tautulli version not supported');
+ }
- settings.save();
- } catch (e) {
- logger.error('Something went wrong testing Tautulli connection', {
- label: 'API',
- errorMessage: e.message,
- });
- return next({
- status: 500,
- message: 'Unable to connect to Tautulli.',
- });
+ settings.save();
+ } catch (e) {
+ logger.error('Something went wrong testing Tautulli connection', {
+ label: 'API',
+ errorMessage: e.message,
+ });
+ return next({
+ status: 500,
+ message: 'Unable to connect to Tautulli.',
+ });
+ }
}
return res.status(200).json(settings.tautulli);
diff --git a/server/routes/tv.ts b/server/routes/tv.ts
index d45e40620..95c8dc11c 100644
--- a/server/routes/tv.ts
+++ b/server/routes/tv.ts
@@ -1,4 +1,4 @@
-import RottenTomatoes from '@server/api/rottentomatoes';
+import RottenTomatoes from '@server/api/rating/rottentomatoes';
import TheMovieDb from '@server/api/themoviedb';
import { MediaType } from '@server/constants/media';
import Media from '@server/entity/Media';
diff --git a/server/routes/user/index.ts b/server/routes/user/index.ts
index 5f50eb14b..d34371497 100644
--- a/server/routes/user/index.ts
+++ b/server/routes/user/index.ts
@@ -379,7 +379,14 @@ router.delete<{ id: string }>(
* we manually remove all requests from the user here so the parent media's
* properly reflect the change.
*/
- await requestRepository.remove(user.requests);
+ await requestRepository.remove(user.requests, {
+ /**
+ * Break-up into groups of 1000 requests to be removed at a time.
+ * Necessary for users with >1000 requests, else an SQLite 'Expression tree is too large' error occurs.
+ * https://typeorm.io/repository-api#additional-options
+ */
+ chunk: user.requests.length / 1000,
+ });
await userRepository.delete(user.id);
return res.status(200).json(user.filter());
diff --git a/server/utils/typeHelpers.ts b/server/utils/typeHelpers.ts
index 507ece8cd..548378ff7 100644
--- a/server/utils/typeHelpers.ts
+++ b/server/utils/typeHelpers.ts
@@ -1,4 +1,5 @@
import type {
+ TmdbCollectionResult,
TmdbMovieDetails,
TmdbMovieResult,
TmdbPersonDetails,
@@ -8,17 +9,35 @@ import type {
} from '@server/api/themoviedb/interfaces';
export const isMovie = (
- movie: TmdbMovieResult | TmdbTvResult | TmdbPersonResult
+ movie:
+ | TmdbMovieResult
+ | TmdbTvResult
+ | TmdbPersonResult
+ | TmdbCollectionResult
): movie is TmdbMovieResult => {
return (movie as TmdbMovieResult).title !== undefined;
};
export const isPerson = (
- person: TmdbMovieResult | TmdbTvResult | TmdbPersonResult
+ person:
+ | TmdbMovieResult
+ | TmdbTvResult
+ | TmdbPersonResult
+ | TmdbCollectionResult
): person is TmdbPersonResult => {
return (person as TmdbPersonResult).known_for !== undefined;
};
+export const isCollection = (
+ collection:
+ | TmdbMovieResult
+ | TmdbTvResult
+ | TmdbPersonResult
+ | TmdbCollectionResult
+): collection is TmdbCollectionResult => {
+ return (collection as TmdbCollectionResult).media_type === 'collection';
+};
+
export const isMovieDetails = (
movie: TmdbMovieDetails | TmdbTvDetails | TmdbPersonDetails
): movie is TmdbMovieDetails => {
diff --git a/src/components/CollectionDetails/index.tsx b/src/components/CollectionDetails/index.tsx
index 34b379e24..ff22ee107 100644
--- a/src/components/CollectionDetails/index.tsx
+++ b/src/components/CollectionDetails/index.tsx
@@ -348,7 +348,7 @@ const CollectionDetails = ({ collection }: CollectionDetailsProps) => {
/>
))}
/>
-
+
);
};
diff --git a/src/components/Common/ListView/index.tsx b/src/components/Common/ListView/index.tsx
index 6f09f768b..b46086862 100644
--- a/src/components/Common/ListView/index.tsx
+++ b/src/components/Common/ListView/index.tsx
@@ -5,6 +5,7 @@ import useVerticalScroll from '@app/hooks/useVerticalScroll';
import globalMessages from '@app/i18n/globalMessages';
import type { WatchlistItem } from '@server/interfaces/api/discoverInterfaces';
import type {
+ CollectionResult,
MovieResult,
PersonResult,
TvResult,
@@ -12,7 +13,7 @@ import type {
import { useIntl } from 'react-intl';
type ListViewProps = {
- items?: (TvResult | MovieResult | PersonResult)[];
+ items?: (TvResult | MovieResult | PersonResult | CollectionResult)[];
plexItems?: WatchlistItem[];
isEmpty?: boolean;
isLoading?: boolean;
@@ -90,6 +91,18 @@ const ListView = ({
/>
);
break;
+ case 'collection':
+ titleCard = (
+
+ );
+ break;
case 'person':
titleCard = (
+
+ {intl.formatMessage(messages.tmdbuservotecount)}
+
+
+ {
+ updateQueryParams(
+ 'voteCountGte',
+ min !== 0 && Number(currentFilters.voteCountLte) !== 1000
+ ? min.toString()
+ : undefined
+ );
+ }}
+ onUpdateMax={(max) => {
+ updateQueryParams(
+ 'voteCountLte',
+ max !== 1000 && Number(currentFilters.voteCountGte) !== 0
+ ? max.toString()
+ : undefined
+ );
+ }}
+ subText={intl.formatMessage(messages.voteCount, {
+ minValue: currentFilters.voteCountGte ?? 0,
+ maxValue: currentFilters.voteCountLte ?? 1000,
+ })}
+ />
+
{intl.formatMessage(messages.streamingservices)}
diff --git a/src/components/Discover/constants.ts b/src/components/Discover/constants.ts
index 802ba7c6e..0571f1fc7 100644
--- a/src/components/Discover/constants.ts
+++ b/src/components/Discover/constants.ts
@@ -104,6 +104,8 @@ export const QueryFilterOptions = z.object({
withRuntimeLte: z.string().optional(),
voteAverageGte: z.string().optional(),
voteAverageLte: z.string().optional(),
+ voteCountLte: z.string().optional(),
+ voteCountGte: z.string().optional(),
watchRegion: z.string().optional(),
watchProviders: z.string().optional(),
});
@@ -169,6 +171,14 @@ export const prepareFilterValues = (
filterValues.voteAverageLte = values.voteAverageLte;
}
+ if (values.voteCountGte) {
+ filterValues.voteCountGte = values.voteCountGte;
+ }
+
+ if (values.voteCountLte) {
+ filterValues.voteCountLte = values.voteCountLte;
+ }
+
if (values.watchProviders) {
filterValues.watchProviders = values.watchProviders;
}
@@ -190,6 +200,12 @@ export const countActiveFilters = (filterValues: FilterOptions): number => {
delete clonedFilters.voteAverageLte;
}
+ if (clonedFilters.voteCountGte || filterValues.voteCountLte) {
+ totalCount += 1;
+ delete clonedFilters.voteCountGte;
+ delete clonedFilters.voteCountLte;
+ }
+
if (clonedFilters.withRuntimeGte || filterValues.withRuntimeLte) {
totalCount += 1;
delete clonedFilters.withRuntimeGte;
diff --git a/src/components/Layout/PullToRefresh/index.tsx b/src/components/Layout/PullToRefresh/index.tsx
new file mode 100644
index 000000000..cdedcf43c
--- /dev/null
+++ b/src/components/Layout/PullToRefresh/index.tsx
@@ -0,0 +1,118 @@
+import { ArrowPathIcon } from '@heroicons/react/24/outline';
+import { useRouter } from 'next/router';
+import { useEffect, useRef, useState } from 'react';
+
+const PullToRefresh = () => {
+ const router = useRouter();
+
+ const [pullStartPoint, setPullStartPoint] = useState(0);
+ const [pullChange, setPullChange] = useState(0);
+ const refreshDiv = useRef(null);
+
+ // Various pull down thresholds that determine icon location
+ const pullDownInitThreshold = pullChange > 20;
+ const pullDownStopThreshold = 120;
+ const pullDownReloadThreshold = pullChange > 340;
+ const pullDownIconLocation = pullChange / 3;
+
+ useEffect(() => {
+ // Reload function that is called when reload threshold has been hit
+ // Add loading class to determine when to add spin animation
+ const forceReload = () => {
+ refreshDiv.current?.classList.add('loading');
+ setTimeout(() => {
+ router.reload();
+ }, 1000);
+ };
+
+ const html = document.querySelector('html');
+
+ // Determines if we are at the top of the page
+ // Locks or unlocks page when pulling down to refresh
+ const pullStart = (e: TouchEvent) => {
+ setPullStartPoint(e.targetTouches[0].screenY);
+
+ if (window.scrollY === 0 && window.scrollX === 0) {
+ refreshDiv.current?.classList.add('block');
+ refreshDiv.current?.classList.remove('hidden');
+ document.body.style.touchAction = 'none';
+ document.body.style.overscrollBehavior = 'none';
+ if (html) {
+ html.style.overscrollBehaviorY = 'none';
+ }
+ } else {
+ refreshDiv.current?.classList.remove('block');
+ refreshDiv.current?.classList.add('hidden');
+ }
+ };
+
+ // Tracks how far we have pulled down the refresh icon
+ const pullDown = async (e: TouchEvent) => {
+ const screenY = e.targetTouches[0].screenY;
+
+ const pullLength =
+ pullStartPoint < screenY ? Math.abs(screenY - pullStartPoint) : 0;
+
+ setPullChange(pullLength);
+ };
+
+ // Will reload the page if we are past the threshold
+ // Otherwise, we reset the pull
+ const pullFinish = () => {
+ setPullStartPoint(0);
+
+ if (pullDownReloadThreshold) {
+ forceReload();
+ } else {
+ setPullChange(0);
+ }
+
+ document.body.style.touchAction = 'auto';
+ document.body.style.overscrollBehaviorY = 'auto';
+ if (html) {
+ html.style.overscrollBehaviorY = 'auto';
+ }
+ };
+
+ window.addEventListener('touchstart', pullStart, { passive: false });
+ window.addEventListener('touchmove', pullDown, { passive: false });
+ window.addEventListener('touchend', pullFinish, { passive: false });
+
+ return () => {
+ window.removeEventListener('touchstart', pullStart);
+ window.removeEventListener('touchmove', pullDown);
+ window.removeEventListener('touchend', pullFinish);
+ };
+ }, [pullDownInitThreshold, pullDownReloadThreshold, pullStartPoint, router]);
+
+ return (
+
+ );
+};
+
+export default PullToRefresh;
diff --git a/src/components/Layout/Sidebar/index.tsx b/src/components/Layout/Sidebar/index.tsx
index d9f8ffd51..81ebb86c7 100644
--- a/src/components/Layout/Sidebar/index.tsx
+++ b/src/components/Layout/Sidebar/index.tsx
@@ -71,9 +71,7 @@ const SidebarLinks: SidebarLinkProps[] = [
{
href: '/issues',
messagesKey: 'issues',
- svgIcon: (
-
- ),
+ svgIcon: ,
activeRegExp: /^\/issues/,
requiredPermission: [
Permission.MANAGE_ISSUES,
diff --git a/src/components/Layout/index.tsx b/src/components/Layout/index.tsx
index b30b9712a..878f27b18 100644
--- a/src/components/Layout/index.tsx
+++ b/src/components/Layout/index.tsx
@@ -1,8 +1,8 @@
import MobileMenu from '@app/components/Layout/MobileMenu';
+import PullToRefresh from '@app/components/Layout/PullToRefresh';
import SearchInput from '@app/components/Layout/SearchInput';
import Sidebar from '@app/components/Layout/Sidebar';
import UserDropdown from '@app/components/Layout/UserDropdown';
-import PullToRefresh from '@app/components/PullToRefresh';
import type { AvailableLocale } from '@app/context/LanguageContext';
import useLocale from '@app/hooks/useLocale';
import useSettings from '@app/hooks/useSettings';
diff --git a/src/components/MovieDetails/index.tsx b/src/components/MovieDetails/index.tsx
index 1b142d4de..eaaa902e8 100644
--- a/src/components/MovieDetails/index.tsx
+++ b/src/components/MovieDetails/index.tsx
@@ -2,6 +2,7 @@ import RTAudFresh from '@app/assets/rt_aud_fresh.svg';
import RTAudRotten from '@app/assets/rt_aud_rotten.svg';
import RTFresh from '@app/assets/rt_fresh.svg';
import RTRotten from '@app/assets/rt_rotten.svg';
+import ImdbLogo from '@app/assets/services/imdb.svg';
import TmdbLogo from '@app/assets/tmdb_logo.svg';
import Button from '@app/components/Common/Button';
import CachedImage from '@app/components/Common/CachedImage';
@@ -40,7 +41,7 @@ import {
ChevronDoubleDownIcon,
ChevronDoubleUpIcon,
} from '@heroicons/react/24/solid';
-import type { RTRating } from '@server/api/rottentomatoes';
+import { type RatingResponse } from '@server/api/ratings';
import { IssueStatus } from '@server/constants/issue';
import { MediaStatus } from '@server/constants/media';
import type { MovieDetails as MovieDetailsType } from '@server/models/Movie';
@@ -86,6 +87,7 @@ const messages = defineMessages({
rtcriticsscore: 'Rotten Tomatoes Tomatometer',
rtaudiencescore: 'Rotten Tomatoes Audience Score',
tmdbuserscore: 'TMDB User Score',
+ imdbuserscore: 'IMDB User Score',
});
interface MovieDetailsProps {
@@ -120,8 +122,8 @@ const MovieDetails = ({ movie }: MovieDetailsProps) => {
),
});
- const { data: ratingData } = useSWR(
- `/api/v1/movie/${router.query.movieId}/ratings`
+ const { data: ratingData } = useSWR(
+ `/api/v1/movie/${router.query.movieId}/ratingscombined`
);
const sortedCrew = useMemo(
@@ -511,44 +513,62 @@ const MovieDetails = ({ movie }: MovieDetailsProps) => {
)}
{(!!data.voteCount ||
- (ratingData?.criticsRating && !!ratingData?.criticsScore) ||
- (ratingData?.audienceRating && !!ratingData?.audienceScore)) && (
+ (ratingData?.rt?.criticsRating &&
+ !!ratingData?.rt?.criticsScore) ||
+ (ratingData?.rt?.audienceRating &&
+ !!ratingData?.rt?.audienceScore) ||
+ ratingData?.imdb?.criticsScore) && (
diff --git a/src/components/PullToRefresh/index.tsx b/src/components/PullToRefresh/index.tsx
deleted file mode 100644
index 68939c486..000000000
--- a/src/components/PullToRefresh/index.tsx
+++ /dev/null
@@ -1,45 +0,0 @@
-import { ArrowPathIcon } from '@heroicons/react/24/outline';
-import { useRouter } from 'next/router';
-import PR from 'pulltorefreshjs';
-import { useEffect } from 'react';
-import ReactDOMServer from 'react-dom/server';
-
-const PullToRefresh = () => {
- const router = useRouter();
-
- useEffect(() => {
- PR.init({
- mainElement: '#pull-to-refresh',
- onRefresh() {
- router.reload();
- },
- iconArrow: ReactDOMServer.renderToString(
-
- ),
- iconRefreshing: ReactDOMServer.renderToString(
-
- ),
- instructionsPullToRefresh: ReactDOMServer.renderToString(
),
- instructionsReleaseToRefresh: ReactDOMServer.renderToString(
),
- instructionsRefreshing: ReactDOMServer.renderToString(
),
- distReload: 60,
- distIgnore: 15,
- shouldPullToRefresh: () =>
- !window.scrollY && document.body.style.overflow !== 'hidden',
- });
- return () => {
- PR.destroyAll();
- };
- }, [router]);
-
- return
;
-};
-
-export default PullToRefresh;
diff --git a/src/components/Selector/index.tsx b/src/components/Selector/index.tsx
index 8a21d3fbe..7b2165872 100644
--- a/src/components/Selector/index.tsx
+++ b/src/components/Selector/index.tsx
@@ -169,15 +169,19 @@ export const GenreSelector = ({
loadDefaultGenre();
}, [defaultValue, type]);
- const loadGenreOptions = async () => {
+ const loadGenreOptions = async (inputValue: string) => {
const results = await axios.get
(
`/api/v1/discover/genreslider/${type}`
);
- return results.data.map((result) => ({
- label: result.name,
- value: result.id,
- }));
+ return results.data
+ .map((result) => ({
+ label: result.name,
+ value: result.id,
+ }))
+ .filter(({ label }) =>
+ label.toLowerCase().includes(inputValue.toLowerCase())
+ );
};
return (
@@ -433,6 +437,7 @@ export const WatchProviderSelector = ({
{otherProviders.length > 0 && (
+
+
+
+
+
+
);
diff --git a/src/components/Settings/SonarrModal/index.tsx b/src/components/Settings/SonarrModal/index.tsx
index d9ff0c172..6c61d5dbf 100644
--- a/src/components/Settings/SonarrModal/index.tsx
+++ b/src/components/Settings/SonarrModal/index.tsx
@@ -62,6 +62,9 @@ const messages = defineMessages({
syncEnabled: 'Enable Scan',
externalUrl: 'External URL',
enableSearch: 'Enable Automatic Search',
+ tagRequests: 'Tag Requests',
+ tagRequestsInfo:
+ "Automatically add an additional tag with the requester's user ID & display name",
validationApplicationUrl: 'You must provide a valid URL',
validationApplicationUrlTrailingSlash: 'URL must not end in a trailing slash',
validationBaseUrlLeadingSlash: 'Base URL must have a leading slash',
@@ -252,6 +255,7 @@ const SonarrModal = ({ onClose, sonarr, onSave }: SonarrModalProps) => {
externalUrl: sonarr?.externalUrl,
syncEnabled: sonarr?.syncEnabled ?? false,
enableSearch: !sonarr?.preventSearch,
+ tagRequests: sonarr?.tagRequests ?? false,
}}
validationSchema={SonarrSettingsSchema}
onSubmit={async (values) => {
@@ -292,6 +296,7 @@ const SonarrModal = ({ onClose, sonarr, onSave }: SonarrModalProps) => {
externalUrl: values.externalUrl,
syncEnabled: values.syncEnabled,
preventSearch: !values.enableSearch,
+ tagRequests: values.tagRequests,
};
if (!sonarr) {
await axios.post('/api/v1/settings/sonarr', submission);
@@ -960,6 +965,21 @@ const SonarrModal = ({ onClose, sonarr, onSave }: SonarrModalProps) => {
/>
+
+
+
+
+
+
);
diff --git a/src/components/Slider/index.tsx b/src/components/Slider/index.tsx
index 2498805c5..66a17116b 100644
--- a/src/components/Slider/index.tsx
+++ b/src/components/Slider/index.tsx
@@ -156,6 +156,7 @@ const Slider = ({
}`}
onClick={() => slide(Direction.LEFT)}
disabled={scrollPos.isStart}
+ type="button"
>
@@ -165,6 +166,7 @@ const Slider = ({
}`}
onClick={() => slide(Direction.RIGHT)}
disabled={scrollPos.isEnd}
+ type="button"
>
diff --git a/src/components/StatusBadge/index.tsx b/src/components/StatusBadge/index.tsx
index 3dbe6e74b..b60b7af04 100644
--- a/src/components/StatusBadge/index.tsx
+++ b/src/components/StatusBadge/index.tsx
@@ -166,11 +166,11 @@ const StatusBadge = ({
{inProgress && (
<>
- {mediaType === 'tv' && (
+ {mediaType === 'tv' && downloadItem[0].episode && (
{intl.formatMessage(messages.seasonepisodenumber, {
- seasonNumber: downloadItem[0].episode?.seasonNumber,
- episodeNumber: downloadItem[0].episode?.episodeNumber,
+ seasonNumber: downloadItem[0].episode.seasonNumber,
+ episodeNumber: downloadItem[0].episode.episodeNumber,
})}
)}
@@ -219,11 +219,11 @@ const StatusBadge = ({
{inProgress && (
<>
- {mediaType === 'tv' && (
+ {mediaType === 'tv' && downloadItem[0].episode && (
{intl.formatMessage(messages.seasonepisodenumber, {
- seasonNumber: downloadItem[0].episode?.seasonNumber,
- episodeNumber: downloadItem[0].episode?.episodeNumber,
+ seasonNumber: downloadItem[0].episode.seasonNumber,
+ episodeNumber: downloadItem[0].episode.episodeNumber,
})}
)}
@@ -272,11 +272,11 @@ const StatusBadge = ({
{inProgress && (
<>
- {mediaType === 'tv' && (
+ {mediaType === 'tv' && downloadItem[0].episode && (
{intl.formatMessage(messages.seasonepisodenumber, {
- seasonNumber: downloadItem[0].episode?.seasonNumber,
- episodeNumber: downloadItem[0].episode?.episodeNumber,
+ seasonNumber: downloadItem[0].episode.seasonNumber,
+ episodeNumber: downloadItem[0].episode.episodeNumber,
})}
)}
diff --git a/src/components/TitleCard/index.tsx b/src/components/TitleCard/index.tsx
index b54a17ade..9056fd57e 100644
--- a/src/components/TitleCard/index.tsx
+++ b/src/components/TitleCard/index.tsx
@@ -23,7 +23,7 @@ interface TitleCardProps {
summary?: string;
year?: string;
title: string;
- userScore: number;
+ userScore?: number;
mediaType: MediaType;
status?: MediaStatus;
canExpand?: boolean;
@@ -73,7 +73,9 @@ const TitleCard = ({
const showRequestButton = hasPermission(
[
Permission.REQUEST,
- mediaType === 'movie' ? Permission.REQUEST_MOVIE : Permission.REQUEST_TV,
+ mediaType === 'movie' || mediaType === 'collection'
+ ? Permission.REQUEST_MOVIE
+ : Permission.REQUEST_TV,
],
{ type: 'or' }
);
@@ -86,7 +88,13 @@ const TitleCard = ({
{mediaType === 'movie'
? intl.formatMessage(globalMessages.movie)
+ : mediaType === 'collection'
+ ? intl.formatMessage(globalMessages.collection)
: intl.formatMessage(globalMessages.tvshow)}
@@ -177,7 +187,15 @@ const TitleCard = ({
leaveTo="opacity-0"
>
-
+
{
useEffect(() => {
- const originalStyle = window.getComputedStyle(document.body).overflow;
+ const originalOverflowStyle = window.getComputedStyle(
+ document.body
+ ).overflow;
+ const originalTouchActionStyle = window.getComputedStyle(
+ document.body
+ ).touchAction;
if (isLocked && !disabled) {
document.body.style.overflow = 'hidden';
+ document.body.style.touchAction = 'none';
}
return () => {
if (!disabled) {
- document.body.style.overflow = originalStyle;
+ document.body.style.overflow = originalOverflowStyle;
+ document.body.style.touchAction = originalTouchActionStyle;
}
};
}, [isLocked, disabled]);
diff --git a/src/i18n/globalMessages.ts b/src/i18n/globalMessages.ts
index 076312a10..ca66a891f 100644
--- a/src/i18n/globalMessages.ts
+++ b/src/i18n/globalMessages.ts
@@ -16,6 +16,7 @@ const globalMessages = defineMessages({
approved: 'Approved',
movie: 'Movie',
movies: 'Movies',
+ collection: 'Collection',
tvshow: 'Series',
tvshows: 'Series',
cancel: 'Cancel',
diff --git a/src/i18n/locale/en.json b/src/i18n/locale/en.json
index 1fd1b2e15..e79da0800 100644
--- a/src/i18n/locale/en.json
+++ b/src/i18n/locale/en.json
@@ -76,7 +76,9 @@
"components.Discover.FilterSlideover.streamingservices": "Streaming Services",
"components.Discover.FilterSlideover.studio": "Studio",
"components.Discover.FilterSlideover.tmdbuserscore": "TMDB User Score",
+ "components.Discover.FilterSlideover.tmdbuservotecount": "TMDB User Vote Count",
"components.Discover.FilterSlideover.to": "To",
+ "components.Discover.FilterSlideover.voteCount": "Number of votes between {minValue} and {maxValue}",
"components.Discover.MovieGenreList.moviegenres": "Movie Genres",
"components.Discover.MovieGenreSlider.moviegenres": "Movie Genres",
"components.Discover.NetworkSlider.networks": "Networks",
@@ -253,6 +255,7 @@
"components.MovieDetails.budget": "Budget",
"components.MovieDetails.cast": "Cast",
"components.MovieDetails.digitalrelease": "Digital Release",
+ "components.MovieDetails.imdbuserscore": "IMDB User Score",
"components.MovieDetails.managemovie": "Manage Movie",
"components.MovieDetails.mark4kavailable": "Mark as Available in 4K",
"components.MovieDetails.markavailable": "Mark as Available",
@@ -681,6 +684,8 @@
"components.Settings.RadarrModal.servername": "Server Name",
"components.Settings.RadarrModal.ssl": "Use SSL",
"components.Settings.RadarrModal.syncEnabled": "Enable Scan",
+ "components.Settings.RadarrModal.tagRequests": "Tag Requests",
+ "components.Settings.RadarrModal.tagRequestsInfo": "Automatically add an additional tag with the requester's user ID & display name",
"components.Settings.RadarrModal.tags": "Tags",
"components.Settings.RadarrModal.testFirstQualityProfiles": "Test connection to load quality profiles",
"components.Settings.RadarrModal.testFirstRootFolders": "Test connection to load root folders",
@@ -858,6 +863,8 @@
"components.Settings.SonarrModal.servername": "Server Name",
"components.Settings.SonarrModal.ssl": "Use SSL",
"components.Settings.SonarrModal.syncEnabled": "Enable Scan",
+ "components.Settings.SonarrModal.tagRequests": "Tag Requests",
+ "components.Settings.SonarrModal.tagRequestsInfo": "Automatically add an additional tag with the requester's user ID & display name",
"components.Settings.SonarrModal.tags": "Tags",
"components.Settings.SonarrModal.testFirstLanguageProfiles": "Test connection to load language profiles",
"components.Settings.SonarrModal.testFirstQualityProfiles": "Test connection to load quality profiles",
@@ -1182,6 +1189,7 @@
"i18n.cancel": "Cancel",
"i18n.canceling": "Canceling…",
"i18n.close": "Close",
+ "i18n.collection": "Collection",
"i18n.decline": "Decline",
"i18n.declined": "Declined",
"i18n.delete": "Delete",
diff --git a/src/pages/movie/[movieId]/index.tsx b/src/pages/movie/[movieId]/index.tsx
index 2bb971c18..053ee3ff3 100644
--- a/src/pages/movie/[movieId]/index.tsx
+++ b/src/pages/movie/[movieId]/index.tsx
@@ -1,7 +1,7 @@
import MovieDetails from '@app/components/MovieDetails';
import type { MovieDetails as MovieDetailsType } from '@server/models/Movie';
import axios from 'axios';
-import type { NextPage } from 'next';
+import type { GetServerSideProps, NextPage } from 'next';
interface MoviePageProps {
movie?: MovieDetailsType;
@@ -11,25 +11,25 @@ const MoviePage: NextPage = ({ movie }) => {
return ;
};
-MoviePage.getInitialProps = async (ctx) => {
- if (ctx.req) {
- const response = await axios.get(
- `http://localhost:${process.env.PORT || 5055}/api/v1/movie/${
- ctx.query.movieId
- }`,
- {
- headers: ctx.req?.headers?.cookie
- ? { cookie: ctx.req.headers.cookie }
- : undefined,
- }
- );
+export const getServerSideProps: GetServerSideProps = async (
+ ctx
+) => {
+ const response = await axios.get(
+ `http://localhost:${process.env.PORT || 5055}/api/v1/movie/${
+ ctx.query.movieId
+ }`,
+ {
+ headers: ctx.req?.headers?.cookie
+ ? { cookie: ctx.req.headers.cookie }
+ : undefined,
+ }
+ );
- return {
+ return {
+ props: {
movie: response.data,
- };
- }
-
- return {};
+ },
+ };
};
export default MoviePage;
diff --git a/src/pages/tv/[tvId]/index.tsx b/src/pages/tv/[tvId]/index.tsx
index 69fe216fd..a8a3cbd7d 100644
--- a/src/pages/tv/[tvId]/index.tsx
+++ b/src/pages/tv/[tvId]/index.tsx
@@ -1,7 +1,7 @@
import TvDetails from '@app/components/TvDetails';
import type { TvDetails as TvDetailsType } from '@server/models/Tv';
import axios from 'axios';
-import type { NextPage } from 'next';
+import type { GetServerSideProps, NextPage } from 'next';
interface TvPageProps {
tv?: TvDetailsType;
@@ -11,25 +11,23 @@ const TvPage: NextPage = ({ tv }) => {
return ;
};
-TvPage.getInitialProps = async (ctx) => {
- if (ctx.req) {
- const response = await axios.get(
- `http://localhost:${process.env.PORT || 5055}/api/v1/tv/${
- ctx.query.tvId
- }`,
- {
- headers: ctx.req?.headers?.cookie
- ? { cookie: ctx.req.headers.cookie }
- : undefined,
- }
- );
+export const getServerSideProps: GetServerSideProps = async (
+ ctx
+) => {
+ const response = await axios.get(
+ `http://localhost:${process.env.PORT || 5055}/api/v1/tv/${ctx.query.tvId}`,
+ {
+ headers: ctx.req?.headers?.cookie
+ ? { cookie: ctx.req.headers.cookie }
+ : undefined,
+ }
+ );
- return {
+ return {
+ props: {
tv: response.data,
- };
- }
-
- return {};
+ },
+ };
};
export default TvPage;
diff --git a/src/styles/globals.css b/src/styles/globals.css
index fac7272d7..8110e87e0 100644
--- a/src/styles/globals.css
+++ b/src/styles/globals.css
@@ -17,7 +17,7 @@
body {
@apply bg-gray-900;
- overscroll-behavior-y: contain;
+ -webkit-overflow-scrolling: touch;
}
code {
diff --git a/yarn.lock b/yarn.lock
index b619d2c0b..802e672f7 100644
--- a/yarn.lock
+++ b/yarn.lock
@@ -3954,11 +3954,6 @@
resolved "https://registry.yarnpkg.com/@types/prop-types/-/prop-types-15.7.5.tgz#5f19d2b85a98e9558036f6a3cacc8819420f05cf"
integrity sha512-JCB8C6SnDoQf0cNycqd/35A7MjcnK+ZTqE7judS6o7utxUCg6imJg3QK2qzHKszlTjcj2cn+NwMB2i96ubpj7w==
-"@types/pulltorefreshjs@0.1.5":
- version "0.1.5"
- resolved "https://registry.yarnpkg.com/@types/pulltorefreshjs/-/pulltorefreshjs-0.1.5.tgz#f15c9dbc91b8fdd8135093d81ece9e9d4d2324d7"
- integrity sha512-/VRTgBettvBg1KI8mGnA9oeWs359tTXQ7qsxLuXnksL88jvK6ZNMStG5T9x9vUO9O7jLsgREB0cElz/BWFfdew==
-
"@types/qs@*":
version "6.9.7"
resolved "https://registry.yarnpkg.com/@types/qs/-/qs-6.9.7.tgz#63bb7d067db107cc1e457c303bc25d511febf6cb"
@@ -11434,11 +11429,6 @@ pug@3.0.2, pug@^3.0.2:
pug-runtime "^3.0.1"
pug-strip-comments "^2.0.0"
-pulltorefreshjs@0.1.22:
- version "0.1.22"
- resolved "https://registry.yarnpkg.com/pulltorefreshjs/-/pulltorefreshjs-0.1.22.tgz#ddb5e3feee0b2a49fd46e1b18e84fffef2c47ac0"
- integrity sha512-haxNVEHnS4NCQA7NeG7TSV69z4uqy/N7nfPRuc4dPWe8H6ygUrMjdNeohE+6v0lVVX/ukSjbLYwPUGUYtFKfvQ==
-
pump@^3.0.0:
version "3.0.0"
resolved "https://registry.yarnpkg.com/pump/-/pump-3.0.0.tgz#b4a2116815bde2f4e1ea602354e8c75565107a64"