import express from "express"; import path from "path"; import fs from "fs"; import vm from "vm"; import { createServer as createViteServer } from "vite"; const app = express(); const PORT = process.env.PORT ? parseInt(process.env.PORT) : 3000; const DATA_DIR = path.join(process.cwd(), "data"); const CONFIG_PATH = path.join(DATA_DIR, "config.json"); // Ensure data directory exists if (!fs.existsSync(DATA_DIR)) { fs.mkdirSync(DATA_DIR, { recursive: true }); } // Interfaces interface Channel { id: string; name: string; url: string; logo: string; overrideUrl: string; m3u8Url: string | null; referer: string | null; status: "Active" | "No Stream" | "Override" | "Error" | "Pending"; lastTested: string | null; logs: string[]; } interface AppConfig { userAgent: string; referer: string; scrapeIntervalMs: number; channels: Channel[]; enableHfPush?: boolean; hfToken?: string; hfSpace?: string; } const DEFAULT_CHANNELS: Channel[] = []; const DEFAULT_CONFIG: AppConfig = { userAgent: "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36", referer: "https://11.yallashoot1.cc/", scrapeIntervalMs: 3600000, // 1 hour channels: DEFAULT_CHANNELS, enableHfPush: true, hfToken: process.env.HF_TOKEN || "", hfSpace: "subrato1/streamapi" }; // State let appConfig: AppConfig = { ...DEFAULT_CONFIG }; let lastUpdated: string | null = null; let isScraping = false; let globalLogs: string[] = []; // Load config function loadConfig() { try { if (fs.existsSync(CONFIG_PATH)) { const data = JSON.parse(fs.readFileSync(CONFIG_PATH, "utf-8")); // Merge properties safely appConfig = { userAgent: data.userAgent || DEFAULT_CONFIG.userAgent, referer: data.referer || DEFAULT_CONFIG.referer, scrapeIntervalMs: data.scrapeIntervalMs || DEFAULT_CONFIG.scrapeIntervalMs, enableHfPush: data.enableHfPush !== undefined ? data.enableHfPush : DEFAULT_CONFIG.enableHfPush, hfToken: data.hfToken !== undefined ? data.hfToken : DEFAULT_CONFIG.hfToken, hfSpace: data.hfSpace !== undefined ? data.hfSpace : DEFAULT_CONFIG.hfSpace, channels: [ ...DEFAULT_CONFIG.channels.map(defaultCh => { const savedCh = (data.channels || []).find((c: any) => c.id === defaultCh.id); return { ...defaultCh, name: savedCh?.name || defaultCh.name, url: savedCh?.url || defaultCh.url, logo: savedCh?.logo || defaultCh.logo, overrideUrl: savedCh?.overrideUrl || defaultCh.overrideUrl, m3u8Url: savedCh?.m3u8Url || defaultCh.m3u8Url, referer: savedCh?.referer || defaultCh.referer || null, status: savedCh?.status || defaultCh.status, lastTested: savedCh?.lastTested || defaultCh.lastTested, logs: savedCh?.logs || defaultCh.logs }; }), ...(data.channels || []) .filter((savedCh: any) => savedCh.id && (savedCh.id.startsWith("fifa-") || savedCh.id.startsWith("rugby-"))) .map((savedCh: any) => ({ id: savedCh.id, name: savedCh.name, url: savedCh.url, logo: savedCh.logo || "https://cdn-icons-png.flaticon.com/512/3076/3076841.png", overrideUrl: savedCh.overrideUrl || "", m3u8Url: savedCh.m3u8Url || null, referer: savedCh.referer || null, status: savedCh.status || "Pending", lastTested: savedCh.lastTested || null, logs: savedCh.logs || [] })) ] }; if (data.lastUpdated) { lastUpdated = data.lastUpdated; } console.log("Config loaded and cleaned successfully."); saveConfig(); } else { saveConfig(); } } catch (error) { console.error("Error loading config:", error); } } // Save config function saveConfig() { try { fs.writeFileSync(CONFIG_PATH, JSON.stringify({ ...appConfig, lastUpdated }, null, 2), "utf-8"); } catch (error) { console.error("Error saving config:", error); } } loadConfig(); // Custom fetch helper with maximum execution timeout to prevent crawler hangs async function fetchWithTimeout(url: string, options: any = {}, timeoutMs = 8000) { const controller = new AbortController(); const id = setTimeout(() => controller.abort(), timeoutMs); try { const response = await fetch(url, { ...options, signal: controller.signal }); return response; } finally { clearTimeout(id); } } // Custom fetch helper that wraps both fetch and body reading to prevent stalls during body reading async function fetchTextWithTimeout(url: string, options: any = {}, timeoutMs = 8000): Promise { const controller = new AbortController(); const id = setTimeout(() => { controller.abort(); }, timeoutMs); try { const response = await fetch(url, { ...options, signal: controller.signal }); if (!response.ok) { throw new Error(`HTTP ${response.status} ${response.statusText}`); } const text = await response.text(); return text; } finally { clearTimeout(id); } } // Special scraper for playerAio protected embeds async function scrapePlayerAio(targetUrl: string, userAgent: string, defaultReferer: string): Promise<{ m3u8Url: string | null; referer: string | null; logs: string[] }> { const logs: string[] = []; logs.push(`[${new Date().toISOString()}] Initiating PlayerAio premium scraper for: ${targetUrl}`); try { let html: string; try { html = await fetchTextWithTimeout(targetUrl, { headers: { "User-Agent": userAgent, "Referer": defaultReferer || "https://playeraio.top/", "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8" }, method: "GET" }, 8000); } catch (fetchErr: any) { logs.push(`Failed to fetch playeraio page: ${fetchErr.message}`); return { m3u8Url: null, referer: null, logs }; } const vconMatch = html.match(/v_con\s*=\s*["']([^"']+)["']/i); const vdtMatch = html.match(/v_dt\s*=\s*["']([^"']+)["']/i); const fidMatch = html.match(/fid\s*=\s*["']([^"']+)["']/i); const v_con = vconMatch ? vconMatch[1] : null; const v_dt = vdtMatch ? vdtMatch[1] : null; const fid = fidMatch ? fidMatch[1] : null; if (!v_con || !v_dt || !fid) { logs.push(`Failed to extract player variables: v_con=${v_con}, v_dt=${v_dt}, fid=${fid}`); return { m3u8Url: null, referer: null, logs }; } logs.push(`Extracted player variables: fid=${fid}, secure=${v_con}, expires=${v_dt}`); const bhalocastUrl = `https://bhalocast.pro/atofplay.php?v=${fid}&secure=${v_con}&expires=${v_dt}`; logs.push(`Fetching decrypted iframe page: ${bhalocastUrl}`); let bhaloHtml: string; try { bhaloHtml = await fetchTextWithTimeout(bhalocastUrl, { headers: { "User-Agent": userAgent, "Referer": targetUrl } }, 8000); } catch (fetchErr: any) { logs.push(`Failed to fetch bhalocast page: ${fetchErr.message}`); return { m3u8Url: null, referer: null, logs }; } const arrayRegex = /\["h"\s*,\s*"t"\s*,\s*"t"\s*,\s*"p"\s*,\s*"s"[^\]]+\]/g; const matches = bhaloHtml.match(arrayRegex); if (!matches || matches.length === 0) { logs.push(`Could not find any stream array source matches in the bhalocast HTML structure.`); return { m3u8Url: null, referer: null, logs }; } logs.push(`Found ${matches.length} stream source array matches.`); let resolvedUrl: string | null = null; for (let i = matches.length - 1; i >= 0; i--) { try { const parsed = JSON.parse(matches[i]); const urlStr = parsed.join(""); if (urlStr.startsWith("http") && urlStr.includes(".m3u8")) { logs.push(`Testing stream source match ${i}: ${urlStr}`); const testRes = await fetchWithTimeout(urlStr, { headers: { "User-Agent": userAgent, "Referer": "https://bhalocast.pro/", "Origin": "https://bhalocast.pro" } }, 3000); logs.push(`Stream test status for match ${i}: ${testRes.status}`); if (testRes.status === 200 || testRes.status === 206) { resolvedUrl = urlStr; break; } } } catch (err: any) { logs.push(`JSON parsing error for match ${i}: ${err.message}`); } } if (!resolvedUrl && matches.length > 0) { try { const idx = matches.length > 1 ? 1 : 0; resolvedUrl = JSON.parse(matches[idx]).join(""); logs.push(`Fallback to match ${idx}: ${resolvedUrl}`); } catch (err) { // Ignore } } if (resolvedUrl) { return { m3u8Url: resolvedUrl, referer: "https://bhalocast.pro/", logs }; } return { m3u8Url: null, referer: null, logs }; } catch (error: any) { logs.push(`PlayerAio scraping error: ${error?.message || error}`); return { m3u8Url: null, referer: null, logs }; } } // Scraper function async function scrapeUrl(targetUrl: string, userAgent: string, referer: string, depth = 0): Promise<{ m3u8Url: string | null; referer: string | null; logs: string[] }> { if (targetUrl && (targetUrl.includes("playeraio.top") || targetUrl.includes("embed2.php"))) { return scrapePlayerAio(targetUrl, userAgent, referer); } const logs: string[] = []; logs.push(`[${new Date().toISOString()}] Initiating fetch for target: ${targetUrl}`); try { let html: string; try { html = await fetchTextWithTimeout(targetUrl, { headers: { "User-Agent": userAgent, "Referer": referer, "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8", "Accept-Language": "en-US,en;q=0.5", "Cache-Control": "max-age=0" }, method: "GET" }, 8000); } catch (fetchErr: any) { logs.push(`Failed to fetch page: ${fetchErr.message}`); return { m3u8Url: null, referer: null, logs }; } logs.push(`Page fetched successfully. HTML content length: ${html.length} characters.`); // 1. Direct Regex search for any .m3u8 URLs in the HTML const m3u8Regex = /(https?:\/\/[^"'\s<>]+?\.m3u8[^"'\s<>]*)/gi; let match; const foundUrls: string[] = []; while ((match = m3u8Regex.exec(html)) !== null) { const u = match[1]; // Skip common static placeholder/images/js if they somehow match m3u8 if (!u.includes("favicon") && !u.includes("assets")) { foundUrls.push(u); } } if (foundUrls.length > 0) { logs.push(`Found ${foundUrls.length} direct .m3u8 stream links.`); // Return first clean url found return { m3u8Url: foundUrls[0], referer: targetUrl, logs }; } // 2. Base64 encoded streams. Often sport pages obfuscate sources inside base64: atob("aHR0cHM6Ly8...") logs.push(`Scanning for Base64 obfuscated URLs...`); const base64Regex = /[A-Za-z0-9+/]{40,}/g; const bMatches = html.match(base64Regex) || []; for (const bStr of bMatches) { // "aHR0c" is the base64 code for "http" if (bStr.includes("aHR0c")) { try { const decoded = Buffer.from(bStr, "base64").toString("utf-8"); if (decoded.startsWith("http") && decoded.includes(".m3u8")) { logs.push(`Successfully found & decoded obfuscated stream: "${decoded}"`); return { m3u8Url: decoded, referer: targetUrl, logs }; } } catch (_) {} } } // 3. Search common variable declarations (source, file, url, src) const propertyPatterns = [ /source\s*:\s*["']([^"']+\.m3u8[^"']*)["']/i, /file\s*:\s*["']([^"']+\.m3u8[^"']*)["']/i, /src\s*:\s*["']([^"']+\.m3u8[^"']*)["']/i, /url\s*:\s*["']([^"']+\.m3u8[^"']*)["']/i, /videoSrc\s*=\s*["']([^"']+\.m3u8[^"']*)["']/i ]; for (const pat of propertyPatterns) { const match = html.match(pat); if (match && match[1]) { logs.push(`Found stream within javascript player variables: ${match[1]}`); return { m3u8Url: match[1], referer: targetUrl, logs }; } } // 3.5 Check for dynadopt.net player page or if window._econfig is present if (html.includes("window._econfig")) { logs.push("Detected dynadopt.net player payload: attempting VM decrypter..."); const match = html.match(/window\._econfig\s*=\s*['"]([^'"]+)['"]/); if (match && match[1]) { const econfig = match[1]; logs.push(`Found _econfig string of length ${econfig.length}`); try { const parsedUrl = new URL(targetUrl); const jsUrl = `${parsedUrl.origin}/assets/stream.js?_v=0.0.19`; logs.push(`Configuring VM execution context and fetching decoding script: ${jsUrl}`); let jsCode: string; try { jsCode = await fetchTextWithTimeout(jsUrl, { headers: { "User-Agent": userAgent, "Referer": targetUrl } }, 5000); } catch (jsErr: any) { throw new Error(`Failed to fetch stream.js: ${jsErr.message}`); } logs.push(`Downloaded stream.js (${jsCode.length} bytes). Launching secure VM sandbox...`); let decryptedM3u8: string | null = null; const createMockElement = () => { const el: any = { style: {}, classList: { add: () => el, remove: () => el, contains: () => false, }, setAttribute: () => el, getAttribute: () => "", removeAttribute: () => el, appendChild: () => el, removeChild: () => el, remove: () => el, addEventListener: () => {}, innerHTML: "", textContent: "", innerText: "", }; return el; }; const createChainableMock = () => { const thenable = { then: (cb: any) => { try { if (typeof cb === "function") cb(); } catch (e) {} return thenable; }, catch: (cb: any) => { return thenable; } }; const fn = () => thenable; Object.setPrototypeOf(fn, thenable); return fn; }; const mockP2PProxy = new Proxy(() => {}, { get: (target, prop) => { if (typeof prop === "symbol") return undefined; return createChainableMock(); } }); const mockWindow: any = { _econfig: econfig, atob: (str: string) => Buffer.from(str, "base64").toString("binary"), btoa: (str: string) => Buffer.from(str, "binary").toString("base64"), location: { href: targetUrl, hostname: parsedUrl.hostname, protocol: parsedUrl.protocol, origin: parsedUrl.origin, reload: () => {} }, navigator: { userAgent: userAgent }, addEventListener: () => {}, removeEventListener: () => {}, clearInterval: () => {}, setInterval: () => {}, setTimeout: () => {}, clearTimeout: () => {}, P2PEngineHls: mockP2PProxy, P2pEngineHls: mockP2PProxy, Clappr: { Player: class MockClappr { constructor(config: any) { if (config && config.source) { decryptedM3u8 = config.source; } } } } }; mockWindow.window = mockWindow; mockWindow.top = mockWindow; mockWindow.self = mockWindow; const mockDocument: any = { location: mockWindow.location, referrer: referer, addEventListener: () => {}, removeEventListener: () => {}, createElement: (tag: string) => createMockElement(), getElementById: () => createMockElement(), getElementsByTagName: () => [{ parentNode: { insertBefore: () => {} } }], querySelector: () => createMockElement(), querySelectorAll: () => [], body: { appendChild: () => {}, innerHTML: "" } }; mockWindow.document = mockDocument; const context = vm.createContext(mockWindow); vm.runInContext(jsCode, context, { timeout: 4000 }); if (decryptedM3u8) { logs.push(`VM decryption successful! Found stream source: "${decryptedM3u8}"`); const originReferer = parsedUrl.origin + "/"; return { m3u8Url: decryptedM3u8, referer: originReferer, logs }; } else { logs.push("VM execution completed but failed to capture m3u8 stream."); } } catch (vmErr: any) { logs.push(`VM Decrypt failed: ${vmErr.message}`); } } else { logs.push("Detected window._econfig pattern but matches are empty."); } } // 4. Look for embedded iframes (e.g., albaplayer uses standard players or streams inside iframes) logs.push(`Looking for nested frames...`); const iframeRegex = /]+src=["']([^"']+)["']/i; const iframeMatch = html.match(iframeRegex); if (iframeMatch && iframeMatch[1]) { const iframeUrl = iframeMatch[1]; logs.push(`Detected iframe source: ${iframeUrl}`); let targetIframe = iframeUrl; if (iframeUrl.startsWith("//")) { targetIframe = "https:" + iframeUrl; } else if (iframeUrl.startsWith("/")) { const parsedTargetUrl = new URL(targetUrl); targetIframe = `${parsedTargetUrl.origin}${iframeUrl}`; } if (depth >= 2) { logs.push(`Interrupting iframe traversal: Max depth limit of 2 reached. Preempting loop on: ${targetIframe}`); } else { logs.push(`Entering nested iframe scraper: ${targetIframe} (Depth: ${depth + 1})`); let nestedReferer = targetUrl; try { const parsedParent = new URL(targetUrl); nestedReferer = parsedParent.origin + "/"; } catch (_) {} const nestedScrape = await scrapeUrl(targetIframe, userAgent, nestedReferer, depth + 1); logs.push(...nestedScrape.logs.map(l => " [Nested Frame] " + l)); if (nestedScrape.m3u8Url) { return { m3u8Url: nestedScrape.m3u8Url, referer: nestedScrape.referer || targetIframe, logs }; } } } logs.push("Could not extract any active .m3u8 link from the page structure directly."); logs.push(`Failed Page Snippet: ${html.substring(0, 1500).replace(/\s+/g, ' ')}`); return { m3u8Url: null, referer: null, logs }; } catch (error: any) { logs.push(`Network or extraction failure: ${error?.message || error}`); return { m3u8Url: null, referer: null, logs }; } } // Discover FIFA World Cup streams from footystream.pk async function discoverFifaStreams(): Promise { const discovered: Channel[] = []; const ua = appConfig.userAgent; try { globalLogs.push(`[${new Date().toISOString()}] FIFA Discovery: Initiating fetch for https://footystream.pk/leagues/fifa-world-cup`); const mainHtml = await fetchTextWithTimeout("https://footystream.pk/leagues/fifa-world-cup", { headers: { "User-Agent": ua } }); const eventRegex = /href=["']([^"']+\/events\/[^"']+)["']/gi; let match; const events = new Set(); while ((match = eventRegex.exec(mainHtml)) !== null) { events.add(match[1]); } const relativeEventRegex = /href=["'](\/events\/[^"']+)["']/gi; while ((match = relativeEventRegex.exec(mainHtml)) !== null) { events.add("https://footystream.pk" + match[1]); } const eventList = Array.from(events); globalLogs.push(`[${new Date().toISOString()}] FIFA Discovery: Found ${eventList.length} FIFA World Cup event pages.`); for (const eventUrl of eventList) { try { const eventSlugMatch = eventUrl.match(/\/events\/([^/?#]+)/); if (!eventSlugMatch) continue; const eventSlug = eventSlugMatch[1]; const eventTitle = eventSlug .split("-") .map(word => word.charAt(0).toUpperCase() + word.slice(1)) .join(" "); globalLogs.push(`[${new Date().toISOString()}] FIFA Discovery: Processing event: ${eventTitle}`); const eventHtml = await fetchTextWithTimeout(eventUrl, { headers: { "User-Agent": ua } }); const alphaRegex = /href=["']([^"']+\/alpha\/[^"']+)["']/gi; const alphaServers = new Set(); while ((match = alphaRegex.exec(eventHtml)) !== null) { alphaServers.add(match[1]); } const relativeAlphaRegex = /href=["'](\/alpha\/[^"']+)["']/gi; while ((match = relativeAlphaRegex.exec(eventHtml)) !== null) { alphaServers.add("https://footystream.pk" + match[1]); } const serverList = Array.from(alphaServers); globalLogs.push(`[${new Date().toISOString()}] FIFA Discovery: Found ${serverList.length} alpha server(s) for event.`); for (const serverUrl of serverList) { const serverIdMatch = serverUrl.match(/\/alpha\/[^/]+\/(\d+)/i); const serverId = serverIdMatch ? serverIdMatch[1] : "1"; discovered.push({ id: `fifa-${eventSlug}-${serverId}`, name: `FIFA: ${eventTitle} - Server ${serverId}`, url: serverUrl, logo: "https://cdn-icons-png.flaticon.com/512/3076/3076841.png", overrideUrl: "", m3u8Url: null, referer: null, status: "Pending", lastTested: null, logs: [] }); } } catch (err: any) { globalLogs.push(`[${new Date().toISOString()}] FIFA Discovery: Failed to process event ${eventUrl}: ${err.message}`); } } } catch (err: any) { globalLogs.push(`[${new Date().toISOString()}] FIFA Discovery: Failed: ${err.message}`); } return discovered; } // Full Run async function runCompleteScraper() { if (isScraping) return; isScraping = true; globalLogs = [`[${new Date().toISOString()}] Started live streaming extractor cycle.`]; try { // Dynamically discover FIFA streams and update configuration channels const discoveredFifa = await discoverFifaStreams(); const staticChannels = appConfig.channels.filter(ch => !ch.id.startsWith("fifa-") && !ch.id.startsWith("rugby-")); const existingFifa = appConfig.channels.filter(ch => ch.id.startsWith("fifa-")); const mergedFifa = discoveredFifa.map(newCh => { const match = existingFifa.find(oldCh => oldCh.id === newCh.id); if (match) { return { ...newCh, status: match.status, m3u8Url: match.m3u8Url, referer: match.referer, lastTested: match.lastTested, logs: match.logs }; } return newCh; }); appConfig.channels = [...staticChannels, ...mergedFifa]; saveConfig(); const total = appConfig.channels.length; for (let idx = 0; idx < total; idx++) { const ch = appConfig.channels[idx]; if (ch.overrideUrl) { ch.status = "Override"; ch.m3u8Url = ch.overrideUrl; ch.lastTested = new Date().toISOString(); ch.logs = [`Channel has active custom stream URL overrides, skipping crawl: ${ch.overrideUrl}`]; saveConfig(); continue; } ch.status = "Pending"; globalLogs.push(`[${new Date().toISOString()}] (${idx + 1}/${total}) Crawling: ${ch.name}...`); saveConfig(); const start = Date.now(); const result = await scrapeUrl(ch.url, appConfig.userAgent, appConfig.referer); ch.logs = result.logs; ch.lastTested = new Date().toISOString(); if (result.m3u8Url) { ch.m3u8Url = result.m3u8Url; ch.referer = result.referer; ch.status = "Active"; ch.logs.push(`Scrape successful in ${Date.now() - start}ms. Saved source.`); globalLogs.push(`[${new Date().toISOString()}] (${idx + 1}/${total}) Success: ${ch.name}`); } else { ch.m3u8Url = null; ch.referer = null; ch.status = "No Stream"; ch.logs.push(`Failing link discovery. Stream marked offline.`); globalLogs.push(`[${new Date().toISOString()}] (${idx + 1}/${total}) Failed: ${ch.name}`); } saveConfig(); } lastUpdated = new Date().toISOString(); saveConfig(); // Auto sync with Hugging Face Space await pushToHuggingFace(); } catch (e: any) { globalLogs.push(`Fatal error in extractor cycle: ${e?.message || e}`); } finally { isScraping = false; } } // Direct M3U Playlist Content Generator function generateM3uContent(type: "standard" | "suffix" | "ott" | "raw"): string { let m3u = "#EXTM3U\n"; appConfig.channels.forEach((ch) => { const finalStreamUrl = ch.m3u8Url; if (!finalStreamUrl) return; // Logo default fallback const logoUrl = ch.logo || "https://cdn-icons-png.flaticon.com/512/861/861512.png"; const displayName = ch.name; m3u += `#EXTINF:-1 tvg-logo="${logoUrl}",${displayName}\n`; let refererToUse = ch.referer || appConfig.referer; let origin = ""; try { if (refererToUse) { origin = new URL(refererToUse).origin; } } catch (_) { origin = refererToUse; } if (type === "standard") { // VLC format: separate properties m3u += `#EXTVLCOPT:http-referrer=${refererToUse}\n`; if (origin) { m3u += `#EXTVLCOPT:http-origin=${origin}\n`; } m3u += `${finalStreamUrl}\n`; } else if (type === "suffix") { // Suffix header parameters format (useful for TiviMate, OTT Navigator etc.) const connectionParams = `|User-Agent=${encodeURIComponent(appConfig.userAgent)}&Referer=${encodeURIComponent(refererToUse)}`; m3u += `${finalStreamUrl}${connectionParams}\n`; } else if (type === "ott") { // Alternative tag directives format m3u += `#EXTHTTP:{"User-Agent":"${appConfig.userAgent}","Referer":"${refererToUse}"}\n`; m3u += `${finalStreamUrl}\n`; } else { // Plain m3u += `${finalStreamUrl}\n`; } }); return m3u; } // Push Generated Playlist to Hugging Face Space async function pushToHuggingFace() { if (!appConfig.enableHfPush) { globalLogs.push(`[HuggingFace API] Push is disabled in settings.`); return; } const token = appConfig.hfToken || process.env.HF_TOKEN || ""; const space = appConfig.hfSpace || "subrato1/streamapi"; if (!token || !space) { globalLogs.push(`[HuggingFace API] Push missing required token or Space path.`); return; } globalLogs.push(`[HuggingFace API] Initiating git push to HF Space: ${space}`); const tempDir = path.join(process.cwd(), "data", `hf_push_${Date.now()}`); try { const { execSync } = await import("child_process"); // 1. Generate M3U playlist content const m3uContent = generateM3uContent("standard"); // 2. Clone space repository globalLogs.push(`[HuggingFace API] Cloning repo target info...`); const hfGitUrl = `https://user:${token}@huggingface.co/spaces/${space}`; // Silence git clone prompts to avoid hanging if auth fails execSync(`git clone ${hfGitUrl} ${tempDir} --depth 1`, { env: { ...process.env, GIT_TERMINAL_PROMPT: "0" }, stdio: "ignore", timeout: 30000 // 30 seconds execution timeout }); if (!fs.existsSync(tempDir)) { throw new Error("Target folder not created after cloning command."); } // 3. Write playlist file inside clone const destinationPath = path.join(tempDir, "yallashoot_playlist.m3u"); fs.writeFileSync(destinationPath, m3uContent, "utf-8"); // 4. Git configure, add, commit & push const gitCmd = (cmd: string) => { return execSync(cmd, { cwd: tempDir, encoding: "utf8", env: { ...process.env, GIT_TERMINAL_PROMPT: "0" }, timeout: 20000 // 20 seconds execution timeout }); }; gitCmd(`git config user.name "M3u8 Stream Auto Updater"`); gitCmd(`git config user.email "auto-updater@streamapi.com"`); gitCmd(`git add yallashoot_playlist.m3u`); const statusMap = gitCmd(`git status --porcelain`).trim(); if (statusMap.length === 0) { globalLogs.push(`[HuggingFace API] Playlist is already up to date on Space. No push needed.`); } else { globalLogs.push(`[HuggingFace API] Committing playlist changes...`); gitCmd(`git commit -m "Auto-update playlist: ${new Date().toISOString()}"`); globalLogs.push(`[HuggingFace API] Pushing commits securely...`); gitCmd(`git push origin main`); globalLogs.push(`[HuggingFace API] Push successfully completed and synced to Hugging Face Space!`); } } catch (error: any) { globalLogs.push(`[HuggingFace API] Error pushing to Space: ${error?.message || error}`); console.error("Huggingface push err:", error); } finally { // 5. Clean up temporary directory if (fs.existsSync(tempDir)) { try { fs.rmSync(tempDir, { recursive: true, force: true }); } catch (err: any) { console.error("Cleanup temp dir error:", err); } } } } // Initial background scrape on server start setTimeout(() => { console.log("Triggering initialization scrape..."); runCompleteScraper(); }, 2000); // Setup hourly interval for automatic scraping let schedulerInterval = setInterval(() => { console.log("Triggering periodic hourly auto-updater..."); runCompleteScraper(); }, appConfig.scrapeIntervalMs); // Helper to rebuild dynamic scheduler if interval is updated function restartInterval() { clearInterval(schedulerInterval); schedulerInterval = setInterval(() => { console.log(`Triggering periodic auto-updater every ${appConfig.scrapeIntervalMs / 60000} minutes`); runCompleteScraper(); }, appConfig.scrapeIntervalMs); } // API Routes app.use(express.json()); // Secure Stream Proxy to bypass browser CORS / Referer restrictions app.get("/api/stream-proxy", async (req, res) => { const target = req.query.url as string; const queryReferer = req.query.referer as string; if (!target) { return res.status(400).send("Missing url parameter"); } try { let refererToUse = queryReferer || appConfig.referer || "https://11.yallashoot1.cc/"; if (!queryReferer) { if (target.includes("09193519.net") || target.includes("12703830.net") || target.includes("dynadopt.net")) { // Find matching channel to retrieve the dynamic discovered referer const matchingChannel = appConfig.channels.find(ch => { if (!ch.m3u8Url) return false; try { const chPath = new URL(ch.m3u8Url).pathname; const targetPath = new URL(target).pathname; return chPath === targetPath || target.includes(ch.m3u8Url) || ch.m3u8Url.includes(target.split('?')[0]); } catch (_) { return target.includes(ch.m3u8Url) || ch.m3u8Url.includes(target.split('?')[0]); } }); if (matchingChannel && matchingChannel.referer) { refererToUse = matchingChannel.referer; } else { // Heuristic fallback if not specified: find any active channel that holds a dynadopt.net referer const anyDynChannel = appConfig.channels.find(ch => ch.referer && ch.referer.includes("dynadopt.net")); refererToUse = anyDynChannel?.referer || "https://d21201b285d0052ce3c7e2cd2e62d5d5.dynadopt.net/"; } } } const headers: any = { "User-Agent": appConfig.userAgent, "Referer": refererToUse, "Accept": "*/*" }; const response = await fetchWithTimeout(target, { headers }, 15000); // Inject permissive CORS headers for browser player sandbox res.setHeader("Access-Control-Allow-Origin", "*"); res.setHeader("Access-Control-Allow-Headers", "*"); res.setHeader("Access-Control-Allow-Methods", "GET, HEAD, OPTIONS"); // Copy Content-Type cleanly const contentType = response.headers.get("content-type"); if (contentType) { res.setHeader("Content-Type", contentType); } const targetUrlObj = new URL(target); const isPlaylist = targetUrlObj.pathname.endsWith(".m3u8") || contentType?.includes("application/vnd.apple.mpegurl") || contentType?.includes("mpegurl"); if (isPlaylist) { let text = await response.text(); const lines = text.split("\n"); const rewrittenLines = lines.map(line => { const trimmed = line.trim(); if (!trimmed || trimmed.startsWith("#")) { return line; } let absoluteUrl = trimmed; if (!trimmed.startsWith("http")) { try { absoluteUrl = new URL(trimmed, targetUrlObj.href).href; } catch (_) { return line; } } const host = req.get("host") || "localhost:3000"; let proxyUrl = `${req.protocol}://${host}/api/stream-proxy?url=${encodeURIComponent(absoluteUrl)}`; if (refererToUse) { proxyUrl += `&referer=${encodeURIComponent(refererToUse)}`; } return proxyUrl; }); return res.send(rewrittenLines.join("\n")); } else { // Stream buffer chunk const buffer = await response.arrayBuffer(); return res.send(Buffer.from(buffer)); } } catch (err: any) { console.error(`Stream proxy failure: ${err.message}`); res.status(500).send(`Proxy Error: ${err.message}`); } }); // Get status app.get("/api/status", (req, res) => { res.json({ lastUpdated, isScraping, globalLogs, config: { userAgent: appConfig.userAgent, referer: appConfig.referer, scrapeIntervalMs: appConfig.scrapeIntervalMs, enableHfPush: appConfig.enableHfPush || false, hfToken: appConfig.hfToken || "", hfSpace: appConfig.hfSpace || "" }, channels: appConfig.channels }); }); // Run Manual Extract app.post("/api/extract", async (req, res) => { if (isScraping) { return res.status(409).json({ error: "Extractor is already in progress, please wait." }); } await runCompleteScraper(); res.json({ success: true, channels: appConfig.channels, lastUpdated }); }); // Update single channel custom configuration app.post("/api/update-channel", (req, res) => { const { id, name, url, logo, overrideUrl } = req.body; const index = appConfig.channels.findIndex(c => c.id === id); if (index === -1) { return res.status(404).json({ error: "Channel not found" }); } appConfig.channels[index] = { ...appConfig.channels[index], name: name !== undefined ? name : appConfig.channels[index].name, url: url !== undefined ? url : appConfig.channels[index].url, logo: logo !== undefined ? logo : appConfig.channels[index].logo, overrideUrl: overrideUrl !== undefined ? overrideUrl : appConfig.channels[index].overrideUrl, }; // Re-adjust status if override is changed if (overrideUrl) { appConfig.channels[index].m3u8Url = overrideUrl; appConfig.channels[index].status = "Override"; appConfig.channels[index].lastTested = new Date().toISOString(); } else if (appConfig.channels[index].status === "Override") { appConfig.channels[index].status = "Pending"; appConfig.channels[index].m3u8Url = null; } saveConfig(); res.json({ success: true, channel: appConfig.channels[index] }); }); // Update global config app.post("/api/update-config", (req, res) => { const { userAgent, referer, scrapeIntervalMs, enableHfPush, hfToken, hfSpace } = req.body; if (userAgent !== undefined) appConfig.userAgent = userAgent; if (referer !== undefined) appConfig.referer = referer; if (scrapeIntervalMs !== undefined && typeof scrapeIntervalMs === "number" && scrapeIntervalMs >= 60000) { appConfig.scrapeIntervalMs = scrapeIntervalMs; restartInterval(); } if (enableHfPush !== undefined) appConfig.enableHfPush = enableHfPush; if (hfToken !== undefined) appConfig.hfToken = hfToken; if (hfSpace !== undefined) appConfig.hfSpace = hfSpace; saveConfig(); res.json({ success: true, config: { userAgent: appConfig.userAgent, referer: appConfig.referer, scrapeIntervalMs: appConfig.scrapeIntervalMs, enableHfPush: appConfig.enableHfPush, hfToken: appConfig.hfToken, hfSpace: appConfig.hfSpace } }); }); // Direct text representation generator of m3u playlist app.get("/playlist.m3u", (req, res) => { const { format } = req.query; // standard | suffix | raw | ott const type = format || "standard"; let m3u = generateM3uContent(type as any); res.setHeader("Content-Type", "application/x-mpegurl; charset=utf-8"); res.setHeader("Content-Disposition", `attachment; filename="yallashoot_playlist.m3u"`); res.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); res.send(m3u); }); // Setup Vite & Frontend static routing async function init() { if (process.env.NODE_ENV !== "production") { const vite = await createViteServer({ server: { middlewareMode: true }, appType: "spa", }); app.use(vite.middlewares); } else { const distPath = path.join(process.cwd(), "dist"); app.use(express.static(distPath)); app.get("*", (req, res) => { res.sendFile(path.join(distPath, "index.html")); }); } app.listen(PORT, "0.0.0.0", () => { console.log(`Server started successfully on http://localhost:${PORT}`); }); } init();