/* Lazy classic chunk; its executing singleton stays pinned until reload. */ (window.YT ||= {}).Remote = (() => { const noop = { boot() {}, changed() {} }; if (!WEB || typeof WebSocket === 'undefined') return noop; const HOST_KEY = 'ytpRemoteHost'; const PAIR_KEY = 'ytpRemotePair'; const load = (k) => { try { return JSON.parse(localStorage.getItem(k) || 'null'); } catch { return null; } }; const save = (k, v) => { try { if (v) localStorage.setItem(k, JSON.stringify(v)); else localStorage.removeItem(k); } catch { /* storage blocked */ } }; const wsUrl = (q) => `${location.protocol === 'https:' ? 'wss' : 'ws'}://${location.host}/ws/remote?${new URLSearchParams(q)}`; const newSecret = () => { const b = new Uint8Array(32); crypto.getRandomValues(b); return btoa(String.fromCharCode(...b)).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, ''); }; const guessName = (fallback) => { const ua = navigator.userAgent || ''; if (/iPhone/.test(ua)) return 'iPhone'; if (/iPad/.test(ua)) return 'iPad'; if (/Android/.test(ua)) return 'Android phone'; if (/Windows/.test(ua)) return 'Windows PC'; if (/Mac/.test(ua)) return 'Mac'; return fallback; }; const clock = (t) => (window.LyricsCore ? LyricsCore.fmtClock(t) : fmtTime(t)); // ========================================================================== // Host (the screen being controlled) // ========================================================================== const host = { ws: null, remotes: [], code: '', codeExpires: 0, retryMs: 2000, timer: null, lastState: '', lastQueue: '', replaced: false, pending: false }; function hostCfg() { let cfg = load(HOST_KEY); if (!cfg || !cfg.secret) cfg = { secret: newSecret(), name: guessName('Desktop'), enabled: false }; return cfg; } function hostConnect() { const cfg = hostCfg(); if (!cfg.enabled) return; try { if (host.ws) host.ws.close(); } catch { /* already closed */ } const ws = new WebSocket(wsUrl({ role: 'host', secret: cfg.secret, name: cfg.name })); host.ws = ws; host.replaced = false; ws.onopen = () => { host.retryMs = 2000; }; ws.onmessage = (e) => { let m; try { m = JSON.parse(e.data); } catch { return; } onHostMessage(m); }; ws.onclose = (e) => { if (host.ws !== ws) return; host.ws = null; host.remotes = []; renderChip(); renderHostModal(); if (e.code === 4000) { host.replaced = true; renderHostModal(); return; } // another tab hosts now if (hostCfg().enabled) { clearTimeout(host.timer); host.timer = setTimeout(hostConnect, host.retryMs); host.retryMs = Math.min(host.retryMs * 2, 30000); } }; } const hostSend = (m) => { if (host.ws && host.ws.readyState === 1) host.ws.send(JSON.stringify(m)); }; function onHostMessage(m) { DirectMedia.attach('remote-host', { send: hostSend, peers: () => host.remotes.map(r => ({ id: r.rid, name: r.name })) }); if (m.type === 'direct') { DirectMedia.handle('remote-host', m); return; } if (m.type === 'hello') { host.code = m.code; host.codeExpires = m.codeExpires; host.remotes = m.remotes || []; host.lastState = ''; host.lastQueue = ''; pushState(); pushQueue(); } else if (m.type === 'code') { host.code = m.code; host.codeExpires = m.codeExpires; } else if (m.type === 'remotes') { host.remotes = m.remotes || []; if (m.joined) { toast(`📱 ${m.joined} connected as a remote`); host.lastState = ''; host.lastQueue = ''; pushState(); pushQueue(); } if (m.left) toast(`📱 ${m.left} disconnected`); } else if (m.type === 'ping') { hostSend({ type: 'pong', rid: m.rid, t: m.t }); return; } else if (m.type === 'cmd') { runCommand(m); return; } renderChip(); renderHostModal(); } function stateNow() { const meta = current && current.meta; const M = Player.master; return { directAvailable: !!meta && cachedIds.has(meta.id) && DirectMedia.enabled() && data.settings.p2pShare !== false, v: meta ? { id: meta.id, title: meta.title || '', channel: meta.channel || '', thumbnail: meta.thumbnail || '' } : null, cur: M ? Math.floor((M.currentTime || 0) * 10) / 10 : 0, dur: (M && isFinite(M.duration) && M.duration) || (meta && meta.duration) || 0, paused: !M || M.paused, volume: data.settings.volume ?? 1, service: isServiceModeOpen(), sleep: sleepTimerRemaining || 0, hostName: hostCfg().name, // For the presenter screen: this screen's personal lyric offset for the // song and the playback speed (to extrapolate between updates). off: meta && data.lyricOffsets ? Number(data.lyricOffsets[meta.id]) || 0 : 0, rate: (M && M.playbackRate) || 1, }; } function pushState(force = false) { if (!host.ws || !host.remotes.length) return; const st = stateNow(); const key = JSON.stringify({ ...st, cur: Math.floor(st.cur) }); if (!force && key === host.lastState) return; host.lastState = key; hostSend({ type: 'state', state: { ...st, at: Date.now() } }); } function pushQueue() { if (!host.ws || !host.remotes.length) return; const items = queue.slice(0, 200).map((v) => ({ id: v.id, title: v.title || '', channel: v.channel || '', duration: v.duration || 0, thumbnail: v.thumbnail || '', })); const key = queueIndex + '|' + items.map((v) => v.id).join(','); if (key === host.lastQueue) return; host.lastQueue = key; hostSend({ type: 'queue', queue: { items, idx: queueIndex } }); } // Coalesce bursts (play event + renderUpNext + afterLoad) into one push. function changed() { if (!host.ws || host.pending) return; host.pending = true; setTimeout(() => { host.pending = false; pushState(); pushQueue(); }, 50); } const validIdx = (i) => Number.isInteger(i) && i > queueIndex && i < queue.length; function runCommand(m) { const who = m.from || 'Phone'; switch (m.cmd) { case 'toggle': Player.toggle(); break; case 'play': Player.play(); break; case 'pause': Player.pause(); break; case 'next': playNext(); break; case 'prev': playPrev(); break; case 'seek': { const t = Number(m.t); if (isFinite(t) && t >= 0) Player.seek(t); break; } case 'volume': { const v = Math.max(0, Math.min(1, Number(m.v))); if (!isFinite(v)) break; data.settings.volume = v; els.volume.value = String(v); Player.applyVolume(); syncMuteIcon(); persist(); break; } case 'jump': { const i = Number(m.i); if (Number.isInteger(i) && i >= 0 && i < queue.length) { queueIndex = i - 1; playNext(); } break; } case 'remove': { const i = Number(m.i); if (validIdx(i)) { queue.splice(i, 1); renderUpNext(); } break; } case 'move': { const from = Number(m.from), to = Number(m.to); if (validIdx(from) && validIdx(to) && from !== to) { const [v] = queue.splice(from, 1); queue.splice(to, 0, v); renderUpNext(); } break; } case 'add': { const v = m.video; if (!v || typeof v.id !== 'string' || !isMediaId(v.id)) break; const item = slim({ ...v, title: String(v.title || v.id).slice(0, 300), channel: String(v.channel || '').slice(0, 200) }); if (!current || !queue.length) { playFromList([item], 0, 'remote'); } else if (!queue.slice(queueIndex + 1).some((x) => x.id === item.id)) { queue.push(item); renderUpNext(); } toast(`📱 ${who} added “${item.title}”`); break; } case 'sleep': { const min = Number(m.min) || 0; if (min > 0) startSleepTimer(Math.min(min, 240)); else cancelSleepTimer(); break; } case 'service': if (m.on) enterServiceMode(); else exitServiceMode(); break; default: return; } changed(); } function startHosting() { const cfg = hostCfg(); cfg.enabled = true; save(HOST_KEY, cfg); hostConnect(); renderHostModal(); } function stopHosting() { const cfg = hostCfg(); cfg.enabled = false; save(HOST_KEY, cfg); clearTimeout(host.timer); const ws = host.ws; host.ws = null; host.remotes = []; try { if (ws) ws.close(); } catch { /* gone */ } renderChip(); renderHostModal(); } function unpairAll() { hostSend({ type: 'unpair-all' }); const cfg = hostCfg(); cfg.secret = newSecret(); // every phone's token was derived from the old one save(HOST_KEY, cfg); setTimeout(hostConnect, 300); toast('All phones unpaired'); } function renderChip() { const chip = $('remoteChip'); if (!chip) return; const n = host.remotes.length; chip.classList.toggle('hidden', !host.ws || !n); if (n) { $('remoteChipText').textContent = n === 1 ? `Remote connected — ${host.remotes[0].name}` : `${n} remotes connected`; } } let hostModalOpen = false; function renderHostModal() { if (!hostModalOpen) return; const body = $('modalBody') && $('modalBody').querySelector('.remote-host'); if (!body) { hostModalOpen = false; return; } const cfg = hostCfg(); const live = !!host.ws; const mins = host.codeExpires ? Math.max(0, Math.round((host.codeExpires - Date.now()) / 60000)) : 0; body.querySelector('.rh-body').innerHTML = !cfg.enabled ? `
Let a phone drive this screen — play/pause, seek, volume, the queue and service mode — while this computer plays to the TV or speakers. Pairing uses a one-time 6-digit code; nothing to sign in to.
` : host.replaced ? `Another tab on this computer took over as the remote-controlled screen.
` : !live ? `Connecting to the server…
` : `${escapeHtml(location.origin)}/?present=${host.code} (same code), or scan the QR.Play on a computer hooked to the TV or speakers, and drive it from your phone.
`; showModal('📱 Remote', body, [ { label: paired ? `Control “${paired.hostName}”` : 'Use this phone as a remote', onClick: () => { closeModal(); openRemoteView(); } }, { label: hosting ? 'This screen: remote on' : 'Control this screen from a phone', primary: true, onClick: () => { closeModal(); openHostModal(); } }, ]); } function bindUi() { $('rvClose').addEventListener('click', closeRemoteView); $('rvMenu').addEventListener('click', () => { const p = load(PAIR_KEY); showModal('Remote options', document.createTextNode(p ? `Paired with “${p.hostName}”.` : 'Not paired.'), [ { label: 'Close', onClick: closeModal }, ...(p ? [{ label: 'Unpair this phone', danger: true, onClick: () => { closeModal(); save(PAIR_KEY, null); try { rc.ws && rc.ws.close(); } catch { /* gone */ } showPairForm('Unpaired.'); } }] : []), ]); }); $('rvPairBtn').addEventListener('click', () => doPair($('rvCode').value)); $('rvCode').addEventListener('keydown', (e) => { if (e.key === 'Enter') doPair($('rvCode').value); }); $('rvToggle').addEventListener('click', () => { cmd('toggle'); if (rc.state) { rc.state.cur = liveCur(); rc.stateAt = Date.now(); rc.state.paused = !rc.state.paused; renderRemote(); } }); $('rvPrev').addEventListener('click', () => cmd('prev')); $('rvNext').addEventListener('click', () => cmd('next')); const seek = $('rvSeek'); seek.addEventListener('input', () => { rc.seeking = true; const dur = (rc.state && rc.state.dur) || 0; $('rvCur').textContent = clock((Number(seek.value) / 1000) * dur); }); seek.addEventListener('change', () => { const dur = (rc.state && rc.state.dur) || 0; const t = (Number(seek.value) / 1000) * dur; cmd('seek', { t }); if (rc.state) { rc.state.cur = t; rc.stateAt = Date.now(); } rc.seeking = false; }); $('rvVolume').addEventListener('input', (e) => { const pct = Number(e.target.value); $('rvVolVal').textContent = pct + '%'; clearTimeout(rc.volTimer); rc.volTimer = setTimeout(() => { rc.volTimer = null; cmd('volume', { v: pct / 100 }); }, 120); }); $('rvQueue').addEventListener('pointerdown', onDragStart); $('rvQueue').addEventListener('click', (e) => { const rm = e.target.closest('[data-rm]'); if (rm) { cmd('remove', { i: Number(rm.dataset.rm) }); return; } if (e.target.closest('.rv-handle')) return; const row = e.target.closest('.rv-row'); if (row) cmd('jump', { i: Number(row.dataset.i) }); }); $('rvAdd').addEventListener('click', openAddSheet); $('rvSleep').addEventListener('click', () => { const options = [0, 15, 30, 45, 60, 90]; const curMin = rc.state && rc.state.sleep ? Math.ceil(rc.state.sleep / 60) : 0; const next = options.find((o) => o > curMin) ?? 0; cmd('sleep', { min: next }); toast(next ? `Screen pauses in ${next} min` : 'Sleep timer off'); }); $('rvService').addEventListener('click', () => cmd('service', { on: !(rc.state && rc.state.service) })); // Hosts keep phones current once a second while anything plays. setInterval(() => { if (host.ws && host.remotes.length) { pushState(); pushQueue(); } }, 1000); document.addEventListener('visibilitychange', () => { if (document.visibilityState === 'visible' && rc.open && !rc.ws) rcConnect(); }); } function boot() { bindUi(); if (hostCfg().enabled) hostConnect(); // A scanned QR / shared link: /?pair=482913 let code = ''; try { code = (new URLSearchParams(location.search).get('pair') || '').replace(/\D/g, ''); } catch { /* no URL */ } if (code) { try { const u = new URL(location.href); u.searchParams.delete('pair'); history.replaceState(null, '', u.pathname + u.search + u.hash); } catch { /* leave the URL */ } openRemoteView({ code }); } } return { boot, changed, openChooser, openHostModal }; })();