Improves episode source retrieval from Aniwatch

Refactors episode source fetching to handle multiple servers.

It now attempts to retrieve the episode URL from multiple servers if the initial request fails, improving the chances of finding a valid source.
This commit is contained in:
2025-03-06 09:35:10 -05:00
parent d589087ad9
commit d1306f06ba

View File

@@ -5,9 +5,33 @@ export async function getSourcesFromAniwatch(
watchId: string,
): Promise<FetchUrlResponse | null> {
console.log(`Fetching sources from aniwatch for ${watchId}`);
const { source, intro, outro, subtitles } = await fetch(
`https://aniwatch.up.railway.app/api/v2/hianime/episode/sources?animeEpisodeId=${encodeURIComponent(watchId)}`,
)
const url = await getEpisodeUrl(watchId);
if (url) {
return url;
}
const servers = await getEpisodeServers(watchId);
if (servers.length === 0) {
return null;
}
for (const server of servers) {
const url = await getEpisodeUrl(watchId, server.serverName);
if (url) {
return url;
}
}
return null;
}
async function getEpisodeUrl(watchId: string, server?: string) {
let url = `https://aniwatch.up.railway.app/api/v2/hianime/episode/sources?animeEpisodeId=${encodeURIComponent(watchId)}`;
if (server) {
url += `&server=${encodeURIComponent(server)}`;
}
const { source, intro, outro, subtitles } = await fetch(url)
.then(
(res) =>
res.json() as Promise<{
@@ -44,6 +68,24 @@ export async function getSourcesFromAniwatch(
};
}
async function getEpisodeServers(watchId: string) {
const { data } = await fetch(
`https://aniwatch.up.railway.app/api/v2/hianime/episode/servers?animeEpisodeId=${encodeURIComponent(
watchId,
)}`,
)
.then((res) => res.json() as Promise<AniwatchEpisodeServersResponse>)
.then((res) => {
if (!res.success) {
throw new Error(res.message);
}
return res;
});
return data.sub;
}
interface AniwatchEpisodeUrlResponse {
tracks: Track[];
intro: SkipTime;
@@ -64,3 +106,26 @@ interface Track {
kind: string;
default?: boolean;
}
type AniwatchEpisodeServersResponse =
| {
success: true;
data: AniwatchEpisodeServers;
}
| {
success: false;
message: string;
};
interface AniwatchEpisodeServers {
sub: AniwatchEpisodeServer[];
dub: AniwatchEpisodeServer[];
raw: AniwatchEpisodeServer[];
episodeID: string;
episodeNo: number;
}
interface AniwatchEpisodeServer {
serverName: string;
serverID: number;
}