1
0
Fork 0
mirror of https://github.com/sussy-code/smov.git synced 2024-12-21 14:47:41 +01:00

Clean up extension code

This commit is contained in:
mrjvs 2024-01-09 20:07:22 +01:00
parent ef85c217f7
commit f70d13f2c9
9 changed files with 172 additions and 98 deletions

View file

@ -0,0 +1,51 @@
import {
MessagesMetadata,
sendToBackgroundViaRelay,
} from "@plasmohq/messaging";
let activeExtension = false;
export interface ExtensionHello {
version: string;
}
function sendMessage<T, Payload>(
message: keyof MessagesMetadata,
payload: any,
timeout: number = -1,
) {
return new Promise<T | null>((resolve) => {
if (timeout >= 0) setTimeout(() => resolve(null), timeout);
sendToBackgroundViaRelay<Payload, T>({
name: message,
body: payload,
})
.then((res) => {
activeExtension = true;
resolve(res);
})
.catch(() => {
activeExtension = false;
resolve(null);
});
});
}
export async function sendExtensionRequest(
url: string,
ops: any,
): Promise<ExtensionHello | null> {
return sendMessage("proxy-request", { url, ...ops });
}
export async function extensionInfo(): Promise<ExtensionHello | null> {
return sendMessage("hello", null, 300);
}
export function isExtensionActiveCached(): boolean {
return activeExtension;
}
export async function isExtensionActive(): Promise<boolean> {
return !!(await extensionInfo());
}

View file

