From d9fd16613a14eb4ee2addec44fa5a84e924393d1 Mon Sep 17 00:00:00 2001 From: mrjvs Date: Wed, 20 Dec 2023 15:22:05 +0100 Subject: [PATCH] Implement turnstile on provider package simple proxy --- src/utils/providers.ts | 26 ++++++++++++++++++++++++-- 1 file changed, 24 insertions(+), 2 deletions(-) diff --git a/src/utils/providers.ts b/src/utils/providers.ts index 73c3849e..d38796ac 100644 --- a/src/utils/providers.ts +++ b/src/utils/providers.ts @@ -7,6 +7,7 @@ import { targets, } from "@movie-web/providers"; +import { getApiToken, setApiToken } from "@/backend/helpers/providerApi"; import { getProviderApiUrls, getProxyUrls } from "@/utils/proxyUrls"; function makeLoadbalancedList(getter: () => string[]) { @@ -26,11 +27,32 @@ export const getLoadbalancedProxyUrl = makeLoadbalancedList(getProxyUrls); export const getLoadbalancedProviderApiUrl = makeLoadbalancedList(getProviderApiUrls); +async function fetchButWithApiTokens( + input: RequestInfo | URL, + init?: RequestInit | undefined +): Promise { + const apiToken = await getApiToken(); + const headers = new Headers(init?.headers); + if (apiToken) headers.set("X-Token", apiToken); + const response = await fetch( + input, + init + ? { + ...init, + headers, + } + : undefined + ); + const newApiToken = response.headers.get("X-Token"); + if (newApiToken) setApiToken(newApiToken); + return response; +} + function makeLoadBalancedSimpleProxyFetcher() { - const fetcher: ProviderBuilderOptions["fetcher"] = (a, b) => { + const fetcher: ProviderBuilderOptions["fetcher"] = async (a, b) => { const currentFetcher = makeSimpleProxyFetcher( getLoadbalancedProxyUrl(), - fetch + fetchButWithApiTokens ); return currentFetcher(a, b); };