Spaces:
Paused
Paused
Download index.js from JAYNESTV/api: direct link, hf CLI and curl.
- Browser
- Download file 26.5 kB
-
https://huggingface.co/spaces/JAYNESTV/api/resolve/refs%2Fpr%2F8/index.js
- Command line
-
hf download hf://spaces/JAYNESTV/api@refs/pr/8/index.js
-
curl -L -o index.js https://huggingface.co/spaces/JAYNESTV/api/resolve/refs%2Fpr%2F8/index.js
26.5 kB
| /** | |
| * JAYNES MAX TV β Node.js/Puppeteer backend | |
| * Port ya kraudius_core.php (v3.2-split, PHP) kwenda Node.js. | |
| * | |
| * Tofauti kuu kutoka PHP: | |
| * - fetchPage() inatumia Puppeteer (Chromium halisi) badala ya curl, | |
| * ili kupita anti-bot ya InfinityFree (imethibitishwa kufanya kazi). | |
| * - Browser instance MOJA inabaki wazi (reuse) badala ya kufunguliwa | |
| * upya kila request β hii ni muhimu kwa ufanisi. | |
| * - kraudius: channels 1-36 | liveblog: channels 1-52 | |
| * - Kwa channel 1-36: jaribu kraudius kwanza, liveblog ni fallback. | |
| * - Kwa channel 37-52: liveblog pekee (kraudius haina hizo). | |
| */ | |
| const express = require('express'); | |
| const puppeteer = require('puppeteer'); | |
| const app = express(); | |
| const PORT = process.env.PORT || 7860; | |
| // βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| // DATA β sawa kabisa na kraudius_core.php | |
| // βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| const CHANNEL_NAMES = { | |
| 1: 'Azam Sports 1', 2: 'Azam Sports 2', 3: 'Azam Sports 3', 4: 'Azam Sports 4', | |
| 5: 'ZBC', 6: 'ZBC 2', 7: 'Azam One', 8: 'Azam Two', 9: 'Sinema Zetu', | |
| 10: 'Kix Movies', 11: 'UTV', 12: 'Cheka Plus', 13: 'Wasafi TV', 14: 'Crown TV', | |
| 15: 'Fubo Sports', 16: 'Premier Sports 1', 17: 'Premier Sports 2', | |
| 18: 'TNT Sports 1', 19: 'TNT Sports 2', 20: 'TNT Sports 3', 21: 'TNT Sports 4', | |
| 22: 'LaLiga TV', | |
| // 23-52: zitatoka HTML (hazina jina tuli bado) | |
| }; | |
| const CLEARKEY_OVERRIDE = { | |
| 'azam sports 1': 'c31df1600afc33799ecac543331803f2:dd2101530e222f545997d4c553787f85', | |
| 'azam sports 2': '739e7499125b31cc9948da8057b84cf9:1b7d44d798c351acc02f33ddfbb7682a', | |
| 'azam sports 3': '2f12d7b889de381a9fb5326ca3aa166d:51c2d733a54306fdf89acd4c9d4f6005', | |
| 'azam sports 4': 'fbcac74e355b3b5d9b6cbc56c7597dbf:5f980e872b378d88b46f656a806205c3', | |
| 'zbc': 'e91fec140bc5316f919b4dc9c16287d7:79884fad0dbfcdc43d3e33c82a1f1cfa', | |
| 'zbc 2': 'f38b03549d023f3a883997328537bf4d:90f9d2d9cc26009c437905692ad70730', | |
| 'azam one': 'b5cbe1bb5acf3c7f9995be428245cfcd:89f1188a11e5e000d4443eb27ca378e1', | |
| 'azam two': '18f515fd536b3e728e9844e77d9f0fa8:c96dfd9b65560f87a1a95b8aeda0432d', | |
| 'sinema zetu': 'd628ae37a8f0336b970f250d9699461e:1194c3d60bb494aabe9114ca46c2738e', | |
| 'kix movies': 'a7e155b282f33335ae8d553f169f443c:c3fdcfd5d509f1ed8550d76a525e34e5', | |
| 'utv': '31b8fc6289fe3ca698588a59d845160c:f8c4e73f419cb80db3bdf4a974e31894', | |
| 'cheka plus': '4dce7643f03c3327832b657d74056b6b:8b8675b9d2ff24dd7c7619d86a698231', | |
| 'wasafi tv': '8714fe102679348e9c76cfd315dacaa0:a8b86ceda831061c13c7c4c67bd77f8e', | |
| 'crown tv': 'e3eb6e0656ec3c22aa308aaa3f82c565:a7634d6defd2c255135095c45bc442fb', | |
| 'fubo sports': 'dc69b6159a0f9f0a4e03b3ff91cbacd5:d0dcbcd7723bc40df0bf34c9c092d51f', | |
| 'premier sports 1': '1444f4235529f183f0a5a486befe9cdb:e5e3fec67a1bb3472a2089c8a0a2557f', | |
| 'premier sports 2': '1a5df53609ebc9857898c490f4724918:77f62980d582ec541280796acf8b2d19', | |
| 'tnt sports 1': '294b5761cefc22d0c6312939e13d8278:52148f1042d238849f0a7813f1da8a7b', | |
| 'tnt sports 2': 'f288380ca4cef9ad3f27a92a08e9bb8b:9f18d26291d9230833501f7f822f6875', | |
| 'tnt sports 3': '1d96ab366bbe6451edf7407b58e2fa16:0116201f4a63ac5bf5787d2c610c41a7', | |
| 'tnt sports 4': '192b1115da041585c77200128549efa1:634e10efe4abbb14be400a3ccbac0258', | |
| 'laliga tv': '620e51b82596475517a27aa425c52280:2b9ba811e9c5aeafc8ae1b71cdca4d6a', | |
| }; | |
| const LOGOS = { | |
| 'azam sports 1': 'https://i.postimg.cc/BZFnGMrq/azam-sports-1.png', | |
| 'azam sports 2': 'https://i.postimg.cc/BZFnGMrq/azam-sports-2.png', | |
| 'azam sports 3': 'https://i.postimg.cc/BZFnGMrq/azam-sports-3.png', | |
| 'azam sports 4': 'https://i.postimg.cc/BZFnGMrq/azam-sports-4.png', | |
| 'zbc': 'https://i.postimg.cc/BZFnGMrq/zbc.png', | |
| 'zbc 2': 'https://i.postimg.cc/BZFnGMrq/zbc2.png', | |
| 'azam one': 'https://i.postimg.cc/BZFnGMrq/azam-one.png', | |
| 'azam two': 'https://i.postimg.cc/BZFnGMrq/azam-two.png', | |
| 'sinema zetu': 'https://i.postimg.cc/BZFnGMrq/sinema-zetu.png', | |
| 'wasafi tv': 'https://i.postimg.cc/x199GSXJ/Wasafi-319ee69a217e4c351694412919fca27d.png', | |
| 'tnt sports 1': 'https://upload.wikimedia.org/wikipedia/en/thumb/4/49/TNT_Sports_1.svg/120px-TNT_Sports_1.svg.png', | |
| 'tnt sports 2': 'https://upload.wikimedia.org/wikipedia/en/thumb/4/49/TNT_Sports_1.svg/120px-TNT_Sports_1.svg.png', | |
| 'tnt sports 3': 'https://upload.wikimedia.org/wikipedia/en/thumb/4/49/TNT_Sports_1.svg/120px-TNT_Sports_1.svg.png', | |
| 'tnt sports 4': 'https://upload.wikimedia.org/wikipedia/en/thumb/4/49/TNT_Sports_1.svg/120px-TNT_Sports_1.svg.png', | |
| 'laliga tv': 'https://upload.wikimedia.org/wikipedia/commons/thumb/1/13/LaLiga_TV_logo.svg/120px-LaLiga_TV_logo.svg.png', | |
| 'premier sports 1': 'https://upload.wikimedia.org/wikipedia/en/thumb/d/d0/Premier_Sports_logo.svg/120px-Premier_Sports_logo.svg.png', | |
| 'premier sports 2': 'https://upload.wikimedia.org/wikipedia/en/thumb/d/d0/Premier_Sports_logo.svg/120px-Premier_Sports_logo.svg.png', | |
| 'fubo sports': 'https://upload.wikimedia.org/wikipedia/commons/thumb/5/5f/FuboTV_logo.svg/120px-FuboTV_logo.svg.png', | |
| }; | |
| const CATEGORIES = { | |
| 'azam sports 1': 'Sports', 'azam sports 2': 'Sports', 'azam sports 3': 'Sports', 'azam sports 4': 'Sports', | |
| 'zbc': 'News', 'zbc 2': 'News', | |
| 'azam one': 'Movie Channels', 'azam two': 'Movie Channels', 'sinema zetu': 'Movie Channels', 'kix movies': 'Movie Channels', | |
| 'utv': 'News', 'cheka plus': 'Entertainment', 'wasafi tv': 'Entertainment', 'crown tv': 'Entertainment', | |
| 'fubo sports': 'Sports', 'premier sports 1': 'Sports', 'premier sports 2': 'Sports', | |
| 'tnt sports 1': 'Sports', 'tnt sports 2': 'Sports', 'tnt sports 3': 'Sports', 'tnt sports 4': 'Sports', | |
| 'laliga tv': 'Sports', | |
| }; | |
| const DISPLAY_NAMES = { | |
| 'tnt sports 1': 'TNT Sports 1', 'tnt sports 2': 'TNT Sports 2', 'tnt sports 3': 'TNT Sports 3', 'tnt sports 4': 'TNT Sports 4', | |
| 'laliga tv': 'LaLiga TV', 'cheka plus': 'Cheka Plus', 'utv': 'UTV', 'zbc': 'ZBC', 'zbc 2': 'ZBC 2', | |
| 'kix movies': 'Kix Movies', 'wasafi tv': 'Wasafi TV', 'crown tv': 'Crown TV', | |
| 'azam sports 1': 'Azam Sports 1', 'azam sports 2': 'Azam Sports 2', 'azam sports 3': 'Azam Sports 3', 'azam sports 4': 'Azam Sports 4', | |
| 'azam one': 'Azam One', 'azam two': 'Azam Two', 'sinema zetu': 'Sinema Zetu', 'fubo sports': 'Fubo Sports', | |
| 'premier sports 1': 'Premier Sports 1', 'premier sports 2': 'Premier Sports 2', | |
| }; | |
| // βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| // KIKOMO CHA CHANNELS KWA KILA CHANZO | |
| // βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| const KRAUDIUS_MAX_CHANNEL = 36; | |
| const LIVEBLOG_MAX_CHANNEL = 52; | |
| const TOTAL_CHANNELS = 52; // jumla ya app (kraudius 1-36 + liveblog 37-52) | |
| function channelExistsForSource(source, channel) { | |
| if (source === 'kraudius') return channel >= 1 && channel <= KRAUDIUS_MAX_CHANNEL; | |
| if (source === 'liveblog') return channel >= 1 && channel <= LIVEBLOG_MAX_CHANNEL; | |
| return false; | |
| } | |
| function sourceUrl(source, channel) { | |
| if (source === 'kraudius') return `https://kraudiustv.iceiy.com/index.php?channel=${channel}&i=1`; | |
| if (source === 'liveblog') return `https://mfumo.liveblog365.com/player.php?channel=${channel}`; | |
| return ''; | |
| } | |
| function sourceLabel(source) { | |
| if (source === 'kraudius') return 'KraudiusTV'; | |
| if (source === 'liveblog') return 'LiveBlog365'; | |
| return source; | |
| } | |
| // βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| // HELPERS | |
| // βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| function normName(name) { | |
| let n = name.toLowerCase().trim(); | |
| n = n.replace(/\s*(hd)\s*$/i, ''); | |
| n = n.replace(/\s+/g, ' '); | |
| return n.trim(); | |
| } | |
| function guessCategory(norm) { | |
| if (/sport|bein|tnt|laliga|premier sport|fubo|sky sport|espn|fox sport|nbc sport|dazn|eleven|eurosport|supersport|canal.*sport|arena sport|setanta|gtv|osn sport|racing|horse|freesport/.test(norm)) return 'Sports'; | |
| if (/sinema|movie|film|hbo|azam one|azam two|mbc|kix|rock action/.test(norm)) return 'Movie Channels'; | |
| if (/zbc|tbc|bbc|aljazeera|utv|news/.test(norm)) return 'News'; | |
| if (/wasafi|crown|cheka|zamaradi|trace|entertain/.test(norm)) return 'Entertainment'; | |
| if (/cartoon|kid|family/.test(norm)) return 'Kids'; | |
| if (/nature|safari|food|history|document/.test(norm)) return 'Documentary'; | |
| if (/mahaasin|hope|imaan|religion/.test(norm)) return 'Religion'; | |
| return 'General'; | |
| } | |
| // βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| // PUPPETEER β browser instance MOJA, inabaki wazi (reuse) | |
| // βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| let browserPromise = null; | |
| async function getBrowser() { | |
| if (!browserPromise) { | |
| browserPromise = puppeteer.launch({ | |
| headless: 'new', | |
| args: ['--no-sandbox', '--disable-setuid-sandbox', '--disable-dev-shm-usage'], | |
| }); | |
| } | |
| return browserPromise; | |
| } | |
| // Kikomo cha pages zinazoendeshwa kwa wakati mmoja (usizidishe CPU | |
| // ndogo ya free tier). Queue rahisi. | |
| const MAX_CONCURRENT_PAGES = 3; | |
| let activePages = 0; | |
| const waitQueue = []; | |
| function acquireSlot() { | |
| return new Promise((resolve) => { | |
| const tryAcquire = () => { | |
| if (activePages < MAX_CONCURRENT_PAGES) { | |
| activePages++; | |
| resolve(); | |
| } else { | |
| waitQueue.push(tryAcquire); | |
| } | |
| }; | |
| tryAcquire(); | |
| }); | |
| } | |
| function releaseSlot() { | |
| activePages--; | |
| const next = waitQueue.shift(); | |
| if (next) next(); | |
| } | |
| async function fetchPage(url) { | |
| await acquireSlot(); | |
| let page; | |
| try { | |
| const browser = await getBrowser(); | |
| page = await browser.newPage(); | |
| await page.setUserAgent( | |
| 'Mozilla/5.0 (Linux; Android 13; SM-G991B) AppleWebKit/537.36 ' + | |
| '(KHTML, like Gecko) Chrome/124.0.0.0 Mobile Safari/537.36' | |
| ); | |
| const response = await page.goto(url, { waitUntil: 'networkidle2', timeout: 20000 }); | |
| const html = await page.content(); | |
| const code = response ? response.status() : 0; | |
| return { html: html || '', code, error: '' }; | |
| } catch (err) { | |
| return { html: '', code: 0, error: err.message }; | |
| } finally { | |
| if (page) await page.close().catch(() => {}); | |
| releaseSlot(); | |
| } | |
| } | |
| // βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| // STREAM EXTRACTOR β port ya extractStream() ya PHP | |
| // βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| function firstMatch(html, patterns) { | |
| for (const p of patterns) { | |
| const m = html.match(p); | |
| if (m) return m[1].trim(); | |
| } | |
| return ''; | |
| } | |
| function extractStream(html) { | |
| const mpdUrl = firstMatch(html, [ | |
| /const\s+mpdUrl\s*=\s*["']([^"']+)["']/, | |
| /var\s+mpdUrl\s*=\s*["']([^"']+)["']/, | |
| /let\s+mpdUrl\s*=\s*["']([^"']+)["']/, | |
| /mpdUrl\s*[:=]\s*["']([^"']+\.mpd[^"']*)["']/, | |
| /source\s*[:=]\s*["']([^"']+\.mpd[^"']*)["']/, | |
| /["'](https?:\/\/[^"']{10,}\.mpd(?:\?[^"']*)?)["']/, | |
| ]); | |
| const hlsUrl = firstMatch(html, [ | |
| /const\s+hlsUrl\s*=\s*["']([^"']+)["']/, | |
| /var\s+hlsUrl\s*=\s*["']([^"']+)["']/, | |
| /let\s+hlsUrl\s*=\s*["']([^"']+)["']/, | |
| /hlsUrl\s*[:=]\s*["']([^"']+\.m3u8[^"']*)["']/, | |
| /["'](https?:\/\/[^"']{10,}\.m3u8(?:\?[^"']*)?)["']/, | |
| ]); | |
| let mp4Url = ''; | |
| if (!mpdUrl && !hlsUrl) { | |
| mp4Url = firstMatch(html, [ | |
| /["'](https?:\/\/[^"']{10,}\.mp4(?:\?[^"']*)?)["']/, | |
| /<source[^>]+src=["']([^"']+\.mp4[^"']*)["']/, | |
| ]); | |
| } | |
| let clearKey = firstMatch(html, [ | |
| /const\s+clearKey\s*=\s*["']([a-f0-9]{32}:[a-f0-9]{32})["']/, | |
| /var\s+clearKey\s*=\s*["']([a-f0-9]{32}:[a-f0-9]{32})["']/, | |
| /clearKey\s*[:=]\s*["']([a-f0-9]{32}:[a-f0-9]{32})["']/, | |
| /["']([a-f0-9]{32}:[a-f0-9]{32})["']/, | |
| ]); | |
| if (!clearKey) { | |
| const kidMatch = html.match(/["']?(?:kid|KID)["']?\s*[:=]\s*["']([a-f0-9]{32})["']/); | |
| const keyMatch = html.match(/["']?(?:key|KEY)["']?\s*[:=]\s*["']([a-f0-9]{32})["']/); | |
| if (kidMatch && keyMatch) clearKey = `${kidMatch[1]}:${keyMatch[1]}`; | |
| } | |
| let licenseUrl = ''; | |
| if (!clearKey) { | |
| licenseUrl = firstMatch(html, [ | |
| /licenseUrl\s*[:=]\s*["']([^"']+)["']/, | |
| /license_url\s*[:=]\s*["']([^"']+)["']/, | |
| ]); | |
| } | |
| let name = ''; | |
| const titleMatch = html.match(/<title[^>]*>([^<]+)<\/title>/i); | |
| if (titleMatch) { | |
| const raw = titleMatch[1].trim(); | |
| let n = raw.replace(/\s*[-β|:]\s*(player|live|stream|tv|channel|watch).*$/i, '').trim(); | |
| n = n.replace(/\s*[-β|]\s*.*$/, '').trim(); | |
| name = n.length > 60 ? raw : n; | |
| } | |
| if (!name) { | |
| const hMatch = html.match(/<h[1-3][^>]*>([^<]+)<\/h[1-3]>/i); | |
| if (hMatch) name = hMatch[1].replace(/<[^>]*>/g, '').trim(); | |
| } | |
| const streamUrl = mpdUrl || hlsUrl || mp4Url; | |
| // Amua "type" kutoka extension HALISI ya streamUrl iliyochaguliwa | |
| // mwishoni (siyo kutoka variable tofauti) β hii inaepuka hitilafu | |
| // ya kusema "DASH" wakati URL ni .m3u8 (au kinyume chake) endapo | |
| // mpdUrl/hlsUrl zilipata match isiyo sahihi kwenye HTML. | |
| let type = ''; | |
| if (/\.mpd(\?|$)/i.test(streamUrl)) type = 'DASH'; | |
| else if (/\.m3u8(\?|$)/i.test(streamUrl)) type = 'HLS'; | |
| else if (/\.mp4(\?|$)/i.test(streamUrl)) type = 'MP4'; | |
| else type = mpdUrl ? 'DASH' : (hlsUrl ? 'HLS' : (mp4Url ? 'MP4' : '')); | |
| const drm = clearKey ? 'CLEARKEY' : (licenseUrl ? 'WIDEVINE' : 'NONE'); | |
| return { name, stream_url: streamUrl, type, drm, clearkey: clearKey, license_url: licenseUrl }; | |
| } | |
| // βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| // PROCESS CHANNEL β port ya processChannel() ya PHP | |
| // βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| async function processChannel(src, chNo) { | |
| const url = sourceUrl(src, chNo); | |
| const t0 = Date.now(); | |
| const result = await fetchPage(url); | |
| const ms = Date.now() - t0; | |
| if (!result.html) { | |
| return { | |
| ok: false, channel: chNo, source: sourceLabel(src), | |
| error: result.error || 'Empty response', code: result.code, ms, | |
| }; | |
| } | |
| const ext = extractStream(result.html); | |
| const rawName = CHANNEL_NAMES[chNo] || ext.name || `Channel ${chNo}`; | |
| const norm = normName(rawName); | |
| const finalName = DISPLAY_NAMES[norm] || rawName; | |
| let ck = ext.clearkey; | |
| let drm = ext.drm; | |
| if (!ck && CLEARKEY_OVERRIDE[norm]) { | |
| ck = CLEARKEY_OVERRIDE[norm]; | |
| drm = 'CLEARKEY'; | |
| } | |
| let clearkeyObj = null; | |
| if (ck && ck.includes(':')) { | |
| const [kid, key] = ck.split(':'); | |
| clearkeyObj = { kid, key }; | |
| } | |
| return { | |
| ok: !!ext.stream_url, | |
| channel: chNo, | |
| source: sourceLabel(src), | |
| name: finalName, | |
| norm, | |
| stream_url: ext.stream_url, | |
| type: ext.type, | |
| drm, | |
| clearkey: clearkeyObj, | |
| license_url: ext.license_url || undefined, | |
| code: result.code, | |
| ms, | |
| }; | |
| } | |
| /** | |
| * Inajaribu vyanzo kwa mfuatano (kraudius kisha liveblog kwa 1-36, | |
| * liveblog pekee kwa 37-52), inarudisha ya kwanza yenye stream_url. | |
| */ | |
| async function getChannelData(chNo, preferredSource) { | |
| let sourcesToTry; | |
| if (preferredSource) { | |
| sourcesToTry = [preferredSource]; | |
| } else if (chNo <= KRAUDIUS_MAX_CHANNEL) { | |
| sourcesToTry = ['kraudius', 'liveblog']; | |
| } else { | |
| sourcesToTry = ['liveblog']; | |
| } | |
| let lastError = null; | |
| for (const src of sourcesToTry) { | |
| if (!channelExistsForSource(src, chNo)) continue; | |
| const data = await processChannel(src, chNo); | |
| if (data.ok && data.stream_url) return data; | |
| lastError = data; | |
| } | |
| return lastError; // ya mwisho iliyojaribiwa (yenye error), au null | |
| } | |
| // βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| // CACHE β faili ya sekunde chache kwa kila channel | |
| // βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| const cache = new Map(); | |
| const CACHE_TTL_MS = 60 * 1000; // sekunde 60 | |
| function getCached(key) { | |
| const entry = cache.get(key); | |
| if (entry && Date.now() - entry.time < CACHE_TTL_MS) return entry.data; | |
| return null; | |
| } | |
| function setCached(key, data) { | |
| cache.set(key, { data, time: Date.now() }); | |
| } | |
| // βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| // SUPABASE β kuandika (upsert) matokeo ya refresh | |
| // βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| const SUPABASE_URL = process.env.SUPABASE_URL || 'https://xxxxxxxxxxxx.supabase.co'; | |
| const SUPABASE_SERVICE_KEY = process.env.SUPABASE_SERVICE_KEY || 'WEKA_SERVICE_ROLE_KEY_YAKO'; | |
| // Tumia service_role key (siyo anon) kwa sababu server-to-server | |
| // inahitaji ruhusa ya kuandika (insert/update), si soma tu. | |
| // Funguo ya siri kulinda /refresh isiitwe na mtu yeyote asiyeruhusiwa | |
| // (weka thamani yako mwenyewe, tumia hiyo hiyo kwenye cron-job.org) | |
| const REFRESH_SECRET = process.env.REFRESH_SECRET || 'badilisha-hii-kuwa-siri-yako'; | |
| async function upsertChannelToSupabase(channelData) { | |
| const row = { | |
| channel_id: channelData.channel, | |
| name: channelData.name, | |
| source: channelData.source, | |
| url: channelData.url, | |
| mpd: channelData.mpd || null, | |
| type: channelData.type, | |
| category: channelData.norm ? guessCategory(channelData.norm) : 'General', | |
| clearkey_kid: channelData.clearkey ? channelData.clearkey.kid : null, | |
| clearkey_key: channelData.clearkey ? channelData.clearkey.key : null, | |
| updated_at: new Date().toISOString(), | |
| }; | |
| const res = await fetch(`${SUPABASE_URL}/rest/v1/channel_streams`, { | |
| method: 'POST', | |
| headers: { | |
| 'apikey': SUPABASE_SERVICE_KEY, | |
| 'Authorization': `Bearer ${SUPABASE_SERVICE_KEY}`, | |
| 'Content-Type': 'application/json', | |
| 'Prefer': 'resolution=merge-duplicates', // upsert kwa unique(channel_id) | |
| }, | |
| body: JSON.stringify(row), | |
| }); | |
| if (!res.ok) { | |
| const text = await res.text().catch(() => ''); | |
| throw new Error(`Supabase upsert HTTP ${res.status}: ${text}`); | |
| } | |
| } | |
| // βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| // REFRESH TIERS | |
| // FAST (channels 1-15) β kila dakika 30 | |
| // SLOW (channels 16-52) β kila masaa 24 | |
| // βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| const FAST_TIER_IDS = Array.from({ length: 15 }, (_, i) => i + 1); // 1-15 | |
| const SLOW_TIER_IDS = Array.from({ length: 52 - 15 }, (_, i) => i + 16); // 16-52 | |
| const FAST_INTERVAL_MS = 30 * 60 * 1000; // dakika 30 | |
| const SLOW_INTERVAL_MS = 24 * 60 * 60 * 1000; // masaa 24 | |
| let isRefreshingFast = false; | |
| let isRefreshingSlow = false; | |
| let lastRefresh = { fast: null, slow: null }; | |
| async function refreshTier(ids, tierName) { | |
| const results = { ok: 0, fail: 0, errors: [] }; | |
| for (const id of ids) { | |
| try { | |
| const data = await getChannelData(id, null); | |
| if (data && data.ok && data.stream_url) { | |
| const isDash = data.type === 'DASH'; | |
| await upsertChannelToSupabase({ | |
| channel: id, | |
| name: data.name, | |
| source: data.source, | |
| url: data.stream_url, | |
| mpd: isDash ? data.stream_url : null, | |
| type: data.type, | |
| norm: data.norm, | |
| clearkey: data.clearkey, | |
| }); | |
| results.ok++; | |
| } else { | |
| results.fail++; | |
| results.errors.push({ channel: id, error: (data && data.error) || 'no stream' }); | |
| } | |
| } catch (err) { | |
| results.fail++; | |
| results.errors.push({ channel: id, error: err.message }); | |
| } | |
| } | |
| lastRefresh[tierName] = { time: new Date().toISOString(), ...results }; | |
| return results; | |
| } | |
| async function runFastRefresh() { | |
| if (isRefreshingFast) return { skipped: true, reason: 'already running' }; | |
| isRefreshingFast = true; | |
| try { | |
| return await refreshTier(FAST_TIER_IDS, 'fast'); | |
| } finally { | |
| isRefreshingFast = false; | |
| } | |
| } | |
| async function runSlowRefresh() { | |
| if (isRefreshingSlow) return { skipped: true, reason: 'already running' }; | |
| isRefreshingSlow = true; | |
| try { | |
| return await refreshTier(SLOW_TIER_IDS, 'slow'); | |
| } finally { | |
| isRefreshingSlow = false; | |
| } | |
| } | |
| // Ratiba ya NDANI (setInterval) β inafanya kazi Space ikiwa "wazi". | |
| // Hii ni ya ziada juu ya cron-job.org (nje), si badala yake β kama | |
| // Space ililala na cron-job.org ikaigusa, refresh itaanza upya papo | |
| // hapo (onPageFinished ya kwanza), kisha setInterval inaendelea | |
| // kutoka hapo mpaka Space ilale tena. | |
| setInterval(() => { runFastRefresh().catch((e) => console.error('fast refresh error:', e.message)); }, FAST_INTERVAL_MS); | |
| setInterval(() => { runSlowRefresh().catch((e) => console.error('slow refresh error:', e.message)); }, SLOW_INTERVAL_MS); | |
| // βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| // ROUTES | |
| // βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| app.get('/', (req, res) => { | |
| res.json({ | |
| name: 'JAYNES MAX TV backend (Node.js/Puppeteer)', | |
| endpoints: ['/api/content/channels', '/api/channel/:id'], | |
| total_channels: TOTAL_CHANNELS, | |
| }); | |
| }); | |
| app.get('/api/content/channels', (req, res) => { | |
| const channels = []; | |
| for (let id = 1; id <= TOTAL_CHANNELS; id++) { | |
| const rawName = CHANNEL_NAMES[id] || `Channel ${id}`; | |
| const norm = normName(rawName); | |
| const finalName = DISPLAY_NAMES[norm] || rawName; | |
| const image = LOGOS[norm] || undefined; | |
| const entry = { id, name: finalName }; | |
| if (image) entry.image = image; | |
| channels.push(entry); | |
| } | |
| res.json({ success: true, total: channels.length, channels }); | |
| }); | |
| // Endpoint ya NJE β cron-job.org inapiga hii kwa ratiba (dakika 30 | |
| // kwa "fast", masaa 24 kwa "slow"). Hii ndiyo pia inayoiamsha Space | |
| // ikiwa imelala (HF Space "kulala" kunatatuliwa moja kwa moja na | |
| // request yoyote ya HTTP inayoifikia). | |
| // | |
| // MUHIMU: refresh ya channels kadhaa kwa Puppeteer inachukua muda | |
| // mrefu kuliko timeout ya cron-job.org (kawaida sekunde 30). Kwa | |
| // hiyo endpoint hii INARUDISHA JIBU MARA MOJA (haisubiri refresh | |
| // ikamilike), na refresh inaendelea NYUMA (background). Tumia | |
| // GET /status kuona hali/matokeo ya refresh ya mwisho. | |
| app.get('/refresh', (req, res) => { | |
| if (req.query.key !== REFRESH_SECRET) { | |
| return res.status(403).json({ success: false, error: 'Funguo si sahihi' }); | |
| } | |
| const tier = req.query.tier || 'all'; | |
| const started = []; | |
| if ((tier === 'fast' || tier === 'all') && !isRefreshingFast) { | |
| started.push('fast'); | |
| runFastRefresh().catch((e) => console.error('fast refresh error:', e.message)); | |
| } | |
| if ((tier === 'slow' || tier === 'all') && !isRefreshingSlow) { | |
| started.push('slow'); | |
| runSlowRefresh().catch((e) => console.error('slow refresh error:', e.message)); | |
| } | |
| // Jibu la HARAKA β halisubiri refresh ikamilike kabisa | |
| res.json({ | |
| success: true, | |
| tier, | |
| message: started.length | |
| ? `Refresh imeanza nyuma (background) kwa: ${started.join(', ')}. Tumia GET /status kuona matokeo.` | |
| : 'Refresh tayari inaendelea (au haikuombwa) β angalia /status.', | |
| already_running: { | |
| fast: isRefreshingFast, | |
| slow: isRefreshingSlow, | |
| }, | |
| }); | |
| }); | |
| app.get('/status', (req, res) => { | |
| res.json({ | |
| success: true, | |
| fast_tier: { channels: FAST_TIER_IDS, interval_minutes: 30, last_refresh: lastRefresh.fast, running: isRefreshingFast }, | |
| slow_tier: { channels: SLOW_TIER_IDS, interval_hours: 24, last_refresh: lastRefresh.slow, running: isRefreshingSlow }, | |
| }); | |
| }); | |
| app.get('/api/channel/:id', async (req, res) => { | |
| const id = parseInt(req.params.id, 10); | |
| const preferredSource = req.query.source ? String(req.query.source) : null; | |
| if (!id || id < 1 || id > TOTAL_CHANNELS) { | |
| return res.status(404).json({ | |
| success: false, | |
| error: `Channel id lazima iwe kati ya 1 na ${TOTAL_CHANNELS}`, | |
| }); | |
| } | |
| const cacheKey = `${id}:${preferredSource || 'auto'}`; | |
| const cached = getCached(cacheKey); | |
| if (cached) { | |
| return res.json({ ...cached, cached: true }); | |
| } | |
| const data = await getChannelData(id, preferredSource); | |
| if (!data || !data.ok || !data.stream_url) { | |
| return res.status(502).json({ | |
| success: false, | |
| channel: id, | |
| error: (data && data.error) || 'Imeshindwa kupata stream kutoka vyanzo vyote', | |
| }); | |
| } | |
| const isDash = data.type === 'DASH'; | |
| const result = { | |
| success: true, | |
| channel: id, | |
| name: data.name, | |
| source: data.source, | |
| url: data.stream_url, | |
| mpd: isDash ? data.stream_url : undefined, | |
| type: data.type, | |
| clearkey: data.clearkey || undefined, | |
| }; | |
| // ondoa fields undefined | |
| Object.keys(result).forEach((k) => result[k] === undefined && delete result[k]); | |
| setCached(cacheKey, result); | |
| res.json(result); | |
| }); | |
| app.listen(PORT, () => { | |
| console.log(`JAYNES MAX TV backend (Node.js) inaendesha kwenye port ${PORT}`); | |
| }); | |