movie-web/src/backend/metadata/getmeta.ts

85 lines
2 KiB
TypeScript
Raw Normal View History

2023-01-15 15:01:07 +00:00
import { FetchError } from "ofetch";
2023-06-12 19:25:24 +00:00
import { formatJWMeta, mediaTypeToJW } from "./justwatch";
2023-01-15 15:01:07 +00:00
import {
JWMediaResult,
JWSeasonMetaResult,
2023-01-15 15:01:07 +00:00
JW_API_BASE,
2023-06-12 19:25:24 +00:00
MWMediaMeta,
MWMediaType,
} from "./types";
import { makeUrl, proxiedFetch } from "../helpers/fetch";
type JWExternalIdType =
| "eidr"
| "imdb_latest"
| "imdb"
| "tmdb_latest"
| "tmdb"
| "tms";
interface JWExternalId {
provider: JWExternalIdType;
external_id: string;
}
interface JWDetailedMeta extends JWMediaResult {
external_ids: JWExternalId[];
}
export interface DetailedMeta {
meta: MWMediaMeta;
2023-05-21 16:12:45 +00:00
imdbId?: string;
2023-05-21 19:00:35 +00:00
tmdbId?: string;
}
export async function getMetaFromId(
type: MWMediaType,
id: string,
seasonId?: string
2023-01-15 15:01:07 +00:00
): Promise<DetailedMeta | null> {
const queryType = mediaTypeToJW(type);
let data: JWDetailedMeta;
try {
const url = makeUrl("/content/titles/{type}/{id}/locale/en_US", {
type: queryType,
id,
});
data = await proxiedFetch<JWDetailedMeta>(url, { baseURL: JW_API_BASE });
2023-01-15 15:01:07 +00:00
} catch (err) {
if (err instanceof FetchError) {
// 400 and 404 are treated as not found
if (err.statusCode === 400 || err.statusCode === 404) return null;
}
throw err;
}
2023-03-10 19:54:56 +00:00
let imdbId = data.external_ids.find(
(v) => v.provider === "imdb_latest"
2023-03-10 19:59:10 +00:00
)?.external_id;
2023-03-10 19:54:56 +00:00
if (!imdbId)
2023-03-10 19:59:10 +00:00
imdbId = data.external_ids.find((v) => v.provider === "imdb")?.external_id;
2023-03-10 19:54:56 +00:00
2023-05-21 19:00:35 +00:00
let tmdbId = data.external_ids.find(
(v) => v.provider === "tmdb_latest"
)?.external_id;
if (!tmdbId)
tmdbId = data.external_ids.find((v) => v.provider === "tmdb")?.external_id;
let seasonData: JWSeasonMetaResult | undefined;
if (data.object_type === "show") {
const seasonToScrape = seasonId ?? data.seasons?.[0].id.toString() ?? "";
const url = makeUrl("/content/titles/show_season/{id}/locale/en_US", {
id: seasonToScrape,
});
seasonData = await proxiedFetch<any>(url, { baseURL: JW_API_BASE });
}
return {
meta: formatJWMeta(data, seasonData),
imdbId,
2023-05-21 19:00:35 +00:00
tmdbId,
};
}