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

move.ts

287 lines · 14.4 KB · TypeScript
/**
 * One-time move of this browser's MEGA Radio data from the old address to the new one (src/origins.ts).
 *
 * Moves exactly one item: localStorage `mega-radio:repeat` (the repeat setting, `off` | `all` | `one`).
 * Its own markers: `mega-radio:migrated` (OLD, after a confirmed import) and `mega-radio:imported` (NEW,
 * with the payload's exportedAt). Nothing else in storage is read or written, and nothing is deleted.
 *
 * OLD (location.origin === data-old-origin exactly):
 * - migrated marker set: send the visitor to the matching NEW URL.
 * - repeat setting present and no marker: show a notice with "Move my data to the new address" (window
 *   handoff) and "Download my data" (file). Nothing moves or redirects on page load.
 * NEW (location.origin === data-new-origin exactly), on the /move page ([data-move-page]):
 * - opened by OLD (window.opener + nonce): posts { type: 'ready', nonce } to OLD, accepts one payload from
 *   OLD for that nonce, imports it, replies { type: 'imported' | 'error', nonce }.
 * - "Import data" reads a file the visitor picks.
 *
 * Payload: { format: 'noah/mega-radio-migration', version: 1, exportedAt, data: { 'mega-radio:repeat' } }.
 * The data never goes in a URL and there is no server relay. postMessage never uses '*'.
 *
 * Runtime-free; the script exposes its pieces as window.__megaRadioMove for the tests.
 */
export const MIGRATION_FORMAT = 'noah/mega-radio-migration'
export const MIGRATION_VERSION = 1
export const REPEAT_KEY = 'mega-radio:repeat'
export const MIGRATED_KEY = 'mega-radio:migrated'
export const IMPORTED_KEY = 'mega-radio:imported'
export const READY_WAIT_MS = 2 * 60 * 1000

