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'); // Queue items received from trusted devices. Podcast episodes play through // the podcast API (tests/player_podcasts.test.cjs); Jam placeholders and // unresolved federated music never play here. const podcast = { id: -11, title: 'Episode 42', unavailable: false, stream_url: '', source: {kind: 'podcast_episode', episode_id: 'ep1:x'}, wire_track: {id: 0, title: 'Episode 42', source: {kind: 'podcast_episode', episode_id: 'ep1:x'}}, }; const privateItem = { id: -12, title: 'Private item', unavailable: true, stream_url: '', source: {kind: 'private'}, wire_track: {id: 0, title: 'Private item', source: {kind: 'private'}}, }; const remoteMusic = {id: -13, title: 'Remote', unavailable: true, stream_url: '', wire_track: {id: 4, title: 'Remote'}}; const song = id => ({id, title: `Song ${id}`, stream_url: `/api/player/stream/${id}`}); function player(queue) { // Exercise the production methods with audio and store stubs. const methods = template.slice( template.indexOf(' _queueItemSourceKind(track)'), template.indexOf(' _saveState()'), ); const audio = {paused: false, src: 'old', pause() { this.paused = true; }, removeAttribute(name) { if (name === 'src') this.src = ''; }, load() {}}; const stores = {queue: Object.assign({syncCurrentIndexToTrack() {}}, queue)}; const context = vm.createContext({ audio, T: {queuePodcastItem: 'Podcast episode', queuePrivateItem: 'Private item · hidden'}, Alpine: {store: name => stores[name]}, }); vm.runInContext('this.methods = {' + methods + '};', context); return Object.assign(context.methods, {audio, currentTrack: null, currentTime: 0, volume: 0.5, shuffle: false, repeatMode: 'off'}); } test('episodes play here, placeholders never; both stay private in a Jam', () => { const p = player({tracks: [], currentIndex: 0}); assert.equal(p._isUnplayableQueueItem(podcast), false); assert.equal(p._isPodcastEpisode(podcast), true); assert.equal(p._isUnplayableQueueItem(privateItem), true); assert.equal(p._isUnplayableQueueItem(remoteMusic), false); assert.equal(p._isUnplayableQueueItem(song(1)), false); // Jam rules treat episodes and placeholders as private. assert.equal(p._isPrivateQueueItem(podcast), true); assert.equal(p._isPrivateQueueItem(privateItem), true); assert.equal(p._isPrivateQueueItem(song(1)), false); assert.equal(p._unplayableQueueLabel(podcast), ''); assert.equal(p._unplayableQueueLabel(privateItem), 'Private item · hidden'); assert.equal(p._queueItemNote(podcast), 'Podcast episode'); assert.equal(p._queueItemNote(privateItem), 'Private item · hidden'); assert.equal(p._queueItemNote(song(1)), ''); // A browser item that only carries the verbatim wire item is recognised too. assert.equal(p._isPodcastEpisode({id: -1, wire_track: podcast.wire_track}), true); assert.equal(p._isUnplayableQueueItem({id: -1, wire_track: privateItem.wire_track}), true); }); test('skipping finds the next playable item in the direction of travel', () => { const p = player({tracks: [], currentIndex: 0}); const tracks = [song(1), privateItem, podcast, privateItem, song(2)]; assert.equal(p._playableQueueIndex(tracks, 1, 1), 2); assert.equal(p._playableQueueIndex(tracks, 3, 1), 4); assert.equal(p._playableQueueIndex(tracks, 1, -1), 0); assert.equal(p._playableQueueIndex([privateItem], 0, 1), -1); }); test('showing an unplayable item stops and unloads the previous audio', () => { const p = player({tracks: [privateItem], currentIndex: 0}); p.isPlaying = true; p._showUnplayableQueueItem(privateItem); assert.equal(p.audio.paused, true); assert.equal(p.audio.src, ''); assert.equal(p.isPlaying, false); assert.equal(p.currentTrack, privateItem); assert.equal(p._historyTrack, null); }); test('persisted queue keeps external items verbatim and in order', () => { const tracks = [song(1), podcast, remoteMusic, {id: 'pending', federation_pending: true}, song(2)]; const p = player({tracks, currentIndex: 4}); p.currentTrack = tracks[4]; p.currentTime = 12.3; const state = p._buildStatePayload(); assert.deepEqual(JSON.parse(JSON.stringify(state.queue_items)), [ {kind: 'library', track_id: 1}, {kind: 'external', track: podcast.wire_track}, {kind: 'external', track: remoteMusic.wire_track}, {kind: 'library', track_id: 2}, ]); // The pending federation entry is not persisted, as before. assert.equal(state.queue_items_position, 3); // The legacy id list is unchanged for rollback. assert.deepEqual(JSON.parse(JSON.stringify(state.queue)), [1, -11, -13, 2]); assert.equal(state.current_track_id, 2); }); test('restoring merges library tracks and external items', () => { const p = player({tracks: [], currentIndex: 0}); const restored = p._restoredQueueTracks([ {kind: 'library', track_id: 1}, {kind: 'external', track: podcast}, {kind: 'library', track_id: 99}, {kind: 'library', track_id: 2}, ], [song(2), song(1)]); assert.deepEqual(Array.from(restored.tracks, track => track.id), [1, -11, 2]); assert.equal(restored.positions[3], 2); assert.equal(restored.positions[2], undefined); }); // Production methods by name, for flows that span several of them. function method(name) { const start = template.indexOf(`\n ${name}(`); assert.ok(start >= 0, `method ${name} not found`); const end = template.indexOf('\n },\n', start); return template.slice(start + 1, end + 11); } function activePlayer(queueTracks, currentIndex, audioState = {}, options = {}) { // The browser as the active (local) playback device. const names = [ '_executeRemoteCommand', '_applyRemotePlaybackState', '_tickRemoteProgress', '_devicePlaybackStatePayload', '_remotePlaybackPayload', '_trackDuration', '_pauseLocal', '_playLocal', 'resume', 'next', 'prev', 'playQueueIndex', 'seek', '_skipUnplayableCurrentItem', '_knownPosition', '_currentItemHasLocalAudio', '_showUnplayableQueueItem', '_syncLocalPlaybackState', '_queueItemSourceKind', '_isUnplayableQueueItem', '_playableQueueIndex', '_jamParticipantCommandAllowed', '_dropJamPlaceholders', '_isPodcastEpisode', '_isPrivateQueueItem', '_episodeRef', '_endEpisode', '_reportEpisode', ]; const audio = Object.assign({ paused: true, currentTime: 0, duration: NaN, src: '', played: [], pause() { this.paused = true; }, play() { this.paused = false; this.played.push(this.src); return Promise.resolve(); }, removeAttribute(name) { if (name === 'src') this.src = ''; }, load() { this.currentTime = 0; }, addEventListener() {}, removeEventListener() {}, }, audioState); const queue = { tracks: queueTracks, currentIndex, _tracksWithJamDefaults: tracks => tracks, syncCurrentIndexToTrack(track) { const index = this.tracks.indexOf(track); if (index >= 0) this.currentIndex = index; }, // Simplified local queue edits, as the host applies remote commands. _removeLocal(index) { if (index >= 0 && index < this.tracks.length) this.tracks.splice(index, 1); }, _moveTrackLocal(from, to) { this.tracks.splice(to, 0, this.tracks.splice(from, 1)[0]); }, _clearLocal() { this.tracks = []; }, _addToEndLocal(tracks) { this.tracks.push(...tracks); }, }; const stores = {queue, devices: {heartbeat() {}}}; const context = vm.createContext({audio, Alpine: {store: name => stores[name]}}); if (options.random != null) vm.runInContext(`Math.random = () => ${options.random};`, context); vm.runInContext('this.methods = {' + names.map(method).join('\n') + '};', context); return Object.assign(context.methods, { audio, queue, currentTrack: queueTracks[currentIndex] || null, currentTime: 0, duration: 0, progress: 0, isPlaying: false, shuffle: false, repeatMode: 'off', volume: 0.5, _remoteStateBaseTime: 0, _remoteStateReceivedAt: 0, _isLocalPlaybackDevice: () => true, _shouldSendRemote: () => false, _shouldMirrorRemoteLocally: () => false, _setVolumeLocal(v) { this.volume = v; }, _updateMediaSession() {}, _saveState() {}, _recordHistory() {}, _resetPlaybackTracking() {}, _mirrorRemoteTrack() {}, }); } const episode = Object.assign({}, podcast, {duration_seconds: 1800}); // An item this player cannot play (a Jam placeholder) with a duration. const placeholder = Object.assign({}, privateItem, {duration_seconds: 1800}); test('handoff of an unplayable item keeps its position for the next handoff', () => { for (const audioTime of [95, 0]) { //