Files
WaifuTV-Extensions/anime/hianime/source.js
2025-12-26 18:48:46 +01:00

385 lines
12 KiB
JavaScript

class HiAnime {
constructor() {
this.type = "anime-streaming";
this.version = "1.0.4";
this.baseUrl = "https://hianime.to";
}
getSettings() {
return {
episodeServers: ["HD-1", "HD-2", "HD-3", "HD-4"],
supportsDub: 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, "");
const body = String(res.body || "");
try {
return JSON.parse(body || "{}");
} catch (e) {
return { _raw: body };
}
}
safeString(str) {
return (typeof str === "string" ? str : "");
}
normalizeSeasonParts(title) {
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 {
"User-Agent": "Mozilla/5.0",
"Accept": "*/*",
"Referer": this.baseUrl + "/",
"Origin": this.baseUrl,
"X-Requested-With": "XMLHttpRequest"
};
}
_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(ep) {
const e = ep || {};
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";
}
_extractWatchIdFromUrl(url) {
const s = String(url || "");
const m = s.match(/\/watch\/[^\/]+-(\d+)/i);
return m ? m[1] : "";
}
search(a1) {
const query = this._parseQuery(a1);
const normalize = (str) =>
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 "[]";
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 regex = /<a href="\/watch\/([^"]+)"[^>]+title="([^"]+)"[^>]+data-id="(\d+)"/g;
const matches = [];
let m;
while ((m = regex.exec(html)) !== null) {
const id = m[3];
const pageUrl = m[1];
const title = this._decodeHtml(m[2]);
const jnameRegex = new RegExp(
`<h3 class="film-name">[\\s\\S]*?<a[^>]+href="\\/${pageUrl}[^"]*"[^>]+data-jname="([^"]+)"`,
"i"
);
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 "[]";
const wantTrack = query.dub ? "dub" : "sub";
const out = matches.map(x => ({
id: String(x.id),
title: String(x.title || ""),
image: String(x.image || ""),
url: `${this.baseUrl}/watch/${x.pageUrl}`,
subOrDub: wantTrack
}));
return JSON.stringify(out);
}
findEpisodes(animeId) {
const raw = String(animeId || "").trim();
if (!raw) return "[]";
const parts = raw.split("/");
const id = parts[0];
const subOrDub = (parts[1] && (parts[1] === "dub" || parts[1] === "sub")) ? parts[1] : "sub";
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] || "")
});
}
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 m = strictRe.exec(serverHtml);
let serverId = m ? String(m[1] || "").trim() : "";
if (!serverId) {
const trackAnyRe = new RegExp(
`<div[^>]*class="item\\s+server-item"[^>]*data-type="${esc(wantTrack)}"[^>]*data-id="(\\d+)"`,
"i"
);
m = trackAnyRe.exec(serverHtml);
serverId = m ? String(m[1] || "").trim() : "";
}
if (!serverId) {
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(
`${this.baseUrl}/ajax/v2/episode/sources?id=${encodeURIComponent(serverId)}`,
{ "X-Requested-With": "XMLHttpRequest" }
);
const embedUrl = sourcesJson && sourcesJson.link ? String(sourcesJson.link) : "";
if (!embedUrl) throw new Error("No embed link returned");
let decryptData = null;
let requiredHeaders = {};
try {
decryptData = this.extractMegaCloudSync(embedUrl);
requiredHeaders = (decryptData && decryptData.headersProvided) ? decryptData.headersProvided : {};
} catch (e) {
decryptData = null;
}
if (!decryptData) {
decryptData = this._getJson(
`https://ac-api.ofchaos.com/api/anime/embed/convert/v2?embedUrl=${encodeURIComponent(embedUrl)}`,
{}
);
requiredHeaders = {
"Referer": "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",
"X-Requested-With": "XMLHttpRequest"
};
}
if (!decryptData || !decryptData.sources) throw new Error("No video sources from any decrypter");
const sources = decryptData.sources || [];
const streamSource =
sources.find((s) => s && String(s.type || "").toLowerCase() === "hls" && s.file) ||
sources.find((s) => s && String(s.type || "").toLowerCase() === "mp4" && s.file) ||
sources.find((s) => s && s.file);
if (!streamSource || !streamSource.file) throw new Error("No valid stream file found");
const subtitles = (decryptData.tracks || [])
.filter((t) => t && String(t.kind || "").toLowerCase() === "captions" && t.file)
.map((track, index) => ({
id: `sub-${index}`,
language: String(track.label || "Unknown"),
url: String(track.file),
isDefault: !!track.default
}));
const outType = (String(streamSource.type || "").toLowerCase() === "hls") ? "m3u8" : "mp4";
return JSON.stringify({
server: serverName,
headers: requiredHeaders || {},
_debug: { scUsed: wantTrack, serverId: serverId },
videoSources: [{
url: String(streamSource.file),
type: outType,
quality: "auto",
subtitles
}]
});
}
extractMegaCloudSync(embedUrl) {
const s = String(embedUrl || "");
const mm = s.match(/^(https?):\/\/([^\/]+)(\/.*)?$/i);
if (!mm) throw new Error("Invalid embedUrl");
const protocol = mm[1].toLowerCase();
const host = mm[2];
const baseDomain = `${protocol}://${host}/`;
const headers = {
"Accept": "*/*",
"X-Requested-With": "XMLHttpRequest",
"Referer": baseDomain,
"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"
};
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 = [];
const re = /["']([A-Za-z0-9]{16})["']/g;
let m;
while ((m = re.exec(html)) !== null) match3x16.push(m[1]);
if (match3x16.length >= 3) nonce = match3x16[0] + match3x16[1] + match3x16[2];
}
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();