class HiAnime { constructor() { this.type = "anime-streaming"; this.version = "1.0.3"; this.baseUrl = "https://hianime.to"; } getSettings() { return { episodeServers: ["HD-1", "HD-2", "HD-3"], 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, ""); const body = String(res.body || ""); try { return JSON.parse(body || "{}"); } catch (e) { return { _raw: body }; } } _safeStr(v) { return typeof v === "string" ? v : (v == null ? "" : String(v)); } _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(/</g, "<") .replace(/>/g, ">") .replace(///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 || {}; } _norm(s) { return String(s || "") .toLowerCase() .replace(/(season|cour|part|uncensored|movie|ova|ona|special)/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 || !b) return 0; const la = a.length, lb = b.length; const dp = Array.from({ length: la + 1 }, () => 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); } _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 || ""); } _extractWatchIdFromUrl(url) { const s = String(url || ""); const m = s.match(/\/watch\/[^\/]+-(\d+)/i); return m ? m[1] : ""; } _parseSearchHtmlToResults(html) { const out = []; const h = this._decodeHtml(html || ""); const re = /]+href="([^"]+\/watch\/[^"]+)"[^>]*>([\s\S]*?)<\/a>/gi; let m; const seen = {}; while ((m = re.exec(h)) !== null) { const href = String(m[1] || ""); const full = href.startsWith("http") ? href : (this.baseUrl + href); const id = this._extractWatchIdFromUrl(full); if (!id) continue; if (seen[id]) continue; seen[id] = true; const inner = String(m[2] || "").replace(/<[^>]+>/g, " ").replace(/\s+/g, " ").trim(); const title = inner || ""; out.push({ id: id, title: title, url: full }); } return out; } search(a1) { const arg = this._parseQuery(a1); const q = this._safeStr(arg.query || arg.q || "").trim(); if (!q) return "[]"; const url = `${this.baseUrl}/ajax/search/suggest?keyword=${encodeURIComponent(q)}`; const j = this._getJson(url, this._headers()); let results = []; if (j && Array.isArray(j.results)) { results = j.results.map((x) => { const title = this._bestTitle(x) || String(x.name || ""); const u = x.url ? String(x.url) : ""; const full = u.startsWith("http") ? u : (u ? (this.baseUrl + u) : ""); const id = x.id ? String(x.id) : this._extractWatchIdFromUrl(full); return { id, title, url: full }; }).filter((x) => x.id && x.url); } else { const html = String(j.html || j.result || ""); if (html) results = this._parseSearchHtmlToResults(html); } if (!results || results.length === 0) { const page = this._getText(`${this.baseUrl}/search?keyword=${encodeURIComponent(q)}`, { "User-Agent": "Mozilla/5.0", "Accept": "text/html", "Referer": this.baseUrl + "/", "Origin": this.baseUrl }); const re = /href="(\/watch\/[^"]+-\d+)"/gi; let mm; const seen = {}; while ((mm = re.exec(page)) !== null) { const href = mm[1]; const full = this.baseUrl + href; const id = this._extractWatchIdFromUrl(full); if (!id || seen[id]) continue; seen[id] = true; results.push({ id, title: q, url: full }); if (results.length >= 20) break; } } const nq = this._norm(q); results.forEach((r) => { const nt = this._norm(r.title || ""); r._score = this._levSim(nq, nt); }); results.sort((a, b) => (b._score || 0) - (a._score || 0)); return JSON.stringify(results.map((r) => ({ id: String(r.id), title: String(r.title || ""), url: String(r.url || "") }))); } findEpisodes(animeId) { const id = this._safeStr(animeId).trim(); if (!id) return "[]"; const j = this._getJson(`${this.baseUrl}/ajax/v2/episode/list/${encodeURIComponent(id)}`, this._headers()); const html = this._decodeHtml(String(j.html || j.result || "")); const episodes = []; const re = /data-number="([^"]+)"[^>]*data-id="([^"]+)"/gi; let m; while ((m = re.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({ id: epId, number: num, title: "", url: "" }); } if (episodes.length === 0) { const re2 = /data-episode-id="([^"]+)"[^>]*data-num="([^"]+)"/gi; while ((m = re2.exec(html)) !== null) { const epId = String(m[1] || "").trim(); const numRaw = String(m[2] || "").trim(); const num = parseFloat(numRaw); if (!epId || !isFinite(num)) continue; episodes.push({ id: epId, number: num, title: "", url: "" }); } } episodes.sort((a, b) => (a.number || 0) - (b.number || 0)); return JSON.stringify(episodes); } findEpisodeServer(episodeObj, serverName) { let ep = episodeObj; if (typeof ep === "string") { try { ep = JSON.parse(ep); } catch (e) { ep = {}; } } const epId = this._safeStr(ep && ep.id ? ep.id : "").trim(); if (!epId) throw new Error("Missing episode id"); const server = String(serverName || "").trim() || "HD-1"; const j = this._getJson(`${this.baseUrl}/ajax/v2/episode/servers?episodeId=${encodeURIComponent(epId)}`, this._headers()); const html = this._decodeHtml(String(j.html || j.result || "")); let serverId = ""; const re = new RegExp(`data-id="([^"]+)"[^>]*>\\s*${server.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}\\s*<`, "i"); const mm = re.exec(html); if (mm) serverId = String(mm[1] || "").trim(); if (!serverId) { const re2 = /data-id="([^"]+)"/i; const mm2 = re2.exec(html); if (mm2) serverId = String(mm2[1] || "").trim(); } if (!serverId) throw new Error("No server id found"); 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) { decryptData = this._getJson( `https://ac-api.ofchaos.com/api/anime/embed/convert/v2?embedUrl=${encodeURIComponent(embed)}`, {} ); 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 && 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 tracks = decryptData.tracks || []; const subtitles = (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: server, headers: requiredHeaders || {}, videoSources: [ { url: String(streamSource.file), type: outType, quality: "auto", subtitles: 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(/\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();