JAYNESTV commited on
Commit
108ec79
Β·
verified Β·
1 Parent(s): 3367da6

Upload index.js

Browse files
Files changed (1) hide show
  1. index.js +150 -0
index.js CHANGED
@@ -389,6 +389,123 @@ function setCached(key, data) {
389
  cache.set(key, { data, time: Date.now() });
390
  }
391
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
392
  // ═══════════════════════════════════════════════════════════
393
  // ROUTES
394
  // ═══════════════════════════════════════════════════════════
@@ -415,6 +532,39 @@ app.get('/api/content/channels', (req, res) => {
415
  res.json({ success: true, total: channels.length, channels });
416
  });
417
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
418
  app.get('/api/channel/:id', async (req, res) => {
419
  const id = parseInt(req.params.id, 10);
420
  const preferredSource = req.query.source ? String(req.query.source) : null;
 
389
  cache.set(key, { data, time: Date.now() });
390
  }
391
 
392
+ // ═══════════════════════════════════════════════════════════
393
+ // SUPABASE β€” kuandika (upsert) matokeo ya refresh
394
+ // ═══════════════════════════════════════════════════════════
395
+
396
+ const SUPABASE_URL = process.env.SUPABASE_URL || 'https://xxxxxxxxxxxx.supabase.co';
397
+ const SUPABASE_SERVICE_KEY = process.env.SUPABASE_SERVICE_KEY || 'WEKA_SERVICE_ROLE_KEY_YAKO';
398
+ // Tumia service_role key (siyo anon) kwa sababu server-to-server
399
+ // inahitaji ruhusa ya kuandika (insert/update), si soma tu.
400
+
401
+ // Funguo ya siri kulinda /refresh isiitwe na mtu yeyote asiyeruhusiwa
402
+ // (weka thamani yako mwenyewe, tumia hiyo hiyo kwenye cron-job.org)
403
+ const REFRESH_SECRET = process.env.REFRESH_SECRET || 'badilisha-hii-kuwa-siri-yako';
404
+
405
+ async function upsertChannelToSupabase(channelData) {
406
+ const row = {
407
+ channel_id: channelData.channel,
408
+ name: channelData.name,
409
+ source: channelData.source,
410
+ url: channelData.url,
411
+ mpd: channelData.mpd || null,
412
+ type: channelData.type,
413
+ clearkey_kid: channelData.clearkey ? channelData.clearkey.kid : null,
414
+ clearkey_key: channelData.clearkey ? channelData.clearkey.key : null,
415
+ updated_at: new Date().toISOString(),
416
+ };
417
+
418
+ const res = await fetch(`${SUPABASE_URL}/rest/v1/channel_streams`, {
419
+ method: 'POST',
420
+ headers: {
421
+ 'apikey': SUPABASE_SERVICE_KEY,
422
+ 'Authorization': `Bearer ${SUPABASE_SERVICE_KEY}`,
423
+ 'Content-Type': 'application/json',
424
+ 'Prefer': 'resolution=merge-duplicates', // upsert kwa unique(channel_id)
425
+ },
426
+ body: JSON.stringify(row),
427
+ });
428
+
429
+ if (!res.ok) {
430
+ const text = await res.text().catch(() => '');
431
+ throw new Error(`Supabase upsert HTTP ${res.status}: ${text}`);
432
+ }
433
+ }
434
+
435
+ // ═══════════════════════════════════════════════════════════
436
+ // REFRESH TIERS
437
+ // FAST (channels 1-15) β€” kila dakika 30
438
+ // SLOW (channels 16-52) β€” kila masaa 24
439
+ // ═══════════════════════════════════════════════════════════
440
+
441
+ const FAST_TIER_IDS = Array.from({ length: 15 }, (_, i) => i + 1); // 1-15
442
+ const SLOW_TIER_IDS = Array.from({ length: 52 - 15 }, (_, i) => i + 16); // 16-52
443
+
444
+ const FAST_INTERVAL_MS = 30 * 60 * 1000; // dakika 30
445
+ const SLOW_INTERVAL_MS = 24 * 60 * 60 * 1000; // masaa 24
446
+
447
+ let isRefreshingFast = false;
448
+ let isRefreshingSlow = false;
449
+ let lastRefresh = { fast: null, slow: null };
450
+
451
+ async function refreshTier(ids, tierName) {
452
+ const results = { ok: 0, fail: 0, errors: [] };
453
+ for (const id of ids) {
454
+ try {
455
+ const data = await getChannelData(id, null);
456
+ if (data && data.ok && data.stream_url) {
457
+ const isDash = data.type === 'DASH';
458
+ await upsertChannelToSupabase({
459
+ channel: id,
460
+ name: data.name,
461
+ source: data.source,
462
+ url: data.stream_url,
463
+ mpd: isDash ? data.stream_url : null,
464
+ type: data.type,
465
+ clearkey: data.clearkey,
466
+ });
467
+ results.ok++;
468
+ } else {
469
+ results.fail++;
470
+ results.errors.push({ channel: id, error: (data && data.error) || 'no stream' });
471
+ }
472
+ } catch (err) {
473
+ results.fail++;
474
+ results.errors.push({ channel: id, error: err.message });
475
+ }
476
+ }
477
+ lastRefresh[tierName] = { time: new Date().toISOString(), ...results };
478
+ return results;
479
+ }
480
+
481
+ async function runFastRefresh() {
482
+ if (isRefreshingFast) return { skipped: true, reason: 'already running' };
483
+ isRefreshingFast = true;
484
+ try {
485
+ return await refreshTier(FAST_TIER_IDS, 'fast');
486
+ } finally {
487
+ isRefreshingFast = false;
488
+ }
489
+ }
490
+
491
+ async function runSlowRefresh() {
492
+ if (isRefreshingSlow) return { skipped: true, reason: 'already running' };
493
+ isRefreshingSlow = true;
494
+ try {
495
+ return await refreshTier(SLOW_TIER_IDS, 'slow');
496
+ } finally {
497
+ isRefreshingSlow = false;
498
+ }
499
+ }
500
+
501
+ // Ratiba ya NDANI (setInterval) β€” inafanya kazi Space ikiwa "wazi".
502
+ // Hii ni ya ziada juu ya cron-job.org (nje), si badala yake β€” kama
503
+ // Space ililala na cron-job.org ikaigusa, refresh itaanza upya papo
504
+ // hapo (onPageFinished ya kwanza), kisha setInterval inaendelea
505
+ // kutoka hapo mpaka Space ilale tena.
506
+ setInterval(() => { runFastRefresh().catch((e) => console.error('fast refresh error:', e.message)); }, FAST_INTERVAL_MS);
507
+ setInterval(() => { runSlowRefresh().catch((e) => console.error('slow refresh error:', e.message)); }, SLOW_INTERVAL_MS);
508
+
509
  // ═══════════════════════════════════════════════════════════
510
  // ROUTES
511
  // ═══════════════════════════════════════════════════════════
 
532
  res.json({ success: true, total: channels.length, channels });
533
  });
