diff --git a/README.md b/README.md index 5a85d990..edf12894 100644 --- a/README.md +++ b/README.md @@ -35,6 +35,7 @@ - local search matches name/language/tags/cc/localized country name (Intl.DisplayNames) - مشغّل مصغّر ثابت، مع لوحة قابلة للتوسيع للصوت والتنقل ومؤقت النوم. +- **تبديل آمن بين روابط المحطة:** أربع وصلات HTTPS مباشرة بحد أقصى ورابط relay اختياري كآخر محاولة؛ يتم رفض HTTP والرابط ذي بيانات الدخول، وإزالة المكرر، مع إبقاء اسم المحطة والمفضلة والاستماع على عنصر الصوت نفسه. روابط البدائل هي روابط مرشحة وليست ضمانًا للتشغيل ما لم يُثبت فحص الصوت ذلك. ### 🌍 تبويب عربي - تبويب مستقل «🌍 عربي» يعرض جميع المحطات العربية في 22 دولة عربية @@ -93,7 +94,7 @@ ### Frontend - **HTML5 + CSS3 + Vanilla JavaScript** (بدون مكتبات خارجية) -- **Service Worker** (sw.js v78) لـ caching و offline +- **Service Worker** (sw.js v79) لـ caching و offline - **HLS.js** (1.6.10) لدعم HLS - **hls.js CDN**: jsdelivr → unpkg fallback @@ -131,7 +132,7 @@ Radio/ │ └── tools.mjs # لوحة الأوامر + المشاركة + الإبلاغ + عشوائي (~8KB) ├── css/ │ └── styles.css # أنماط CSS -├── sw.js # Service Worker (v78) +├── sw.js # Service Worker (v79) ├── manifest.webmanifest # PWA Manifest ├── offline.html # صفحة offline ├── robots.txt # robots.txt diff --git a/ROADMAP.md b/ROADMAP.md index 87fd5e20..78e5a49f 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -8,6 +8,8 @@ > **صيانة المصادر العالمية — 2026-11-19:** خط الأساس المعلن في manifest v34 هو 60,732 محطة، بينما صفوف stations.json الفعلية 60,741 (انحراف سابق +9)؛ آخر سجل قديم فحص 1,185 رابطًا وصنّف 1,071 alive (مش ضمان تشغيل صوت). أضفنا فاحص دليل الصوت التدريجي (48 رابطًا في دورة المحطات)، وحماية تمنع فقد أكثر من 20% من المحطات بسبب جلب ناقص. لا حذف للمحطات ولا تغيير لمعرّفاتها. التفاصيل والتقييم في [تقرير تدقيق المصادر](docs/RADIO_SOURCES_AUDIT_2026-11-19.md). اكتمال التفعيل معلق على CI والنشر ودورة صيانة فعلية. +> **تحسين موثوقية تشغيل البث — 2026-11-19:** استكمال بند المشغّل P1-3: قائمة بدائل المحطة نفسها أصبحت HTTPS فقط، تُزال منها الروابط المكررة وغير الآمنة، ويُسمح بأربع محاولات مباشرة كحد أقصى ثم بروكسي اختياري مرة واحدة، وتُستخدم نفس القائمة عند استعادة آخر محطة. لا دمج حسب تشابه الأسماء، ولا تغيير لعنصر الصوت أو بيانات المفضلة. Service Worker v79. + ## 1) الوضع الحالي — نوفمبر 2026 ### ✅ منجز (سجل مختصر — السجل الكامل في PRs المستودع) @@ -41,7 +43,7 @@ | ملف الإقلاع السريع | stations_head.json (~530KB) | data/ | | تدفق منسّق مُتحقق | 1185 مُفحوص · 1086 شغّال · 50 «جرّبها» · 49 ميت | data/stream_checks.json | | جسم الواجهة | js/app.js ~79KB (نواة) + 5 وحدات ES Modules | js/app.js | -| إصدار Service Worker | v78 | sw.js (الجذر — المسار المسجل في js/app.js) | +| إصدار Service Worker | v79 | sw.js (الجذر — المسار المسجل في js/app.js) | | الاختبارات | 92 اختبار crawler + مجموعة اختبارات JS (node --test) | tests/ | | جدولة التحديث | SDR كل 6 ساعات · المحطات يوميًا | .github/workflows/update-data.yml | diff --git a/js/app.js b/js/app.js index 86a58ae9..7eb86500 100644 --- a/js/app.js +++ b/js/app.js @@ -500,6 +500,12 @@ function safeHttpsUrl(value) { return url && /^https:/i.test(url) ? url : ''; } +function buildPlaybackSourceList(p,f,o,r) { + var s=[],a=[p].concat(Array.isArray(f)?f.slice(0,16):[],[o,r]); + a.forEach(function(v,i){v=safeHttpsUrl(v);if(v&&s.length<(i===a.length-1?5:4)&&s.indexOf(v)<0)s.push(v);}); + return s; +} + /* Optional stream relay; see proxy/README.md. */ var STREAM_PROXY = ''; @@ -1340,7 +1346,7 @@ function renderFeatured() { } -/* Modal focus bookkeeping shared by the sdr and player modules. */ +/* Shared modal focus. */ var previousSDRFocus = null; function initResume() { @@ -1352,11 +1358,10 @@ function initResume() { if (isDmEmbed(last.url)) return; var station = stationByUrl(last.url); state.playbackStation = station || { name: last.name || '', url: last.url }; - state.playbackSources = [last.url].concat(state.playbackStation.fallbacks || []); var resumeRelay = (station && station.tokenEndpoint && station.tokenType === 'easy_b') ? '' : proxyStreamUrl(last.url); - if (resumeRelay && state.playbackSources.indexOf(resumeRelay) === -1) { - state.playbackSources.push(resumeRelay); - } + state.playbackSources = buildPlaybackSourceList( + last.url, state.playbackStation.fallbacks, '', resumeRelay + ); state.playbackIndex = 0; state.playbackGeneration += 1; var generation = state.playbackGeneration; diff --git a/js/modules/player.mjs b/js/modules/player.mjs index b4d90ffe..80afa45f 100644 --- a/js/modules/player.mjs +++ b/js/modules/player.mjs @@ -132,8 +132,11 @@ function loadHlsLib(cb) { } next(); } -function failCurrentPlayback(generation, reason) { - if (generation !== state.playbackGeneration || state.playbackAttemptFailed) return; +function failCurrentPlayback(generation, reason, sourceUrl) { + // A rejected play() promise from an earlier attempt must not stop the + // working fallback after playbackIndex has already advanced. + if (generation !== state.playbackGeneration || state.playbackAttemptFailed || + (sourceUrl && state.playbackSources[state.playbackIndex] !== sourceUrl)) return; state.playbackAttemptFailed = true; destroyHls(); var audio = $('audio'); @@ -211,7 +214,7 @@ function attachHls(url, generation, station) { mediaRetries += 1; try { hls.recoverMediaError(); return; } catch (e) {} } - failCurrentPlayback(generation, data.details || data.type || 'fatal HLS error'); + failCurrentPlayback(generation, data.details || data.type || 'fatal HLS error', url); }); hls.loadSource(url); hls.attachMedia(audio); @@ -245,21 +248,22 @@ function startCurrentPlayback(generation) { var needsHlsJs = isHlsUrl(baseUrl) && (requiresTokenLoader || !audio.canPlayType('application/vnd.apple.mpegurl')); if (needsHlsJs) { loadHlsLib(function (loaded) { - if (generation !== state.playbackGeneration) return; + if (generation !== state.playbackGeneration || + state.playbackSources[state.playbackIndex] !== baseUrl) return; if (!loaded || !attachHls(baseUrl, generation, station)) { - failCurrentPlayback(generation, 'HLS.js unavailable or MediaSource unsupported'); + failCurrentPlayback(generation, 'HLS.js unavailable or MediaSource unsupported', baseUrl); return; } audio.play().catch(function (error) { if (error && error.name === 'NotAllowedError') { toast(t('toast_tap_play')); } else { - failCurrentPlayback(generation, error && error.message); + failCurrentPlayback(generation, error && error.message, baseUrl); } }); }); } else if (requiresTokenLoader) { - failCurrentPlayback(generation, 'Token-protected HLS requires HLS.js'); + failCurrentPlayback(generation, 'Token-protected HLS requires HLS.js', baseUrl); } else { audio.src = baseUrl; audio.load(); @@ -267,7 +271,7 @@ function startCurrentPlayback(generation) { if (error && error.name === 'NotAllowedError') { toast(t('toast_tap_play')); } else { - failCurrentPlayback(generation, error && error.message); + failCurrentPlayback(generation, error && error.message, baseUrl); } }); } @@ -427,21 +431,18 @@ function play(url, name) { } state.playbackStation = station || { name: name || '', url: url }; var saverStation = pickSaverStation(state.playbackStation, url); - state.playbackSources = [saverStation ? saverStation.url : url] - .concat(state.playbackStation.fallbacks || []) - .concat(saverStation ? [url] : []) - .filter(function (source, index, list) { - return !!source && list.indexOf(source) === index; - }); - // Last-resort relay tier: some streams fail direct playback from the - // browser (CORS or geo blocks) while our Cloudflare Worker relay can - // still fetch them. Token-gated easybroadcast streams are skipped: their - // loader signs the original playlist URL and would break through a proxy. + // Preserve the original station identity while retrying its OWN verified + // or curated alternative mounts; never mix stations by similar names. + // Bound to four direct HTTPS sources and one optional last-resort relay. + // Token-gated easybroadcast must never go through the relay. var isEasyB = station && station.tokenEndpoint && station.tokenType === 'easy_b'; var relayUrl = isEasyB ? '' : proxyStreamUrl(url); - if (relayUrl && state.playbackSources.indexOf(relayUrl) === -1) { - state.playbackSources.push(relayUrl); - } + state.playbackSources = buildPlaybackSourceList( + saverStation ? saverStation.url : url, + state.playbackStation.fallbacks, + saverStation ? url : '', + relayUrl + ); state.playbackIndex = 0; state.playbackGeneration += 1; var generation = state.playbackGeneration; @@ -836,7 +837,11 @@ export function boot() { $('audio').addEventListener('waiting', function () { setPlayerStatus('connecting'); }); $('audio').addEventListener('stalled', function () { setPlayerStatus('connecting'); }); $('audio').addEventListener('error', function () { - if (state.playbackSources.length) failCurrentPlayback(state.playbackGeneration, 'HTML audio element error'); + if (hls || !state.playbackSources.length) return; + var source = $('audio').currentSrc; + if (source && source === state.playbackSources[state.playbackIndex]) { + failCurrentPlayback(state.playbackGeneration, 'HTML audio element error', source); + } }); $('audio').addEventListener('play', function () { state.playbackRequestedInSession = true; diff --git a/scripts/browser_qa.cjs b/scripts/browser_qa.cjs index 08ae6d67..c4e2b6de 100644 --- a/scripts/browser_qa.cjs +++ b/scripts/browser_qa.cjs @@ -12,6 +12,8 @@ const BASE = process.env.RADIO_QA_BASE || 'http://127.0.0.1:8765/'; const DIR = path.resolve(process.env.RADIO_QA_OUTPUT || 'artifacts/mobile-browser-qa'); fs.mkdirSync(DIR, {recursive: true}); const TEST_URL = 'https://qa.radio.invalid/test-live.wav'; +const FAILED_URL = 'https://qa.radio.invalid/fail-live.wav'; +const BACKUP_URL = 'https://qa.radio.invalid/backup-live.wav'; const results = {base: BASE, run: new Date().toISOString(), checks: [], screenshots: [], errors: [], note: 'Playback uses a deterministic WAV fixture intercepted by Playwright, not a live radio endpoint.'}; @@ -157,6 +159,63 @@ async function shot(page,name) { },TEST_URL)); await page.locator('#player-collapse').click(); + // Real Chromium native audio error (HTTP 404) -> verified-in-fixture + // alternative WAV playback, preserving the chosen broadcaster identity. + await page.route(FAILED_URL,route=>route.fulfill({ + status:404,contentType:'text/html',body:'No stream' + })); + await page.route(BACKUP_URL,route=>route.fulfill({ + status:200,contentType:'audio/wav', + headers:{'Access-Control-Allow-Origin':'*'},body:createWav() + })); + await page.evaluate(([primary,backup])=>{ + state.fm.unshift({ + name:'Radio Atlas QA Fallback',url:primary,fallbacks:[backup], + cc:'EG',language:'english',tags:'news',codec:'WAV' + }); + // This fixture is injected after normal catalog UI QA. A real click + // still goes through the application's public play() path and audio. + const button=document.createElement('button'); + button.id='qa-fallback-launch'; + button.textContent='Start fallback QA'; + button.addEventListener('click',()=>play(primary,'Radio Atlas QA Fallback')); + document.body.appendChild(button); + },[FAILED_URL,BACKUP_URL]); + await page.locator('#qa-fallback-launch').click(); + try { + await page.waitForFunction(backup=>{ + const audio=document.querySelector('#audio'); + return state.playbackStation&&state.playbackStation.name==='Radio Atlas QA Fallback' + &&state.currentName==='Radio Atlas QA Fallback' + &&audio.currentSrc===backup&&!audio.paused&&audio.readyState>=2; + },BACKUP_URL,{timeout:20000}); + } catch (error) { + const diagnostics=await page.evaluate(()=>{ + const a=document.querySelector('#audio'); + return {sources:state.playbackSources,index:state.playbackIndex, + generation:state.playbackGeneration,attemptFailed:state.playbackAttemptFailed, + currentSrc:a.currentSrc,paused:a.paused,readyState:a.readyState, + error:a.error&&{code:a.error.code,message:a.error.message}, + name:state.currentName,station:state.playbackStation&&state.playbackStation.url, + status:document.querySelector('#player-status').textContent}; + }); + results.fallbackDiagnostics=diagnostics; + throw new Error(error.message+'; fallback diagnostics: '+JSON.stringify(diagnostics)); + } + const failover=await page.evaluate(()=>({ + station:state.playbackStation&&state.playbackStation.url, + stationName:state.currentName, + currentSrc:document.querySelector('#audio').currentSrc, + index:state.playbackIndex, + sources:state.playbackSources, + audioCount:document.querySelectorAll('#audio').length + })); + results.fallbackPlayback=failover; + check('Failed primary switches to its own HTTPS backup', + failover.index===1&&failover.currentSrc===BACKUP_URL + &&failover.station===FAILED_URL&&failover.audioCount===1, + JSON.stringify(failover)); + await page.locator('#lang-btn').click(); check('English LTR',await page.locator('html').getAttribute('dir')==='ltr'); await shot(page,'08-english-ltr'); diff --git a/sw.js b/sw.js index 39eb6258..46cfc17f 100644 --- a/sw.js +++ b/sw.js @@ -1,4 +1,4 @@ -var CACHE = 'radio-atlas-v78'; +var CACHE = 'radio-atlas-v79'; var SHELL = ['./', './index.html', './offline.html', './about.html', './contact.html', './terms.html', './privacy.html', './dmca.html', './css/styles.css', './js/app.js', './js/analytics.js', './manifest.webmanifest', './icons/icon.svg', './icons/icon-192.png', './icons/icon-512.png', './icons/icon-maskable-192.png', './icons/icon-maskable-512.png', './js/modules/mobile.mjs', './js/modules/map.mjs', './js/modules/player.mjs', './js/modules/regions.mjs', './js/modules/sdr.mjs', './js/modules/tools.mjs']; diff --git a/tests/search.test.cjs b/tests/search.test.cjs index 592dcc95..5dff49fc 100644 --- a/tests/search.test.cjs +++ b/tests/search.test.cjs @@ -693,3 +693,49 @@ test('late shared-link handling never restarts a station selected during this se assert.deepEqual(attempt(true), [], 'in-session playback should not be replaced'); assert.deepEqual(attempt(false), [[url,'Current station']], 'fresh deep link should start exactly once'); }); + + +test('player fallback list is HTTPS-only, unique and preserves the selected station', () => { + const sources = Array.from(sandbox.buildPlaybackSourceList( + 'https://radio.test/live', + ['http://insecure.test/live', 'javascript:alert(1)', + 'https://radio.test/live', 'https://radio.test/backup', + 'https://user:pass@radio.test/secret'], + 'https://radio.test/original', + 'https://relay.test/stream?url=encoded' + )); + assert.deepEqual(sources, [ + 'https://radio.test/live', + 'https://radio.test/backup', + 'https://radio.test/original', + 'https://relay.test/stream?url=encoded' + ]); +}); + +test('player fallback attempts are bounded to four direct sources and relay last', () => { + const tooMany = Array.from({length: 20}, (_, i) => 'https://radio.test/alt' + i); + const sources = Array.from(sandbox.buildPlaybackSourceList( + 'https://radio.test/live', tooMany, 'https://radio.test/original', + 'https://relay.test/stream' + )); + assert.equal(sources.length, 5); + assert.equal(sources[0], 'https://radio.test/live'); + assert.deepEqual(sources.slice(1, 4), tooMany.slice(0, 3)); + assert.equal(sources[4], 'https://relay.test/stream'); +}); + +test('untrusted fallback strings do not turn into individual characters or URL attempts', () => { + const sources = Array.from(sandbox.buildPlaybackSourceList( + 'https://radio.test/live', 'https://untrusted.test/stream', '', '' + )); + assert.deepEqual(sources, ['https://radio.test/live']); +}); + +test('player resume and direct play share the same safe source builder', () => { + const app = fs.readFileSync('js/app.js', 'utf8'); + const player = fs.readFileSync('js/modules/player.mjs', 'utf8'); + assert.match(app, /state\.playbackSources = buildPlaybackSourceList\(/); + assert.match(player, /state\.playbackSources = buildPlaybackSourceList\(/); + assert.match(player, /state\.playbackIndex < state\.playbackSources\.length/); + assert.match(player, /generation !== state\.playbackGeneration/); +});