diff --git a/src/config.js b/src/config.js index 08d5b17..687913f 100644 --- a/src/config.js +++ b/src/config.js @@ -168,6 +168,25 @@ export const SOURCES = [ }], }, + { + key: 'bingebang', + label: 'BingeBang', + sourceFile: 'bingebang', + proxyParam: 'bb', + timeout: 30000, + jitter: 500, + retries: 2, + multiUrl: true, + dedicated: true, + cdnHeaders: [{ + pattern: /bingebang\.st/i, + headers: { + Referer: 'https://bingebang.st/', + Origin: 'https://bingebang.st', + }, + }], + }, + { key: 'castle', label: 'Castle', @@ -369,6 +388,18 @@ export const SOURCES = [ dedicated: true, }, + { + key: 'hicine', + label: 'Hicine', + sourceFile: 'hicine', + proxyParam: 'hc', + timeout: 30000, + jitter: 500, + retries: 2, + multiUrl: true, + dedicated: true, + }, + { key: 'hexa', label: 'Hexa', diff --git a/src/sources/bingebang.js b/src/sources/bingebang.js new file mode 100644 index 0000000..640fa09 --- /dev/null +++ b/src/sources/bingebang.js @@ -0,0 +1,383 @@ +import { USER_AGENT, getTmdbMetadata, resolveTmdbKey } from '../utils/helpers.js'; + +const encoder = new TextEncoder(); +const decoder = new TextDecoder(); + +const K256 = new Int32Array([ + 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, + 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, + 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, + 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, + 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, + 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, + 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, + 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 +]); + +const rotr = (x, n) => (x >>> n) | (x << (32 - n)); + +function sha256(bytes) { + const len = bytes.length; + const padded = new Uint8Array(((len + 9 + 63) >> 6) << 6); + padded.set(bytes); + padded[len] = 0x80; + const view = new DataView(padded.buffer); + view.setUint32(padded.length - 8, Math.floor((len * 8) / 4294967296)); + view.setUint32(padded.length - 4, (len * 8) >>> 0); + + const H = new Int32Array([0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19]); + const w = new Int32Array(64); + + for (let off = 0; off < padded.length; off += 64) { + for (let i = 0; i < 16; i++) w[i] = view.getInt32(off + i * 4); + for (let i = 16; i < 64; i++) { + const s0 = rotr(w[i - 15], 7) ^ rotr(w[i - 15], 18) ^ (w[i - 15] >>> 3); + const s1 = rotr(w[i - 2], 17) ^ rotr(w[i - 2], 19) ^ (w[i - 2] >>> 10); + w[i] = (w[i - 16] + s0 + w[i - 7] + s1) | 0; + } + let [a, b, c, d, e, f, g, h] = H; + for (let i = 0; i < 64; i++) { + const t1 = (h + (rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25)) + ((e & f) ^ (~e & g)) + K256[i] + w[i]) | 0; + const t2 = ((rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22)) + ((a & b) ^ (a & c) ^ (b & c))) | 0; + h = g; g = f; f = e; e = (d + t1) | 0; d = c; c = b; b = a; a = (t1 + t2) | 0; + } + H[0] += a; H[1] += b; H[2] += c; H[3] += d; H[4] += e; H[5] += f; H[6] += g; H[7] += h; + } + + const out = new Uint8Array(32); + const outView = new DataView(out.buffer); + for (let i = 0; i < 8; i++) outView.setInt32(i * 4, H[i]); + return out; +} + +function base64UrlDecode(v) { + let s = v.replace(/-/g, '+').replace(/_/g, '/').replace(/=+$/, ''); + s += '='.repeat((4 - (s.length % 4)) % 4); + const bin = Buffer.from(s, 'base64').toString('binary'); + const out = new Uint8Array(bin.length); + for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i); + return out; +} + +function parseNumList(s) { + return s.split(',').map((x) => parseInt(x, 10)).filter((x) => !isNaN(x)); +} + +function decryptXorBlock(html) { + if (!html) return null; + // Try multiple patterns for the key and data arrays + const km = /k\s*=\s*\[([0-9,\s]+)\]/i.exec(html) || + /key\s*=\s*\[([0-9,\s]+)\]/i.exec(html) || + /const\s+k\s*=\s*\[([0-9,\s]+)\]/i.exec(html); + const dm = /d\s*=\s*\[([0-9,\s]+)\]/i.exec(html) || + /data\s*=\s*\[([0-9,\s]+)\]/i.exec(html) || + /const\s+d\s*=\s*\[([0-9,\s]+)\]/i.exec(html); + if (!km || !dm) return null; + const key = parseNumList(km[1]); + const data = parseNumList(dm[1]); + if (!key.length || !data.length) return null; + return decoder.decode(Uint8Array.from(data, (x, i) => (x ^ key[i % key.length]) & 255)); +} + +function decryptPayload(body, ticket) { + const m = /"enc":"([^"]+)"/.exec(body); + if (!m) return body; + let raw; + try { + raw = base64UrlDecode(m[1]); + } catch { + return body; + } + if (raw.length <= 48) return body; + + const payload = raw.subarray(16); + const k = [199, 71, 13, 231, 255, 68, 237]; + const v = [254, 34, 63, 133, 200, 39, 217, 246, 38, 61, 129, 201, 32, 213, 242, 37, 62, 132, 206, 33, 218, 166, 126, 57, 129, 205, 113, 137, 247, 37, 53, 209]; + const seed = String.fromCharCode(...v.map((x, i) => x ^ k[i % k.length])); + const block = new Uint8Array(52); + block.set(sha256(encoder.encode(seed + ticket))); + block.set(raw.subarray(0, 16), 32); + const counterView = new DataView(block.buffer, 48, 4); + const out = new Uint8Array(payload.length); + + for (let pos = 0, counter = 0; pos < payload.length; pos += 32, counter++) { + counterView.setUint32(0, counter); + const stream = sha256(block); + const n = Math.min(32, payload.length - pos); + for (let i = 0; i < n; i++) out[pos + i] = payload[pos + i] ^ stream[i]; + } + return decoder.decode(out); +} + +function normalizeTitle(s) { + return String(s || '').toLowerCase().replace(/[^a-z0-9]+/g, ' ').trim(); +} + +function parseStreamQuality(raw) { + const s = String(raw || '').toLowerCase(); + if (s.includes('2160') || s.includes('4k')) return '4K'; + if (s.includes('1440') || s.includes('2k')) return '1440p'; + if (s.includes('1080') || s.includes('full hd') || s.includes('fhd')) return '1080p'; + if (s.includes('720') || s.includes('hd')) return '720p'; + if (s.includes('480') || s.includes('sd')) return '480p'; + return raw || 'Auto'; +} + +const BASE_URL = 'https://bingebang.sx'; + +const HEADERS = { + 'User-Agent': USER_AGENT, + Accept: 'application/json, text/plain, */*', + Referer: `${BASE_URL}/` +}; + +const PAGE_HEADERS = { + 'User-Agent': USER_AGENT, + Accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', + Referer: `${BASE_URL}/` +}; + +const PLAYBACK_HEADERS = { + Referer: `${BASE_URL}/`, + 'User-Agent': USER_AGENT +}; + +async function findWatchUrl({ title, year, tmdbId, isTv }) { + const searchQueries = new Set(); + if (title) searchQueries.add(title); + + if (tmdbId && searchQueries.size === 0) { + try { + const tmdbKey = process.env.TMDB_API_KEY || '45dbdd5e714da212424bda0336167447'; + const tmdbUrl = `https://api.themoviedb.org/3/${isTv ? 'tv' : 'movie'}/${tmdbId}?api_key=${tmdbKey}`; + const res = await fetch(tmdbUrl, { signal: AbortSignal.timeout(3000) }); + const data = await res.json(); + if (data?.title) searchQueries.add(data.title); + if (data?.name) searchQueries.add(data.name); + if (data?.original_title) searchQueries.add(data.original_title); + if (data?.original_name) searchQueries.add(data.original_name); + } catch {} + } + + for (const q of searchQueries) { + try { + const searchRes = await fetch( + `${BASE_URL}/api/search/multi?query=${encodeURIComponent(q)}`, + { headers: HEADERS, signal: AbortSignal.timeout(4000) } + ); + + const searchData = await searchRes.json(); + const results = (searchData?.results || []).filter( + (r) => r && r.url && (r.media_type === 'tv') === isTv + ); + + if (tmdbId) { + const byId = results.find( + (r) => String(r.id) === String(tmdbId) || String(r.tmdb_id) === String(tmdbId) + ); + if (byId) return byId.url; + } + + const wanted = normalizeTitle(q); + let best = null; + let bestScore = 0; + + for (const r of results) { + const t = normalizeTitle(r.title || r.name); + let score = 0; + if (t === wanted) score = 100; + else if (t.startsWith(wanted) || wanted.startsWith(t)) score = 60; + if (score && year && r.year && Math.abs(r.year - parseInt(year, 10)) <= 1) score += 20; + + if (score > bestScore) { + bestScore = score; + best = r; + } + } + + if (bestScore >= 60 && best?.url) { + return best.url; + } + } catch {} + } + + return null; +} + +export async function getStream(args) { + const { id, s, e, sdk, title: initialTitle, year: initialYear } = args || {}; + if (!id) return null; + + const isTv = s != null && e != null; + const season = parseInt(s, 10) || 1; + const episode = parseInt(e, 10) || 1; + + const apiKey = resolveTmdbKey(args, sdk); + const meta = await getTmdbMetadata(id, isTv, apiKey).catch(() => null); + + const title = initialTitle || meta?.title || ''; + const year = initialYear || meta?.year || ''; + + try { + const watchUrl = await findWatchUrl({ title, year, tmdbId: id, isTv }); + if (!watchUrl) return null; + + const playBase = (watchUrl.startsWith('http') ? watchUrl : `${BASE_URL}${watchUrl[0] === '/' ? '' : '/'}${watchUrl}`).replace('/watch/', '/play/'); + const playUrl = isTv ? `${playBase}/${season}/${episode}` : playBase; + + const pageRes = await fetch(playUrl, { + headers: PAGE_HEADERS, + signal: AbortSignal.timeout(5000), + }); + + const html = await pageRes.text(); + + // Try to extract ticket from various sources + let ticket = null; + + // Method 1: Try XOR decryption first + const decryptedConfig = decryptXorBlock(html); + if (decryptedConfig) { + const ticketMatch = /ticket:\s*"([^"]+)"/.exec(decryptedConfig) || + /ticket:\s*'([^']+)'/.exec(decryptedConfig) || + /"ticket"\s*:\s*"([^"]+)"/.exec(decryptedConfig) || + /ticket=([a-zA-Z0-9_-]+)/.exec(decryptedConfig); + if (ticketMatch) ticket = ticketMatch[1]; + } + + // Method 2: Try extracting from inline scripts + if (!ticket) { + const scriptMatch = /ticket["']?\s*[:=]\s*["']([a-zA-Z0-9_\-\.]+)["']/.exec(html) || + /"ticket"\s*:\s*"([^"]+)"/.exec(html) || + /data-ticket=["']([^"']+)["']/.exec(html); + if (scriptMatch) ticket = scriptMatch[1]; + } + + // Method 3: Try extracting from JSON-like structures in scripts + if (!ticket) { + const jsonMatch = /"ticket"\s*:\s*"([^"]{20,})"/.exec(html); + if (jsonMatch) ticket = jsonMatch[1]; + } + + if (!ticket) { + // If no ticket found, try without it (some endpoints might not require it) + console.log('No ticket found, trying without ticket'); + } + + // Build player headers + const playerHeaders = { + 'User-Agent': USER_AGENT, + Accept: 'application/json, text/plain, */*', + Referer: playUrl, + Origin: BASE_URL, + 'X-BB-Player': '1', + }; + + // Only add ticket if we found one + if (ticket) { + playerHeaders['X-BB-Ticket'] = ticket; + } + + // Also try with CSRF token if present in HTML + const csrfMatch = /name="csrf" content="([^"]+)"/.exec(html) || + /csrf-token" content="([^"]+)"/.exec(html); + if (csrfMatch && csrfMatch[1]) { + playerHeaders['X-CSRF-Token'] = csrfMatch[1]; + } + + const sourcesRes = await fetch(`${BASE_URL}/api/player/sources`, { + headers: playerHeaders, + signal: AbortSignal.timeout(5000), + }); + + const sourcesBody = await sourcesRes.text(); + const decryptedSources = decryptPayload(sourcesBody, ticket); + let sourcesData; + try { + sourcesData = JSON.parse(decryptedSources); + } catch { + return null; + } + + const rawServers = sourcesData.servers || []; + if (!Array.isArray(rawServers) || rawServers.length === 0) return null; + + const servers = rawServers.filter((s) => { + const idLower = String(s.id || '').toLowerCase(); + const labelLower = String(s.label || '').toLowerCase(); + return ( + idLower.includes('ymovies') || + idLower.includes('nepu') || + labelLower === 'yildun' || + labelLower === 'nashira' + ); + }); + + if (servers.length === 0) return null; + + const resolvePromises = servers.map(async (server, index) => { + const idLower = String(server.id || '').toLowerCase(); + let serverLabel = server.label || `Server ${index + 1}`; + if (idLower.includes('ymovies') || serverLabel.toLowerCase() === 'yildun') { + serverLabel = 'YMovies'; + } else if (idLower.includes('nepu') || serverLabel.toLowerCase() === 'nashira') { + serverLabel = 'Nepu'; + } + + if (!server.source_url) return null; + + try { + const resolveUrl = `${BASE_URL}/api/player/resolve?src=${encodeURIComponent(server.source_url)}`; + const resolveRes = await fetch(resolveUrl, { + headers: playerHeaders, + signal: AbortSignal.timeout(6000), + }); + + const resolveBody = await resolveRes.text(); + const decryptedResolve = decryptPayload(resolveBody, ticket); + const r = JSON.parse(decryptedResolve); + if (!r || !r.url) return null; + + const subtitles = []; + if (Array.isArray(r.subtitles)) { + for (const sub of r.subtitles) { + if (sub && sub.url) { + subtitles.push({ + url: sub.url, + language: sub.label || sub.lang || 'English', + name: sub.label || sub.lang || 'English' + }); + } + } + } + + const rawQuality = r.quality || server.quality || 'Auto'; + const quality = parseStreamQuality(rawQuality); + + return { + url: r.url, + server: `BingeBang · ${serverLabel}`, + quality, + type: r.url.includes('.m3u8') ? 'hls' : 'mp4', + headers: PLAYBACK_HEADERS, + subtitles: subtitles.length > 0 ? subtitles : undefined, + }; + } catch { + return null; + } + }); + + const resolvedList = await Promise.all(resolvePromises); + const allUrls = resolvedList.filter(Boolean); + + if (!allUrls.length) return null; + + return { + url: allUrls[0].url, + headers: allUrls[0].headers, + allUrls, + }; + } catch { + return null; + } +} diff --git a/src/sources/hicine.js b/src/sources/hicine.js new file mode 100644 index 0000000..b4118fa --- /dev/null +++ b/src/sources/hicine.js @@ -0,0 +1,540 @@ +import { USER_AGENT, getTmdbMetadata, resolveTmdbKey } from '../utils/helpers.js'; + +const API_BASE = 'https://api.hicine.sbs'; +const TMDB_API = 'https://api.themoviedb.org/3'; +const FALLBACK_WORKER_BASE = 'https://quiet-lab-41f9.yolku.workers.dev'; +const KNOWN_DEAD_WORKERS = new Set([ + 'snowy-sea-35bf.rukoy.workers.dev' +]); + +const HEADERS = { + 'User-Agent': USER_AGENT, + Accept: 'application/json', +}; + +const PLAYBACK_HEADERS = { + 'User-Agent': USER_AGENT, +}; + +function normalizeTitle(s) { + return String(s || '').toLowerCase() + .replace(/^(the|a|an)\s+/i, '') + .replace(/&/g, 'and') + .replace(/[^a-z0-9]+/g, ' ') + .trim(); +} + +function isTitleCompatible(foundTitle, expectedTitle) { + if (!foundTitle || !expectedTitle) return true; + const f = normalizeTitle(foundTitle); + const e = normalizeTitle(expectedTitle); + if (f === e) return true; + if (f.startsWith(e + ' ') || e.startsWith(f + ' ')) return true; + return false; +} + +function extractQuality(text) { + const s = String(text || ''); + const m = s.match(/\b(2160p|1440p|1080p|720p|480p|360p)\b/i) || s.match(/\b4k\b/i); + if (!m) return ''; + const q = m[1] ? m[1].toLowerCase() : '4k'; + return q === '4k' ? '2160p' : q; +} + +function extractSize(text) { + const m = String(text || '').match(/([\d.]+)\s*(GB|MB)/i); + return m ? `${m[1]} ${m[2].toUpperCase()}` : ''; +} + +function extractLanguages(text) { + const s = String(text || '').toLowerCase(); + const map = [ + { key: 'english', code: 'ENG' }, + { key: 'hindi', code: 'HIN' }, + { key: 'tamil', code: 'TAM' }, + { key: 'telugu', code: 'TEL' }, + { key: 'punjabi', code: 'PAN' }, + { key: 'urdu', code: 'URD' }, + { key: 'malayalam', code: 'MAL' }, + { key: 'kannada', code: 'KAN' }, + { key: 'marathi', code: 'MAR' }, + { key: 'bengali', code: 'BEN' }, + { key: 'japanese', code: 'JPN' }, + { key: 'korean', code: 'KOR' }, + { key: 'spanish', code: 'SPA' }, + { key: 'french', code: 'FRA' }, + { key: 'german', code: 'GER' } + ]; + + const detected = []; + if (/dual|dual audio|hindi-english|english-hindi/i.test(s)) { + detected.push('ENG', 'HIN'); + } + + for (const item of map) { + if (s.includes(item.key) && !detected.includes(item.code)) { + detected.push(item.code); + } + } + + return detected.length > 0 ? detected : ['ENG']; +} + +function extractMediaMeta(text) { + const s = String(text || ''); + const videoParts = []; + const audioParts = []; + + if (/imax/i.test(s)) videoParts.push('IMAX'); + if (/dolby\s*vision|dovi/i.test(s)) videoParts.push('Dolby Vision'); + else if (/hdr10\+/i.test(s)) videoParts.push('HDR10+'); + else if (/hdr10/i.test(s)) videoParts.push('HDR10'); + else if (/hdr/i.test(s)) videoParts.push('HDR'); + + if (/10bit|10\-bit/i.test(s)) videoParts.push('10-Bit'); + if (/hevc|x265|h265/i.test(s)) videoParts.push('HEVC'); + else if (/x264|h264/i.test(s)) videoParts.push('H.264'); + + if (/truehd\s*7\.1/i.test(s)) audioParts.push('TrueHD 7.1'); + else if (/ddp\s*7\.1|dd\+\s*7\.1/i.test(s)) audioParts.push('DDP 7.1'); + else if (/ddp\s*5\.1|dd\+\s*5\.1/i.test(s)) audioParts.push('DDP 5.1'); + else if (/dd\s*5\.1|5\.1/i.test(s)) audioParts.push('DD 5.1'); + + if (/atmos/i.test(s)) audioParts.push('Atmos'); + + return { + videoDetails: videoParts.join(' · '), + audioDetails: audioParts.join(' · ') + }; +} + +async function searchHicine(query) { + const fetchQuery = async (q) => { + try { + const res = await fetch(`${API_BASE}/api/search/${encodeURIComponent(q)}`, { + headers: HEADERS, + signal: AbortSignal.timeout(4000), + }); + const d = await res.json(); + return Array.isArray(d?.data) ? d.data : Array.isArray(d) ? d : []; + } catch { + return []; + } + }; + + let items = await fetchQuery(query); + const words = query.toLowerCase().split(/[^a-z0-9]+/i).filter((w) => w.length > 1); + + if (items.length < 3 && words.length > 1) { + const simplified = words.join(' '); + if (simplified !== query.toLowerCase()) { + const extra = await fetchQuery(simplified); + items = [...items, ...extra]; + } + } + + const seen = new Set(); + return items.filter((it) => it?.record_id && !seen.has(it.record_id) && seen.add(it.record_id)); +} + +function rankMatches(results, { title, year, isTv }) { + const norm = (s) => String(s || '').toLowerCase().replace(/&/g, 'and').replace(/[^a-z0-9]+/g, ' ').trim(); + const normTarget = norm(title); + const targetWords = normTarget.split(/\s+/).filter((w) => w.length > 1); + const targetYear = year ? parseInt(year, 10) : null; + + const scored = []; + + for (const rec of results) { + if (!rec || !rec.record_id) continue; + + const recCats = String(rec.categories || '').toLowerCase(); + const recType = String(rec.contentType || '').toLowerCase(); + const recIsTv = recType === 'series' || recCats.includes('series'); + + if (isTv && !recIsTv) continue; + if (!isTv && recIsTv) continue; + + const rawTitle = rec.title || rec.name || ''; + const cleanRecTitle = norm(rawTitle.replace(/\((19\d{2}|20\d{2})\).*/, '')); + + let score = 0; + if (cleanRecTitle === normTarget) { + score += 100; + } else if (cleanRecTitle.startsWith(normTarget) || normTarget.startsWith(cleanRecTitle)) { + score += 65; + } else if (cleanRecTitle.includes(normTarget) || normTarget.includes(cleanRecTitle)) { + score += 45; + } else if (targetWords.length > 0 && targetWords.every((w) => cleanRecTitle.includes(w))) { + score += 35; + } else { + continue; + } + + const titleYearMatch = rawTitle.match(/\b(19\d{2}|20\d{2})\b/); + if (titleYearMatch && targetYear) { + const y = parseInt(titleYearMatch[1], 10); + if (Math.abs(y - targetYear) <= 1) { + score += 50; + } else { + score -= 100; + } + } else if (targetYear) { + const catYears = (recCats.match(/\b(19\d{2}|20\d{2})\b/g) || []).map((y) => parseInt(y, 10)); + if (catYears.includes(targetYear)) { + score += 30; + } + } + + if (recCats.includes('hollywood')) score += 10; + if (recCats.includes('dual audio')) score += 5; + + if (score > 0) { + scored.push({ score, rec }); + } + } + + scored.sort((a, b) => b.score - a.score); + return scored.map((s) => s.rec); +} + +function detectCollection(categories, isTv) { + const cats = String(categories || '').toLowerCase(); + if (cats.includes('bollywood') && cats.includes('series')) return 'bollywood_series'; + if (cats.includes('bollywood')) return 'bollywood_movies'; + if (cats.includes('anime')) return 'anime'; + return isTv ? 'hollywood_series' : 'hollywood_movies'; +} + +function extractTitleFromSeasonHeader(header) { + const clean = String(header || '').replace(/^\[[^\]]*\]\s*/, '').trim(); + const m = clean.match(/^([^\(\n\r]+?)(?:\s*\((?:19\d{2}|20\d{2})\))?\s*Season\s*\d+/i); + return m ? m[1].trim() : null; +} + +function parseMovieTargets(linksField, expectedTitle = '') { + const out = []; + if (!linksField) return out; + + const lines = String(linksField).split(/\r?\n/); + for (const line of lines) { + const urlMatch = line.match(/https?:\/\/[^\s,]+/); + if (!urlMatch) continue; + + const quality = extractQuality(line) || '1080p'; + const size = extractSize(line); + const langs = extractLanguages(line); + const meta = extractMediaMeta(line); + + out.push({ + workerUrl: urlMatch[0], + quality, + size, + langs, + expectedTitle, + ...meta + }); + } + + return out; +} + +function parseSeriesTargets(seasonText, targetEpNum, expectedTitle = '') { + const out = []; + if (!seasonText) return out; + + const decoded = String(seasonText) + .replace(/&/g, '&') + .replace(/</g, '<') + .replace(/>/g, '>') + .replace(/"/g, '"') + .replace(/�?39;/g, "'") + .replace(/ /g, ' '); + + const lines = decoded.split(/\r?\n/); + const headerTitle = extractTitleFromSeasonHeader(lines[0] || ''); + if (headerTitle && expectedTitle && !isTitleCompatible(headerTitle, expectedTitle)) { + return out; + } + + const seasonHeaderLang = extractLanguages(lines[0] || ''); + + for (const line of lines) { + const epMatch = line.match(/episode\s*(\d+)\s*[:\-]?\s*(.*)/i); + if (!epMatch) continue; + + const num = parseInt(epMatch[1], 10); + if (num !== targetEpNum) continue; + + const content = epMatch[2] || ''; + const re = /(https?:\/\/[^\s,]+(?:https?:\/\/[^\s,]+)?)([\s\S]*?)(?=(?:https?:\/\/[a-z0-9.-]+\.workers\.dev|$))/gi; + let m; + + while ((m = re.exec(content)) !== null) { + const url = m[1].replace(/,.*$/, '').trim(); + const tail = m[2] || ''; + + const quality = extractQuality(tail) || '1080p'; + const size = extractSize(tail); + const meta = extractMediaMeta(tail || line); + + out.push({ + workerUrl: url, + quality, + size, + langs: seasonHeaderLang, + expectedTitle, + ...meta + }); + } + } + + return out; +} + +async function resolveWorker(target) { + const { workerUrl, quality, size, langs, expectedTitle, videoDetails, audioDetails } = target; + const qi = workerUrl.indexOf('?'); + if (qi < 0) return []; + + let base = workerUrl.slice(0, qi).replace(/\/+$/, ''); + const urlObj = new URL(workerUrl); + const vcloud = urlObj.searchParams.get('vcloud'); + if (!vcloud) return []; + + let hostname = ''; + try { + hostname = new URL(base).hostname.toLowerCase(); + } catch {} + + if (KNOWN_DEAD_WORKERS.has(hostname) || hostname.endsWith('.rukoy.workers.dev')) { + base = FALLBACK_WORKER_BASE; + } + + let data; + try { + const res = await fetch(`${base}/api/links?vcloud=${encodeURIComponent(vcloud)}`, { + headers: HEADERS, + signal: AbortSignal.timeout(15000), + }); + data = await res.json(); + } catch {} + + if ((!data || !data.tokens) && base !== FALLBACK_WORKER_BASE) { + try { + const fbRes = await fetch(`${FALLBACK_WORKER_BASE}/api/links?vcloud=${encodeURIComponent(vcloud)}`, { + headers: HEADERS, + signal: AbortSignal.timeout(15000), + }); + const fbData = await fbRes.json(); + if (fbData?.tokens) { + data = fbData; + base = FALLBACK_WORKER_BASE; + } + } catch {} + } + + if (!data) { + return [{ + url: workerUrl, + host: 'Worker', + serverLabel: 'Worker (Direct)', + quality, + size, + audioLanguages: langs, + videoDetails, + audioDetails + }]; + } + + if (data?.title && expectedTitle) { + const releaseMatch = String(data.title).match(/^([^\n\r]+?)\s+(?:S\d+|(?:\d{4}))/i); + const releaseTitle = releaseMatch ? releaseMatch[1].trim() : ''; + if (releaseTitle && !isTitleCompatible(releaseTitle, expectedTitle)) { + return []; + } + } + + const tokens = data?.tokens; + if (!tokens || typeof tokens !== 'object' || Object.keys(tokens).length === 0) { + return [{ + url: workerUrl, + host: 'Worker', + serverLabel: 'Worker (Direct)', + quality, + size, + audioLanguages: langs, + videoDetails, + audioDetails + }]; + } + + const candidateKeys = ['fsl2', 'fsl', 'server1', 'pixel']; + const activeKeys = candidateKeys.filter((k) => tokens[k]?.ts && tokens[k]?.sig); + + const resolvedStreams = []; + const exactSize = (data?.size && String(data.size).trim()) || size; + + for (const k of activeKeys) { + const tk = tokens[k]; + const goUrl = `${base}/go?type=${encodeURIComponent(k)}&vcloud=${encodeURIComponent(vcloud)}&ts=${encodeURIComponent(tk.ts)}&sig=${encodeURIComponent(tk.sig)}`; + + if (k === 'pixel') { + try { + const directRes = await fetch(goUrl, { + headers: { 'User-Agent': USER_AGENT, 'Range': 'bytes=0-0' }, + signal: AbortSignal.timeout(15000), + redirect: 'manual', + }); + const redirectedUrl = directRes.headers?.location || directRes.url || ''; + const m = redirectedUrl.match(/^https?:\/\/(pixeldrain\.[a-z]+)\/(?:u|api\/file)\/([A-Za-z0-9]+)/); + if (m) { + resolvedStreams.push({ + url: `https://${m[1]}/api/file/${m[2]}`, + host: 'PixelDrain', + serverLabel: 'PixelDrain', + quality, + size: exactSize, + audioLanguages: langs, + videoDetails, + audioDetails + }); + } + } catch {} + } else { + resolvedStreams.push({ + url: goUrl, + host: 'vCloud', + serverLabel: 'vCloud (R2)', + quality, + size: exactSize, + audioLanguages: langs, + videoDetails, + audioDetails + }); + } + } + + return resolvedStreams; +} + +export async function getStream(args) { + const { id, s, e, sdk, title: initialTitle, year: initialYear } = args || {}; + if (!id) return null; + + const isTv = s != null && e != null; + const seasonNum = parseInt(s, 10) || 1; + const epNum = parseInt(e, 10) || 1; + + const apiKey = resolveTmdbKey(args, sdk); + const meta = await getTmdbMetadata(id, isTv, apiKey).catch(() => null); + + let searchTitle = initialTitle || meta?.title || ''; + let searchYear = initialYear || meta?.year || ''; + + if (!searchTitle) { + return null; + } + + try { + const searchResults = await searchHicine(searchTitle); + if (!searchResults || searchResults.length === 0) { + return null; + } + + const candidates = rankMatches(searchResults, { + title: searchTitle, + year: searchYear, + isTv + }); + + if (!candidates || candidates.length === 0) { + return null; + } + + let targets = []; + for (const candidate of candidates) { + let record = candidate; + const needFetch = isTv + ? !record[`season_${seasonNum}`] + : !record.links; + + if (needFetch) { + const collection = detectCollection(record.categories, isTv); + try { + const detailRes = await fetch(`${API_BASE}/api/${collection}/${record.record_id}`, { + headers: HEADERS, + signal: AbortSignal.timeout(4000), + }); + const detailData = await detailRes.json(); + if (detailData && !detailData.error) { + record = { ...record, ...detailData }; + } + } catch {} + } + + const candidateTargets = isTv + ? parseSeriesTargets(record[`season_${seasonNum}`], epNum, searchTitle) + : parseMovieTargets(record.links, searchTitle); + + if (candidateTargets && candidateTargets.length > 0) { + targets = candidateTargets; + break; + } + } + + if (!targets || targets.length === 0) { + return null; + } + + const qRank = { '2160p': 4, '1440p': 3, '1080p': 2, '720p': 1, '480p': 0 }; + targets.sort((a, b) => (qRank[b.quality] || 0) - (qRank[a.quality] || 0)); + + const topTargets = targets.slice(0, 3); + + const resolvePromises = topTargets.map((target) => + resolveWorker(target).catch(() => []) + ); + + const resolvedBatches = await Promise.allSettled(resolvePromises); + const allCandidates = resolvedBatches + .map((r) => (r.status === 'fulfilled' && Array.isArray(r.value) ? r.value : [])) + .flat() + .filter(Boolean); + + const seenUrls = new Set(); + const seenHostSize = new Set(); + const allUrls = []; + + for (const item of allCandidates) { + if (!item?.url || seenUrls.has(item.url)) continue; + seenUrls.add(item.url); + + const dedupKey = `${item.host}|${item.size || ''}|${item.quality}`; + if (item.size && seenHostSize.has(dedupKey)) continue; + if (item.size) seenHostSize.add(dedupKey); + + const serverLabel = item.serverLabel || 'Hicine'; + const quality = item.quality || 'Auto'; + const type = item.url.includes('.m3u8') ? 'hls' : 'mp4'; + + allUrls.push({ + url: item.url, + server: serverLabel, + quality, + type, + headers: PLAYBACK_HEADERS, + }); + } + + if (!allUrls.length) return null; + + return { + url: allUrls[0].url, + headers: allUrls[0].headers, + allUrls, + }; + } catch { + return null; + } +}