Update anime/hianime/source.js

This commit is contained in:
2025-12-26 19:14:59 +01:00
parent 22296962c4
commit afe025e133

View File

@@ -1,14 +1,16 @@
class HiAnime { class HiAnime {
constructor() { constructor() {
this.type = "anime-streaming"; this.type = "anime-streaming";
this.version = "1.0.4"; this.version = "1.0.5";
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 supportsSub: true,
supportsDub: true,
supportsHls: true
}; };
} }
@@ -33,52 +35,52 @@ class HiAnime {
_getJson(url, headers) { _getJson(url, headers) {
const res = this._nativeFetch(url, "GET", headers, ""); const res = this._nativeFetch(url, "GET", headers, "");
const body = String(res.body || "");
try { try {
return JSON.parse(body || "{}"); return JSON.parse(String(res.body || "{}"));
} catch (e) { } catch (e) {
return { _raw: body }; return {};
} }
} }
safeString(str) { _safeStr(v) {
return (typeof str === "string" ? str : ""); return typeof v === "string" ? v : (v == null ? "" : String(v));
} }
normalizeSeasonParts(title) { _headersHtml() {
const s = this.safeString(title);
return s.toLowerCase()
.replace(/[^a-z0-9]+/g, "")
.replace(/\d+(st|nd|rd|th)/g, (m) => m.replace(/st|nd|rd|th/, ""))
.replace(/season|cour|part/g, "");
}
_decodeHtml(str) {
return String(str || "")
.replace(/\\u0026/g, "&")
.replace(/&#(\d+);?/g, (m, dec) => {
const n = parseInt(dec, 10);
if (!isFinite(n)) return m;
return String.fromCharCode(n);
})
.replace(/"/g, '"')
.replace(/'/g, "'")
.replace(/&/g, "&")
.replace(/&lt;/g, "<")
.replace(/&gt;/g, ">")
.replace(/&#x2F;/g, "/");
}
_headers() {
return { return {
"User-Agent": "Mozilla/5.0", "User-Agent": "Mozilla/5.0",
"Accept": "*/*", "Accept": "text/html",
"Referer": this.baseUrl + "/", "Referer": this.baseUrl + "/",
"Origin": this.baseUrl, "Origin": this.baseUrl,
"X-Requested-With": "XMLHttpRequest" "X-Requested-With": "XMLHttpRequest"
}; };
} }
_headersJson() {
return {
"User-Agent": "Mozilla/5.0",
"Accept": "application/json",
"Referer": this.baseUrl + "/",
"Origin": this.baseUrl,
"X-Requested-With": "XMLHttpRequest"
};
}
_decodeHtml(s) {
const str = this._safeStr(s);
if (!str) return "";
return str
.replace(/&amp;/g, "&")
.replace(/&quot;/g, '"')
.replace(/&#039;/g, "'")
.replace(/&lt;/g, "<")
.replace(/&gt;/g, ">")
.replace(/&#(\d+);/g, (_, n) => {
const code = parseInt(n, 10);
return isFinite(code) ? String.fromCharCode(code) : "";
});
}
_parseQuery(q) { _parseQuery(q) {
if (typeof q === "string") { if (typeof q === "string") {
const s = q.trim(); const s = q.trim();
@@ -90,8 +92,8 @@ class HiAnime {
return q || {}; return q || {};
} }
_wantTrackFromEpisode(ep) { _getSubOrDubFromAny(obj) {
const e = ep || {}; const e = obj || {};
if (typeof e.dub === "boolean") return e.dub ? "dub" : "sub"; if (typeof e.dub === "boolean") return e.dub ? "dub" : "sub";
const sod = String(e.subOrDub || "").toLowerCase(); const sod = String(e.subOrDub || "").toLowerCase();
@@ -114,255 +116,240 @@ class HiAnime {
return m ? m[1] : ""; return m ? m[1] : "";
} }
_bestTitle(obj) {
if (!obj) return "";
const t = obj.title;
if (typeof t === "string") return t;
if (t && typeof t === "object") {
return String(t.english || t.romaji || t.native || t.userPreferred || "");
}
return String(obj.name || obj.english || obj.romaji || "");
}
search(a1) { search(a1) {
const query = this._parseQuery(a1); const arg = this._parseQuery(a1);
const normalize = (str) => const q = this._safeStr(arg.query || arg.q || "").trim();
this.safeString(str).toLowerCase().replace(/[^a-z0-9]+/g, "");
const media = query.media || {};
const start = media.startDate || {};
const q = this.safeString(query.query || "").trim();
if (!q) return "[]"; if (!q) return "[]";
const url = `${this.baseUrl}/search?keyword=${encodeURIComponent(q)}&sy=${encodeURIComponent(String(start.year || ""))}&sm=${encodeURIComponent(String(start.month || ""))}&sort=default`; const subOrDub = this._getSubOrDubFromAny(arg);
const html = this._getText(url, {
"User-Agent": "Mozilla/5.0",
"Accept": "text/html",
"Referer": this.baseUrl + "/",
"Origin": this.baseUrl
});
const regex = /<a href="\/watch\/([^"]+)"[^>]+title="([^"]+)"[^>]+data-id="(\d+)"/g; const url = `${this.baseUrl}/ajax/search/suggest?keyword=${encodeURIComponent(q)}`;
const j = this._getJson(url, this._headersJson());
const matches = []; let results = [];
let m; if (j && Array.isArray(j.results)) {
while ((m = regex.exec(html)) !== null) { results = j.results
const id = m[3]; .map((x) => {
const pageUrl = m[1]; const title = this._bestTitle(x) || String(x.name || "");
const title = this._decodeHtml(m[2]); const u = x.url ? String(x.url) : "";
const full = u.startsWith("http") ? u : (u ? (this.baseUrl + u) : "");
const jnameRegex = new RegExp( const id = x.id ? String(x.id) : this._extractWatchIdFromUrl(full);
`<h3 class="film-name">[\\s\\S]*?<a[^>]+href="\\/${pageUrl}[^"]*"[^>]+data-jname="([^"]+)"`, return { id, title, url: full };
"i" })
); .filter((x) => x.id && x.url);
const jnameMatch = html.match(jnameRegex);
const jname = jnameMatch ? this._decodeHtml(jnameMatch[1]) : "";
const imageRegex = new RegExp(
`<a href="/watch/${pageUrl.replace(/\//g, "\\/")}"[\\s\\S]*?<img[^>]+data-src="([^"]+)"`,
"i"
);
const imageMatch = html.match(imageRegex);
const image = imageMatch ? String(imageMatch[1]) : "";
matches.push({
id,
pageUrl,
title,
image,
normTitleJP: normalize(this.normalizeSeasonParts(jname)),
normTitle: normalize(this.normalizeSeasonParts(title))
});
} }
if (matches.length === 0) return "[]"; if (!results.length) {
const url2 = `${this.baseUrl}/search?keyword=${encodeURIComponent(q)}`;
const html = this._getText(url2, this._headersHtml());
const wantTrack = query.dub ? "dub" : "sub"; const out = [];
const re = /href="(\/watch\/[^"]+)"/gi;
const seen = {};
let m;
while ((m = re.exec(html)) !== null) {
const href = String(m[1] || "");
const full = href.startsWith("http") ? href : (this.baseUrl + href);
const id = this._extractWatchIdFromUrl(full);
if (!id || seen[id]) continue;
seen[id] = true;
out.push({ id, title: q, url: full });
if (out.length >= 20) break;
}
results = out;
}
const out = matches.map(x => ({ const mapped = results.map((r) => ({
id: String(x.id), id: `${r.id}/${subOrDub}`,
title: String(x.title || ""), title: this._decodeHtml(r.title || ""),
image: String(x.image || ""), url: r.url,
url: `${this.baseUrl}/watch/${x.pageUrl}`, subOrDub
subOrDub: wantTrack
})); }));
return JSON.stringify(out); return JSON.stringify(mapped);
} }
findEpisodes(animeId) { findEpisodes(animeId) {
const raw = String(animeId || "").trim(); const parts = String(animeId || "").split("/");
if (!raw) return "[]";
const parts = raw.split("/");
const id = parts[0]; const id = parts[0];
const subOrDub = (parts[1] && (parts[1] === "dub" || parts[1] === "sub")) ? parts[1] : "sub"; const subOrDub = parts[1] || "sub";
if (!id) return "[]";
const json = this._getJson(`${this.baseUrl}/ajax/v2/episode/list/${encodeURIComponent(id)}`, { const j = this._getJson(
"X-Requested-With": "XMLHttpRequest" `${this.baseUrl}/ajax/v2/episode/list/${encodeURIComponent(id)}`,
}); this._headersJson()
);
const html = this._decodeHtml(String(json.html || json.result || "")); const html = this._decodeHtml(String(j.html || j.result || ""));
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 re = /data-number="([^"]+)"[^>]*data-id="([^"]+)"/gi;
let m;
let match; while ((m = re.exec(html)) !== null) {
while ((match = regex.exec(html)) !== null) { const numRaw = String(m[1] || "").trim();
const epId = String(m[2] || "").trim();
const num = parseFloat(numRaw);
if (!epId || !isFinite(num)) continue;
episodes.push({ episodes.push({
id: `${match[2]}/${subOrDub}`, id: `${epId}/${subOrDub}`,
number: parseInt(match[1], 10), number: num,
url: this.baseUrl + match[3], title: "",
title: this._decodeHtml(match[4] || "") url: ""
}); });
} }
episodes.sort((a, b) => (a.number || 0) - (b.number || 0));
return JSON.stringify(episodes); return JSON.stringify(episodes);
} }
findEpisodeServer(episodeObj, _server) { findEpisodeServer(episodeObj, serverName) {
let episode = episodeObj; let ep = episodeObj;
if (typeof episode === "string") { if (typeof ep === "string") {
try { episode = JSON.parse(episode); } catch (e) { episode = {}; } try { ep = JSON.parse(ep); } catch (e) { ep = {}; }
}
episode = episode || {};
const idParts = String(episode.id || "").split("/");
const episodeId = idParts[0];
if (!episodeId) throw new Error("Missing episode id");
const wantTrack = this._wantTrackFromEpisode(episode);
let serverName = String(_server || "").trim();
if (!serverName || serverName === "default") serverName = "HD-1";
if (serverName === "HD-4") {
throw new Error("HD-4 not implemented");
} }
const serverJson = this._getJson( const epIdRaw = this._safeStr(ep && ep.id ? ep.id : "").trim();
`${this.baseUrl}/ajax/v2/episode/servers?episodeId=${encodeURIComponent(episodeId)}`, if (!epIdRaw) throw new Error("Missing episode id");
{ "X-Requested-With": "XMLHttpRequest" }
const parts = epIdRaw.split("/");
const epId = parts[0];
const subOrDub = (parts[1] || "sub").toLowerCase();
const server = String(serverName || "").trim() || "HD-1";
if (server === "HD-4") return "null";
const j = this._getJson(
`${this.baseUrl}/ajax/v2/episode/servers?episodeId=${encodeURIComponent(epId)}`,
this._headersJson()
); );
const serverHtml = this._decodeHtml(String(serverJson.html || serverJson.result || "")); const html = this._decodeHtml(String(j.html || j.result || ""));
if (!serverHtml) throw new Error("Empty server list");
const esc = (s) => String(s || "").replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); const escapedServer = server.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
const strictRe = new RegExp( const reExact = new RegExp(
`<div[^>]*class="item\\s+server-item"[^>]*data-type="${esc(wantTrack)}"[^>]*data-id="(\\d+)"[^>]*>[\\s\\S]*?<a[^>]*>[\\s\\S]*?${esc(serverName)}[\\s\\S]*?<\\/a>`, `class="item server-item"[^>]*data-type="${subOrDub}"[^>]*data-id="([^"]+)"[^>]*>[\\s\\S]*?>\\s*${escapedServer}\\s*<`,
"i" "i"
); );
const mmExact = reExact.exec(html);
let m = strictRe.exec(serverHtml); let serverId = mmExact ? String(mmExact[1] || "").trim() : "";
let serverId = m ? String(m[1] || "").trim() : "";
if (!serverId) { if (!serverId) {
const trackAnyRe = new RegExp( const reFirst = new RegExp(`class="item server-item"[^>]*data-type="${subOrDub}"[^>]*data-id="([^"]+)"`, "i");
`<div[^>]*class="item\\s+server-item"[^>]*data-type="${esc(wantTrack)}"[^>]*data-id="(\\d+)"`, const mmFirst = reFirst.exec(html);
"i" if (mmFirst) serverId = String(mmFirst[1] || "").trim();
);
m = trackAnyRe.exec(serverHtml);
serverId = m ? String(m[1] || "").trim() : "";
} }
if (!serverId) { if (!serverId) throw new Error(`No server id found for track=${subOrDub}`);
const anyRe = /data-id="(\d+)"/i;
const mm = anyRe.exec(serverHtml);
serverId = mm ? String(mm[1] || "").trim() : "";
}
if (!serverId) throw new Error(`Server id not found (track=${wantTrack} server=${serverName})`);
const sourcesJson = this._getJson( const sourcesJson = this._getJson(
`${this.baseUrl}/ajax/v2/episode/sources?id=${encodeURIComponent(serverId)}`, `${this.baseUrl}/ajax/v2/episode/sources?id=${encodeURIComponent(serverId)}`,
{ "X-Requested-With": "XMLHttpRequest" } this._headersJson()
); );
const embedUrl = sourcesJson && sourcesJson.link ? String(sourcesJson.link) : ""; const embed = (sourcesJson && sourcesJson.link) ? String(sourcesJson.link) : "";
if (!embedUrl) throw new Error("No embed link returned"); if (!embed) throw new Error("No embed link returned");
let decryptData = null; let decryptData = null;
let requiredHeaders = {}; let requiredHeaders = {};
try { try {
decryptData = this.extractMegaCloudSync(embedUrl); decryptData = this.extractMegaCloudSync(embed);
requiredHeaders = (decryptData && decryptData.headersProvided) ? decryptData.headersProvided : {}; requiredHeaders = (decryptData && decryptData.headersProvided) ? decryptData.headersProvided : {};
} catch (e) { } catch (e) {
decryptData = null; decryptData = null;
} }
if (!decryptData) { if (!decryptData) {
decryptData = this._getJson( const fb = this._getJson(
`https://ac-api.ofchaos.com/api/anime/embed/convert/v2?embedUrl=${encodeURIComponent(embedUrl)}`, `https://ac-api.ofchaos.com/api/anime/embed/convert/v2?embedUrl=${encodeURIComponent(embed)}`,
{} { "User-Agent": "Mozilla/5.0", "Accept": "application/json" }
); );
decryptData = fb || {};
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": "Mozilla/5.0",
"X-Requested-With": "XMLHttpRequest" "X-Requested-With": "XMLHttpRequest"
}; };
} }
if (!decryptData || !decryptData.sources) throw new Error("No video sources from any decrypter"); const sources = Array.isArray(decryptData.sources) ? decryptData.sources : [];
const tracks = Array.isArray(decryptData.tracks) ? decryptData.tracks : [];
const sources = decryptData.sources || [];
const streamSource = const streamSource =
sources.find((s) => s && String(s.type || "").toLowerCase() === "hls" && s.file) || sources.find((s) => s && s.type === "hls" && s.file) ||
sources.find((s) => s && String(s.type || "").toLowerCase() === "mp4" && s.file) || sources.find((s) => s && s.type === "mp4" && s.file) ||
sources.find((s) => s && s.file); sources.find((s) => s && s.file);
if (!streamSource || !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 = tracks
.filter((t) => t && String(t.kind || "").toLowerCase() === "captions" && t.file) .filter((t) => t && String(t.kind || "").toLowerCase() === "captions" && t.file)
.map((track, index) => ({ .map((t, index) => ({
id: `sub-${index}`, id: `sub-${index}`,
language: String(track.label || "Unknown"), language: String(t.label || "Unknown"),
url: String(track.file), url: String(t.file),
isDefault: !!track.default isDefault: !!t.default
})); }));
const outType = (String(streamSource.type || "").toLowerCase() === "hls") ? "m3u8" : "mp4"; const out = {
server: server,
headers: requiredHeaders,
videoSources: [
{
url: String(streamSource.file),
type: String(streamSource.type || "").toLowerCase() === "hls" ? "m3u8" : "mp4",
quality: "auto",
subtitles: subtitles
}
]
};
return JSON.stringify({ return JSON.stringify(out);
server: serverName,
headers: requiredHeaders || {},
_debug: { scUsed: wantTrack, serverId: serverId },
videoSources: [{
url: String(streamSource.file),
type: outType,
quality: "auto",
subtitles
}]
});
} }
extractMegaCloudSync(embedUrl) { extractMegaCloudSync(embedUrl) {
const s = String(embedUrl || ""); const url = new URL(String(embedUrl));
const mm = s.match(/^(https?):\/\/([^\/]+)(\/.*)?$/i); const baseDomain = `${url.protocol}//${url.host}/`;
if (!mm) throw new Error("Invalid embedUrl");
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": `${protocol}://${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"
}; };
const html = this._getText(embedUrl, headers); const html = this._getText(String(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];
let nonce = null; let nonce = null;
const match48 = html.match(/\b[a-zA-Z0-9]{48}\b/); const match48 = html.match(/\b[a-zA-Z0-9]{48}\b/);
if (match48) nonce = match48[0]; if (match48) nonce = match48[0];
else {
const match3x16 = []; if (!nonce) {
const re = /["']([A-Za-z0-9]{16})["']/g; const match3x16 = [...html.matchAll(/["']([A-Za-z0-9]{16})["']/g)];
let m; if (match3x16.length >= 3) {
while ((m = re.exec(html)) !== null) match3x16.push(m[1]); nonce = match3x16[0][1] + match3x16[1][1] + match3x16[2][1];
if (match3x16.length >= 3) nonce = match3x16[0] + match3x16[1] + match3x16[2]; }
} }
if (!nonce) throw new Error("nonce not found"); if (!nonce) throw new Error("nonce not found");
const sourcesJson = this._getJson( const sourcesJson = this._getJson(
@@ -381,4 +368,4 @@ class HiAnime {
} }
} }
module.exports = new HiAnime(); module.exports = HiAnime;