Files
WaifuTV-Extensions/anime/hianime/source.js
2025-12-26 20:19:08 +01:00

409 lines
13 KiB
JavaScript

class HiAnime {
constructor() {
this.type = "anime-streaming";
this.version = "1.0.2";
this.baseUrl = "https://hianime.to";
}
getSettings() {
return {
episodeServers: ["HD-1", "HD-2", "HD-3", "HD-4"],
supportsSub: true,
supportsDub: true,
supportsHls: true
};
}
_nativeFetch(url, method, headers, body) {
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: "" };
}
}
_getText(url, headers) {
const res = this._nativeFetch(url, "GET", headers, "");
return String(res.body || "");
}
_getJson(url, headers) {
const res = this._nativeFetch(url, "GET", headers, "");
try {
return JSON.parse(String(res.body || "{}"));
} catch (e) {
return {};
}
}
safeString(str) {
return typeof str === "string" ? str : (str == null ? "" : String(str));
}
_decodeHtml(s) {
const t = this.safeString(s);
if (!t) return "";
return t
.replace(/&/g, "&")
.replace(/"/g, "\"")
.replace(/'/g, "'")
.replace(/&lt;/g, "<")
.replace(/&gt;/g, ">")
.replace(/&nbsp;/g, " ")
.replace(/&#(\d+);/g, (_, n) => {
try { return String.fromCharCode(parseInt(n, 10)); } catch (e) { return ""; }
});
}
normalizeSeasonParts(title) {
const s = this.safeString(title);
return s.toLowerCase()
.replace(/\d+(st|nd|rd|th)/g, (m) => m.replace(/st|nd|rd|th/, ""))
.replace(/season|cour|part/g, "")
.replace(/[^a-z0-9]+/g, "");
}
_levSim(a, b) {
a = this.safeString(a);
b = this.safeString(b);
if (!a && !b) return 1;
if (!a || !b) return 0;
const la = a.length, lb = b.length;
const dp = new Array(la + 1);
for (let i = 0; i <= la; i++) dp[i] = new Array(lb + 1).fill(0);
for (let i = 0; i <= la; i++) dp[i][0] = i;
for (let j = 0; j <= lb; j++) dp[0][j] = j;
for (let i = 1; i <= la; i++) {
for (let j = 1; j <= lb; j++) {
const cost = a[i - 1] === b[j - 1] ? 0 : 1;
dp[i][j] = Math.min(
dp[i - 1][j] + 1,
dp[i][j - 1] + 1,
dp[i - 1][j - 1] + cost
);
}
}
const dist = dp[la][lb];
const maxLen = Math.max(la, lb) || 1;
return 1 - (dist / maxLen);
}
_titleOk(candidateNorm, targetNorm, targetNormJP) {
if (!candidateNorm) return false;
if (candidateNorm === targetNorm || candidateNorm === targetNormJP) return true;
if (candidateNorm.includes(targetNorm) || targetNorm.includes(candidateNorm)) return true;
if (candidateNorm.includes(targetNormJP) || targetNormJP.includes(candidateNorm)) return true;
return (this._levSim(candidateNorm, targetNorm) >= 0.72) || (this._levSim(candidateNorm, targetNormJP) >= 0.72);
}
_parseQuery(q) {
if (typeof q === "string") {
const s = q.trim();
if (s.startsWith("{") || s.startsWith("[")) {
try { return JSON.parse(s); } catch (e) { return { query: s }; }
}
return { query: s };
}
return q || {};
}
_wantTrackFromEpisode(e) {
if (!e) return "sub";
if (typeof e.dub === "boolean") return e.dub ? "dub" : "sub";
const sod = String(e.subOrDub || "").toLowerCase();
if (sod === "dub" || sod === "sub") return sod;
const tr = String(e.track || "").toLowerCase();
if (tr === "dub" || tr === "sub") return tr;
const id = String(e.id || "");
const parts = id.split("/");
const last = (parts.length >= 2 ? parts[parts.length - 1] : "").toLowerCase();
if (last === "dub" || last === "sub") return last;
return "sub";
}
search(a1) {
const query = this._parseQuery(a1);
const media = query.media || {};
const start = media.startDate || {};
const q = this.safeString(query.query || "").trim();
if (!q) return "[]";
const targetEn = this.safeString(media.englishTitle || media.english || media.titleEnglish || "");
const targetRo = this.safeString(media.romajiTitle || media.romaji || media.titleRomaji || "");
const targetNorm = this.normalizeSeasonParts(this._decodeHtml(targetEn || targetRo || q));
const targetNormJP = this.normalizeSeasonParts(this._decodeHtml(targetRo || q));
const url =
`${this.baseUrl}/search?keyword=${encodeURIComponent(q)}` +
`&sy=${encodeURIComponent(String(start.year || ""))}` +
`&sm=${encodeURIComponent(String(start.month || ""))}` +
`&sort=default`;
const html = this._getText(url, {
"User-Agent": "Mozilla/5.0",
"Accept": "text/html",
"Referer": this.baseUrl + "/",
"Origin": this.baseUrl
});
const re = /<a href="\/watch\/([^"]+)"[^>]+title="([^"]+)"[^>]+data-id="(\d+)"/g;
const matches = [];
let m;
while ((m = re.exec(html)) !== null) {
const id = String(m[3] || "");
const pageUrl = String(m[1] || "");
const title = this._decodeHtml(String(m[2] || ""));
const jnameRe = new RegExp(
`<h3 class="film-name">[\\s\\S]*?<a[^>]+href="\\/${pageUrl}[^"]*"[^>]+data-jname="([^"]+)"`,
"i"
);
const jnameMatch = html.match(jnameRe);
const jname = jnameMatch ? this._decodeHtml(jnameMatch[1]) : "";
const imageRe = new RegExp(
`<a href="/watch/${pageUrl.replace(/\//g, "\\/")}"[\\s\\S]*?<img[^>]+data-src="([^"]+)"`,
"i"
);
const imageMatch = html.match(imageRe);
const image = imageMatch ? String(imageMatch[1]) : "";
const normTitle = this.normalizeSeasonParts(title);
const normJP = this.normalizeSeasonParts(jname);
matches.push({
id,
pageUrl,
title,
image,
normTitle,
normJP
});
}
if (!matches.length) return "[]";
const wantTrack = query.dub ? "dub" : "sub";
let filtered = matches.filter(x => this._titleOk(x.normTitle, targetNorm, targetNormJP) || this._titleOk(x.normJP, targetNorm, targetNormJP));
if (!filtered.length) {
const qNorm = this.normalizeSeasonParts(q);
filtered = matches.filter(x => this._titleOk(x.normTitle, qNorm, qNorm) || this._titleOk(x.normJP, qNorm, qNorm));
}
if (!filtered.length) return "[]";
filtered.sort((a, b) => {
const sa = Math.max(this._levSim(a.normTitle, targetNorm), this._levSim(a.normJP, targetNormJP));
const sb = Math.max(this._levSim(b.normTitle, targetNorm), this._levSim(b.normJP, targetNormJP));
return sb - sa;
});
return JSON.stringify(filtered.map(x => ({
id: `${x.id}/${wantTrack}`,
title: x.title,
image: x.image,
url: `${this.baseUrl}/watch/${x.pageUrl}`,
subOrDub: wantTrack
})));
}
findEpisodes(animeId) {
const parts = String(animeId || "").split("/");
const id = parts[0];
const subOrDub = (parts[1] || "sub").toLowerCase();
const json = this._getJson(`${this.baseUrl}/ajax/v2/episode/list/${encodeURIComponent(id)}`, {
"X-Requested-With": "XMLHttpRequest"
});
const html = this._decodeHtml(String(json.html || json.result || ""));
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;
while ((match = regex.exec(html)) !== null) {
episodes.push({
id: `${match[2]}/${subOrDub}`,
number: parseInt(match[1], 10),
url: this.baseUrl + match[3],
title: this._decodeHtml(match[4] || "")
});
}
episodes.sort((a, b) => (a.number || 0) - (b.number || 0));
return JSON.stringify(episodes);
}
findEpisodeServer(episodeObj, _server) {
let episode = episodeObj;
if (typeof episode === "string") {
try { episode = JSON.parse(episode); } catch (e) { episode = {}; }
}
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(
`${this.baseUrl}/ajax/v2/episode/servers?episodeId=${encodeURIComponent(episodeId)}`,
{ "X-Requested-With": "XMLHttpRequest" }
);
const serverHtml = this._decodeHtml(String(serverJson.html || serverJson.result || ""));
if (!serverHtml) throw new Error("Empty server list");
const esc = (s) => String(s || "").replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
const strictRe = 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>`,
"i"
);
let mm = strictRe.exec(serverHtml);
let serverId = mm ? String(mm[1] || "").trim() : "";
if (!serverId) {
const trackAnyRe = new RegExp(
`<div[^>]*class="item\\s+server-item"[^>]*data-type="${esc(wantTrack)}"[^>]*data-id="(\\d+)"`,
"i"
);
mm = trackAnyRe.exec(serverHtml);
serverId = mm ? String(mm[1] || "").trim() : "";
}
if (!serverId) throw new Error(`No server id found for track=${wantTrack}`);
const sourcesJson = this._getJson(
`${this.baseUrl}/ajax/v2/episode/sources?id=${encodeURIComponent(serverId)}`,
{ "X-Requested-With": "XMLHttpRequest" }
);
const embed = (sourcesJson && sourcesJson.link) ? String(sourcesJson.link) : "";
if (!embed) throw new Error("No embed link returned");
let decryptData = null;
let requiredHeaders = {};
try {
decryptData = this.extractMegaCloudSync(embed);
requiredHeaders = (decryptData && decryptData.headersProvided) ? decryptData.headersProvided : {};
} catch (e) {
decryptData = null;
}
if (!decryptData) {
const fb = this._getJson(
`https://ac-api.ofchaos.com/api/anime/embed/convert/v2?embedUrl=${encodeURIComponent(embed)}`,
{ "User-Agent": "Mozilla/5.0", "Accept": "application/json" }
);
decryptData = fb || {};
requiredHeaders = {
"Referer": "https://megacloud.club/",
"Origin": "https://megacloud.club",
"User-Agent": "Mozilla/5.0",
"X-Requested-With": "XMLHttpRequest"
};
}
const sources = Array.isArray(decryptData.sources) ? decryptData.sources : [];
const tracks = Array.isArray(decryptData.tracks) ? decryptData.tracks : [];
let streamSource =
sources.find((s) => s && s.type === "hls" && s.file) ||
sources.find((s) => s && s.type === "mp4" && s.file) ||
sources.find((s) => s && s.file);
if (!streamSource || !streamSource.file) throw new Error("No valid stream file found");
const subtitles = tracks
.filter((t) => t && String(t.kind || "").toLowerCase() === "captions" && t.file)
.map((t, idx) => ({
id: `sub-${idx}`,
language: this._decodeHtml(t.label || "Unknown"),
url: String(t.file),
isDefault: !!t.default
}));
return JSON.stringify({
server: serverName,
headers: requiredHeaders,
videoSources: [{
url: String(streamSource.file),
type: (String(streamSource.type || "").toLowerCase() === "hls" || String(streamSource.file).includes(".m3u8")) ? "m3u8" : "mp4",
quality: "auto",
subtitles
}]
});
}
extractMegaCloudSync(embedUrl) {
const url = new URL(String(embedUrl));
const baseDomain = `${url.protocol}//${url.host}/`;
const headers = {
"Accept": "*/*",
"X-Requested-With": "XMLHttpRequest",
"Referer": baseDomain,
"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"
};
const html = this._getText(embedUrl, headers);
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");
const fileId = fileIdMatch[1];
let nonce = null;
const match48 = html.match(/\b[a-zA-Z0-9]{48}\b/);
if (match48) nonce = match48[0];
else {
const match3x16 = Array.from(html.matchAll(/["']([A-Za-z0-9]{16})["']/g));
if (match3x16.length >= 3) {
nonce = match3x16[0][1] + match3x16[1][1] + match3x16[2][1];
}
}
if (!nonce) throw new Error("nonce not found");
const sourcesJson = this._getJson(
`${baseDomain}embed-2/v3/e-1/getSources?id=${encodeURIComponent(fileId)}&_k=${encodeURIComponent(nonce)}`,
headers
);
return {
sources: sourcesJson.sources,
tracks: sourcesJson.tracks || [],
intro: sourcesJson.intro || null,
outro: sourcesJson.outro || null,
server: sourcesJson.server || null,
headersProvided: headers
};
}
}
module.exports = new HiAnime();