Spaces:
Paused
Paused
File size: 23,580 Bytes
669f9d0 4537b20 669f9d0 5913cf1 669f9d0 4537b20 669f9d0 5913cf1 669f9d0 4537b20 669f9d0 5913cf1 4537b20 669f9d0 5913cf1 669f9d0 4537b20 669f9d0 4537b20 669f9d0 4537b20 669f9d0 4537b20 669f9d0 5913cf1 669f9d0 5913cf1 669f9d0 5913cf1 669f9d0 4537b20 669f9d0 4537b20 669f9d0 4537b20 669f9d0 4537b20 669f9d0 5913cf1 669f9d0 4537b20 669f9d0 4537b20 669f9d0 4537b20 669f9d0 4537b20 669f9d0 4537b20 669f9d0 4537b20 669f9d0 4537b20 669f9d0 4537b20 669f9d0 4537b20 669f9d0 4537b20 669f9d0 4537b20 669f9d0 4537b20 669f9d0 4537b20 669f9d0 5913cf1 669f9d0 108ec79 e51b106 108ec79 4537b20 108ec79 e51b106 108ec79 669f9d0 4537b20 669f9d0 108ec79 ac29e23 108ec79 ac29e23 108ec79 ac29e23 108ec79 ac29e23 108ec79 669f9d0 4537b20 669f9d0 5913cf1 669f9d0 4537b20 669f9d0 4537b20 669f9d0 4537b20 5913cf1 669f9d0 5913cf1 669f9d0 5913cf1 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 | /**
* JAYNES MAX TV β Node.js/Puppeteer backend
*
* v4: badala ya kutembelea kraudiustv.iceiy.com / mfumo.liveblog365.com moja
* kwa moja, Puppeteer sasa inatembelea relay yetu wenyewe (kraudius_fetch_lite.php,
* kwenye jaynes.freedev.app) β relay hiyo tayari imefanya curl+extraction (PHP)
* na inarudisha JSON. Puppeteer inahitajika kwa sababu InfinityFree (hosting ya
* relay) wakati mwingine inaonyesha JS-challenge yake (aes.js) badala ya kupitisha
* ombi moja kwa moja kwenye PHP script β curl/fetch ya kawaida haiwezi kuitatua,
* lakini Chromium halisi (Puppeteer) inaendesha JS hiyo na kupita kiotomatiki.
*
* Tofauti kuu kutoka toleo la awali:
* - Chanzo kimoja pekee (LiveBlog365, kupitia relay) β "kraudius" kama chanzo
* tofauti kimeondolewa (relay yenyewe haikitumii tena); channel zote 1-52
* sasa zinapitia njia moja.
* - extractStream()/firstMatch() (regex dhidi ya HTML ya tovuti asili) zimeondolewa
* kabisa β relay tayari inarudisha JSON iliyochakatwa, hatuhitaji kuchambua HTML.
* - Browser instance MOJA inabaki wazi (reuse) badala ya kufunguliwa upya kila
* request β bado ni muhimu kwa ufanisi.
*/
const express = require('express');
const puppeteer = require('puppeteer');
const app = express();
const PORT = process.env.PORT || 7860;
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
// DATA
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
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 kwenye data ya relay (hazina jina tuli bado)
};
// Hifadhi ya ziada β relay ikikosa clearkey kwa channel inayojulikana, tumia hii.
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',
};
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
// CHANNEL RANGE β chanzo kimoja (relay/LiveBlog365), 1-52
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
const TOTAL_CHANNELS = 52;
function channelValid(channel) {
return Number.isInteger(channel) && channel >= 1 && channel <= TOTAL_CHANNELS;
}
const RELAY_BASE = 'https://jaynes.freedev.app/kraudius_fetch_lite.php';
function relayUrl(channel) {
return `${RELAY_BASE}?channel=${channel}`;
}
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
// 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();
}
const UA = 'Mozilla/5.0 (Linux; Android 13; SM-G991B) AppleWebKit/537.36 ' +
'(KHTML, like Gecko) Chrome/124.0.0.0 Mobile Safari/537.36';
/**
* Inatembelea relay (kraudius_fetch_lite.php) kwa Puppeteer. InfinityFree
* wakati mwingine inaonyesha JS-challenge (aes.js) kabla ya kufikisha JSON
* halisi β Puppeteer inaiendesha hiyo JS kiotomatiki (waitUntil: networkidle2
* inasubiri hadi redirect ya challenge ikamilike), kisha tunasoma maandishi
* ghafi ya ukurasa (Chrome inaonyesha JSON ndani ya <pre> ikiwa Content-Type
* ni application/json β innerText inatupa JSON safi bila escaping ya HTML).
*/
async function fetchRelayJson(url) {
await acquireSlot();
let page;
try {
const browser = await getBrowser();
page = await browser.newPage();
await page.setUserAgent(UA);
const response = await page.goto(url, { waitUntil: 'networkidle2', timeout: 20000 });
const code = response ? response.status() : 0;
const text = await page.evaluate(() => (document.body && (document.body.innerText || document.body.textContent)) || '');
try {
return { data: JSON.parse(text), code, error: '' };
} catch (_e) {
return { data: null, code, error: 'Relay haijarudisha JSON halali (challenge haijatatuliwa?)' };
}
} catch (err) {
return { data: null, code: 0, error: err.message };
} finally {
if (page) await page.close().catch(() => {});
releaseSlot();
}
}
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
// PROCESS CHANNEL β inatumia JSON ya relay moja kwa moja (relay
// tayari imefanya extraction; hatuhitaji tena ku-regex HTML hapa)
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
async function processChannel(chNo) {
const url = relayUrl(chNo);
const t0 = Date.now();
const { data, code, error } = await fetchRelayJson(url);
const ms = Date.now() - t0;
if (!data) {
return { ok: false, channel: chNo, source: 'LiveBlog365', error: error || 'Relay haijarudisha JSON', code, ms };
}
if (!data.ok) {
return {
ok: false, channel: chNo, source: 'LiveBlog365',
error: data.error || 'Relay imeshindwa kupata stream', code: data.code ?? code, ms: data.ms ?? ms,
};
}
const rawName = CHANNEL_NAMES[chNo] || data.name || `Channel ${chNo}`;
const norm = normName(rawName);
const finalName = DISPLAY_NAMES[norm] || rawName;
let ck = data.clearkey;
let drm = data.drm;
if (!ck && CLEARKEY_OVERRIDE[norm]) {
ck = CLEARKEY_OVERRIDE[norm];
drm = 'CLEARKEY';
}
let clearkeyObj = null;
if (ck && ck.includes(':')) {
const parts = ck.split(':');
if (parts.length === 2) clearkeyObj = { kid: parts[0], key: parts[1] };
}
return {
ok: !!data.stream_url,
channel: chNo,
source: 'LiveBlog365',
name: finalName,
norm,
stream_url: data.stream_url,
type: data.type,
drm,
clearkey: clearkeyObj,
license_url: data.license_url || undefined,
code: data.code ?? code,
ms: data.ms ?? ms,
};
}
/** Chanzo kimoja pekee sasa (relay/LiveBlog365) β hakuna fallback ya vyanzo. */
async function getChannelData(chNo) {
if (!channelValid(chNo)) return null;
return processChannel(chNo);
}
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
// 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);
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 β relay)',
endpoints: ['/api/content/channels', '/api/channel/:id', '/refresh', '/status'],
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);
if (!channelValid(id)) {
return res.status(404).json({
success: false,
error: `Channel id lazima iwe kati ya 1 na ${TOTAL_CHANNELS}`,
});
}
const cacheKey = String(id);
const cached = getCached(cacheKey);
if (cached) {
return res.json({ ...cached, cached: true });
}
const data = await getChannelData(id);
if (!data || !data.ok || !data.stream_url) {
return res.status(502).json({
success: false,
channel: id,
error: (data && data.error) || 'Imeshindwa kupata stream kutoka relay',
});
}
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}`);
});
|