// Per-voice-channel watch room: shared playback state, source ranking/auto-pick // (ported from bug-tv web/js/views/watch.js), failover, episodes, prefetch, idle close. const { EventEmitter } = require('events'); const { createBugtv, img } = require('./bugtv'); const GRACE_MS = 1500; const IDLE_MS = 2 * 60e3; const DRIFT_S = 1; const KINDS = new Set(['hls', 'file', 'remux', 'torrent']); const KIND_LABEL = { hls: 'HLS', file: 'MP4', remux: 'Remux', torrent: 'Torrent' }; /* ---- ranking (same rules as the web player) ---- */ function kindOf(s) { return (s && s.playback && s.playback.kind) || 'file'; } function scoreStream(s, lastProvider) { const px = Number(s.pixels) || 0; // compress 4K so a browser-friendly 1080p beats a heavy 4K remux/torrent const q = px >= 2160 ? 1150 : px || 400; const kind = kindOf(s); let score = q; if (kind === 'remux') score -= 150; else if (kind === 'torrent') score -= 320 - Math.min(Number(s.seeds) || 0, 100); if (s.playback && s.playback.fallback) score += 40; // direct-capable if (lastProvider && s.provider === lastProvider) score += 100; return score; } function isPlayable(s) { return !!(s && s.playback && s.playback.url && KINDS.has(kindOf(s))); } function rank(streams, lastProvider) { return streams .filter(isPlayable) .map((s) => ({ s, score: scoreStream(s, lastProvider) })) .sort((a, b) => b.score - a.score) // stable: ties keep arrival order .map((x) => x.s); } function qualityLabel(s) { const px = Number(s.pixels) || 0; if (px >= 2160) return '4K'; if (px) return `${px}p`; return s.quality || 'SD?'; } // position + elapsed while playing, clamped to [0, duration || ∞] function clockOf(state, now = Date.now()) { let t = (Number(state.position) || 0) + (state.playing ? (now - (state.updatedAt == null ? now : state.updatedAt)) / 1000 : 0); if (t < 0) t = 0; if (state.duration > 0 && t > state.duration) t = state.duration; return t; } /* ---- Room ---- */ class Room extends EventEmitter { constructor(rooms, { id, guildId, textChannelId }) { super(); this.rooms = rooms; this.bugtv = rooms.bugtv; this.now = rooms.now; this._setTimeout = rooms.setTimeout; this._clearTimeout = rooms.clearTimeout; this._gen = 0; this._ac = null; this._streams = new Map(); this._grace = null; this._idle = null; this._conns = new Map(); // userId → open connection count this._autoplay = false; // start playing when the first viewer joins this._seasonsMeta = []; this.closed = false; this.voiceCount = null; this.state = { id, guildId: guildId || null, textChannelId: textChannelId || null, messageId: null, media: null, sources: [], scraping: false, providers: { done: 0, total: 0 }, sourceId: null, failed: [], notice: null, subtitle: -1, quality: -1, levels: [], playing: false, position: 0, updatedAt: this.now(), duration: 0, buffering: false, viewers: [], leader: null, rev: 0, }; } get id() { return this.state.id; } clock(now = this.now()) { return clockOf(this.state, now); } current() { const s = this.state; return s.sourceId ? s.sources.find((x) => x.id === s.sourceId) || this._streams.get(s.sourceId) || null : null; } publicState(now = this.now()) { const s = this.state; return { media: s.media, stream: this.current(), subtitle: s.subtitle, quality: s.quality, playing: s.playing, position: s.position, updatedAt: s.updatedAt, now, duration: s.duration, viewers: s.viewers.slice(), leader: s.leader, rev: s.rev, notice: s.notice, buffering: s.buffering, }; } _emit(reason) { if (this.closed && reason !== 'stop' && reason !== 'idle') return; this.state.rev++; this.emit('change', this.state, reason); } _setClock(position, playing, user = true) { const s = this.state; if (user) this._clockSetAt = this.now(); s.position = Math.max(0, s.duration > 0 ? Math.min(position, s.duration) : position); s.updatedAt = this.now(); s.playing = !!playing; } _timer(fn, ms) { return this._setTimeout(fn, ms); } /* ---- loading ---- */ async load({ type, tmdb, season, episode } = {}) { if (this.closed) return; type = type === 'tv' ? 'tv' : 'movie'; tmdb = Number(tmdb); if (!tmdb) throw new Error('load: tmdb id required'); const s = this.state; const gen = ++this._gen; const prev = s.media && s.media.type === type && s.media.tmdb === tmdb ? s.media : null; if (type === 'tv') { season = Number(season) || 1; episode = Number(episode) || 1; } else { season = null; episode = null; } this._abortScrape(); this._streams.clear(); this._started = false; this._eager = false; this._done = false; this._resumeAt = 0; this._prefetched = false; this._autoplay = false; Object.assign(s, { media: { type, tmdb, title: prev ? prev.title : '', year: prev ? prev.year : '', poster: prev ? prev.poster : null, backdrop: prev ? prev.backdrop : null, logo: prev ? prev.logo : null, overview: prev && type === 'movie' ? prev.overview : '', season, episode, episodeTitle: '', still: null, seasons: prev ? prev.seasons : [], }, sources: [], scraping: true, providers: { done: 0, total: 0 }, sourceId: null, failed: [], notice: null, subtitle: -1, quality: -1, levels: [], duration: 0, buffering: false, }); this._setClock(0, false); this._emit('load'); this._startScrape(gen); await this._fetchMeta(gen); } async _fetchMeta(gen) { const m = this.state.media; try { const d = await this.bugtv.details(m.type, m.tmdb); if (gen !== this._gen) return; m.title = d.title || d.name || ''; m.year = String(d.release_date || d.first_air_date || '').slice(0, 4); m.poster = img(d.poster_path, 'w500'); m.backdrop = img(d.backdrop_path, 'w1280'); const logos = (d.images && d.images.logos) || []; const logo = logos.find((l) => l.iso_639_1 === 'en') || logos[0]; m.logo = logo ? img(logo.file_path, 'w500') : null; m.overview = d.overview || ''; if (m.type === 'tv') { this._seasonsMeta = (d.seasons || []) .filter((x) => x.season_number > 0 && (x.episode_count || 0) > 0) .sort((a, b) => a.season_number - b.season_number); m.seasons = this._seasonsMeta.map((x) => ({ n: x.season_number, count: x.episode_count })); const sd = await this._season(m.season); if (gen !== this._gen) return; const ep = sd && (sd.episodes || []).find((e) => e.episode_number === m.episode); if (ep) { m.episodeTitle = ep.name || ''; m.still = img(ep.still_path, 'w780'); if (ep.overview) m.overview = ep.overview; } } this._emit('meta'); } catch (e) { if (gen !== this._gen) return; console.warn(`[room ${this.id}] tmdb: ${e.message}`); } } async _season(n) { try { return await this.bugtv.season(this.state.media.tmdb, n); } catch { return null; } } _abortScrape() { if (this._ac) this._ac.abort(); this._ac = null; if (this._grace) this._clearTimeout(this._grace); this._grace = null; } _lastProviderKey() { const m = this.state.media; return m ? `${m.type}:${m.tmdb}` : ''; } _rerank() { const lp = this.rooms.lastProvider.get(this._lastProviderKey()) || ''; this.state.sources = rank([...this._streams.values()], lp); } _startScrape(gen) { const m = this.state.media; const ac = new AbortController(); this._ac = ac; const live = () => gen === this._gen && !ac.signal.aborted && !this.closed; const params = { tmdb: m.tmdb, type: m.type }; if (m.type === 'tv') { params.season = m.season; params.episode = m.episode; } const s = this.state; const p = this.bugtv.streams(params, { signal: ac.signal, onMeta: (meta) => { if (!live()) return; s.providers = { done: s.providers.done, total: (meta.providers || []).length }; this._emit('providers'); }, onStreams: (ev) => { if (!live()) return; let best = null; for (const x of ev.streams || []) { if (!x) continue; if (!x.provider) x.provider = ev.provider; if (!x.id) x.id = `${ev.provider}:${x.playback && x.playback.url}`; if (this._streams.has(x.id)) continue; this._streams.set(x.id, x); if (isPlayable(x) && (!best || (x.pixels || 0) > (best.pixels || 0))) best = x; } this._rerank(); this._emit('sources'); if (!best || this._started) return; if (this._eager) return this._begin('eager'); const k = kindOf(best); if ((best.pixels || 0) >= 1080 && (k === 'hls' || k === 'file')) this._begin('fast'); else if (!this._grace) this._grace = this._timer(() => live() && this._begin('grace'), GRACE_MS); }, onProvider: () => { if (!live()) return; s.providers = { done: s.providers.done + 1, total: Math.max(s.providers.total, s.providers.done + 1) }; this._emit('providers'); }, onDone: () => { if (!live()) return; this._done = true; s.scraping = false; s.providers = { done: s.providers.total, total: s.providers.total }; if (!this._started) this._begin('done'); else if (!s.sourceId) this._noSources(); this._emit('scrape-done'); }, onError: (e) => { if (!live()) return; console.warn(`[room ${this.id}] streams: ${e.message}`); s.notice = `bug-tv error: ${e.message}`; }, }); if (p && p.catch) p.catch((e) => console.warn(`[room ${this.id}] streams: ${e.message}`)); } _noSources() { const s = this.state; s.notice = s.failed.length ? 'None of the sources would play.' : 'No sources found for this title.'; s.sourceId = null; this._setClock(this.clock(), false); } // auto-pick the best unfailed source _begin(why) { if (this._started || this.closed) return; if (this._grace) this._clearTimeout(this._grace); this._grace = null; const s = this.state; const first = s.sources.find((x) => !s.failed.includes(x.id)); if (!first) { if (this._done) { this._noSources(); this._emit('notice'); } return; } this._started = true; this._eager = false; this._why = why; const playing = s.viewers.length > 0; if (!playing) this._autoplay = true; this._select(first, this._resumeAt || 0, playing); this._emit('source'); } _select(stream, position, playing) { const s = this.state; const prev = this.current(); const prevLang = prev && s.subtitle >= 0 && prev.subtitles && prev.subtitles[s.subtitle] ? prev.subtitles[s.subtitle].lang : null; s.sourceId = stream.id; s.subtitle = prevLang ? (stream.subtitles || []).findIndex((x) => x.lang === prevLang) : -1; s.quality = -1; s.levels = []; s.buffering = false; this._started = true; this._setClock(position, playing); } _failover(message) { const s = this.state; const cur = this.current(); if (!cur) return; if (!s.failed.includes(cur.id)) s.failed.push(cur.id); const pos = this.clock(); const next = s.sources.find((x) => !s.failed.includes(x.id)); const what = `${cur.provider} ${qualityLabel(cur)}`; if (next) { s.notice = `${what} failed${message ? ` (${String(message).slice(0, 80)})` : ''}, trying ${next.provider} ${qualityLabel(next)}`; this._select(next, pos, s.playing); } else if (!this._done) { s.notice = `${what} failed, waiting for more sources…`; s.sourceId = null; this._started = false; this._eager = true; this._resumeAt = pos; this._setClock(pos, s.playing); } else { this._noSources(); s.notice = `${what} failed. No more sources to try.`; } this._emit('source'); } /* ---- episodes ---- */ async episodeRef(dir) { const m = this.state.media; if (!m || m.type !== 'tv') return null; const today = new Date(this.now()).toISOString().slice(0, 10); const cur = await this._season(m.season); const eps = ((cur && cur.episodes) || []).slice().sort((a, b) => a.episode_number - b.episode_number); const seasons = this._seasonsMeta; if (dir > 0) { const nxt = eps.find((e) => e.episode_number > m.episode); if (nxt) return nxt.air_date && nxt.air_date > today ? null : { season: m.season, episode: nxt.episode_number }; const ns = seasons.find((x) => x.season_number > m.season); if (ns) return ns.air_date && ns.air_date > today ? null : { season: ns.season_number, episode: 1 }; if (!cur && !seasons.length) return { season: m.season, episode: m.episode + 1 }; return null; } const prv = eps.filter((e) => e.episode_number < m.episode).pop(); if (prv) return { season: m.season, episode: prv.episode_number }; if (!cur && m.episode > 1) return { season: m.season, episode: m.episode - 1 }; const ps = seasons.filter((x) => x.season_number < m.season).pop(); if (ps) { const pd = await this._season(ps.season_number); const nums = ((pd && pd.episodes) || []).map((e) => e.episode_number); return { season: ps.season_number, episode: nums.length ? Math.max(...nums) : ps.episode_count }; } return null; } async _gotoEpisode(dir) { const ref = await this.episodeRef(dir); if (!ref) return { ok: false, error: dir > 0 ? 'No next episode.' : 'No previous episode.' }; await this.load({ type: 'tv', tmdb: this.state.media.tmdb, ...ref }); return { ok: true }; } _checkPrefetch() { const s = this.state; if (this._prefetched || !s.media || s.media.type !== 'tv' || !(s.duration > 0)) return; if (this.clock() / s.duration < 0.8) return; this._prefetched = true; const tmdb = s.media.tmdb; this.episodeRef(1) .then((ref) => ref && this.bugtv.prefetch({ tmdb, type: 'tv', ...ref })) .catch((e) => console.warn(`[room ${this.id}] prefetch: ${e.message}`)); } /* ---- commands (anyone in the VC) ---- */ async command(op, args = {}, userId = null) { if (this.closed) return { ok: false, error: 'This session has ended.' }; args = args || {}; const s = this.state; try { switch (op) { case 'play': this._autoplay = false; if (!s.playing) { // replay from the start when paused at the end const t = this.clock(); this._setClock(s.duration > 0 && t >= s.duration - 0.5 ? 0 : t, true); this._emit('play'); } return { ok: true }; case 'pause': this._autoplay = false; if (s.playing) { this._setClock(this.clock(), false); this._emit('pause'); } return { ok: true }; case 'toggle': return this.command(s.playing ? 'pause' : 'play', {}, userId); case 'seek': case 'seekBy': { const t = op === 'seek' ? Number(args.t) : this.clock() + Number(args.d); if (!Number.isFinite(t)) return { ok: false, error: 'Bad time.' }; this._setClock(Math.max(0, t), s.playing); this._emit('seek'); this._checkPrefetch(); return { ok: true }; } case 'source': { const x = s.sources.find((v) => v.id === args.id) || this._streams.get(args.id); if (!x) return { ok: false, error: 'Unknown source.' }; s.failed = s.failed.filter((f) => f !== x.id); s.notice = null; this._eager = false; this._select(x, this.clock(), s.playing); this._emit('source'); return { ok: true }; } case 'subtitle': { const cur = this.current(); const i = Number(args.index); const n = (cur && cur.subtitles && cur.subtitles.length) || 0; if (!(i === -1 || (Number.isInteger(i) && i >= 0 && i < n))) return { ok: false, error: 'Unknown subtitle.' }; s.subtitle = i; this._emit('subtitle'); return { ok: true }; } case 'quality': { const i = Number(args.index); if (!(i === -1 || s.levels.some((l) => l.index === i))) return { ok: false, error: 'Unknown quality.' }; s.quality = i; this._emit('quality'); return { ok: true }; } case 'episode': { if (!s.media || s.media.type !== 'tv') return { ok: false, error: 'Not a series.' }; const season = Number(args.season); const episode = Number(args.episode); if (!(season > 0 && episode > 0)) return { ok: false, error: 'Bad episode.' }; await this.load({ type: 'tv', tmdb: s.media.tmdb, season, episode }); return { ok: true }; } case 'next': return await this._gotoEpisode(1); case 'prev': return await this._gotoEpisode(-1); case 'stop': this.close('stop'); return { ok: true }; default: return { ok: false, error: `Unknown op ${op}` }; } } catch (e) { console.warn(`[room ${this.id}] command ${op}: ${e.message}`); return { ok: false, error: e.message }; } } /* ---- client reports (leader only) ---- */ report(data = {}, userId) { const s = this.state; if (this.closed || !userId || userId !== s.leader || !data) return false; if (data.sourceId && data.sourceId !== s.sourceId) return false; // stale report about an old source const reasons = []; if (Number(data.duration) > 0 && Math.abs(data.duration - s.duration) > 0.5) { s.duration = Number(data.duration); const cur = this.current(); if (cur) this.rooms.lastProvider.set(this._lastProviderKey(), cur.provider); reasons.push('duration'); } if (Array.isArray(data.levels)) { const levels = data.levels .map((l, i) => ({ index: Number.isInteger(l.index) ? l.index : i, height: Number(l.height) || 0, bitrate: Number(l.bitrate) || 0 })) .slice(0, 50); if (JSON.stringify(levels) !== JSON.stringify(s.levels)) { s.levels = levels; if (s.quality >= 0 && !levels.some((l) => l.index === s.quality)) s.quality = -1; reasons.push('levels'); } } if (typeof data.buffering === 'boolean' && data.buffering !== s.buffering) { s.buffering = data.buffering; reasons.push('buffering'); } const settled = this.now() - (this._clockSetAt || 0) > 3000; // heartbeat may predate a seek if (s.playing && settled && data.position != null && Number.isFinite(Number(data.position))) { const p = Number(data.position); if (Math.abs(p - this.clock()) > DRIFT_S) { this._setClock(p, true, false); reasons.push('drift'); } } if (reasons.length) this._emit(reasons[0]); this._checkPrefetch(); if (data.error && data.error.fatal) { this._failover(data.error.message); return true; } if (data.ended) this._ended(); return true; } _ended() { const s = this.state; if (s.media && s.media.type === 'tv') { this.episodeRef(1) .then((ref) => { if (this.closed) return; if (ref) return this.load({ type: 'tv', tmdb: s.media.tmdb, ...ref }); this._setClock(s.duration || this.clock(), false); this._emit('ended'); }) .catch((e) => console.warn(`[room ${this.id}] next: ${e.message}`)); } else { this._setClock(s.duration || this.clock(), false); this._emit('ended'); } } /* ---- viewers / leader ---- */ join(userId) { if (this.closed || !userId) return; const s = this.state; this._conns.set(userId, (this._conns.get(userId) || 0) + 1); let reason = null; if (!s.viewers.includes(userId)) { s.viewers.push(userId); reason = 'join'; } if (!s.leader) { s.leader = userId; reason = reason || 'leader'; } if (this._autoplay && s.sourceId) { this._autoplay = false; this._setClock(this.clock(), true); reason = 'play'; } if (reason) this._emit(reason); } leave(userId) { const s = this.state; const n = (this._conns.get(userId) || 0) - 1; if (n > 0) return void this._conns.set(userId, n); this._conns.delete(userId); if (!s.viewers.includes(userId)) return; s.viewers = s.viewers.filter((v) => v !== userId); if (s.leader === userId) { s.leader = s.viewers[0] || null; s.buffering = false; } // nobody watching: hold the clock, resume when someone opens the Activity again if (!s.viewers.length && s.playing) { this._setClock(this.clock(), false); this._autoplay = true; } this._emit('leave'); } /* ---- voice channel presence / lifecycle ---- */ setVoiceCount(n) { this.voiceCount = n; if (n > 0) { if (this._idle) this._clearTimeout(this._idle); this._idle = null; } else if (!this._idle && !this.closed) { this._idle = this._timer(() => this.close('idle'), IDLE_MS); } } close(reason = 'stop') { if (this.closed) return; this._gen++; this._abortScrape(); if (this._idle) this._clearTimeout(this._idle); this._idle = null; this._setClock(this.clock(), false); this.closed = true; this._emit(reason); this.emit('closed', this.state, reason); this.rooms.delete(this.id, this); } } function createRooms(cfg = {}, opts = {}) { const rooms = new EventEmitter(); const map = new Map(); rooms.bugtv = opts.bugtv || createBugtv(cfg); rooms.now = opts.now || (() => Date.now()); rooms.setTimeout = opts.setTimeout || ((fn, ms) => setTimeout(fn, ms)); rooms.clearTimeout = opts.clearTimeout || ((t) => clearTimeout(t)); rooms.lastProvider = new Map(); // ":" → provider that last played rooms.get = (id) => map.get(String(id)) || null; rooms.all = () => [...map.values()]; rooms.create = ({ id, guildId, textChannelId }) => { id = String(id); let room = map.get(id); if (room) { if (textChannelId) room.state.textChannelId = textChannelId; return room; } room = new Room(rooms, { id, guildId, textChannelId }); map.set(id, room); rooms.emit('created', room); return room; }; rooms.delete = (id, which) => { id = String(id); const room = map.get(id); if (!room || (which && room !== which)) return false; map.delete(id); if (!room.closed) room.close('stop'); rooms.emit('deleted', room); return true; }; return rooms; } module.exports = { createRooms, Room, scoreStream, isPlayable, rank, kindOf, qualityLabel, clockOf, KIND_LABEL, GRACE_MS, IDLE_MS };