refactor: move fetchEpisodes in to subfolder

This commit is contained in:
2024-05-29 08:37:51 -04:00
parent d19f76689c
commit 8b6aecca5c
7 changed files with 1 additions and 1 deletions

View File

@@ -0,0 +1,107 @@
import { PromiseTimedOutError, promiseTimeout } from "~/libs/promiseTimeout";
import { sortByProperty } from "~/libs/sortByProperty";
import type { EpisodesResponse } from "./episode";
export async function getEpisodesFromAnify(
isAnifyEnabled: boolean,
aniListId: number,
): Promise<EpisodesResponse | null> {
if (shouldSkipAnify(isAnifyEnabled, aniListId)) {
return null;
}
let response: AnifyEpisodesResponse[] | null = null;
const abortController = new AbortController();
try {
response = await promiseTimeout(
fetch(`https://api.anify.tv/episodes/${aniListId}`, {
signal: abortController.signal,
}).then((res) => res.json<AnifyEpisodesResponse[]>()),
30 * 1000,
);
} catch (e) {
if (e instanceof PromiseTimedOutError) {
abortController.abort("Loading episodes from Anify timed out");
}
console.error(
new Error(
`Error trying to load episodes from anify; aniListId: ${aniListId}`,
{ cause: e },
),
);
}
if (!response || response.length === 0) {
return null;
}
const sourcePriority = {
gogoanime: 1,
};
const filteredEpisodesData = response
.filter(({ providerId }) => {
if (providerId === "9anime") {
return false;
}
if (aniListId == 166873 && providerId === "zoro") {
// Mushoku Tensei: Job Reincarnation S2 Part 2 returns incorrect mapping for Zoro only
return false;
}
return true;
})
.sort(sortByProperty(sourcePriority, "providerId"));
const selectedEpisodeData = filteredEpisodesData[0];
return {
providerId: selectedEpisodeData.providerId,
episodes: selectedEpisodeData.episodes.map(
({ id, number, description, img, rating, title, updatedAt }) => ({
id,
number,
description,
img,
rating,
title,
updatedAt: updatedAt ?? 0,
}),
),
};
}
export function shouldSkipAnify(
isAnifyEnabled: boolean,
aniListId: number,
): boolean {
if (!isAnifyEnabled) {
return true;
}
// Some mappings on Anify are incorrect so they return episodes from a similar title
if (
[
158927, // Spy x Family S2
166873, // Mushoku Tensei: Jobless Reincarnation S2 part 2
].includes(aniListId)
) {
return true;
}
return false;
}
interface AnifyEpisodesResponse {
providerId: string;
episodes: {
id: string;
isFiller: boolean | undefined;
number: number;
title: string;
img: string | null;
hasDub: boolean;
description: string | null;
rating: number | null;
updatedAt: number | undefined;
}[];
}