534
 
535
+ // Endpoint ya NJE β€” cron-job.org inapiga hii kwa ratiba (dakika 30
536
+ // kwa "fast", masaa 24 kwa "slow"). Hii ndiyo pia inayoiamsha Space
537
+ // ikiwa imelala (HF Space "kulala" kunatatuliwa moja kwa moja na
538
+ // request yoyote ya HTTP inayoifikia).
539
+ app.get('/refresh', async (req, res) => {
540
+ if (req.query.key !== REFRESH_SECRET) {
541
+ return res.status(403).json({ success: false, error: 'Funguo si sahihi' });
542
+ }
543
+
544
+ const tier = req.query.tier || 'all';
545
+ const response = { success: true, tier };
546
+
547
+ try {
548
+ if (tier === 'fast' || tier === 'all') {
549
+ response.fast = await runFastRefresh();
550
+ }
551
+ if (tier === 'slow' || tier === 'all') {
552
+ response.slow = await runSlowRefresh();
553
+ }
554
+ res.json(response);
555
+ } catch (err) {
556
+ res.status(500).json({ success: false, error: err.message });
557
+ }
558
+ });
559
+
560
+ app.get('/status', (req, res) => {
561
+ res.json({
562
+ success: true,
563
+ fast_tier: { channels: FAST_TIER_IDS, interval_minutes: 30, last_refresh: lastRefresh.fast, running: isRefreshingFast },
564
+ slow_tier: { channels: SLOW_TIER_IDS, interval_hours: 24, last_refresh: lastRefresh.slow, running: isRefreshingSlow },
565
+ });
566
+ });
567
+
568
  app.get('/api/channel/:id', async (req, res) => {
569
  const id = parseInt(req.params.id, 10);
570
  const preferredSource = req.query.source ? String(req.query.source) : null;