Skip to content

Black Friday

Annual Pro is $90 for the first year, normally $120. Or start monthly at $6 for two months, then $12.

Ends Dec 4, 11:59 PM PT.

Create an account
← Public packages

@noah/mega-radio

MEGA Radio (the WAKE album) for members of the MEGA.dev Discord: sign in with Kody, verify with Discord, listen with repeat.

FollowForkOpen app

Files

player.ts

212 lines · 9.1 KB · TypeScript
/**
 * Client script for the track list. Built to keep playing with the screen locked or the tab in the
 * background (iOS Safari, Android Chrome):
 *
 * - One persistent `<audio id="radio-audio" playsinline>` element plays every track (no Web Audio graph and
 *   no element per track). Track rows are buttons that set its `src`.
 * - On `ended`, the next (or repeated) track's `src` is set and `play()` is called synchronously in the
 *   handler, which is what lets the browser advance while locked.
 * - Media Session (set on every play and track change): title, artist "MEGA.dev", album "WAKE - Control Plane",
 *   the cover at 512 and 256 px from a signed, cookie-free URL (data-cover, see src/art.ts) as artwork; play, pause,
 *   previous, next, seekto, seekbackward and seekforward actions; position state kept up to date.
 * - Audio is same-origin, so the gate's cookies ride along on every (Range) request; no crossorigin attribute.
 *
 * Listen stats: a play is reported (POST <base>/plays/NN, same-origin cookies, keepalive) once 30 s have
 * played or the track ends, once per pass, so each repeat loop counts; the server checks membership and
 * rate-limits. The ▶ count is a button: hover shows its title, tap toggles a tooltip (iOS has no hover).
 *
 * Tap-to-play: a tap anywhere on a released track row plays it right away; tapping the playing row pauses or
 * resumes it. The active row gets aria-current and data-state (playing or paused) for the now-playing bars.
 *
 * Repeat: one icon button cycles off (default) -> all -> one. Off stops at a track's end; all moves to the next
 * released track and wraps from the last to the first; one replays the same track. Remembered per browser in
 * localStorage (`mega-radio:repeat`).
 */
