Update anime/hianime/source.js

This commit is contained in:
2025-12-26 17:52:10 +01:00
parent 05b77e18b0
commit 708cf12b88

View File

@@ -1,104 +1,261 @@
class HiAnime { class HiAnime {
constructor() { constructor() {
this.type = "anime-streaming"; this.type = "anime-streaming";
this.version = "1.0.0"; this.version = "1.0.1";
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"],
supportsSub: true, supportsSub: true,
supportsDub: true, supportsDub: true,
supportsHls: true supportsHls: true
}; };
} }
_nativeFetch(url, method, headers, body) { async _getText(url, headers) {
const raw = Native.fetch( const res = await fetch(String(url), { method: "GET", headers: headers || {} });
String(url), return String(await res.text());
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) { async _getJson(url, headers) {
const res = this._nativeFetch(url, "GET", headers, ""); const res = await fetch(String(url), { method: "GET", headers: headers || {} });
return String(res.body || "");
}
_getJson(url, headers) {
const res = this._nativeFetch(url, "GET", headers, "");
try { try {
return JSON.parse(String(res.body || "{}")); return await res.json();
} catch (e) { } catch (e) {
return {}; return {};
} }
} }
search(query) { _decodeHtml(s) {
if (typeof query === "string") return String(s || "")
query = { query, media: { startDate: { year: 0, month: 0, day: 0 } } }; .replace(/\\u0026/g, "&")
.replace(/&#(\d+);?/g, (m, d) => {
const start = (query.media && query.media.startDate) || { year: 0, month: 0, day: 0 }; try { return String.fromCharCode(parseInt(d, 10)); } catch (e) { return m; }
const sy = start.year || 0; })
const sm = start.month || 0; .replace(/"/g, '"')
const sd = start.day || 0; .replace(/'/g, "'")
.replace(/&/g, "&")
const url = .replace(/&lt;/g, "<")
`${this.baseUrl}/search?keyword=${encodeURIComponent(query.query)}` + .replace(/&gt;/g, ">");
`&sy=${sy}&sm=${sm}` +
(sd ? `&sd=${sd}` : ``) +
`&sort=default`;
const html = this._getText(url, {});
const regex = /<a href="\/watch\/([^"]+)"[^>]+title="([^"]+)"[^>]+data-id="(\d+)"/g;
const matches = [...html.matchAll(regex)].map((m) => {
const id = m[3];
const pageUrl = m[1];
const title = m[2];
const imageRegex = new RegExp(
`<a href="/watch/${pageUrl.replace(/\//g, "\\/")}"[\\s\\S]*?<img[^>]+data-src="([^"]+)"`,
"i"
);
const imageMatch = html.match(imageRegex);
const image = imageMatch ? imageMatch[1] : null;
return { id, pageUrl, title, image };
});
if (!matches.length) return [];
const subOrDub = query.dub ? "dub" : "sub";
return matches.map((m) => ({
id: `${m.id}/${subOrDub}`,
title: m.title,
image: m.image,
url: `${this.baseUrl}/watch/${m.pageUrl}`,
subOrDub
}));
} }
findEpisodes(animeId) { _normalizeTitle(s) {
const parts = String(animeId).split("/"); return String(s || "")
.toLowerCase()
.replace(/(season|cour|part|uncensored)/g, " ")
.replace(/\d+(st|nd|rd|th)\b/g, (m) => m.replace(/st|nd|rd|th/g, ""))
.replace(/[^a-z0-9\s]+/g, " ")
.replace(/\s+/g, " ")
.trim();
}
_levSim(a, b) {
a = String(a || "");
b = String(b || "");
if (!a.length || !b.length) return 0;
const la = a.length, lb = b.length;
const dp = [];
for (let i = 0; i <= la; i++) {
dp[i] = new Array(lb + 1);
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++) {
if (a[i - 1] === b[j - 1]) dp[i][j] = dp[i - 1][j - 1];
else {
const x = dp[i - 1][j] + 1;
const y = dp[i][j - 1] + 1;
const z = dp[i - 1][j - 1] + 1;
dp[i][j] = Math.min(x, y, z);
}
}
}
const dist = dp[la][lb];
const maxLen = Math.max(la, lb) || 1;
return 1 - dist / maxLen;
}
_parseStartDate(dateStr) {
const s = String(dateStr || "").trim();
const m = s.match(/([A-Za-z]+)\s+(\d{1,2}),\s*(\d{4})/);
if (!m) return { year: 0, month: 0, day: 0 };
const monthMap = {
Jan: 1, Feb: 2, Mar: 3, Apr: 4, May: 5, Jun: 6,
Jul: 7, Aug: 8, Sep: 9, Oct: 10, Nov: 11, Dec: 12
};
const mm = monthMap[m[1]] || 0;
const dd = parseInt(m[2], 10) || 0;
const yy = parseInt(m[3], 10) || 0;
return { year: yy, month: mm, day: dd };
}
_scoreCandidate(candidateTitle, candidateJp, targetEn, targetRo, targetYear) {
const cand = this._normalizeTitle(this._decodeHtml(candidateTitle));
const candJ = this._normalizeTitle(this._decodeHtml(candidateJp));
const tEn = this._normalizeTitle(targetEn);
const tRo = this._normalizeTitle(targetRo);
let best = 0;
const pairs = [
[cand, tEn],
[cand, tRo],
[candJ, tRo],
[candJ, tEn]
];
for (let i = 0; i < pairs.length; i++) {
const a = pairs[i][0], b = pairs[i][1];
if (!a || !b) continue;
if (a === b) best = Math.max(best, 1000);
if (a.includes(b) || b.includes(a)) best = Math.max(best, 700);
const sim = this._levSim(a, b);
best = Math.max(best, Math.floor(sim * 650));
}
if (targetYear && targetYear > 0) {
best += 0;
}
return best;
}
async search(query) {
if (typeof query === "string") {
query = { query, media: { startDate: { year: 0, month: 0, day: 0 } } };
}
const q = query && query.query ? String(query.query) : "";
const media = (query && query.media) || {};
const start = (media && media.startDate) || { year: 0, month: 0, day: 0 };
const targetYear = (start && start.year) ? (start.year | 0) : 0;
const targetEn = media.englishTitle || media.english || media.titleEnglish || "";
const targetRo = media.romajiTitle || media.romaji || media.titleRomaji || "";
const subOrDub = query && query.dub ? "dub" : "sub";
let candidates = [];
try {
const url = `${this.baseUrl}/ajax/search/suggest?keyword=${encodeURIComponent(q)}`;
const reply = await this._getJson(url, { "X-Requested-With": "XMLHttpRequest" });
const html = String((reply && reply.html) || "");
const regex =
/<a[^>]+href="\/([^"]+)"[^>]*class="nav-item"[^>]*>[\s\S]*?<h3[^>]*class="film-name"[^>]*data-jname="([^"]*)"[^>]*>([^<]*)<\/h3>[\s\S]*?<div[^>]*class="film-infor"[^>]*>[\s\S]*?<span[^>]*>([^<]*)<\/span>/gi;
const imgRegex = /<img[^>]+(?:data-src|src)="([^"]+)"[^>]*>/i;
const matches = [...html.matchAll(regex)];
for (let i = 0; i < matches.length; i++) {
const pageUrlRaw = matches[i][1] || "";
if (!pageUrlRaw || pageUrlRaw.startsWith("search?")) continue;
const jname = matches[i][2] || "";
const title = matches[i][3] || "";
const dateStr = matches[i][4] || "";
const startDate = this._parseStartDate(dateStr);
const pageUrl = pageUrlRaw.startsWith("watch/") ? pageUrlRaw : pageUrlRaw;
const idMatch = String(pageUrl).match(/-(\d+)$/);
const id = idMatch ? idMatch[1] : pageUrl;
const blockStart = html.indexOf(matches[i][0]);
const slice = blockStart >= 0 ? html.slice(blockStart, blockStart + 800) : matches[i][0];
const im = slice.match(imgRegex);
const image = im ? im[1] : null;
candidates.push({
id,
pageUrl,
title: this._decodeHtml(title),
jname: this._decodeHtml(jname),
image,
startDate
});
}
} catch (e) {
}
if (!candidates.length) {
const url = `${this.baseUrl}/search?keyword=${encodeURIComponent(q)}`;
const html = await this._getText(url, {});
const regex = /<a href="\/watch\/([^"]+)"[^>]+title="([^"]+)"[^>]+data-id="(\d+)"/g;
const matches = [...html.matchAll(regex)];
for (let i = 0; i < matches.length; i++) {
const pageUrl = matches[i][1];
const title = matches[i][2];
const id = matches[i][3];
const imageRegex = new RegExp(
`<a href="/watch/${String(pageUrl).replace(/\//g, "\\/")}"[\\s\\S]*?<img[^>]+(?:data-src|src)="([^"]+)"`,
"i"
);
const imageMatch = html.match(imageRegex);
const image = imageMatch ? imageMatch[1] : null;
candidates.push({
id,
pageUrl: "watch/" + pageUrl,
title: this._decodeHtml(title),
jname: "",
image,
startDate: { year: 0, month: 0, day: 0 }
});
}
}
if (!candidates.length) return [];
// Score + filter by year when available
const scored = candidates.map((c) => {
const score = this._scoreCandidate(c.title, c.jname, targetEn, targetRo, targetYear);
let yearBonus = 0;
if (targetYear > 0 && c.startDate && c.startDate.year > 0) {
if (c.startDate.year === targetYear) yearBonus = 140;
else if (Math.abs(c.startDate.year - targetYear) === 1) yearBonus = 40;
else yearBonus = -80;
}
return { c, score: score + yearBonus };
});
scored.sort((a, b) => b.score - a.score);
const top = scored.slice(0, 30).map((x) => x.c);
return top.map((m) => {
const id = String(m.id || "");
const pageUrl = String(m.pageUrl || "");
const url = pageUrl.startsWith("http") ? pageUrl : (pageUrl.startsWith("watch/") ? `${this.baseUrl}/${pageUrl}` : `${this.baseUrl}/${pageUrl}`);
return {
id: `${id}/${subOrDub}`,
title: m.title || "",
image: m.image || null,
url,
subOrDub
};
});
}
async findEpisodes(animeId) {
const parts = String(animeId || "").split("/");
const id = parts[0]; const id = parts[0];
const subOrDub = parts[1] || "sub"; const subOrDub = parts[1] || "sub";
const json = this._getJson( const json = await this._getJson(
`${this.baseUrl}/ajax/v2/episode/list/${id}`, `${this.baseUrl}/ajax/v2/episode/list/${id}`,
{ "X-Requested-With": "XMLHttpRequest" } { "X-Requested-With": "XMLHttpRequest" }
); );
const html = String(json.html || "");
const html = String((json && json.html) || "");
const episodes = []; const episodes = [];
const regex = const regex =
/<a[^>]*class="[^"]*\bep-item\b[^"]*"[^>]*data-number="(\d+)"[^>]*data-id="(\d+)"[^>]*href="([^"]+)"[\s\S]*?<div class="ep-name[^"]*"[^>]*title="([^"]+)"/g; /<a[^>]*class="[^"]*\bep-item\b[^"]*"[^>]*data-number="(\d+)"[^>]*data-id="(\d+)"[^>]*href="([^"]+)"[\s\S]*?<div class="ep-name[^"]*"[^>]*title="([^"]+)"/g;
@@ -108,56 +265,60 @@ class HiAnime {
id: `${match[2]}/${subOrDub}`, id: `${match[2]}/${subOrDub}`,
number: parseInt(match[1], 10), number: parseInt(match[1], 10),
url: this.baseUrl + match[3], url: this.baseUrl + match[3],
title: match[4] title: this._decodeHtml(match[4] || "")
}); });
} }
return episodes; return episodes;
} }
findEpisodeServer(episode, _server) { async findEpisodeServer(episode, _server) {
if (typeof episode === "string") { if (typeof episode === "string") {
try { episode = JSON.parse(episode); } catch (e) {} try { episode = JSON.parse(episode); } catch (e) {}
} }
const parts = String((episode && episode.id) || "").split("/"); const parts = String((episode && episode.id) || "").split("/");
const id = parts[0]; const epId = parts[0];
const subOrDub = parts[1] || "sub"; const subOrDub = parts[1] || "sub";
const serverName = _server !== "default" ? _server : "HD-1"; let serverName = _server && _server !== "default" ? String(_server) : "HD-1";
if (_server === "HD-4") return null; if (serverName === "HD-4") return null;
const serverJson = this._getJson( const serverJson = await this._getJson(
`${this.baseUrl}/ajax/v2/episode/servers?episodeId=${id}`, `${this.baseUrl}/ajax/v2/episode/servers?episodeId=${encodeURIComponent(epId)}`,
{ "X-Requested-With": "XMLHttpRequest" } { "X-Requested-With": "XMLHttpRequest" }
); );
const serverHtml = String(serverJson.html || ""); const serverHtml = String((serverJson && 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) throw new Error(`Server "${serverName}" (${subOrDub}) not found`);
const serverId = match[1]; const serverId = match[1];
const sourcesJson = this._getJson( const sourcesJson = await this._getJson(
`${this.baseUrl}/ajax/v2/episode/sources?id=${serverId}`, `${this.baseUrl}/ajax/v2/episode/sources?id=${encodeURIComponent(serverId)}`,
{ "X-Requested-With": "XMLHttpRequest" } { "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 decryptData = null;
let requiredHeaders = {}; let requiredHeaders = {};
try { try {
decryptData = this.extractMegaCloudSync(sourcesJson.link); decryptData = await this.extractMegaCloud(embed);
requiredHeaders = decryptData.headersProvided || {}; requiredHeaders = (decryptData && decryptData.headersProvided) ? decryptData.headersProvided : {};
} catch (e) {} } catch (e) {
decryptData = null;
}
if (!decryptData) { if (!decryptData) {
decryptData = this._getJson( decryptData = await this._getJson(
`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(embed)}`,
{} {}
); );
requiredHeaders = { requiredHeaders = {
@@ -169,27 +330,31 @@ class HiAnime {
}; };
} }
const sources = decryptData.sources || []; const sources = (decryptData && decryptData.sources) ? decryptData.sources : [];
const streamSource = const streamSource =
sources.find((s) => s.type === "hls") || sources.find((s) => s.type === "mp4"); 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"); if (!streamSource || !streamSource.file) throw new Error("No valid stream file found");
const subtitles = (decryptData.tracks || []) const tracks = (decryptData && (decryptData.tracks || decryptData.track || decryptData.subtitle)) || [];
.filter((t) => t.kind === "captions") const subtitles = (tracks || [])
.filter((t) => t && String(t.kind || "").toLowerCase() === "captions" && t.file)
.map((track, index) => ({ .map((track, index) => ({
id: `sub-${index}`, id: `sub-${index}`,
language: track.label || "Unknown", language: String(track.label || "Unknown"),
url: track.file, url: String(track.file),
isDefault: !!track.default isDefault: !!track.default
})); }));
return { return {
server: serverName, server: serverName,
headers: requiredHeaders, headers: requiredHeaders || {},
videoSources: [ videoSources: [
{ {
url: streamSource.file, url: String(streamSource.file),
type: streamSource.type === "hls" ? "m3u8" : "mp4", type: String(streamSource.type || "").toLowerCase() === "hls" ? "m3u8" : "mp4",
quality: "auto", quality: "auto",
subtitles subtitles
} }
@@ -197,13 +362,10 @@ class HiAnime {
}; };
} }
extractMegaCloudSync(embedUrl) { async extractMegaCloud(embedUrl) {
const s = String(embedUrl); const u = new URL(String(embedUrl));
const mm = s.match(/^(https?):\/\/([^\/]+)(\/.*)?$/i); const protocol = String(u.protocol || "https:").replace(":", "");
if (!mm) throw new Error("Invalid embedUrl: " + s); const host = String(u.host || "");
const protocol = mm[1].toLowerCase();
const host = mm[2];
const baseDomain = `${protocol}://${host}/`; const baseDomain = `${protocol}://${host}/`;
const headers = { const headers = {
@@ -215,23 +377,26 @@ class HiAnime {
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/139.0.0.0 Safari/537.36" "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 html = await 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];
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 {
if (!nonce) {
const match3x16 = [...html.matchAll(/["']([A-Za-z0-9]{16})["']/g)]; const match3x16 = [...html.matchAll(/["']([A-Za-z0-9]{16})["']/g)];
if (match3x16.length >= 3) nonce = match3x16[0][1] + match3x16[1][1] + match3x16[2][1]; if (match3x16.length >= 3) nonce = match3x16[0][1] + match3x16[1][1] + match3x16[2][1];
} }
if (!nonce) throw new Error("nonce not found"); if (!nonce) throw new Error("nonce not found");
const sourcesJson = this._getJson( const sourcesJson = await this._getJson(
`${baseDomain}embed-2/v3/e-1/getSources?id=${fileId}&_k=${nonce}`, `${baseDomain}embed-2/v3/e-1/getSources?id=${encodeURIComponent(fileId)}&_k=${encodeURIComponent(nonce)}`,
headers headers
); );