From 1ec51699d1bfcda0d284f97d7d90c4aa9b614d47 Mon Sep 17 00:00:00 2001 From: Megh Rathod Date: Fri, 12 Apr 2024 11:33:18 +0530 Subject: [PATCH] fix: add alternate tmdb endpoint to fix errors when main url is blocked Signed-off-by: Megh Rathod --- src/backend/metadata/tmdb.ts | 44 +++++++++++++++++++++++++++++------- 1 file changed, 36 insertions(+), 8 deletions(-) diff --git a/src/backend/metadata/tmdb.ts b/src/backend/metadata/tmdb.ts index 2e11bf73..0f01d684 100644 --- a/src/backend/metadata/tmdb.ts +++ b/src/backend/metadata/tmdb.ts @@ -143,7 +143,8 @@ export function decodeTMDBId( }; } -const baseURL = "https://api.tmdb.org/3"; +const otherUrl = "https://api.tmdb.org/3"; +let baseURL = "https://api.themoviedb.org/3"; const apiKey = conf().TMDB_READ_API_KEY; @@ -155,13 +156,40 @@ const headers = { async function get(url: string, params?: object): Promise { if (!apiKey) throw new Error("TMDB API key not set"); - const res = await mwFetch(encodeURI(url), { - headers, - baseURL, - params: { - ...params, - }, - }); + const controller = new AbortController(); + const { signal } = controller; + + const timeoutId = + baseURL === otherUrl + ? setTimeout(() => controller.abort(), 15000) + : setTimeout(() => controller.abort(), 3000); + let res: Promise; + + try { + res = await mwFetch(encodeURI(url), { + headers, + baseURL, + params: { + ...params, + }, + signal, + }); + clearTimeout(timeoutId); + } catch (err) { + if (baseURL !== otherUrl) { + baseURL = otherUrl; + res = await mwFetch(encodeURI(url), { + headers, + baseURL, + params: { + ...params, + }, + }); + } else { + res = Promise.reject(); + } + } + return res; }