const assert = require('node:assert/strict'); const {readFileSync} = require('node:fs'); const {test} = require('node:test'); const vm = require('node:vm'); const template = readFileSync(`${__dirname}/../templates/player/scripts.html`, 'utf8'); // Podcast episode playback in the web player and the podcasts store, run // on the production methods with stubbed audio, fetch and timers. const BASE = 'https://furumi.test/player'; const DIRECT = 'https://cdn.example/ep42.mp3'; const PROXY = '/api/podcasts/episodes/ep1:x/audio'; function episode(extra = {}) { const source = Object.assign({ kind: 'podcast_episode', episode_id: 'ep1:x', podcast_id: 'pod1:y', feed_url: 'https://podcasts.example/feed.xml', podcast_title: 'Example Cast', episode_title: 'Episode 42', audio_url: DIRECT, duration_ms: 1800000, }, extra); return { id: -11, title: 'Episode 42', unavailable: false, stream_url: '', duration_seconds: 1800, artists: [{id: -1, name: 'Example Cast'}], source, wire_track: {id: 0, title: 'Episode 42', source}, }; } const song = id => ({id, title: `Song ${id}`, stream_url: `/api/player/stream/${id}`}); function method(name) { const start = template.indexOf(`\n ${name}(`); const asyncStart = template.indexOf(`\n async ${name}(`); const at = start >= 0 ? start : asyncStart; assert.ok(at >= 0, `method ${name} not found`); const end = template.indexOf('\n },\n', at); return template.slice(at + 1, end + 11); } const PLAYER_METHODS = [ '_executeRemoteCommand', '_devicePlaybackStatePayload', '_remotePlaybackPayload', '_trackDuration', '_pauseLocal', '_playLocal', 'pause', 'resume', 'next', 'seek', 'playQueueIndex', '_knownPosition', '_currentItemHasLocalAudio', '_showUnplayableQueueItem', '_syncLocalPlaybackState', '_queueItemSourceKind', '_isUnplayableQueueItem', '_isPodcastEpisode', '_isPrivateQueueItem', '_playableQueueIndex', '_skipUnplayableCurrentItem', '_applyRemotePlaybackState', '_tickRemoteProgress', '_jamParticipantCommandAllowed', '_episodeRef', '_newEpisodeSessionId', '_episodeRequest', '_playEpisodeLocal', '_episodeAudioUrl', '_loadEpisodeAudio', '_episodeCanSeek', '_onEpisodeAudioError', '_startEpisodeSession', '_resumeEpisode', '_seekEpisode', '_episodePosition', '_episodeTick', '_onEpisodePaused', '_reportEpisode', '_endEpisode', '_episodeReportBody', '_takeOverEpisode', '_releaseEpisodeSession', '_resumeFromRegister', '_continuePausedEpisode', '_moveEpisodeAudio', '_rewindEpisode', 'prev', '_restoreState', '_restoredQueueTracks', ]; function eventAudio(extra = {}) { const listeners = {}; let src = ''; return Object.assign({ paused: true, currentTime: 0, duration: NaN, ended: false, played: [], seekable: {length: 1, start: () => 0, end: () => 3600}, get src() { return src; }, set src(value) { src = value ? new URL(value, BASE).href : ''; }, pause() { this.paused = true; }, play() { this.paused = false; this.played.push(src); return Promise.resolve(); }, removeAttribute(name) { if (name === 'src') src = ''; }, load() { this.currentTime = 0; }, addEventListener(type, fn) { (listeners[type] ||= []).push(fn); }, removeEventListener(type, fn) { listeners[type] = (listeners[type] || []).filter(other => other !== fn); }, fire(type) { [...(listeners[type] || [])].forEach(fn => fn()); }, }, extra); } function episodePlayer(queueTracks, currentIndex, options = {}) { const audio = eventAudio(options.audio); const calls = []; const beacons = []; const progress = []; let timers = []; const env = { audio, calls, beacons, progress, local: true, runTimers() { const due = timers; timers = []; due.forEach(fn => fn && fn()); }, }; const fetch = (url, init = {}) => new Promise((resolve, reject) => { calls.push({ url, keepalive: !!init.keepalive, body: init.body ? JSON.parse(init.body) : null, respond(data, status = 200) { resolve({ok: status < 400, status, json: async () => data}); }, fail(error) { reject(error); }, }); }); const queue = { tracks: queueTracks, currentIndex, _tracksWithJamDefaults: tracks => tracks, syncCurrentIndexToTrack(track) { const index = this.tracks.indexOf(track); if (index >= 0) this.currentIndex = index; }, }; const stores = {queue, devices: {heartbeat() {}}, podcasts: {episodeProgressChanged: (id, data) => progress.push([id, data])}}; let uuid = 0; const context = vm.createContext({ audio, fetch, URL, Blob, console, GUEST: false, T: {podcastSourceFailed: 'source failed', podcastCannotSeek: 'cannot seek', podcastRequestFailed: 'request failed'}, location: {protocol: new URL(options.base || BASE).protocol, href: options.base || BASE}, navigator: {sendBeacon(url, blob) { beacons.push({url, blob}); return true; }}, setTimeout(fn) { timers.push(fn); return timers.length; }, clearTimeout(id) { if (id) timers[id - 1] = null; }, crypto: {randomUUID: () => `uuid-${++uuid}`}, Alpine: {store: name => stores[name]}, }); vm.runInContext('this.methods = {' + PLAYER_METHODS.map(method).join('\n') + '};', context); env.context = context; env.stores = stores; env.queue = queue; env.player = Object.assign(context.methods, { currentTrack: queueTracks[currentIndex] || null, currentTime: 0, duration: 0, progress: 0, isPlaying: false, shuffle: false, repeatMode: 'off', volume: 0.5, _remoteStateBaseTime: 0, _remoteStateReceivedAt: 0, _positionUnknown: false, _listenedSeconds: 0, _lastAudioTime: 0, _localSourceTrackId: null, _historyTrack: null, episodeNotice: '', episodeLoading: false, _episode: null, _episodeToken: 0, _episodeSeekTimer: null, _episodeCheckpointMs: 20000, _episodeRewindSeconds: 15, _isLocalPlaybackDevice: () => env.local, _shouldSendRemote: () => false, _shouldMirrorRemoteLocally: () => false, _setVolumeLocal(v) { this.volume = v; }, _updateMediaSession() {}, _saveState() {}, _recordHistory() {}, _resetPlaybackTracking() { this._listenedSeconds = 0; }, _mirrorRemoteTrack() {}, _sendRemote() {}, }); stores.player = env.player; return env; } // The devices store's select() (the device picker), on the same stubs. function devicesStore(env, id = 'web-a') { vm.runInContext('this.devicesMethods = {' + method('select') + '};', env.context); const devices = Object.assign(env.context.devicesMethods, { id, activeDeviceId: id, open: true, selectError: '', applied: [], isActive() { return this.activeDeviceId === this.id; }, clearJamSelection() {}, async _errorText(res) { return (await res.json()).error; }, _apply(data) { this.applied.push(data); this.activeDeviceId = data.active_device_id; }, }); env.stores.devices = Object.assign(env.stores.devices, devices); return devices; } const flush = async () => { for (let i = 0; i < 20; i++) await new Promise(resolve => setImmediate(resolve)); }; function answer(call, extra = {}) { call.respond(Object.assign({ episode_id: 'ep1:x', podcast_id: 'pod1:y', session_id: call.body.start ? call.body.session_id : null, generation: call.body.start ? 4 : null, position_ms: call.body.position_ms ?? 600000, status: 'in_progress', duration_ms: 1800000, direct_url: DIRECT, proxy_url: null, mime: 'audio/mpeg', }, extra)); } test('an episode plays from its resume position and saves progress in the background', async () => { const env = episodePlayer([song(1), episode()], 0); const p = env.player; p.playQueueIndex(1); // Nothing plays before the server sent the source and the position. assert.equal(p.currentTrack.title, 'Episode 42'); assert.equal(env.audio.src, ''); assert.equal(p._devicePlaybackStatePayload().position_unknown, true); const [prepare] = env.calls; assert.equal(prepare.url, '/api/podcasts/episodes/ep1:x/playback'); assert.equal(prepare.body.start, true); assert.match(prepare.body.session_id, /^web-/); assert.equal(prepare.body.position_ms, undefined, 'ordinary Play resumes from the register'); assert.equal(prepare.body.episode.episode_id, 'ep1:x'); assert.equal(prepare.body.episode.kind, undefined, 'the reference, not the source wrapper'); answer(prepare); await flush(); assert.equal(env.audio.src, DIRECT); assert.deepEqual(env.audio.played, [], 'the audio starts after the seek'); env.audio.duration = 1800; env.audio.fire('loadedmetadata'); assert.equal(env.audio.currentTime, 600); assert.deepEqual(env.audio.played, [DIRECT]); const state = p._devicePlaybackStatePayload(); assert.equal(state.position_seconds, 600); assert.equal(state.position_unknown, undefined); // Checkpoints every 20 s at the session generation. p.isPlaying = true; env.audio.currentTime = 630; p._listenedSeconds = 30; p._episodeTick(); assert.equal(env.calls.length, 1, 'not before the interval'); p._episode.lastWriteAt -= 20000; p._episodeTick(); await flush(); const checkpoint = env.calls[1]; assert.equal(checkpoint.url, '/api/podcasts/episodes/ep1:x/progress'); const {started_at_ms: startedAt, ...body} = checkpoint.body; assert.equal(typeof startedAt, 'number'); assert.deepEqual(body, { session_id: prepare.body.session_id, generation: 4, event: 'checkpoint', position_ms: 630000, duration_ms: 1800000, listened_ms: 30000, start_position_ms: 600000, }); checkpoint.respond({outcome: 'written', generation: 4, status: 'in_progress', position_ms: 630000}); await flush(); // A seek is an explicit action, written once the user stops dragging. p.seek(300); assert.equal(env.audio.currentTime, 300); assert.equal(env.calls.length, 2); env.runTimers(); await flush(); const seek = env.calls[2]; assert.deepEqual([seek.body.event, seek.body.position_ms, seek.body.generation], ['seek', 300000, 4]); seek.respond({outcome: 'written', generation: 5, status: 'in_progress', position_ms: 300000}); await flush(); p._episode.lastWriteAt -= 20000; p._episodeTick(); await flush(); assert.equal(env.calls[3].body.generation, 5, 'later checkpoints use the explicit generation'); // Another device wrote the episode while nothing was listened here: // no more checkpoints at the old generation; a pause still records // the listening session (the register refuses it). env.calls[3].respond({outcome: 'superseded', generation: 9, status: 'in_progress', position_ms: 1000}); await flush(); p._episode.lastWriteAt -= 20000; p._episodeTick(); await flush(); assert.equal(env.calls.length, 4); p.isPlaying = false; p._onEpisodePaused(); await flush(); assert.equal(env.calls[4].body.event, 'pause'); env.calls[4].respond({outcome: 'superseded', generation: 9, status: 'in_progress', position_ms: 1000}); await flush(); assert.equal(env.calls.length, 5, 'nothing listened here since: no takeover'); // Play here again is an ordinary Play: a new session from the register. p.resume(); await flush(); const again = env.calls[5]; assert.deepEqual([again.body.start, again.body.position_ms], [true, undefined]); assert.notEqual(again.body.session_id, prepare.body.session_id); assert.deepEqual(env.audio.played.length, 1, 'not before the answer'); answer(again, {generation: 10, position_ms: 1000}); await flush(); assert.equal(env.audio.currentTime, 1); assert.equal(p._episode.generation, 10); assert.equal(env.audio.played.length, 2); assert.deepEqual(env.progress.map(([, data]) => data.outcome), ['written', 'written', 'superseded', 'superseded']); }); test('a stale episode answer never starts playback', async () => { const env = episodePlayer([song(1), episode()], 0); env.player.playQueueIndex(1); // The user moves on before the server answered. env.player.playQueueIndex(0); assert.equal(env.audio.src, 'https://furumi.test/api/player/stream/1'); answer(env.calls[0]); await flush(); env.audio.fire('loadedmetadata'); assert.equal(env.audio.src, 'https://furumi.test/api/player/stream/1'); assert.deepEqual(env.audio.played, ['https://furumi.test/api/player/stream/1']); assert.equal(env.player._episode, null); assert.equal(env.calls.length, 1, 'no progress for a session that never started'); }); test('a handed-off episode keeps its position, pause state and generation', async () => { const handed = episode({progress_generation: 7}); const env = episodePlayer([song(1)], 0); const p = env.player; p._executeRemoteCommand({command: 'transfer_state', payload: { tracks: [song(1), handed], index: 1, track: handed, position_seconds: 1200, paused: true, }}); const [prepare] = env.calls; assert.deepEqual( [prepare.body.start, prepare.body.position_ms, prepare.body.carried_generation, prepare.body.session_id], [false, 1200000, 7, null], ); let state = p._devicePlaybackStatePayload(); assert.deepEqual([state.position_seconds, state.paused, state.index], [1200, true, 1]); assert.equal(state.position_unknown, undefined); // Play is pressed while the source is still being prepared. p.resume(); answer(prepare); await flush(); const start = env.calls[1]; assert.deepEqual( [start.body.start, start.body.position_ms, start.body.carried_generation], [true, 1200000, 7], ); env.audio.fire('loadedmetadata'); assert.equal(env.audio.currentTime, 1200); assert.equal(env.audio.played.length, 1); answer(start, {generation: 8}); await flush(); assert.equal(p._episode.generation, 8); // Handing it on writes a final checkpoint at the session generation, // even after this device stopped being the active one. p.isPlaying = true; env.audio.currentTime = 1260; env.local = false; p._reportEpisode('handoff'); await flush(); const handoff = env.calls[2]; assert.deepEqual([handoff.body.event, handoff.body.generation, handoff.body.position_ms], ['handoff', 8, 1260000]); // The device that took over writes from now on. p._episode.lastWriteAt -= 20000; p._episodeTick(); p._onEpisodePaused(); await flush(); assert.equal(env.calls.length, 3); // A play command from another browser starts at the resume position. const remote = episodePlayer([song(1)], 0); remote.player._executeRemoteCommand({command: 'play_from_index', payload: { tracks: [song(1), handed], index: 1, track: handed, position_seconds: 0, paused: false, }}); assert.equal(remote.calls[0].body.position_ms, undefined); assert.equal(remote.calls[0].body.start, true); }); test('a source the browser cannot play falls back to the proxy and keeps the position', async () => { const env = episodePlayer([episode()], 0); const p = env.player; // init() registers _onEpisodeAudioError as the audio 'error' listener. p.playQueueIndex(0); answer(env.calls[0], {proxy_url: PROXY}); await flush(); assert.equal(env.audio.src, DIRECT); p.isPlaying = true; p._onEpisodeAudioError(); assert.equal(env.audio.src, `https://furumi.test${PROXY}`); env.audio.fire('loadedmetadata'); assert.equal(env.audio.currentTime, 600); assert.equal(env.audio.played.length, 1); // The proxy fails too: the user sees it and the position stays. p._onEpisodeAudioError(); assert.equal(p.episodeNotice, 'source failed'); assert.equal(p.isPlaying, false); assert.equal(p._devicePlaybackStatePayload().position_seconds, 600); // An error of an unloaded source is not this episode's. const quiet = episodePlayer([episode()], 0); quiet.player.playQueueIndex(0); answer(quiet.calls[0], {proxy_url: PROXY}); await flush(); quiet.audio.removeAttribute('src'); quiet.player._onEpisodeAudioError(); assert.equal(quiet.player.episodeNotice, ''); // On an https page an http:// file goes through the proxy at once. const mixed = episodePlayer([episode()], 0); mixed.player.playQueueIndex(0); answer(mixed.calls[0], {direct_url: 'http://cdn.example/ep42.mp3', proxy_url: PROXY}); await flush(); assert.equal(mixed.audio.src, `https://furumi.test${PROXY}`); // Without the proxy the publisher URL is used as it is. const direct = episodePlayer([episode()], 0); direct.player.playQueueIndex(0); answer(direct.calls[0], {direct_url: 'http://cdn.example/ep42.mp3'}); await flush(); assert.equal(direct.audio.src, 'http://cdn.example/ep42.mp3'); }); test('a server that cannot seek is never reported as resumed', async () => { const env = episodePlayer([episode()], 0, {audio: {seekable: {length: 0}}}); const p = env.player; p.playQueueIndex(0); answer(env.calls[0]); await flush(); env.audio.fire('loadedmetadata'); assert.equal(p.episodeNotice, 'cannot seek'); assert.deepEqual(env.audio.played, []); assert.equal(p.isPlaying, false); assert.equal(p._devicePlaybackStatePayload().position_seconds, 600, 'the saved position, not 0'); p.isPlaying = true; p._episode.lastWriteAt -= 20000; p._episodeTick(); p._onEpisodePaused(); await flush(); assert.equal(env.calls.length, 1, 'nothing overwrites the saved position'); // Play means: listen from the start, an explicit action at 0. p.resume(); await flush(); assert.deepEqual([env.calls[1].body.start, env.calls[1].body.position_ms], [true, 0]); assert.equal(env.audio.played.length, 1); assert.equal(p.episodeNotice, ''); // A seek the server silently ignored is caught as well. const silent = episodePlayer([episode()], 0); silent.player.playQueueIndex(0); answer(silent.calls[0]); await flush(); silent.audio.fire('loadedmetadata'); silent.audio.currentTime = 0; silent.audio.fire('seeked'); assert.equal(silent.player.episodeNotice, 'cannot seek'); assert.equal(silent.player._devicePlaybackStatePayload().position_seconds, 600); }); test('pause, the end of the stream and the next item report the session', async () => { const env = episodePlayer([episode(), song(2)], 0); const p = env.player; p.playQueueIndex(0); answer(env.calls[0], {generation: 2}); await flush(); env.audio.duration = 1800; env.audio.fire('loadedmetadata'); p.isPlaying = true; env.audio.currentTime = 700; p._listenedSeconds = 95; p.pause(); p._onEpisodePaused(); await flush(); const paused = env.calls[1]; assert.deepEqual([paused.body.event, paused.body.position_ms, paused.body.listened_ms], ['pause', 700000, 95000]); assert.equal(paused.body.start_position_ms, 600000); paused.respond({outcome: 'written', generation: 2, status: 'in_progress', position_ms: 700000}); await flush(); // The end of the stream: a pause event then 'ended'; only 'ended' reports. env.audio.ended = true; env.audio.currentTime = 1800; p._onEpisodePaused(); p._reportEpisode('ended'); await flush(); assert.equal(env.calls.length, 3); assert.equal(env.calls[2].body.event, 'ended'); env.calls[2].respond({outcome: 'written', generation: 3, status: 'completed', position_ms: 1800000, completed: true}); await flush(); assert.equal(p._episode.completed, true); // Play after the end listens again: a new session from the start. p.resume(); await flush(); assert.deepEqual([env.calls[3].body.start, env.calls[3].body.position_ms], [true, 0]); answer(env.calls[3], {generation: 4}); await flush(); env.audio.ended = false; env.audio.currentTime = 20; // The next item replaces the episode: a final stop, kept alive. p.playQueueIndex(1); await flush(); const stop = env.calls[4]; assert.deepEqual([stop.body.event, stop.body.generation, stop.keepalive], ['stop', 4, true]); assert.equal(p._episode, null); assert.equal(env.audio.src, 'https://furumi.test/api/player/stream/2'); }); test('a report always carries the position of its own episode', async () => { const env = episodePlayer([episode(), song(2)], 0); const p = env.player; p.playQueueIndex(0); answer(env.calls[0], {generation: 3}); await flush(); env.audio.fire('loadedmetadata'); env.audio.currentTime = 640; p._episode.lastPosition = 640; // While this browser was not playing, it showed another device's item. const other = episode({episode_id: 'ep1:other', episode_title: 'Other'}); p.currentTrack = other; p.currentTime = 1200; p._endEpisode('stop'); await flush(); const stop = env.calls[1]; assert.deepEqual([stop.body.event, stop.body.position_ms], ['stop', 640000], 'never the other item position'); // A browser that lost the playback role ends its session silently. const quiet = episodePlayer([episode()], 0); quiet.player.playQueueIndex(0); answer(quiet.calls[0]); await flush(); quiet.local = false; quiet.player._endEpisode('stop'); await flush(); assert.equal(quiet.calls.length, 1); assert.equal(quiet.player._episode, null); }); test('a player that loses the playback role records what it listened', async () => { // Another device took playback over (a pull): the stretch listened here // is recorded with this session, at its own generation. const env = episodePlayer([episode()], 0); const p = env.player; p.playQueueIndex(0); answer(env.calls[0], {generation: 3}); await flush(); env.audio.fire('loadedmetadata'); p.isPlaying = true; env.audio.currentTime = 900; p._listenedSeconds = 300; env.local = false; p._endEpisode('stop', {final: true}); await flush(); const stop = env.calls[1]; assert.deepEqual( [stop.body.event, stop.body.generation, stop.body.position_ms, stop.body.listened_ms, stop.keepalive], ['stop', 3, 900000, 300000, true], ); // The new device's explicit start wins: no takeover from here. stop.respond({outcome: 'superseded', generation: 4, status: 'in_progress', position_ms: 905000, session_recorded: true}); await flush(); assert.equal(env.calls.length, 2); assert.equal(p._episode, null); // After a handoff from here the final position was already sent. const pushed = episodePlayer([episode()], 0); pushed.player.playQueueIndex(0); answer(pushed.calls[0], {generation: 3}); await flush(); pushed.audio.fire('loadedmetadata'); pushed.player.isPlaying = true; pushed.player._listenedSeconds = 60; pushed.player._reportEpisode('handoff'); await flush(); pushed.local = false; pushed.player._endEpisode('stop', {final: true}); await flush(); assert.deepEqual(pushed.calls.slice(1).map(call => call.body.event), ['handoff']); }); test('a reload resumes an episode from the register, not from the saved player state', async () => { const env = episodePlayer([], 0); const p = env.player; const restoring = p._restoreState(); const [state] = env.calls; assert.equal(state.url, '/api/player/state'); // This page saved 10:00; another device listened to 40:00 since. state.respond({queue_items: [{kind: 'external', track: episode()}], queue_items_position: 0, position_ms: 600000}); await restoring; await flush(); const prepare = env.calls[1]; assert.equal(prepare.url, '/api/podcasts/episodes/ep1:x/playback'); assert.deepEqual([prepare.body.start, prepare.body.position_ms], [false, undefined]); answer(prepare, {position_ms: 2400000}); await flush(); env.audio.fire('loadedmetadata'); assert.equal(env.audio.currentTime, 2400); assert.deepEqual(env.audio.played, [], 'restored paused'); // Play continues there: an ordinary Play starts from the register. p.resume(); await flush(); const start = env.calls[2]; assert.deepEqual([start.body.start, start.body.position_ms], [true, undefined]); answer(start, {generation: 8, position_ms: 2400000}); await flush(); assert.equal(env.audio.currentTime, 2400); assert.equal(env.audio.played.length, 1); // A seek before Play is the user's choice and is sent. const seeking = episodePlayer([], 0); const restoringAgain = seeking.player._restoreState(); seeking.calls[0].respond({queue_items: [{kind: 'external', track: episode()}], queue_items_position: 0, position_ms: 600000}); await restoringAgain; await flush(); answer(seeking.calls[1], {position_ms: 2400000}); await flush(); seeking.audio.fire('loadedmetadata'); seeking.player.seek(120); seeking.runTimers(); seeking.player.resume(); await flush(); assert.deepEqual([seeking.calls[2].body.start, seeking.calls[2].body.position_ms], [true, 120000]); }); test('Play after a pause continues the session only while the register is its own', async () => { const env = episodePlayer([episode()], 0); const p = env.player; p.playQueueIndex(0); const sessionId = env.calls[0].body.session_id; answer(env.calls[0], {generation: 3}); await flush(); env.audio.fire('loadedmetadata'); p.isPlaying = false; p.resume(); await flush(); const check = env.calls[1]; assert.deepEqual([check.body.start, check.body.session_id], [false, undefined]); assert.equal(env.audio.played.length, 1, 'waits for the check'); answer(check, {register_session_id: sessionId, register_generation: 3}); await flush(); assert.equal(env.audio.played.length, 2); assert.equal(env.calls.length, 2, 'same session'); // While paused, a phone listened further: Play resumes from there. p.isPlaying = false; p.resume(); await flush(); answer(env.calls[2], {register_session_id: 'phone-g7', register_generation: 7, position_ms: 1500000}); await flush(); const start = env.calls[3]; assert.deepEqual([start.body.start, start.body.position_ms], [true, undefined]); assert.notEqual(start.body.session_id, sessionId); answer(start, {generation: 8, position_ms: 1500000}); await flush(); assert.equal(env.audio.currentTime, 1500); assert.equal(p._episode.generation, 8); assert.equal(env.audio.played.length, 3); }); test('a player that keeps listening after a supersede writes again as a new session', async () => { const env = episodePlayer([episode(), song(2)], 0); const p = env.player; p.playQueueIndex(0); const first = env.calls[0].body.session_id; answer(env.calls[0], {generation: 3}); await flush(); env.audio.duration = 1800; env.audio.fire('loadedmetadata'); p.isPlaying = true; env.audio.currentTime = 640; p._listenedSeconds = 40; p._episode.lastWriteAt -= 20000; p._episodeTick(); await flush(); // An offline device's older listening synced in with a higher generation. env.calls[1].respond({outcome: 'superseded', generation: 6, status: 'in_progress', position_ms: 200000}); await flush(); assert.equal(env.calls.length, 2, 'one interval first (a handoff may be on its way)'); env.audio.currentTime = 660; p._listenedSeconds = 60; p._episode.lastWriteAt -= 20000; p._episodeTick(); await flush(); // The old session's listening is recorded, then an explicit start here. const record = env.calls[2]; assert.deepEqual([record.body.event, record.body.session_id, record.body.listened_ms], ['stop', first, 60000]); record.respond({outcome: 'superseded', generation: 6, status: 'in_progress', position_ms: 200000, session_recorded: true}); await flush(); const takeover = env.calls[3]; assert.deepEqual( [takeover.url, takeover.body.start, takeover.body.position_ms], ['/api/podcasts/episodes/ep1:x/playback', true, 660000], ); assert.notEqual(takeover.body.session_id, first); answer(takeover, {generation: 7}); await flush(); assert.equal(p._episode.sessionId, takeover.body.session_id); assert.equal(p._episode.superseded, false); // Later checkpoints use the new session. env.audio.currentTime = 700; p._listenedSeconds = 40; p._episode.lastWriteAt -= 20000; p._episodeTick(); await flush(); assert.deepEqual( [env.calls[4].body.event, env.calls[4].body.session_id, env.calls[4].body.generation], ['checkpoint', takeover.body.session_id, 7], ); env.calls[4].respond({outcome: 'written', generation: 7, status: 'in_progress', position_ms: 700000}); await flush(); // Superseded again, and the stream ends here: the end still completes. env.audio.ended = true; env.audio.currentTime = 1800; p._listenedSeconds = 1100; p._reportEpisode('ended'); await flush(); const ended = env.calls[5]; assert.equal(ended.body.event, 'ended'); ended.respond({outcome: 'superseded', generation: 9, status: 'in_progress', position_ms: 100000, session_recorded: true}); await flush(); const again = env.calls[6]; assert.deepEqual([again.body.start, again.body.position_ms], [true, 1800000]); answer(again, {generation: 10, position_ms: 1800000}); await flush(); const complete = env.calls[7]; assert.deepEqual( [complete.body.event, complete.body.session_id, complete.body.generation, complete.body.started_at_ms], ['ended', again.body.session_id, 10, undefined], 'completes without a second listening session', ); complete.respond({outcome: 'written', generation: 10, status: 'completed', position_ms: 1800000, completed: true}); await flush(); assert.equal(p._episode.completed, true); }); test('marking the playing episode played or unplayed stops its session', async () => { const env = episodePlayer([episode()], 0); const p = env.player; p.playQueueIndex(0); answer(env.calls[0], {generation: 3}); await flush(); env.audio.fire('loadedmetadata'); p.isPlaying = true; env.audio.currentTime = 700; p._listenedSeconds = 100; const devices = {isControllingRemoteJam: () => false}; const {store, calls} = podcastsStore({player: p, devices, queue: env.queue}); store.loadDetail = () => {}; const marking = store.markUnplayed({episode_id: 'ep1:x'}); await flush(); // The listening so far is saved first, then the mark is written. const stop = env.calls[1]; assert.deepEqual([stop.body.event, stop.body.position_ms], ['stop', 700000]); assert.equal(calls.length, 0); stop.respond({outcome: 'written', generation: 3, status: 'in_progress', position_ms: 700000}); await marking; assert.equal(calls[0].url, '/api/podcasts/episodes/ep1:x/unplayed'); assert.equal(env.audio.paused, true); assert.equal(p._episode.sessionId, null); assert.equal(env.audio.currentTime, 0, 'where the register now is'); // Nothing from the old session overrides the mark. p._episode.lastWriteAt -= 20000; p._episodeTick(); p._onEpisodePaused(); await flush(); assert.equal(env.calls.length, 2); // Play starts a new session from the register. p.isPlaying = false; p.resume(); await flush(); assert.deepEqual([env.calls[2].body.start, env.calls[2].body.position_ms], [true, undefined]); }); test('Prev on an episode goes back a little instead of resetting its progress', async () => { const env = episodePlayer([song(1), episode()], 1); const p = env.player; p.playQueueIndex(1); answer(env.calls[0], {generation: 3}); await flush(); env.audio.fire('loadedmetadata'); p.isPlaying = true; env.audio.currentTime = 1500; p.currentTime = 1500; p.prev(); env.runTimers(); await flush(); assert.equal(env.audio.currentTime, 1485); assert.equal(env.calls.length, 1, 'no explicit write'); p._listenedSeconds = 20; p._episode.lastWriteAt -= 20000; p._episodeTick(); await flush(); assert.deepEqual( [env.calls[1].body.event, env.calls[1].body.position_ms, env.calls[1].body.generation], ['checkpoint', 1485000, 3], ); env.calls[1].respond({outcome: 'written', generation: 3, status: 'in_progress', position_ms: 1485000}); await flush(); // Within the first seconds Prev goes to the previous item. env.audio.currentTime = 2; p.currentTime = 2; p.prev(); await flush(); assert.equal(p.currentTrack.title, 'Song 1'); assert.equal(env.calls[2].body.event, 'stop'); }); test('a seek while the episode is being prepared is not lost', async () => { // "Start over" on the current episode before its source arrived. const env = episodePlayer([episode()], 0); const p = env.player; p.playQueueIndex(0); p.seek(0); answer(env.calls[0], {generation: 3, position_ms: 600000}); await flush(); const seek = env.calls[1]; assert.deepEqual([seek.body.event, seek.body.position_ms, seek.body.generation], ['seek', 0, 3]); env.audio.fire('loadedmetadata'); assert.equal(env.audio.currentTime, 0, 'not the old resume position'); env.runTimers(); await flush(); assert.equal(env.calls.length, 2, 'written once'); // Paused preparation: the next Play starts where the user moved it. const paused = episodePlayer([episode()], 0); paused.player._playLocal(episode(), {paused: true}); paused.player.seek(100); answer(paused.calls[0], {position_ms: 600000}); await flush(); paused.audio.fire('loadedmetadata'); assert.equal(paused.audio.currentTime, 100); paused.runTimers(); paused.player.resume(); await flush(); assert.deepEqual([paused.calls[1].body.start, paused.calls[1].body.position_ms], [true, 100000]); }); test('a mirrored Jam state never plays or saves an episode', async () => { const env = episodePlayer([song(1)], 0); env.player._syncLocalPlaybackState({tracks: [song(1), episode()], index: 1, track: episode(), position_seconds: 900, paused: false}); await flush(); assert.equal(env.calls.length, 0); assert.deepEqual(env.audio.played, []); assert.equal(env.player._devicePlaybackStatePayload().position_seconds, 900); }); // --------------------------------------------------------------------------- // Podcasts store // --------------------------------------------------------------------------- function podcastsStore(stores = {}, overrides = {}) { const start = template.indexOf(" Alpine.store('podcasts', {"); assert.ok(start >= 0); const open = template.indexOf('{', start); const end = template.indexOf('\n });\n', start); const calls = []; const context = vm.createContext({ T: { podcastSavedAt: 'Saved at', podcastLeft: 'left', podcastSeason: 'Season', podcastNoSeason: 'No season', podcastEpisodes: 'episodes', podcastUnplayed: 'unplayed', podcastSeasons: 'seasons', podcastFetchError: 'Last check failed', podcastLastChecked: 'Checked', podcastNeverChecked: 'Not checked yet', podcastJamBlocked: 'jam blocked', podcastRequestFailed: 'request failed', }, URLSearchParams, URL, AbortController, GUEST: false, fetch: async (url, init = {}) => { calls.push({url, init}); if (overrides.respond) return overrides.respond(url, init); return {ok: true, json: async () => ({})}; }, Alpine: {store: name => stores[name]}, }); Object.assign(context.T, overrides.T || {}); vm.runInContext('this.store = ' + template.slice(open, end + 6) + ';', context); return {store: context.store, calls}; } test('the podcasts store formats episodes and builds list queries', () => { const {store} = podcastsStore(); assert.equal(store.formatDuration(3723000), '1:02:03'); assert.equal(store.formatDuration(65000), '1:05'); assert.equal(store.formatDuration(0), ''); const inProgress = {status: 'in_progress', position_ms: 600000, duration_ms: 1800000}; assert.ok(Math.abs(store.progressPercent(inProgress) - 100 / 3) < 1e-9); assert.equal(store.progressLabel(inProgress), 'Saved at 10:00 · 20:00 left'); assert.equal(store.progressPercent({status: 'completed'}), 100); assert.equal(store.progressLabel({status: 'not_started'}), ''); assert.equal(store.seasonLabel({season: 2}), 'Season 2'); assert.equal(store.seasonLabel({season: null}), 'No season'); assert.equal(store.seasonValue({season: null}), 'none'); assert.equal(store.episodeMeta({season: 1, episode_number: 3, duration_ms: 120000}), 'S1 · E3 · 2:00'); assert.equal(store.fetchStatus({fetch: {last_error: 'HTTP 500'}}), 'Last check failed: HTTP 500'); assert.equal(store.fetchStatus({fetch: {}}), 'Not checked yet'); assert.equal( store.podcastCounts({episode_count: 12, unplayed_count: 3, season_count: 2}), '12 episodes · 3 unplayed · 2 seasons', ); store.season = 'none'; store.played = 'in_progress'; store.query = ' interview '; store.sort = 'oldest'; assert.equal(store._episodeQuery(50), 'season=none&played=in_progress&q=interview&sort=oldest&limit=50&offset=50'); store.season = 'all'; store.played = 'all'; store.query = ''; store.sort = 'newest'; assert.equal(store._episodeQuery(0), 'limit=50&offset=0'); }); test('sharing a feed URL that looks private asks first and sends back exactly the shown URLs', async () => { const secret = 'https://members.example/feed.xml?token=8f3a9c2e7d1b4a6f'; const warnings = [{reason: 'secret_query_parameter', name: 'token'}]; const privateShare = { shared: false, pending_confirmation: false, can_share: true, card_error: null, warnings, feed_url: secret, id_feed_url: null, discovery: 'running', published: false, }; const answers = []; const {store, calls} = podcastsStore({}, { T: { podcastSharePrivate: 'private', podcastSharePublished: 'published', podcastSharePublishing: 'publishing', podcastShareDiscoveryOff: 'discovery off', podcastSharePending: 'pending', podcastShareUnavailable: 'unavailable', podcastShareDiscoveryUnavailable: 'discovery unavailable', podcastShareOverLimit: 'over limit', podcastShareFailed: 'publication failed', podcastWarningSecretQuery: 'parameter «{name}»', podcastWarningPrivateHost: 'host {host}', podcastWarningEntropyQuery: 'value «{name}»', podcastWarningEntropyPath: 'path', podcastWarningOther: 'other', }, respond: async () => answers.shift(), }); store.current = {podcast_id: 'pod1:x', title: 'Members Only', subscribed: true}; store.share = privateShare; store.loadList = () => {}; assert.equal(store.shareStatus(), 'private'); assert.equal(store.warningText(warnings[0]), 'parameter «token»'); assert.equal(store.warningText({reason: 'private_feed_host', host: 'patreon.com'}), 'host patreon.com'); assert.equal(store.warningText({reason: 'something_new'}), 'other'); // The toggle opens the dialog instead of sharing. store.toggleShare(); assert.equal(calls.length, 0); assert.deepEqual(JSON.parse(JSON.stringify(store.shareDialog)), { podcastId: 'pod1:x', title: 'Members Only', warnings, feed_url: secret, id_feed_url: null, }); store.cancelShare(); assert.equal(store.shareDialog, null); assert.equal(calls.length, 0); // The feed moved meanwhile: the server asks about the new URL. const moved = Object.assign({}, privateShare, {feed_url: secret + '&v=2', id_feed_url: secret}); answers.push({ok: false, status: 409, json: async () => ({error: 'confirm', needs_confirmation: true, share: moved})}); store.toggleShare(); await store.confirmShare(); assert.equal(calls.length, 1); assert.equal(calls[0].url, '/api/podcasts/feeds/pod1:x/share'); assert.equal(calls[0].init.headers['Content-Type'], 'application/json'); assert.deepEqual(JSON.parse(calls[0].init.body), {shared: true, confirm: {feed_url: secret, id_feed_url: null}}); assert.equal(store.shareDialog.feed_url, secret + '&v=2'); assert.equal(store.shareDialog.id_feed_url, secret); assert.equal(store.shareError, ''); const published = Object.assign({}, moved, {shared: true, published: true}); answers.push({ok: true, status: 200, json: async () => ({podcast: {podcast_id: 'pod1:x', title: 'Members Only', subscribed: true, shared: true}, share: published})}); await store.confirmShare(); assert.deepEqual(JSON.parse(calls[1].init.body), { shared: true, confirm: {feed_url: secret + '&v=2', id_feed_url: secret}, }); assert.equal(store.shareDialog, null); assert.equal(store.shareStatus(), 'published'); assert.equal(store.sharing, false); // Turning it off needs no confirmation. answers.push({ok: true, status: 200, json: async () => ({podcast: store.current, share: privateShare})}); await store.toggleShare(); assert.deepEqual(JSON.parse(calls[2].init.body), {shared: false}); assert.equal(store.shareStatus(), 'private'); // States of the status line. store.share = Object.assign({}, privateShare, {shared: true, pending_confirmation: true}); assert.equal(store.shareStatus(), 'pending'); store.share = Object.assign({}, privateShare, {shared: true, discovery: 'off'}); assert.equal(store.shareStatus(), 'discovery off'); store.share = Object.assign({}, privateShare, {shared: true, discovery: 'unavailable'}); assert.equal(store.shareStatus(), 'discovery unavailable'); store.share = Object.assign({}, privateShare, {shared: true}); assert.equal(store.shareStatus(), 'publishing'); store.share = Object.assign({}, privateShare, {shared: true, held: 'over_limit'}); assert.equal(store.shareStatus(), 'over limit'); store.share = Object.assign({}, privateShare, {shared: true, held: 'failed'}); assert.equal(store.shareStatus(), 'publication failed'); store.share = Object.assign({}, privateShare, {shared: true, published: true, held: null}); assert.equal(store.shareStatus(), 'published'); // A public feed is shared directly; a failure is shown. store.share = Object.assign({}, privateShare, {warnings: []}); answers.push({ok: false, status: 409, json: async () => ({error: 'not subscribed'})}); await store.toggleShare(); assert.deepEqual(JSON.parse(calls[3].init.body), {shared: true}); assert.equal(store.shareError, 'not subscribed'); assert.equal(store.shareDialog, null); }); test('playing an episode from the list puts it next in the queue', () => { const played = []; const queue = { tracks: [song(1), song(2)], effectiveCurrentIndex: () => 0, _tracksForQueueAdd: tracks => tracks.map(track => ({...track})), playFromIndex(index) { played.push(index); }, }; const player = {currentTrack: song(1), isPlaying: true, _episodeRef: () => null}; const devices = {isControllingRemoteJam: () => false}; const {store} = podcastsStore({queue, player, devices}); const item = {episode_id: 'ep1:x', track: episode()}; store.play(item); assert.deepEqual(queue.tracks.map(track => track.title), ['Song 1', 'Episode 42', 'Song 2']); assert.deepEqual(played, [1]); // A Jam guest cannot add the host's private items, nor their own. devices.isControllingRemoteJam = () => true; store.play(item); store.addToQueue(item); assert.equal(queue.tracks.length, 3); assert.equal(store.actionError, 'jam blocked'); }); test('a handoff that does not go through still records the listening when the role is lost later', async () => { const env = episodePlayer([episode()], 0); const p = env.player; const devices = devicesStore(env); p.playQueueIndex(0); answer(env.calls[0], {generation: 3}); await flush(); env.audio.fire('loadedmetadata'); p.isPlaying = true; env.audio.currentTime = 700; p._listenedSeconds = 100; // The user picks a device that needs an update for podcast episodes. const selecting = devices.select('tui-b'); await flush(); const handoff = env.calls[1]; assert.equal(handoff.body.event, 'handoff'); handoff.respond({outcome: 'written', generation: 3, status: 'in_progress', position_ms: 700000, session_recorded: true}); await flush(); const transfer = env.calls[2]; assert.equal(transfer.url, '/api/player/devices/active'); transfer.respond({error: 'the device needs an update'}, 409); await selecting; assert.equal(devices.selectError, 'the device needs an update'); assert.equal(devices.isActive(), true, 'this tab keeps playing'); // Ten more minutes here, then another device pulls playback. env.audio.currentTime = 1300; p._listenedSeconds = 700; env.local = false; p._endEpisode('stop', {final: true}); await flush(); assert.equal(env.calls.length, 4, 'a final report after the failed handoff'); const stop = env.calls[3]; assert.deepEqual( [stop.body.event, stop.body.generation, stop.body.position_ms, stop.body.listened_ms], ['stop', 3, 1300000, 700000], ); // A network error during the transfer is the same. const lost = episodePlayer([episode()], 0); const lostDevices = devicesStore(lost); lost.player.playQueueIndex(0); answer(lost.calls[0], {generation: 3}); await flush(); lost.audio.fire('loadedmetadata'); lost.player.isPlaying = true; lost.player._listenedSeconds = 30; const failing = lostDevices.select('tui-b'); await flush(); lost.calls[1].respond({outcome: 'written', generation: 3, status: 'in_progress', position_ms: 600000}); await flush(); lost.calls[2].fail(new Error('offline')); await failing; lost.player._listenedSeconds = 90; lost.local = false; lost.player._endEpisode('stop', {final: true}); await flush(); assert.deepEqual(lost.calls.slice(1).map(call => call.body?.event ?? call.url), ['handoff', '/api/player/devices/active', 'stop']); // A transfer that goes through: the new device writes, this one is quiet. const moved = episodePlayer([episode()], 0); const movedDevices = devicesStore(moved); moved.player.playQueueIndex(0); answer(moved.calls[0], {generation: 3}); await flush(); moved.audio.fire('loadedmetadata'); moved.player.isPlaying = true; moved.player._listenedSeconds = 30; const moving = movedDevices.select('tui-b'); await flush(); moved.calls[1].respond({outcome: 'written', generation: 3, status: 'in_progress', position_ms: 600000}); await flush(); moved.calls[2].respond({active_device_id: 'tui-b', playback_state: null}); await moving; assert.equal(movedDevices.isActive(), false); moved.local = false; moved.player._endEpisode('stop', {final: true}); await flush(); assert.deepEqual(moved.calls.slice(1).map(call => call.body?.event ?? call.url), ['handoff', '/api/player/devices/active']); }); test('Play after a failed source waits for the final report and resumes where the audio stopped', async () => { const env = episodePlayer([episode()], 0); const p = env.player; p.playQueueIndex(0); answer(env.calls[0], {generation: 3}); await flush(); env.audio.fire('loadedmetadata'); p.isPlaying = true; env.audio.currentTime = 640; p._listenedSeconds = 40; p._episode.lastWriteAt -= 20000; p._episodeTick(); await flush(); env.calls[1].respond({outcome: 'written', generation: 3, status: 'in_progress', position_ms: 640000}); await flush(); // 15 s later the publisher drops the stream; the user presses Play. // (timeupdate keeps the shown position in step with the audio.) env.audio.currentTime = 655; p.currentTime = 655; p._listenedSeconds = 55; p._onEpisodeAudioError(); assert.equal(p.episodeNotice, 'source failed'); p.resume(); await flush(); const stop = env.calls[2]; assert.deepEqual([stop.body.event, stop.body.generation, stop.body.position_ms], ['stop', 3, 655000]); assert.equal(env.calls.length, 3, 'the new session waits for the final report'); stop.respond({outcome: 'written', generation: 3, status: 'in_progress', position_ms: 655000, session_recorded: true}); await flush(); const prepare = env.calls[3]; assert.equal(prepare.url, '/api/podcasts/episodes/ep1:x/playback'); assert.equal(prepare.body.start, true); assert.equal(prepare.body.position_ms, undefined, 'from the register, which now has 655 s'); answer(prepare, {position_ms: 655000, generation: 4}); await flush(); env.audio.fire('loadedmetadata'); assert.equal(env.audio.currentTime, 655); // A final report that never answers holds the new session back only briefly. const slow = episodePlayer([episode()], 0); slow.player.playQueueIndex(0); answer(slow.calls[0], {generation: 3}); await flush(); slow.audio.fire('loadedmetadata'); slow.player.isPlaying = true; slow.audio.currentTime = 700; slow.player._listenedSeconds = 100; slow.player._onEpisodeAudioError(); slow.player.resume(); await flush(); assert.equal(slow.calls.length, 2); slow.runTimers(); await flush(); assert.equal(slow.calls.length, 3); assert.equal(slow.calls[2].url, '/api/podcasts/episodes/ep1:x/playback'); // Choosing another item meanwhile: the old episode is never prepared. const other = episodePlayer([episode(), song(2)], 0); other.player.playQueueIndex(0); answer(other.calls[0], {generation: 3}); await flush(); other.audio.fire('loadedmetadata'); other.player.isPlaying = true; other.audio.currentTime = 700; other.player._onEpisodeAudioError(); other.player.resume(); other.player.playQueueIndex(1); await flush(); other.calls[1].respond({outcome: 'written', generation: 3, status: 'in_progress', position_ms: 700000}); await flush(); assert.deepEqual(other.calls.map(call => call.url.split('/').pop()), ['playback', 'progress']); }); // --------------------------------------------------------------------------- // Public podcasts in the federated search // --------------------------------------------------------------------------- const POD_A = 'pod1:' + 'a'.repeat(52); const POD_B = 'pod1:' + 'b'.repeat(52); const POD_LOCAL = 'pod1:' + 'c'.repeat(52); function foundEntity(extra = {}) { return Object.assign({ type: 'podcast', kind: 'podcast', podcast_id: POD_A, feed_url: 'https://feeds.example/show.xml?utm=x', title: 'Night Radio', author: 'Host', description: '', image_url: 'https://cdn.example/art.jpg', link: 'https://show.example/', language: 'en', categories: ['Technology', 7], episode_count: 12, latest_episode_at_ms: 1700000000000, publisher_count: 2, rank: 1, exact_match: true, subscribed: false, local_podcast_id: null, }, extra); } const FOUND_T = { podcastFoundLatest: 'Latest', podcastFoundMore: 'and {count} more', podcastFoundDone: 'subscribed, private', podcastAlready: 'already', podcastFoundSubscribing: 'subscribing', podcastSubscribe: 'Subscribe', }; test('podcast cards from the search keep only typed fields and safe URLs', () => { const {store} = podcastsStore({}, {T: FOUND_T}); const hit = store.foundHit(foundEntity()); // The feed URL is passed on exactly as found (the server hashes it). assert.equal(hit.feed_url, 'https://feeds.example/show.xml?utm=x'); assert.equal(hit.description, '', 'text stays text (x-text)'); assert.deepEqual(Array.from(hit.categories), ['Technology']); assert.equal(hit.image_url, 'https://cdn.example/art.jpg'); assert.equal(store.foundMeta(hit).startsWith('12 episodes · Latest: '), true); assert.equal(store.foundSubtitle(hit), 'Host · 12 episodes'); const unsafe = store.foundHit(foundEntity({ link: 'javascript:alert(1)', image_url: 'http://cdn.example/art.jpg', local_podcast_id: 'javascript:x', rank: 'first', subscribed: 'yes', })); assert.equal(unsafe.link, ''); assert.equal(unsafe.image_url, '', 'artwork only over https'); assert.equal(unsafe.local_podcast_id, null); assert.equal(unsafe.rank, Number.MAX_SAFE_INTEGER); assert.equal(unsafe.subscribed, false); assert.equal(store.foundHit(foundEntity({link: 'https://user:pw@show.example/'})).link, ''); for (const bad of [ foundEntity({type: 'music'}), foundEntity({podcast_id: 'pod1:x'}), foundEntity({feed_url: 'javascript:alert(1)'}), foundEntity({feed_url: 'ftp://feeds.example/show.xml'}), foundEntity({title: ' '}), null, 'podcast', ]) { assert.equal(store.foundHit(bad), null, JSON.stringify(bad)); } }); test('the federated search shows podcast cards next to music, ordered by rank', () => { const podcasts = podcastsStore({}, {T: FOUND_T}).store; const sources = []; class FakeEventSource { constructor(url) { this.url = url; this.listeners = {}; sources.push(this); } addEventListener(name, listener) { this.listeners[name] = listener; } emit(name, data) { this.listeners[name]({data: JSON.stringify(data)}); } close() { this.closed = true; } } const context = vm.createContext({ EventSource: FakeEventSource, encodeURIComponent, window: {setTimeout: () => 1, clearTimeout: () => {}}, Alpine: {store: name => (name === 'podcasts' ? podcasts : null)}, }); vm.runInContext(`this.library = { federationSearch: null, _federationSearchSource: null, federationSearchScore() { return 0; }, withTrackAvailability(track) { return track; }, withFederationArtistFallback(artist) { return artist; }, hydrateFederationSearchRelease(release) { return release; }, ${method('stopFederationSearch')} ${method('startFederationSearch')} ${method('markFoundPodcastSubscribed')} };`, context); const library = context.library; library.startFederationSearch('night radio'); const source = sources[0]; assert.equal(source.url, '/api/player/federation/search/events?q=night%20radio'); assert.deepEqual(Array.from(library.federationSearch.podcasts), []); // Music events are handled as before. source.emit('federation.track', {type: 'music', kind: 'federation.track', entity: {key: {content_id: 'b3:1'}, metadata: {title: 'Theme'}}}); source.emit('federation.podcast', {type: 'podcast', kind: 'federation.podcast', entity: foundEntity({podcast_id: POD_B, title: 'Night Radio Talks', rank: 3})}); source.emit('federation.podcast', {type: 'podcast', kind: 'federation.podcast', entity: foundEntity({rank: 1, subscribed: true, local_podcast_id: POD_LOCAL})}); // Not a podcast card: ignored. source.emit('federation.podcast', {entity: {type: 'music', podcast_id: POD_A}}); // The same podcast again replaces its card. source.emit('federation.podcast', {entity: foundEntity({podcast_id: POD_B, title: 'Night Radio Talks', rank: 3, author: 'New host'})}); assert.equal(library.federationSearch.tracks.length, 1); const ids = Array.from(library.federationSearch.podcasts, hit => hit.podcast_id); assert.deepEqual(ids, [POD_A, POD_B]); assert.equal(library.federationSearch.podcasts[0].subscribed, true); assert.equal(library.federationSearch.podcasts[1].author, 'New host'); library.markFoundPodcastSubscribed(POD_B, POD_B); assert.equal(library.federationSearch.podcasts[1].subscribed, true); assert.equal(library.federationSearch.podcasts[1].local_podcast_id, POD_B); source.emit('search.completed', {entity: {partial: false, podcast_discovery: 'running'}}); assert.equal(library.federationSearch.loading, false); assert.equal(library.federationSearch.podcastDiscovery, 'running'); assert.equal(source.closed, true); // Events of a closed search change nothing. library.startFederationSearch('other'); source.emit('federation.podcast', {entity: foundEntity()}); assert.deepEqual(Array.from(library.federationSearch.podcasts), []); assert.equal(library.federationSearch.podcastDiscovery, ''); // A failed podcast search is reported, not shown as "nothing found"; // the music results stay. const failing = sources[1]; failing.emit('federation.track', {type: 'music', kind: 'federation.track', entity: {key: {content_id: 'b3:2'}, metadata: {title: 'Other'}}}); failing.emit('search.completed', {entity: {partial: false, podcast_discovery: 'failed'}}); assert.equal(library.federationSearch.podcastDiscovery, 'failed'); assert.equal(library.federationSearch.tracks.length, 1); assert.equal(library.federationSearch.error, ''); // Unknown states and malformed data are ignored. library.startFederationSearch('third'); sources[2].emit('search.completed', {entity: {podcast_discovery: 'x'}}); assert.equal(library.federationSearch.podcastDiscovery, ''); library.startFederationSearch('fourth'); sources[3].listeners['search.completed']({data: 'not json'}); assert.equal(library.federationSearch.loading, false); assert.equal(library.federationSearch.podcastDiscovery, ''); }); test('a found podcast is previewed, then subscribed with the card id and origin URL', async () => { const answers = []; const marked = []; const library = {markFoundPodcastSubscribed: (id, local) => marked.push([id, local])}; const {store, calls} = podcastsStore({library}, {T: FOUND_T, respond: async () => answers.shift()}); let listLoads = 0; store.loadList = () => { listLoads += 1; }; const opened = []; store.open = id => opened.push(id); const hit = store.foundHit(foundEntity()); answers.push({ok: true, status: 200, json: async () => ({ podcast_id: POD_A, feed_url: hit.feed_url, moved: false, title: 'Night Radio', link: 'javascript:alert(1)', image_url: 'https://cdn.example/feed.jpg', episode_count: 60, seasons: [{season: 1, episode_count: 59}, {season: null, episode_count: 1}], episodes: [{title: 'Newest', season: 1, episode_number: 59, duration_ms: 60000}], subscribed: false, local_podcast_id: null, })}); store.openFound(hit); assert.equal(store.found.previewLoading, true); await new Promise(resolve => setImmediate(resolve)); assert.equal(calls[0].url, '/api/podcasts/discovery/preview'); assert.equal(calls[0].init.method, 'POST'); assert.equal(calls[0].init.headers['Content-Type'], 'application/json'); assert.deepEqual(JSON.parse(calls[0].init.body), {podcast_id: POD_A, feed_url: 'https://feeds.example/show.xml?utm=x'}); assert.equal(store.found.previewLoading, false); assert.equal(store.found.preview.link, '', 'feed links are checked too'); assert.equal(store.found.preview.episodes[0].title, 'Newest'); assert.equal(store.foundMore(store.found.preview), 'and 59 more'); assert.equal(store.foundButtonLabel(), 'Subscribe'); // Subscribing: the account already knew the feed under another id. answers.push({ok: true, status: 200, json: async () => ({podcast: {podcast_id: POD_LOCAL}, already_subscribed: false, new_episodes: 60})}); const pending = store.subscribeFound(); assert.equal(store.foundButtonLabel(), 'subscribing'); await pending; assert.equal(calls[1].url, '/api/podcasts/discovery/subscribe'); assert.deepEqual(JSON.parse(calls[1].init.body), {podcast_id: POD_A, feed_url: 'https://feeds.example/show.xml?utm=x'}); assert.deepEqual(marked, [[POD_A, POD_LOCAL]]); assert.equal(listLoads, 1); assert.equal(store.found.subscribed, true); assert.equal(store.found.message, 'subscribed, private'); // Subscribed: the button opens the account's podcast; no second request. await store.subscribeFound(); assert.equal(calls.length, 2); store.openFoundPodcast(); assert.equal(store.found, null); assert.deepEqual(opened, [POD_LOCAL]); // An already subscribed card opens directly; a failure is shown. answers.push({ok: true, status: 200, json: async () => ({podcast_id: POD_A, seasons: [], episodes: [], episode_count: 0})}); store.openFound(store.foundHit(foundEntity({subscribed: true, local_podcast_id: POD_LOCAL}))); assert.equal(store.found.subscribed, true); await new Promise(resolve => setImmediate(resolve)); store.found.subscribed = false; answers.push({ok: false, status: 502, json: async () => ({error: 'the feed could not be loaded: timeout'})}); await store.subscribeFound(); assert.equal(store.found.error, 'the feed could not be loaded: timeout'); assert.equal(store.found.subscribing, false); // Closing during the preview drops its late answer. let release; answers.push(new Promise(resolve => { release = resolve; })); store.openFound(hit); store.closeFound(); release({ok: true, status: 200, json: async () => ({title: 'late'})}); await new Promise(resolve => setImmediate(resolve)); assert.equal(store.found, null); }); test('the seasons of a found podcast can be browsed, and an abandoned preview is cancelled', async () => { const pending = []; const {store, calls} = podcastsStore({}, { T: Object.assign({}, FOUND_T, {podcastAllSeasons: 'All seasons'}), respond: (url, init) => new Promise((resolve, reject) => { pending.push(resolve); init.signal?.addEventListener('abort', () => reject(Object.assign(new Error('aborted'), {name: 'AbortError'}))); }), }); const tick = () => new Promise(resolve => setImmediate(resolve)); const answer = (index, preview) => pending[index]({ok: true, status: 200, json: async () => preview}); const body = index => JSON.parse(calls[index].init.body); const hit = store.foundHit(foundEntity()); const preview = (extra = {}) => Object.assign({ podcast_id: POD_A, feed_url: hit.feed_url, moved: false, title: 'Night Radio', episode_count: 4, seasons: [{season: 1, episode_count: 2}, {season: 2, episode_count: 1}, {season: null, episode_count: 1}], listed_count: 4, episodes: [{title: 'Newest', season: 2}], subscribed: false, local_podcast_id: null, }, extra); store.openFound(hit); assert.equal(store.found.season, 'all'); assert.equal(calls[0].init.signal.aborted, false); answer(0, preview()); await tick(); assert.equal(store.foundMore(store.found.preview), 'and 3 more'); // A season chip lists that season; choosing another one cancels the // request still running. store.selectFoundSeason('1'); assert.equal(store.found.season, '1'); assert.deepEqual(body(1), {podcast_id: POD_A, feed_url: hit.feed_url, season: '1'}); store.selectFoundSeason('none'); assert.equal(calls[1].init.signal.aborted, true); assert.deepEqual(body(2), {podcast_id: POD_A, feed_url: hit.feed_url, season: 'none'}); await tick(); // The cancelled request shows no error. assert.equal(store.found.previewError, ''); answer(2, preview({listed_count: 1, episodes: [{title: 'Bonus', season: null}]})); await tick(); assert.equal(store.found.previewLoading, false); assert.equal(store.found.preview.episodes[0].title, 'Bonus'); assert.equal(store.foundMore(store.found.preview), ''); // The same chip again shows every season. store.selectFoundSeason('none'); assert.equal(store.found.season, 'all'); assert.deepEqual(body(3), {podcast_id: POD_A, feed_url: hit.feed_url}); store.selectFoundSeason({season: 1}); assert.equal(calls.length, 4, 'only season values from the chips'); // Closing the card cancels its preview. store.closeFound(); assert.equal(calls[3].init.signal.aborted, true); assert.equal(store.found, null); // So does opening another card. store.openFound(hit); store.openFound(store.foundHit(foundEntity({podcast_id: POD_B}))); assert.equal(calls[4].init.signal.aborted, true); assert.equal(calls[5].init.signal.aborted, false); assert.equal(body(5).podcast_id, POD_B); answer(5, preview({podcast_id: POD_B})); await tick(); assert.equal(store.found.hit.podcast_id, POD_B); assert.equal(store.found.preview.podcast_id, POD_B); assert.equal(store.found.previewError, ''); });