export const MOVE_JS = `(function (win) {
	var FORMAT = '${MIGRATION_FORMAT}'
	var VERSION = ${MIGRATION_VERSION}
	var REPEAT = '${REPEAT_KEY}'
	var MIGRATED = '${MIGRATED_KEY}'
	var IMPORTED = '${IMPORTED_KEY}'
	var WAIT_MS = ${READY_WAIT_MS}
	var MODES = ['off', 'all', 'one']
	var NAMES = { off: 'Off', all: 'Repeat all', one: 'Repeat one' }
	// The approved list: key -> value check. Only these keys are ever exported or imported.
	var ITEMS = {}
	ITEMS[REPEAT] = function (v) { return typeof v === 'string' && MODES.indexOf(v) !== -1 }
	var TOP = ['format', 'version', 'exportedAt', 'data']

	function has(o, k) { return Object.prototype.hasOwnProperty.call(o, k) }
	function ls() { try { return win.localStorage || null } catch (e) { return null } }
	function get(k) { var s = ls(); try { return s ? s.getItem(k) : null } catch (e) { return null } }
	function put(k, v) { var s = ls(); if (!s) throw new Error('This browser is not letting the page save settings.'); s.setItem(k, v) }
	function parse(s) { try { return s ? JSON.parse(s) : null } catch (e) { return null } }

	function hasData() { for (var k in ITEMS) if (has(ITEMS, k) && ITEMS[k](get(k))) return true; return false }
	function isMigrated() { return get(MIGRATED) !== null }

	function buildPayload(now) {
		var data = {}
		for (var k in ITEMS) if (has(ITEMS, k)) { var v = get(k); if (ITEMS[k](v)) data[k] = v }
		return { format: FORMAT, version: VERSION, exportedAt: (now || new Date()).toISOString(), data: data }
	}

	function fail(error) { return { ok: false, error: error } }
	function validate(p) {
		if (!p || typeof p !== 'object' || Array.isArray(p)) return fail('This is not MEGA Radio data.')
		if (p.format !== FORMAT) return fail('This is not MEGA Radio data (format ' + JSON.stringify(String(p.format)) + ').')
		if (p.version !== VERSION) return fail('This data is from a version of MEGA Radio this page does not understand (version ' + JSON.stringify(p.version) + '; expected ' + VERSION + '). Nothing was changed.')
		for (var t in p) if (has(p, t) && TOP.indexOf(t) === -1) return fail('This data has an unexpected field: ' + t + '. Nothing was changed.')
		if (typeof p.exportedAt !== 'string' || !/^\\d{4}-\\d{2}-\\d{2}T/.test(p.exportedAt) || isNaN(Date.parse(p.exportedAt))) return fail('This data has no valid export time. Nothing was changed.')
		if (!p.data || typeof p.data !== 'object' || Array.isArray(p.data)) return fail('This data has no items. Nothing was changed.')
		for (var k in p.data) {
			if (!has(p.data, k)) continue
			if (!has(ITEMS, k)) return fail('This data has an item this page does not know: ' + k + '. Nothing was changed.')
			if (!ITEMS[k](p.data[k])) return fail('This data has a bad value for ' + k + '. Nothing was changed.')
		}
		return { ok: true, payload: p }
	}

	// ask({ key, current, incoming }) resolves 'keep' (keep NEW's value) or 'replace' (use the old one).
	function importPayload(p, ask) {
		var v = validate(p)
		if (!v.ok) return Promise.resolve({ status: 'error', message: v.error, written: [] })
		var marker = parse(get(IMPORTED))
		if (marker && marker.exportedAt === p.exportedAt) return Promise.resolve({ status: 'already', message: 'This data was already imported (exported ' + p.exportedAt + '). Nothing was changed.', written: [] })
		var keys = Object.keys(p.data).filter(function (k) { return has(ITEMS, k) })
		var plan = []
		var kept = false
		var i = 0
		function next() {
			if (i >= keys.length) return Promise.resolve()
			var k = keys[i++]
			var cur = get(k)
			var inc = p.data[k]
			if (cur === null || cur === undefined) { plan.push(k); return next() }
			if (cur === inc) return next()
			return Promise.resolve(ask({ key: k, current: cur, incoming: inc })).then(function (choice) {
				if (choice === 'replace') plan.push(k)
				else if (choice === 'keep') kept = true
				else throw new Error('No choice was made. Nothing was changed.')
				return next()
			})
		}
		return next().then(function () {
			plan.forEach(function (k) { put(k, p.data[k]) })
			put(IMPORTED, JSON.stringify({ exportedAt: p.exportedAt, importedAt: new Date().toISOString() }))
			return { status: 'imported', message: plan.length ? 'Your repeat setting is on the new address.' : kept ? 'Done. The new address kept its own setting.' : 'Done. Your repeat setting was already on the new address.', written: plan }
		}, function (e) { return { status: 'error', message: e && e.message ? e.message : String(e), written: [] } })
	}

	function newUrlFor(loc, origins) {
		var path = loc.pathname || '/'
		var b = origins.oldBase
		if (path === b) path = '/'
		else if (path.indexOf(b + '/') === 0) path = path.slice(b.length)
		return origins.new + path + (loc.search || '') + (loc.hash || '')
	}

	function nonce() {
		var a = new Uint8Array(16)
		win.crypto.getRandomValues(a)
		return Array.prototype.map.call(a, function (x) { return (x < 16 ? '0' : '') + x.toString(16) }).join('')
	}

	// OLD: open NEW's import page from the click and hand the payload over once it says ready.
	function startHandoff(origins, onStatus) {
		var n = nonce()
		var w = win.open(origins.new + '/move?nonce=' + n, '_blank')
		if (!w) { onStatus('blocked'); return null }
		var ready = false
		var finished = false
		function stop() { finished = true; win.clearTimeout(timer); win.removeEventListener('message', onMessage) }
		var timer = win.setTimeout(function () { if (!ready && !finished) { stop(); onStatus('timeout') } }, WAIT_MS)
		function onMessage(ev) {
			if (finished || ev.origin !== origins.new || ev.source !== w) return
			var d = ev.data
			if (!d || typeof d !== 'object' || d.nonce !== n) return
			if (d.type === 'ready' && !ready) {
				ready = true
				win.clearTimeout(timer)
				w.postMessage({ type: 'payload', nonce: n, payload: buildPayload() }, origins.new)
				onStatus('sent')
			} else if (ready && d.type === 'imported') {
				stop()
				put(MIGRATED, JSON.stringify({ migratedAt: new Date().toISOString(), result: d.already ? 'already' : 'imported' }))
				onStatus('done')
			} else if (ready && d.type === 'error') {
				stop()
				onStatus('error', typeof d.message === 'string' ? d.message : 'The new address could not import your data.')
			}
		}
		win.addEventListener('message', onMessage)
		onStatus('waiting')
		return { nonce: n, window: w }
	}

	// NEW: the import page opened by OLD. Says ready, then takes one payload for this nonce.
	function acceptHandoff(origins, n, ask, onResult) {
		var opener = win.opener
		if (!opener || !/^[0-9a-f]{32}$/.test(n || '')) return false
		var handled = false
		function onMessage(ev) {
			if (handled || ev.origin !== origins.old || ev.source !== opener) return
			var d = ev.data
			if (!d || typeof d !== 'object' || d.type !== 'payload' || d.nonce !== n) return
			handled = true
			win.removeEventListener('message', onMessage)
			importPayload(d.payload, ask).then(function (r) {
				var ok = r.status === 'imported' || r.status === 'already'
				opener.postMessage(ok ? { type: 'imported', nonce: n, already: r.status === 'already' } : { type: 'error', nonce: n, message: r.message }, origins.old)
				onResult(r)
			})
		}
		win.addEventListener('message', onMessage)
		opener.postMessage({ type: 'ready', nonce: n }, origins.old)
		return true
	}

	function originsFromPage(doc) {
		var h = doc.documentElement
		var o = h.getAttribute('data-old-origin')
		var nw = h.getAttribute('data-new-origin')
		return o && nw ? { old: o, new: nw, oldBase: h.getAttribute('data-old-base') || '/mega-radio' } : null
	}

	// ---- UI -----------------------------------------------------------------------------------------------
	function el(doc, tag, attrs, text) {
		var e = doc.createElement(tag)
		for (var a in attrs) if (has(attrs, a)) e.setAttribute(a, attrs[a])
		if (text) e.textContent = text
		return e
	}
	function pill(doc, label, cls) { return el(doc, 'button', { type: 'button', class: 'pill ' + cls }, label) }

	function download(doc, payload) {
		var blob = new win.Blob([JSON.stringify(payload, null, 2)], { type: 'application/json' })
		var url = win.URL.createObjectURL(blob)
		var a = el(doc, 'a', { href: url, download: 'mega-radio-data.json' })
		doc.body.appendChild(a)
		a.click()
		a.remove()
		win.setTimeout(function () { win.URL.revokeObjectURL(url) }, 10000)
	}

	function oldNotice(doc, origins) {
		var main = doc.querySelector('main')
		if (!main) return
		var host = origins.new.replace(/^https?:\\/\\//, '')
		var card = el(doc, 'section', { class: 'card move-notice', 'data-move-notice': '', 'aria-labelledby': 'move-title' })
		card.appendChild(el(doc, 'h2', { id: 'move-title' }, 'MEGA Radio has a new address'))
		card.appendChild(el(doc, 'p', { class: 'muted' }, 'MEGA Radio now lives at ' + host + '. Your repeat setting is saved in this browser at the old address. Move it before December 17, 2026, when this address stops working. You may need to sign in with Kody again there.'))
		var actions = el(doc, 'div', { class: 'actions' })
		var move = pill(doc, 'Move my data to the new address', 'kody')
		var dl = pill(doc, 'Download my data', 'ghost')
		actions.appendChild(move)
		actions.appendChild(dl)
		card.appendChild(actions)
		var status = el(doc, 'p', { class: 'muted move-status', role: 'status', 'aria-live': 'polite' })
		card.appendChild(status)
		function say(t) { status.textContent = t }
		var fallback = 'Use Download my data, then open ' + origins.new + '/move and choose Import data.'
		move.addEventListener('click', function () {
			startHandoff(origins, function (s, msg) {
				if (s === 'blocked') say('Your browser blocked the new window. ' + fallback)
				else if (s === 'waiting') say('Opening the new address. Sign in with Kody there if it asks; this page waits up to 2 minutes.')
				else if (s === 'sent') say('Sending your repeat setting…')
				else if (s === 'timeout') say('The new address did not answer within 2 minutes. ' + fallback)
				else if (s === 'error') say('The move did not finish: ' + msg + ' ' + fallback)
				else if (s === 'done') { say('Moved. Taking you to the new address…'); win.setTimeout(function () { win.location.replace(newUrlFor(win.location, origins)) }, 1200) }
			})
		})
		dl.addEventListener('click', function () { download(doc, buildPayload()); say('Saved mega-radio-data.json. Open ' + origins.new + '/move and choose Import data.') })
		main.insertBefore(card, main.firstChild)
	}

	function askUI(doc, box) {
		return function (c) {
			return new Promise(function (resolve) {
				box.textContent = ''
				box.hidden = false
				box.appendChild(el(doc, 'p', null, 'This browser already has a repeat setting here (' + (NAMES[c.current] || c.current) + '). The old address has ' + (NAMES[c.incoming] || c.incoming) + '. Which should MEGA Radio use?'))
				var keep = pill(doc, 'Keep ' + (NAMES[c.current] || c.current) + ' (this address)', 'kody')
				var rep = pill(doc, 'Use ' + (NAMES[c.incoming] || c.incoming) + ' (old address)', 'ghost')
				keep.addEventListener('click', function () { box.hidden = true; resolve('keep') })
				rep.addEventListener('click', function () { box.hidden = true; resolve('replace') })
				box.appendChild(keep)
				box.appendChild(rep)
			})
		}
	}

	function newImportPage(doc, origins) {
		var page = doc.querySelector('[data-move-page]')
		if (!page) return
		var status = page.querySelector('[data-move-status]')
		var box = page.querySelector('[data-move-ask]')
		var input = page.querySelector('[data-move-file]')
		var home = page.querySelector('[data-move-home]')
		var ask = askUI(doc, box)
		function show(r) { status.textContent = r.message; if (home && r.status !== 'error') home.hidden = false }
		var n = null
		try { n = new win.URL(win.location.href).searchParams.get('nonce') } catch (e) {}
		if (acceptHandoff(origins, n, ask, show)) status.textContent = 'Waiting for your data from the old address…'
		if (input) input.addEventListener('change', function () {
			var f = input.files && input.files[0]
			if (!f) return
			f.text().then(function (t) {
				var p
				try { p = JSON.parse(t) } catch (e) { show({ status: 'error', message: 'That file is not MEGA Radio data. Nothing was changed.' }); return }
				return importPayload(p, ask).then(show)
			})
		})
	}

	function init() {
		var doc = win.document
		if (!doc || !doc.documentElement) return
		var origins = originsFromPage(doc)
		if (!origins) return
		var origin = win.location.origin
		if (origin === origins.old) {
			if (isMigrated()) { win.location.replace(newUrlFor(win.location, origins)); return }
			if (hasData()) oldNotice(doc, origins)
		} else if (origin === origins.new) {
			newImportPage(doc, origins)
		}
	}

	win.__megaRadioMove = { buildPayload: buildPayload, validate: validate, importPayload: importPayload, startHandoff: startHandoff, acceptHandoff: acceptHandoff, newUrlFor: newUrlFor, hasData: hasData, isMigrated: isMigrated, init: init }
	if (win.document && win.document.readyState === 'loading') win.document.addEventListener('DOMContentLoaded', init)
	else init()
})(window)
`