@ -1,6 +1,3 @@
/* eslint-disable @typescript-eslint/ban-types */
import "@plasmohq/messaging";
export interface PlasmoRequestBody { export interface PlasmoRequestBody {
ruleId: number; ruleId: number;
domain: string; domain: string;
@ -8,7 +5,11 @@ export interface PlasmoRequestBody {
responseHeaders?: Record<string, string>; responseHeaders?: Record<string, string>;
} }
export type PlasmoResponseBody = export interface ExtensionHelloReply {
version: string;
}
export type ExtensionRequestReply =
| { | {
success: true; success: true;
ruleId: number; ruleId: number;
@ -21,11 +22,15 @@ export type PlasmoResponseBody =
interface MmMetadata { interface MmMetadata {
"declarative-net-request": { "declarative-net-request": {
req: PlasmoRequestBody; req: PlasmoRequestBody;
res: PlasmoResponseBody; res: ExtensionRequestReply;
}; };
"proxy-request": { "proxy-request": {
req: PlasmoRequestBody; req: PlasmoRequestBody;
res: PlasmoResponseBody; res: ExtensionRequestReply;
};
hello: {
req: null;
res: ExtensionHelloReply;
}; };
} }

View file

@ -1,7 +1,7 @@
import { ofetch } from "ofetch"; import { ofetch } from "ofetch";
import { getApiToken, setApiToken } from "@/backend/helpers/providerApi"; import { getApiToken, setApiToken } from "@/backend/helpers/providerApi";
import { getLoadbalancedProxyUrl } from "@/utils/providers"; import { getLoadbalancedProxyUrl } from "@/backend/providers/fetchers";
type P<T> = Parameters<typeof ofetch<T, any>>; type P<T> = Parameters<typeof ofetch<T, any>>;
type R<T> = ReturnType<typeof ofetch<T, any>>; type R<T> = ReturnType<typeof ofetch<T, any>>;

View file

@ -1,12 +1,6 @@
import { import { Fetcher, makeSimpleProxyFetcher } from "@movie-web/providers";
Fetcher,
ProviderControls,
makeProviders,
makeSimpleProxyFetcher,
makeStandardFetcher,
targets,
} from "@movie-web/providers";
import { sendExtensionRequest } from "@/backend/extension/messaging";
import { getApiToken, setApiToken } from "@/backend/helpers/providerApi"; import { getApiToken, setApiToken } from "@/backend/helpers/providerApi";
import { getProviderApiUrls, getProxyUrls } from "@/utils/proxyUrls"; import { getProviderApiUrls, getProxyUrls } from "@/utils/proxyUrls";
@ -48,7 +42,7 @@ async function fetchButWithApiTokens(
return response; return response;
} }
function makeLoadBalancedSimpleProxyFetcher() { export function makeLoadBalancedSimpleProxyFetcher() {
const fetcher: Fetcher = async (a, b) => { const fetcher: Fetcher = async (a, b) => {
const currentFetcher = makeSimpleProxyFetcher( const currentFetcher = makeSimpleProxyFetcher(
getLoadbalancedProxyUrl(), getLoadbalancedProxyUrl(),
@ -59,10 +53,9 @@ function makeLoadBalancedSimpleProxyFetcher() {
return fetcher; return fetcher;
} }
export const providers = makeProviders({ export function makeExtensionFetcher() {
fetcher: makeStandardFetcher(fetch), const fetcher: Fetcher = async (a, b) => {
proxiedFetcher: makeLoadBalancedSimpleProxyFetcher(), return sendExtensionRequest(a, b) as any;
// TODO: Add check whether the extension is installed };
// target: targets.BROWSER, return fetcher;
target: targets.BROWSER_EXTENSION, }
}) as any as ProviderControls;

View file

@ -0,0 +1,26 @@
import {
makeProviders,
makeStandardFetcher,
targets,
} from "@movie-web/providers";
import { isExtensionActiveCached } from "@/backend/extension/messaging";
import {
makeExtensionFetcher,
makeLoadBalancedSimpleProxyFetcher,
} from "@/backend/providers/fetchers";
export function getProviders() {
if (isExtensionActiveCached()) {
return makeProviders({
fetcher: makeExtensionFetcher(),
target: targets.BROWSER_EXTENSION,
});
}
return makeProviders({
fetcher: makeStandardFetcher(fetch),
proxiedFetcher: makeLoadBalancedSimpleProxyFetcher(),
target: targets.BROWSER,
});
}

View file

@ -1,8 +1,6 @@
import { sendToBackgroundViaRelay } from "@plasmohq/messaging";
import fscreen from "fscreen"; import fscreen from "fscreen";
import Hls, { Level } from "hls.js"; import Hls, { Level } from "hls.js";
import { PlasmoRequestBody, PlasmoResponseBody } from "@/@types/plasmo";
import { import {
DisplayInterface, DisplayInterface,
DisplayInterfaceEvents, DisplayInterfaceEvents,
@ -43,6 +41,7 @@ function qualityToHlsLevel(quality: SourceQuality): number | null {
); );
return found ? +found[0] : null; return found ? +found[0] : null;
} }
function hlsLevelsToQualities(levels: Level[]): SourceQuality[] { function hlsLevelsToQualities(levels: Level[]): SourceQuality[] {
return levels return levels
.map((v) => hlsLevelToQuality(v)) .map((v) => hlsLevelToQuality(v))
@ -103,14 +102,6 @@ export function makeVideoElementDisplayInterface(): DisplayInterface {
function setupSource(vid: HTMLVideoElement, src: LoadableSource) { function setupSource(vid: HTMLVideoElement, src: LoadableSource) {
// TODO: Add check whether the extension is installed // TODO: Add check whether the extension is installed
sendToBackgroundViaRelay<PlasmoRequestBody, PlasmoResponseBody>({
name: "declarative-net-request",
body: {
ruleId: 1,
domain: src.type === "hls" ? new URL(src.url).hostname : src.url,
requestHeaders: src.preferredHeaders,
},
}).then(() => {
if (src.type === "hls") { if (src.type === "hls") {
if (canPlayHlsNatively(vid)) { if (canPlayHlsNatively(vid)) {
vid.src = processCdnLink(src.url); vid.src = processCdnLink(src.url);
@ -170,7 +161,6 @@ export function makeVideoElementDisplayInterface(): DisplayInterface {
vid.src = processCdnLink(src.url); vid.src = processCdnLink(src.url);
vid.currentTime = startAt; vid.currentTime = startAt;
});
} }
function setSource() { function setSource() {

View file

@ -13,12 +13,13 @@ import {
scrapeSourceOutputToProviderMetric, scrapeSourceOutputToProviderMetric,
useReportProviders, useReportProviders,
} from "@/backend/helpers/report"; } from "@/backend/helpers/report";
import { getLoadbalancedProviderApiUrl } from "@/backend/providers/fetchers";
import { getProviders } from "@/backend/providers/providers";
import { convertProviderCaption } from "@/components/player/utils/captions"; import { convertProviderCaption } from "@/components/player/utils/captions";
import { convertRunoutputToSource } from "@/components/player/utils/convertRunoutputToSource"; import { convertRunoutputToSource } from "@/components/player/utils/convertRunoutputToSource";
import { useOverlayRouter } from "@/hooks/useOverlayRouter"; import { useOverlayRouter } from "@/hooks/useOverlayRouter";
import { metaToScrapeMedia } from "@/stores/player/slices/source"; import { metaToScrapeMedia } from "@/stores/player/slices/source";
import { usePlayerStore } from "@/stores/player/store"; import { usePlayerStore } from "@/stores/player/store";
import { getLoadbalancedProviderApiUrl, providers } from "@/utils/providers";
export function useEmbedScraping( export function useEmbedScraping(
routerId: string, routerId: string,
@ -47,7 +48,7 @@ export function useEmbedScraping(
); );
result = await conn.promise(); result = await conn.promise();
} else { } else {
result = await providers.runEmbedScraper({ result = await getProviders().runEmbedScraper({
id: embedId, id: embedId,
url, url,
}); });
@ -111,7 +112,7 @@ export function useSourceScraping(sourceId: string | null, routerId: string) {
); );
result = await conn.promise(); result = await conn.promise();
} else { } else {
result = await providers.runSourceScraper({ result = await getProviders().runSourceScraper({
id: sourceId, id: sourceId,
media: scrapeMedia, media: scrapeMedia,
}); });
@ -155,7 +156,7 @@ export function useSourceScraping(sourceId: string | null, routerId: string) {
); );
embedResult = await conn.promise(); embedResult = await conn.promise();
} else { } else {
embedResult = await providers.runEmbedScraper({ embedResult = await getProviders().runEmbedScraper({
id: result.embeds[0].embedId, id: result.embeds[0].embedId,
url: result.embeds[0].url, url: result.embeds[0].url,
}); });

View file

@ -10,7 +10,8 @@ import {
getCachedMetadata, getCachedMetadata,
makeProviderUrl, makeProviderUrl,
} from "@/backend/helpers/providerApi"; } from "@/backend/helpers/providerApi";
import { getLoadbalancedProviderApiUrl, providers } from "@/utils/providers"; import { getLoadbalancedProviderApiUrl } from "@/backend/providers/fetchers";
import { getProviders } from "@/backend/providers/providers";
export interface ScrapingItems { export interface ScrapingItems {
id: string; id: string;
@ -172,8 +173,8 @@ export function useScrape() {
return getResult(sseOutput === "" ? null : sseOutput); return getResult(sseOutput === "" ? null : sseOutput);
} }
if (!providers) return null;
startScrape(); startScrape();
const providers = getProviders();
const output = await providers.runAll({ const output = await providers.runAll({
media, media,
events: { events: {

View file

@ -3,6 +3,7 @@ import { useNavigate, useParams } from "react-router-dom";
import { useAsync } from "react-use"; import { useAsync } from "react-use";
import type { AsyncReturnType } from "type-fest"; import type { AsyncReturnType } from "type-fest";
import { isExtensionActive } from "@/backend/extension/messaging";
import { import {
fetchMetadata, fetchMetadata,
setCachedMetadata, setCachedMetadata,
@ -10,6 +11,8 @@ import {
import { DetailedMeta, getMetaFromId } from "@/backend/metadata/getmeta"; import { DetailedMeta, getMetaFromId } from "@/backend/metadata/getmeta";
import { decodeTMDBId } from "@/backend/metadata/tmdb"; import { decodeTMDBId } from "@/backend/metadata/tmdb";
import { MWMediaType } from "@/backend/metadata/types/mw"; import { MWMediaType } from "@/backend/metadata/types/mw";
import { getLoadbalancedProviderApiUrl } from "@/backend/providers/fetchers";
import { getProviders } from "@/backend/providers/providers";
import { Button } from "@/components/buttons/Button"; import { Button } from "@/components/buttons/Button";
import { Icons } from "@/components/Icon"; import { Icons } from "@/components/Icon";
import { IconPill } from "@/components/layout/IconPill"; import { IconPill } from "@/components/layout/IconPill";
@ -18,7 +21,6 @@ import { Paragraph } from "@/components/text/Paragraph";
import { Title } from "@/components/text/Title"; import { Title } from "@/components/text/Title";
import { ErrorContainer, ErrorLayout } from "@/pages/layouts/ErrorLayout"; import { ErrorContainer, ErrorLayout } from "@/pages/layouts/ErrorLayout";
import { conf } from "@/setup/config"; import { conf } from "@/setup/config";
import { getLoadbalancedProviderApiUrl, providers } from "@/utils/providers";
export interface MetaPartProps { export interface MetaPartProps {
onGetMeta?: (meta: DetailedMeta, episodeId?: string) => void; onGetMeta?: (meta: DetailedMeta, episodeId?: string) => void;
@ -41,8 +43,12 @@ export function MetaPart(props: MetaPartProps) {
const navigate = useNavigate(); const navigate = useNavigate();
const { error, value, loading } = useAsync(async () => { const { error, value, loading } = useAsync(async () => {
// check extension
const isActive = await isExtensionActive();
// use api metadata or providers metadata
const providerApiUrl = getLoadbalancedProviderApiUrl(); const providerApiUrl = getLoadbalancedProviderApiUrl();
if (providerApiUrl) { if (providerApiUrl && !isActive) {
try { try {
await fetchMetadata(providerApiUrl); await fetchMetadata(providerApiUrl);
} catch (err) { } catch (err) {
@ -50,11 +56,12 @@ export function MetaPart(props: MetaPartProps) {
} }
} else { } else {
setCachedMetadata([ setCachedMetadata([
...providers.listSources(), ...getProviders().listSources(),
...providers.listEmbeds(), ...getProviders().listEmbeds(),
]); ]);
} }
// get media meta data
let data: ReturnType<typeof decodeTMDBId> = null; let data: ReturnType<typeof decodeTMDBId> = null;
try { try {
if (!params.media) throw new Error("no media params"); if (!params.media) throw new Error("no media params");