export const PLAYER_JS = `(function () {
	var KEY = 'mega-radio:repeat'
	var MODES = ['off', 'all', 'one']
	var LABEL = { off: 'Repeat: off', one: 'Repeat: one', all: 'Repeat: all' }
	var mode = 'off'
	try { if (MODES.indexOf(localStorage.getItem(KEY)) !== -1) mode = localStorage.getItem(KEY) } catch (e) {}

	var audio = document.getElementById('radio-audio')
	if (!audio) return
	audio.setAttribute('playsinline', '')
	var buttons = Array.prototype.slice.call(document.querySelectorAll('[data-track]'))
	var current = -1
	var ms = 'mediaSession' in navigator ? navigator.mediaSession : null
	var nowTitle = document.getElementById('now-title')
	var counted = false

	function abs(u) { try { return new URL(u, location.href).href } catch (e) { return u } }
	function quiet(p) { if (p && p.catch) p.catch(function () {}) }

	function label(i) { var b = buttons[i]; return String(b.getAttribute('data-n')).padStart(2, '0') + ' · ' + b.getAttribute('data-title') }

	function mark() {
		buttons.forEach(function (b, i) {
			b.setAttribute('aria-current', i === current ? 'true' : 'false')
			if (i === current) b.setAttribute('data-state', audio.paused ? 'paused' : 'playing')
			else b.setAttribute('data-state', 'idle')
			var s = b.querySelector('.track-state')
			if (s) s.textContent = i === current && !audio.paused ? '❚❚' : '▶'
		})
		if (nowTitle) nowTitle.textContent = current >= 0 ? label(current) : 'Pick a track'
	}

	function metadata() {
		if (!ms || current < 0 || typeof MediaMetadata === 'undefined') return
		var b = buttons[current]
		ms.metadata = new MediaMetadata({
			title: b.getAttribute('data-title'),
			artist: 'MEGA.dev',
			album: 'WAKE - Control Plane',
			artwork: ['512x512', '256x256'].map(function (sz) { return { src: abs(b.getAttribute('data-cover')), sizes: sz, type: 'image/png' } }),
		})
	}

	function position() {
		if (!ms || !ms.setPositionState) return
		var d = audio.duration
		if (!isFinite(d) || d <= 0) return
		try { ms.setPositionState({ duration: d, playbackRate: audio.playbackRate || 1, position: Math.min(Math.max(audio.currentTime, 0), d) }) } catch (e) {}
	}

	/** Switch the one element to track i and play. Synchronous up to play(), so it works inside 'ended'. */
	function playIndex(i) {
		if (!buttons.length) return
		current = (i + buttons.length) % buttons.length
		counted = false
		var src = buttons[current].getAttribute('data-src')
		if (audio.getAttribute('src') !== src) audio.src = src
		else audio.currentTime = 0
		audio.loop = false
		quiet(audio.play())
		metadata()
		mark()
	}

	function toggle(i) {
		if (i === current) { if (audio.paused) quiet(audio.play()); else audio.pause(); return }
		playIndex(i)
	}

	function next() { playIndex(current < 0 ? 0 : current + 1) }
	function prev() { if (audio.currentTime > 3 && current >= 0) { audio.currentTime = 0; position(); return } playIndex(current < 0 ? 0 : current - 1) }

	function tipText(total, mine) {
		return total + (total === 1 ? ' play' : ' plays') + ' by MEGA.dev members' + (mine ? ' (' + mine + (mine === 1 ? ' is' : ' are') + ' yours)' : '')
	}

	function showPlays(row, total, mine) {
		var b = row.querySelector('[data-plays]')
		if (b) {
			var tip = tipText(total, mine)
			b.textContent = '▶ ' + total
			b.setAttribute('data-total', String(total))
			b.setAttribute('data-mine', String(mine))
			b.setAttribute('title', tip)
			b.setAttribute('aria-label', tip)
			var t = row.querySelector('[role="tooltip"]')
			if (t) t.textContent = tip
		}
		var r = row.querySelector('[data-on-repeat]')
		if (r) r.textContent = mine >= 3 ? ' · you\u2019ve got it on repeat (' + mine + ')' : ''
	}

	/** Report one play of track i (once per pass). */
	function count(i) {
		if (counted || i < 0 || typeof fetch !== 'function') return
		counted = true
		var row = buttons[i]
		var url = row.getAttribute('data-src').replace(/\\/files\\/radio\\/(\\d+)\\.mp3$/, '/plays/$1')
		try {
			fetch(url, { method: 'POST', credentials: 'same-origin', keepalive: true, headers: { 'content-type': 'application/json' }, body: '{}' })
				.then(function (r) { return r.ok || r.status === 429 ? r.json() : null })
				.then(function (d) { if (d && typeof d.total === 'number') showPlays(row, d.total, d.mine) })
				.catch(function () {})
		} catch (e) {}
	}

	function closeTips(except) {
		Array.prototype.forEach.call(document.querySelectorAll('[data-plays]'), function (b) {
			if (b === except) return
			b.setAttribute('aria-expanded', 'false')
			var t = document.getElementById(b.getAttribute('aria-controls'))
			if (t) t.hidden = true
		})
	}

	function apply() {
		var nextMode = MODES[(MODES.indexOf(mode) + 1) % MODES.length]
		Array.prototype.forEach.call(document.querySelectorAll('[data-repeat]'), function (b) {
			b.setAttribute('data-mode', mode)
			b.setAttribute('aria-label', LABEL[mode] + '. Press for repeat ' + nextMode + '.')
			b.setAttribute('title', LABEL[mode])
		})
		var status = document.getElementById('repeat-status')
		if (status) status.textContent = LABEL[mode]
	}

	document.addEventListener('click', function (e) {
		var t = e.target && e.target.closest ? e.target : null
		if (!t) return
		var r = t.closest('[data-repeat]')
		if (r) { mode = MODES[(MODES.indexOf(mode) + 1) % MODES.length]; try { localStorage.setItem(KEY, mode) } catch (err) {} apply(); return }
		var pl = t.closest('[data-plays]')
		if (pl) {
			var tipEl = document.getElementById(pl.getAttribute('aria-controls'))
			var open = pl.getAttribute('aria-expanded') !== 'true'
			closeTips(pl)
			pl.setAttribute('aria-expanded', open ? 'true' : 'false')
			if (tipEl) tipEl.hidden = !open
			return
		}
		closeTips(null)
		if (t.closest('[data-next]')) { next(); return }
		if (t.closest('[data-prev]')) { prev(); return }
		var b = t.closest('[data-track]')
		if (b && buttons.indexOf(b) !== -1) { toggle(buttons.indexOf(b)); return }
	})

	audio.addEventListener('ended', function () {
		if (current < 0) return
		count(current)
		counted = false
		if (mode === 'one') { audio.currentTime = 0; quiet(audio.play()); return }
		if (mode === 'all') { playIndex(current + 1); return }
		mark()
	})
	audio.addEventListener('play', function () { metadata(); if (ms) ms.playbackState = 'playing'; mark() })
	audio.addEventListener('playing', metadata)
	audio.addEventListener('pause', function () { if (ms) ms.playbackState = 'paused'; mark() })
	audio.addEventListener('loadedmetadata', position)
	audio.addEventListener('durationchange', position)
	audio.addEventListener('ratechange', position)
	audio.addEventListener('seeked', position)
	audio.addEventListener('timeupdate', function () {
		if (!counted && audio.currentTime >= 30) count(current)
		if (Math.floor(audio.currentTime) % 5 === 0) position()
	})

	if (ms) {
		var handlers = {
			play: function () { if (current < 0) playIndex(0); else quiet(audio.play()) },
			pause: function () { audio.pause() },
			previoustrack: prev,
			nexttrack: next,
			seekto: function (d) {
				if (d.seekTime == null) return
				if (d.fastSeek && audio.fastSeek) audio.fastSeek(d.seekTime); else audio.currentTime = d.seekTime
				position()
			},
			seekbackward: function (d) { audio.currentTime = Math.max(audio.currentTime - (d.seekOffset || 10), 0); position() },
			seekforward: function (d) { var t = audio.currentTime + (d.seekOffset || 10); audio.currentTime = isFinite(audio.duration) ? Math.min(t, audio.duration) : t; position() },
		}
		Object.keys(handlers).forEach(function (a) { try { ms.setActionHandler(a, handlers[a]) } catch (e) {} })
	}

	apply()
	mark()
})()
`