Update anime/hianime/source.js

This commit is contained in:
2025-12-24 18:42:19 +01:00
parent 22ad3af128
commit fbbf0c9f34

View File

@@ -1,27 +1,60 @@
class HiAnime { class HiAnime {
constructor() { constructor() {
this.type = "anime-board"; this.type = "anime-board";
this.version = "1.0" this.version = "1.0";
this.baseUrl = "https://hianime.to"; this.baseUrl = "https://hianime.to";
} }
getSettings() { getSettings() {
return { return {
episodeServers: ["HD-1", "HD-2", "HD-3", "HD-4"], episodeServers: ["HD-1", "HD-2", "HD-3", "HD-4"],
supportsDub: true supportsDub: true,
}; };
} }
async search(query) { _nativeFetch(url, method, headers, body) {
const normalize = (str) => this.safeString(str).toLowerCase().replace(/[^a-z0-9]+/g, ""); const raw = Native.fetch(
String(url),
method || "GET",
JSON.stringify(headers || {}),
body == null ? "" : String(body)
);
try {
return JSON.parse(raw || "{}");
} catch (e) {
return { ok: false, status: 0, headers: {}, body: "" };
}
}
const start = query.media.startDate; _getText(url, headers) {
const fetchMatches = async (url) => { const res = this._nativeFetch(url, "GET", headers, "");
const html = await fetch(url).then(res => res.text()); return String(res.body || "");
}
_getJson(url, headers) {
const res = this._nativeFetch(url, "GET", headers, "");
try {
return JSON.parse(String(res.body || "{}"));
} catch (e) {
return {};
}
}
search(query) {
if (typeof query === "string") {
query = { query, media: { startDate: { year: 0, month: 0 } } };
}
const normalize = (str) =>
this.safeString(str).toLowerCase().replace(/[^a-z0-9]+/g, "");
const start = (query.media && query.media.startDate) || { year: 0, month: 0 };
const fetchMatches = (url) => {
const html = this._getText(url, {});
const regex = /<a href="\/watch\/([^"]+)"[^>]+title="([^"]+)"[^>]+data-id="(\d+)"/g; const regex = /<a href="\/watch\/([^"]+)"[^>]+title="([^"]+)"[^>]+data-id="(\d+)"/g;
return [...html.matchAll(regex)].map(m => { return [...html.matchAll(regex)].map((m) => {
const id = m[3]; const id = m[3];
const pageUrl = m[1]; const pageUrl = m[1];
const title = m[2]; const title = m[2];
@@ -51,32 +84,36 @@ class HiAnime {
}); });
}; };
let url = `${this.baseUrl}/search?keyword=${encodeURIComponent(query.query)}&sy=${start.year}&sm=${start.month}&sort=default`; const url =
let matches = await fetchMatches(url); `${this.baseUrl}/search?keyword=${encodeURIComponent(query.query)}` +
`&sy=${start.year || 0}&sm=${start.month || 0}&sort=default`;
if (matches.length === 0) return []; const matches = fetchMatches(url);
if (!matches.length) return [];
return matches.map(m => ({ const subOrDub = query.dub ? "dub" : "sub";
id: `${m.id}/${query.dub ? "dub" : "sub"}`, return matches.map((m) => ({
id: `${m.id}/${subOrDub}`,
title: m.title, title: m.title,
image: m.image, image: m.image,
url: `${this.baseUrl}/${m.pageUrl}`, url: `${this.baseUrl}/${m.pageUrl}`,
subOrDub: query.dub ? "dub" : "sub" subOrDub,
})); }));
} }
async findEpisodes(animeId) { findEpisodes(animeId) {
const [id, subOrDub] = animeId.split("/"); const parts = String(animeId).split("/");
const res = await fetch(`${this.baseUrl}/ajax/v2/episode/list/${id}`, { const id = parts[0];
headers: { "X-Requested-With": "XMLHttpRequest" } const subOrDub = parts[1] || "sub";
const json = this._getJson(`${this.baseUrl}/ajax/v2/episode/list/${id}`, {
"X-Requested-With": "XMLHttpRequest",
}); });
const json = await res.json();
const html = json.html;
console.log(html)
const html = String(json.html || "");
const episodes = []; const episodes = [];
const regex = /<a[^>]*class="[^"]*\bep-item\b[^"]*"[^>]*data-number="(\d+)"[^>]*data-id="(\d+)"[^>]*href="([^"]+)"[\s\S]*?<div class="ep-name[^"]*"[^>]*title="([^"]+)"/g; 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 match;
while ((match = regex.exec(html)) !== null) { while ((match = regex.exec(html)) !== null) {
@@ -91,16 +128,26 @@ class HiAnime {
return episodes; return episodes;
} }
async findEpisodeServer(episode, _server) { findEpisodeServer(episode, _server) {
const [id, subOrDub] = episode.id.split("/"); if (typeof episode === "string") {
let serverName = _server !== "default" ? _server : "HD-1"; try {
episode = JSON.parse(episode);
} catch (e) {}
}
if (_server === "HD-1" || _server === "HD-2" || _server === "HD-3") { const parts = String((episode && episode.id) || "").split("/");
const serverJson = await fetch(`${this.baseUrl}/ajax/v2/episode/servers?episodeId=${id}`, { const id = parts[0];
headers: { "X-Requested-With": "XMLHttpRequest" } const subOrDub = parts[1] || "sub";
}).then(res => res.json()); const serverName = _server !== "default" ? _server : "HD-1";
const serverHtml = serverJson.html; if (_server === "HD-4") return null;
const serverJson = this._getJson(
`${this.baseUrl}/ajax/v2/episode/servers?episodeId=${id}`,
{ "X-Requested-With": "XMLHttpRequest" }
);
const serverHtml = String(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"
@@ -111,45 +158,40 @@ class HiAnime {
const serverId = match[1]; const serverId = match[1];
const sourcesJson = await fetch(`${this.baseUrl}/ajax/v2/episode/sources?id=${serverId}`, { const sourcesJson = this._getJson(
headers: { "X-Requested-With": "XMLHttpRequest" } `${this.baseUrl}/ajax/v2/episode/sources?id=${serverId}`,
}).then(res => res.json()); { "X-Requested-With": "XMLHttpRequest" }
);
let decryptData = null; let decryptData = null;
let requiredHeaders = {}; let requiredHeaders = {};
try { try {
// Pass true to get headers back decryptData = this.extractMegaCloudSync(sourcesJson.link);
decryptData = await this.extractMegaCloud(sourcesJson.link, true); requiredHeaders = decryptData.headersProvided || {};
if (decryptData && decryptData.headersProvided) { } catch (e) {}
requiredHeaders = decryptData.headersProvided;
}
} catch (err) {
console.warn("Primary decrypter failed:", err);
}
if (!decryptData) { if (!decryptData) {
console.warn("Primary decrypter failed — trying ShadeOfChaos fallback..."); decryptData = this._getJson(
const fallbackRes = await fetch( `https://ac-api.ofchaos.com/api/anime/embed/convert/v2?embedUrl=${encodeURIComponent(
`https://ac-api.ofchaos.com/api/anime/embed/convert/v2?embedUrl=${encodeURIComponent(sourcesJson.link)}` sourcesJson.link
)}`,
{}
); );
decryptData = await fallbackRes.json();
// CRITICAL: Fallback headers must mimic the browser behavior expected by the provider
// These MUST be used by a server-side proxy; the browser player cannot set them.
requiredHeaders = { requiredHeaders = {
"Referer": "https://megacloud.club/", Referer: "https://megacloud.club/",
"Origin": "https://megacloud.club", Origin: "https://megacloud.club",
"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":
"X-Requested-With": "XMLHttpRequest" "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",
}; };
} }
const sources = decryptData.sources || [];
const streamSource = const streamSource =
decryptData.sources.find((s) => s.type === "hls") || sources.find((s) => s.type === "hls") || 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) throw new Error("No valid stream file found");
const subtitles = (decryptData.tracks || []) const subtitles = (decryptData.tracks || [])
.filter((t) => t.kind === "captions") .filter((t) => t.kind === "captions")
@@ -163,45 +205,50 @@ class HiAnime {
return { return {
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,
}] },
],
}; };
} }
else if (_server === "HD-4") {
// Implementation for HD-4 if needed
return null;
}
}
safeString(str) { safeString(str) {
return (typeof str === "string" ? str : ""); return typeof str === "string" ? str : "";
} }
normalizeSeasonParts(title) { normalizeSeasonParts(title) {
const s = this.safeString(title); const s = this.safeString(title);
return s.toLowerCase() return s
.toLowerCase()
.replace(/[^a-z0-9]+/g, "") .replace(/[^a-z0-9]+/g, "")
.replace(/\d+(st|nd|rd|th)/g, (m) => m.replace(/st|nd|rd|th/, "")) .replace(/\d+(st|nd|rd|th)/g, (m) => m.replace(/st|nd|rd|th/, ""))
.replace(/season|cour|part/g, ""); .replace(/season|cour|part/g, "");
} }
async extractMegaCloud(embedUrl, returnHeaders = false) { extractMegaCloudSync(embedUrl) {
const url = new URL(embedUrl); const s = String(embedUrl);
const baseDomain = `${url.protocol}//${url.host}/`; const mm = s.match(/^(https?):\/\/([^\/]+)(\/.*)?$/i);
if (!mm) throw new Error("Invalid embedUrl: " + s);
const protocol = mm[1].toLowerCase();
const host = mm[2];
const baseDomain = `${protocol}://${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: `${protocol}://${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 html = this._getText(embedUrl, headers);
const fileIdMatch = html.match(/<title>\s*File\s+#([a-zA-Z0-9]+)\s*-/i); const fileIdMatch = html.match(/<title>\s*File\s+#([a-zA-Z0-9]+)\s*-/i);
if (!fileIdMatch) throw new Error("file_id not found in embed page"); if (!fileIdMatch) throw new Error("file_id not found in embed page");
const fileId = fileIdMatch[1]; const fileId = fileIdMatch[1];
@@ -217,18 +264,18 @@ class HiAnime {
} }
if (!nonce) throw new Error("nonce not found"); if (!nonce) throw new Error("nonce not found");
const sourcesJson = await fetch( const sourcesJson = this._getJson(
`${baseDomain}embed-2/v3/e-1/getSources?id=${fileId}&_k=${nonce}`, `${baseDomain}embed-2/v3/e-1/getSources?id=${fileId}&_k=${nonce}`,
{ headers } headers
).then((r) => r.json()); );
return { return {
sources: sourcesJson.sources, sources: sourcesJson.sources || [],
tracks: sourcesJson.tracks || [], tracks: sourcesJson.tracks || [],
intro: sourcesJson.intro || null, intro: sourcesJson.intro || null,
outro: sourcesJson.outro || null, outro: sourcesJson.outro || null,
server: sourcesJson.server || null, server: sourcesJson.server || null,
headersProvided: returnHeaders ? headers : undefined headersProvided: headers,
}; };
} }
} }