Update anime/hianime/source.js

This commit is contained in:
2025-12-21 15:34:39 +01:00
parent 792e1c3151
commit 28d02b4ad8

View File

@@ -1,11 +1,13 @@
class HiAnime { class HiAnime {
constructor() { constructor() {
this.type = "anime-streaming"; this.type = "anime-streaming";
this.version = "1.0" this.version = "1.0";
this.baseUrl = "https://hianime.to"; this.baseUrl = "https://hianime.to";
console.log("[HiAnime] Constructor initialized");
} }
getSettings() { getSettings() {
console.log("[HiAnime] getSettings called");
return { return {
episodeServers: ["HD-1", "HD-2", "HD-3", "HD-4"], episodeServers: ["HD-1", "HD-2", "HD-3", "HD-4"],
supportsDub: true supportsDub: true
@@ -13,19 +15,53 @@ class HiAnime {
} }
async search(query) { async search(query) {
const normalize = (str) => this.safeString(str).toLowerCase().replace(/[^a-z0-9]+/g, ""); console.log("[HiAnime] search called with:", JSON.stringify(query));
try {
const normalize = (str) => this.safeString(str).toLowerCase().replace(/[^a-z0-9]+/g, "");
const start = query.media.startDate; let searchQuery = query;
const fetchMatches = async (url) => { if (typeof query === "string") {
const html = await fetch(url).then(res => res.text()); try {
searchQuery = JSON.parse(query);
} catch (e) {
searchQuery = { query: query, dub: false };
}
}
console.log("[HiAnime] Parsed search query:", JSON.stringify(searchQuery));
const queryText = searchQuery.query || searchQuery.title || "";
if (!queryText) {
console.error("[HiAnime] No query text provided");
return [];
}
const media = searchQuery.media || {};
const startDate = media.startDate || {};
const year = startDate.year || new Date().getFullYear();
const month = startDate.month || 1;
const url = `${this.baseUrl}/search?keyword=${encodeURIComponent(queryText)}&sy=${year}&sm=${month}&sort=default`;
console.log("[HiAnime] Fetching URL:", url);
const response = fetch(url);
console.log("[HiAnime] Fetch response status:", response.status);
const html = response.text();
console.log("[HiAnime] HTML length:", html.length);
const regex = /<a href="\/watch\/([^"]+)"[^>]+title="([^"]+)"[^>]+data-id="(\d+)"/g; const regex = /<a href="\/watch\/([^"]+)"[^>]+title="([^"]+)"[^>]+data-id="(\d+)"/g;
const matches = [...html.matchAll(regex)];
console.log("[HiAnime] Found", matches.length, "raw matches");
return [...html.matchAll(regex)].map(m => { const results = matches.map((m, idx) => {
const id = m[3]; const id = m[3];
const pageUrl = m[1]; const pageUrl = m[1];
const title = m[2]; const title = m[2];
console.log(`[HiAnime] Match ${idx + 1}: id=${id}, title="${title}"`);
const jnameRegex = new RegExp( const jnameRegex = new RegExp(
`<h3 class="film-name">[\\s\\S]*?<a[^>]+href="\\/${pageUrl}[^"]*"[^>]+data-jname="([^"]+)"`, `<h3 class="film-name">[\\s\\S]*?<a[^>]+href="\\/${pageUrl}[^"]*"[^>]+data-jname="([^"]+)"`,
"i" "i"
@@ -41,98 +77,203 @@ class HiAnime {
const image = imageMatch ? imageMatch[1] : null; const image = imageMatch ? imageMatch[1] : null;
return { return {
id, id: `${id}/${searchQuery.dub ? "dub" : "sub"}`,
pageUrl, title: title,
title, image: image,
image, url: `${this.baseUrl}/${pageUrl}`,
normTitleJP: normalize(this.normalizeSeasonParts(jname)), subOrDub: searchQuery.dub ? "dub" : "sub"
normTitle: normalize(this.normalizeSeasonParts(title)),
}; };
}); });
};
let url = `${this.baseUrl}/search?keyword=${encodeURIComponent(query.query)}&sy=${start.year}&sm=${start.month}&sort=default`; console.log("[HiAnime] Returning", results.length, "results");
let matches = await fetchMatches(url); return results;
if (matches.length === 0) return []; } catch (error) {
console.error("[HiAnime] search error:", error);
return matches.map(m => ({ throw error;
id: `${m.id}/${query.dub ? "dub" : "sub"}`, }
title: m.title,
image: m.image,
url: `${this.baseUrl}/${m.pageUrl}`,
subOrDub: query.dub ? "dub" : "sub"
}));
} }
async findEpisodes(animeId) { async findEpisodes(animeId) {
const [id, subOrDub] = animeId.split("/"); console.log("[HiAnime] findEpisodes called with:", animeId);
const res = await fetch(`${this.baseUrl}/ajax/v2/episode/list/${id}`, {
headers: { "X-Requested-With": "XMLHttpRequest" } try {
}); let id, subOrDub;
const json = await res.json();
const html = json.html; if (typeof animeId === "string") {
console.log(html) if (animeId.includes("/")) {
[id, subOrDub] = animeId.split("/");
} else {
try {
const parsed = JSON.parse(animeId);
id = parsed.id || parsed.animeId || animeId;
subOrDub = parsed.subOrDub || "sub";
} catch (e) {
id = animeId;
subOrDub = "sub";
}
}
} else if (typeof animeId === "object") {
id = animeId.id || animeId.animeId;
subOrDub = animeId.subOrDub || "sub";
} else {
id = String(animeId);
subOrDub = "sub";
}
if (id && id.includes("/")) {
[id, subOrDub] = id.split("/");
}
const episodes = []; console.log("[HiAnime] Parsed episode params: id=", id, "subOrDub=", subOrDub);
const regex = /<a[^>]*class="[^"]*\bep-item\b[^"]*"[^>]*data-number="(\d+)"[^>]*data-id="(\d+)"[^>]*href="([^"]+)"[\s\S]*?<div class="ep-name[^"]*"[^>]*title="([^"]+)"/g;
let match; const url = `${this.baseUrl}/ajax/v2/episode/list/${id}`;
while ((match = regex.exec(html)) !== null) { console.log("[HiAnime] Fetching episodes from:", url);
episodes.push({
id: `${match[2]}/${subOrDub}`, const response = fetch(url, {
number: parseInt(match[1], 10), headers: { "X-Requested-With": "XMLHttpRequest" }
url: this.baseUrl + match[3],
title: match[4],
}); });
}
return episodes; console.log("[HiAnime] Episodes fetch status:", response.status);
const json = response.json();
console.log("[HiAnime] Episodes JSON keys:", Object.keys(json).join(", "));
const html = json.html || "";
console.log("[HiAnime] Episodes HTML length:", html.length);
const episodes = [];
const regex = /<a[^>]*class="[^"]*\bep-item\b[^"]*"[^>]*data-number="(\d+)"[^>]*data-id="(\d+)"[^>]*href="([^"]+)"[\s\S]*?<div class="ep-name[^"]*"[^>]*title="([^"]+)"/g;
let match;
let matchCount = 0;
while ((match = regex.exec(html)) !== null) {
matchCount++;
const episode = {
id: `${match[2]}/${subOrDub}`,
number: parseInt(match[1], 10),
url: this.baseUrl + match[3],
title: match[4],
};
console.log(`[HiAnime] Episode ${matchCount}: num=${episode.number}, id=${episode.id}, title="${episode.title}"`);
episodes.push(episode);
}
console.log("[HiAnime] Total episodes found:", episodes.length);
return episodes;
} catch (error) {
console.error("[HiAnime] findEpisodes error:", error);
throw error;
}
} }
async findEpisodeServer(episode, _server) { async findEpisodeServer(episode, _server) {
const [id, subOrDub] = episode.id.split("/"); console.log("[HiAnime] findEpisodeServer called with episode:", JSON.stringify(episode), "server:", _server);
let serverName = _server !== "default" ? _server : "HD-1";
try {
let episodeId, subOrDub;
if (typeof episode === "string") {
if (episode.includes("/")) {
[episodeId, subOrDub] = episode.split("/");
} else {
try {
const parsed = JSON.parse(episode);
episodeId = parsed.id || parsed.episodeId || episode;
subOrDub = parsed.subOrDub || "sub";
} catch (e) {
episodeId = episode;
subOrDub = "sub";
}
}
} else if (typeof episode === "object") {
const epId = episode.id || episode.episodeId || "";
if (epId.includes("/")) {
[episodeId, subOrDub] = epId.split("/");
} else {
episodeId = epId;
subOrDub = episode.subOrDub || "sub";
}
} else {
episodeId = String(episode);
subOrDub = "sub";
}
if (_server === "HD-1" || _server === "HD-2" || _server === "HD-3") { if (episodeId && episodeId.includes("/")) {
const serverJson = await fetch(`${this.baseUrl}/ajax/v2/episode/servers?episodeId=${id}`, { [episodeId, subOrDub] = episodeId.split("/");
}
console.log("[HiAnime] Parsed server params: episodeId=", episodeId, "subOrDub=", subOrDub);
let serverName = (_server && _server !== "default") ? _server : "HD-1";
console.log("[HiAnime] Using server:", serverName);
if (_server === "HD-4") {
console.log("[HiAnime] HD-4 not supported, returning null");
return null;
}
const serversUrl = `${this.baseUrl}/ajax/v2/episode/servers?episodeId=${episodeId}`;
console.log("[HiAnime] Fetching servers from:", serversUrl);
const serverResponse = fetch(serversUrl, {
headers: { "X-Requested-With": "XMLHttpRequest" } headers: { "X-Requested-With": "XMLHttpRequest" }
}).then(res => res.json()); });
console.log("[HiAnime] Servers fetch status:", serverResponse.status);
const serverJson = serverResponse.json();
const serverHtml = serverJson.html || "";
console.log("[HiAnime] Server HTML length:", serverHtml.length);
const serverHtml = serverJson.html;
const regex = new RegExp( const regex = new RegExp(
`<div[^>]*class="item server-item"[^>]*data-type="${subOrDub}"[^>]*data-id="(\\d+)"[^>]*>\\s*<a[^>]*>\\s*${serverName}\\s*</a>`, `<div[^>]*class="item server-item"[^>]*data-type="${subOrDub}"[^>]*data-id="(\\d+)"[^>]*>\\s*<a[^>]*>\\s*${serverName}\\s*</a>`,
"i" "i"
); );
const match = regex.exec(serverHtml); const match = regex.exec(serverHtml);
if (!match) throw new Error(`Server "${serverName}" (${subOrDub}) not found`); if (!match) {
console.error(`[HiAnime] Server "${serverName}" (${subOrDub}) not found in HTML`);
throw new Error(`Server "${serverName}" (${subOrDub}) not found`);
}
const serverId = match[1]; const serverId = match[1];
console.log("[HiAnime] Found serverId:", serverId);
const sourcesJson = await fetch(`${this.baseUrl}/ajax/v2/episode/sources?id=${serverId}`, { const sourcesUrl = `${this.baseUrl}/ajax/v2/episode/sources?id=${serverId}`;
console.log("[HiAnime] Fetching sources from:", sourcesUrl);
const sourcesResponse = fetch(sourcesUrl, {
headers: { "X-Requested-With": "XMLHttpRequest" } headers: { "X-Requested-With": "XMLHttpRequest" }
}).then(res => res.json()); });
console.log("[HiAnime] Sources fetch status:", sourcesResponse.status);
const sourcesJson = sourcesResponse.json();
console.log("[HiAnime] Sources JSON link:", sourcesJson.link);
let decryptData = null; let decryptData = null;
let requiredHeaders = {}; let requiredHeaders = {};
try { try {
decryptData = await this.extractMegaCloud(sourcesJson.link, true); console.log("[HiAnime] Attempting primary decrypter...");
decryptData = this.extractMegaCloud(sourcesJson.link, true);
if (decryptData && decryptData.headersProvided) { if (decryptData && decryptData.headersProvided) {
requiredHeaders = decryptData.headersProvided; requiredHeaders = decryptData.headersProvided;
} }
console.log("[HiAnime] Primary decrypter succeeded");
} catch (err) { } catch (err) {
console.warn("Primary decrypter failed:", err); console.warn("[HiAnime] Primary decrypter failed:", err);
} }
if (!decryptData) { if (!decryptData) {
console.warn("Primary decrypter failed — trying ShadeOfChaos fallback..."); console.log("[HiAnime] Trying fallback API...");
const fallbackRes = await fetch( const fallbackUrl = `https://ac-api.ofchaos.com/api/anime/embed/convert/v2?embedUrl=${encodeURIComponent(sourcesJson.link)}`;
`https://ac-api.ofchaos.com/api/anime/embed/convert/v2?embedUrl=${encodeURIComponent(sourcesJson.link)}` const fallbackResponse = fetch(fallbackUrl);
); console.log("[HiAnime] Fallback fetch status:", fallbackResponse.status);
decryptData = await fallbackRes.json();
decryptData = fallbackResponse.json();
requiredHeaders = { requiredHeaders = {
"Referer": "https://megacloud.club/", "Referer": "https://megacloud.club/",
@@ -140,13 +281,19 @@ class HiAnime {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/139.0.0.0 Safari/537.36", "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/139.0.0.0 Safari/537.36",
"X-Requested-With": "XMLHttpRequest" "X-Requested-With": "XMLHttpRequest"
}; };
console.log("[HiAnime] Fallback succeeded");
} }
const streamSource = const streamSource =
decryptData.sources.find((s) => s.type === "hls") || (decryptData.sources || []).find((s) => s.type === "hls") ||
decryptData.sources.find((s) => s.type === "mp4"); (decryptData.sources || []).find((s) => s.type === "mp4");
if (!streamSource?.file) throw new Error("No valid stream file found"); if (!streamSource || !streamSource.file) {
console.error("[HiAnime] No valid stream file found in sources");
throw new Error("No valid stream file found");
}
console.log("[HiAnime] Stream URL:", streamSource.file);
const subtitles = (decryptData.tracks || []) const subtitles = (decryptData.tracks || [])
.filter((t) => t.kind === "captions") .filter((t) => t.kind === "captions")
@@ -157,19 +304,25 @@ class HiAnime {
isDefault: !!track.default, isDefault: !!track.default,
})); }));
return { console.log("[HiAnime] Found", subtitles.length, "subtitles");
const result = {
server: serverName, server: serverName,
headers: requiredHeaders, headers: requiredHeaders,
videoSources: [{ videoSources: [{
url: streamSource.file, url: streamSource.file,
type: streamSource.type === "hls" ? "m3u8" : "mp4", type: streamSource.type === "hls" ? "m3u8" : "mp4",
quality: "auto", quality: "auto",
subtitles subtitles: subtitles
}] }]
}; };
}
else if (_server === "HD-4") { console.log("[HiAnime] Returning server result");
return null; return result;
} catch (error) {
console.error("[HiAnime] findEpisodeServer error:", error);
throw error;
} }
} }
@@ -185,47 +338,75 @@ class HiAnime {
.replace(/season|cour|part/g, ""); .replace(/season|cour|part/g, "");
} }
async extractMegaCloud(embedUrl, returnHeaders = false) { extractMegaCloud(embedUrl, returnHeaders) {
const url = new URL(embedUrl); console.log("[HiAnime] extractMegaCloud called with:", embedUrl);
const baseDomain = `${url.protocol}//${url.host}/`;
try {
const url = new URL(embedUrl);
const baseDomain = `${url.protocol}//${url.host}/`;
const headers = { const headers = {
"Accept": "*/*", "Accept": "*/*",
"X-Requested-With": "XMLHttpRequest", "X-Requested-With": "XMLHttpRequest",
"Referer": baseDomain, "Referer": baseDomain,
"Origin": `${url.protocol}//${url.host}`, "Origin": `${url.protocol}//${url.host}`,
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/139.0.0.0 Safari/537.36", "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/139.0.0.0 Safari/537.36",
}; };
const html = await fetch(embedUrl, { headers }).then((r) => r.text()); const response = fetch(embedUrl, { headers: headers });
const fileIdMatch = html.match(/<title>\s*File\s+#([a-zA-Z0-9]+)\s*-/i); console.log("[HiAnime] MegaCloud embed fetch status:", response.status);
if (!fileIdMatch) throw new Error("file_id not found in embed page");
const fileId = fileIdMatch[1]; const html = response.text();
console.log("[HiAnime] MegaCloud HTML length:", html.length);
let nonce = null; const fileIdMatch = html.match(/<title>\s*File\s+#([a-zA-Z0-9]+)\s*-/i);
const match48 = html.match(/\b[a-zA-Z0-9]{48}\b/); if (!fileIdMatch) {
if (match48) nonce = match48[0]; console.error("[HiAnime] file_id not found in embed page");
else { throw new Error("file_id not found in embed page");
const match3x16 = [...html.matchAll(/["']([A-Za-z0-9]{16})["']/g)];
if (match3x16.length >= 3) {
nonce = match3x16[0][1] + match3x16[1][1] + match3x16[2][1];
} }
const fileId = fileIdMatch[1];
console.log("[HiAnime] Found fileId:", fileId);
let nonce = null;
const match48 = html.match(/\b[a-zA-Z0-9]{48}\b/);
if (match48) {
nonce = match48[0];
console.log("[HiAnime] Found 48-char nonce");
} else {
const match3x16 = [...html.matchAll(/["']([A-Za-z0-9]{16})["']/g)];
if (match3x16.length >= 3) {
nonce = match3x16[0][1] + match3x16[1][1] + match3x16[2][1];
console.log("[HiAnime] Found 3x16-char nonce");
}
}
if (!nonce) {
console.error("[HiAnime] nonce not found");
throw new Error("nonce not found");
}
const sourcesUrl = `${baseDomain}embed-2/v3/e-1/getSources?id=${fileId}&_k=${nonce}`;
console.log("[HiAnime] Fetching sources from:", sourcesUrl);
const sourcesResponse = fetch(sourcesUrl, { headers: headers });
console.log("[HiAnime] Sources fetch status:", sourcesResponse.status);
const sourcesJson = sourcesResponse.json();
console.log("[HiAnime] Sources has", (sourcesJson.sources || []).length, "sources");
return {
sources: sourcesJson.sources || [],
tracks: sourcesJson.tracks || [],
intro: sourcesJson.intro || null,
outro: sourcesJson.outro || null,
server: sourcesJson.server || null,
headersProvided: returnHeaders ? headers : undefined
};
} catch (error) {
console.error("[HiAnime] extractMegaCloud error:", error);
throw error;
} }
if (!nonce) throw new Error("nonce not found");
const sourcesJson = await fetch(
`${baseDomain}embed-2/v3/e-1/getSources?id=${fileId}&_k=${nonce}`,
{ headers }
).then((r) => r.json());
return {
sources: sourcesJson.sources,
tracks: sourcesJson.tracks || [],
intro: sourcesJson.intro || null,
outro: sourcesJson.outro || null,
server: sourcesJson.server || null,
headersProvided: returnHeaders ? headers : undefined
};
} }
} }