Play podcast episodes in the web player

Episodes in the queue are no longer skipped. The player asks the
podcast API for the audio source and the resume position, plays the
publisher URL (or the same-origin proxy when the administrator enabled
it and the direct URL fails or is http:// on an https:// page) and
seeks before it starts, so it never reports a resumed episode that
plays from elsewhere: a server that cannot seek to the saved position
shows that and keeps the position until the user plays from the start.

Progress follows the contract: Play starts a listening session as an
explicit action above the handed-off generation, checkpoints go out
every 20 s and on pause, a seek is an explicit action, the end of the
stream completes the episode, and a stop, a page hide (beacon) or a
handoff saves the final position. Writes of a session run one after
another in the background; a superseded session stops writing, and a
device that loses the playback role ends its session without a report.
Reports always carry the position of their own episode.

Jam placeholders stay unplayable and episodes stay private for Jam
rules. A podcasts store holds the list, the podcast page and the
explicit episode actions for the UI of the next commit.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
sanapachandClaude Opus 5.5 committed 2026-11-20 15:12:38 +02:00
1 parent 2c551c5b71
commit 3ebfc45abb
4 files changed
+1566 -64

No files matched your search

+57 -1
View File
@@ -382,8 +382,64 @@ translations! {
player_clear: "Clear" , "Очистить";
player_remove: "Remove" , "Удалить";
player_queue_empty: "Queue is empty" , "Очередь пуста";
player_queue_podcast_unplayable: "Podcast · not playable in the web player yet", "Подкаст · пока не воспроизводится в веб-плеере";
player_queue_podcast_item: "Podcast episode" , "Выпуск подкаста";
player_queue_private_item: "Private item · hidden by its owner", "Приватный элемент · скрыт владельцем";
player_podcasts: "Podcasts", "Подкасты";
player_podcast_add_placeholder: "RSS feed URL", "Адрес RSS-ленты";
player_podcast_add: "Add", "Добавить";
player_podcast_adding: "Loading the feed…", "Загружаем ленту…";
player_podcast_added: "Subscribed", "Подписка добавлена";
player_podcast_already: "Already subscribed", "Вы уже подписаны";
player_podcast_private_note: "New subscriptions are private: they sync only between your own devices.", "Новые подписки приватны: они синхронизируются только между вашими устройствами.";
player_podcasts_empty: "No podcasts yet. Add an RSS feed to subscribe.", "Подкастов пока нет. Добавьте RSS-ленту, чтобы подписаться.";
player_podcast_show_unsubscribed: "Show unsubscribed", "Показать без подписки";
player_podcast_unplayed: "unplayed", "не прослушано";
player_podcast_episodes: "episodes", "выпусков";
player_podcast_seasons: "seasons", "сезонов";
player_podcast_unsubscribed: "Not subscribed", "Нет подписки";
player_podcast_refresh: "Refresh", "Обновить";
player_podcast_refreshing: "Checking the feed…", "Проверяем ленту…";
player_podcast_refresh_updated: "Feed updated", "Лента обновлена";
player_podcast_refresh_not_modified: "No changes in the feed", "Изменений в ленте нет";
player_podcast_refresh_failed: "Could not refresh the feed", "Не удалось обновить ленту";
player_podcast_last_checked: "Checked", "Проверено";
player_podcast_never_checked: "Not checked yet", "Ещё не проверялась";
player_podcast_fetch_error: "Last check failed", "Последняя проверка не удалась";
player_podcast_next_check: "next check", "следующая проверка";
player_podcast_unsubscribe: "Unsubscribe", "Отписаться";
player_podcast_unsubscribe_confirm: "Unsubscribe from “{title}”? The feed will no longer be checked. Your progress and listening history are kept: subscribing again continues where you stopped.", "Отписаться от «{title}»? Лента больше не будет проверяться. Прогресс и история прослушиваний сохранятся: при повторной подписке вы продолжите с того же места.";
player_podcast_subscribe: "Subscribe", "Подписаться";
player_podcast_all_seasons: "All seasons", "Все сезоны";
player_podcast_season: "Season", "Сезон";
player_podcast_no_season: "No season", "Без сезона";
player_podcast_filter_all: "All episodes", "Все выпуски";
player_podcast_filter_unplayed: "Unplayed", "Не прослушано";
player_podcast_filter_in_progress: "In progress", "Начато";
player_podcast_filter_played: "Played", "Прослушано";
player_podcast_sort_newest: "Newest first", "Сначала новые";
player_podcast_sort_oldest: "Oldest first", "Сначала старые";
player_podcast_sort_number: "By number", "По номеру";
player_podcast_search: "Search episodes", "Поиск по выпускам";
player_podcast_no_episodes: "No episodes match.", "Подходящих выпусков нет.";
player_podcast_play: "Play", "Слушать";
player_podcast_resume: "Resume", "Продолжить";
player_podcast_restart: "Start over", "Начать сначала";
player_podcast_mark_played: "Mark played", "Прослушано";
player_podcast_mark_unplayed: "Mark unplayed", "Не прослушано";
player_podcast_add_queue: "Add to queue", "В очередь";
player_podcast_left: "left", "осталось";
player_podcast_saved_at: "Saved at", "Сохранено на";
player_podcast_played_badge: "Played", "Прослушано";
player_podcast_played_times: "Completed listens", "Полных прослушиваний";
player_podcast_not_in_feed: "No longer in the feed", "Больше нет в ленте";
player_podcast_load_more: "Load more", "Показать ещё";
player_podcast_history: "Recently listened", "Недавно прослушано";
player_podcast_jam_blocked: "Podcast episodes are private and cannot be added to a Jam.", "Выпуски подкастов приватны и не добавляются в Jam.";
player_podcast_source_failed: "Could not load this episode from the publisher.", "Не удалось загрузить выпуск у издателя.";
player_podcast_cannot_seek: "The publisher server cannot seek to the saved position. Press Play to listen from the start; until then the saved position is kept.", "Сервер издателя не умеет перематывать к сохранённой позиции. Нажмите Play, чтобы слушать с начала; до этого сохранённая позиция не меняется.";
player_podcast_loading: "Preparing the episode…", "Готовим выпуск…";
player_podcast_feed: "Feed", "Лента";
player_podcast_request_failed: "Request failed", "Запрос не выполнен";
player_shuffle: "Shuffle" , "Перемешать";
player_repeat: "Repeat" , "Повтор";
player_volume: "Volume" , "Громкость";
File diff suppressed because it is too large. Load diff
+532
View File
@@ -0,0 +1,532 @@
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',
];
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,
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.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,
_isLocalPlaybackDevice: () => env.local, _shouldSendRemote: () => false,
_shouldMirrorRemoteLocally: () => false,
_setVolumeLocal(v) { this.volume = v; }, _updateMediaSession() {}, _saveState() {},
_recordHistory() {}, _resetPlaybackTracking() { this._listenedSeconds = 0; },
_mirrorRemoteTrack() {}, _sendRemote() {},
});
return env;
}
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 took over: nothing more at the old generation.
env.calls[3].respond({outcome: 'superseded', generation: 9, status: 'in_progress', position_ms: 1000});
await flush();
p._episode.lastWriteAt -= 20000;
p._episodeTick();
p._onEpisodePaused();
await flush();
assert.equal(env.calls.length, 4);
// Play here again is a new session (explicit action) from where the audio is.
p.resume();
await flush();
const again = env.calls[4];
assert.deepEqual([again.body.start, again.body.position_ms], [true, 300000]);
assert.notEqual(again.body.session_id, prepare.body.session_id);
assert.deepEqual(env.progress.map(([, data]) => data.outcome), ['written', 'written', '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 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 = {}) {
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, GUEST: false,
fetch: async (url, init = {}) => { calls.push({url, init}); return {ok: true, json: async () => ({})}; },
Alpine: {store: name => stores[name]},
});
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('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');
});
+63 -49
View File
@@ -4,9 +4,11 @@ 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 that this player cannot play.
// 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: true, stream_url: '',
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'}},
};
@@ -26,42 +28,51 @@ function player(queue) {
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: {queuePodcastUnplayable: 'Podcast · not playable', queuePrivateItem: 'Private item · hidden'},
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('podcast and private items are labelled and never played locally', () => {
test('episodes play here, placeholders never; both stay private in a Jam', () => {
const p = player({tracks: [], currentIndex: 0});
assert.equal(p._isUnplayableQueueItem(podcast), true);
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);
assert.equal(p._unplayableQueueLabel(podcast), 'Podcast · not playable');
// 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._unplayableQueueLabel(song(1)), '');
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._isUnplayableQueueItem({id: -1, wire_track: podcast.wire_track}), true);
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), podcast, privateItem, song(2)];
assert.equal(p._playableQueueIndex(tracks, 1, 1), 3);
assert.equal(p._playableQueueIndex(tracks, 2, -1), 0);
assert.equal(p._playableQueueIndex([podcast], 0, 1), -1);
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: [podcast], currentIndex: 0});
const p = player({tracks: [privateItem], currentIndex: 0});
p.isPlaying = true;
p._showUnplayableQueueItem(podcast);
p._showUnplayableQueueItem(privateItem);
assert.equal(p.audio.paused, true);
assert.equal(p.audio.src, '');
assert.equal(p.isPlaying, false);
assert.equal(p.currentTrack, podcast);
assert.equal(p.currentTrack, privateItem);
assert.equal(p._historyTrack, null);
});
@@ -115,6 +126,7 @@ function activePlayer(queueTracks, currentIndex, audioState = {}, options = {})
'_showUnplayableQueueItem', '_syncLocalPlaybackState',
'_queueItemSourceKind', '_isUnplayableQueueItem', '_playableQueueIndex',
'_jamParticipantCommandAllowed', '_dropJamPlaceholders',
'_isPodcastEpisode', '_isPrivateQueueItem', '_episodeRef', '_endEpisode', '_reportEpisode',
];
const audio = Object.assign({
paused: true, currentTime: 0, duration: NaN, src: '',
@@ -155,16 +167,18 @@ function activePlayer(queueTracks, currentIndex, audioState = {}, options = {})
}
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 a podcast episode keeps its position for the next handoff', () => {
test('handoff of an unplayable item keeps its position for the next handoff', () => {
for (const audioTime of [95, 0]) {
// <audio> still holds a music track (95 s) or the page is fresh (0 s).
const p = activePlayer([song(1)], 0, {currentTime: audioTime, src: '/api/player/stream/1'});
p._executeRemoteCommand({command: 'transfer_state', payload: {
tracks: [song(1), episode], index: 1, track: episode,
tracks: [song(1), placeholder], index: 1, track: placeholder,
position_seconds: 1200, duration_seconds: 1800, paused: false,
}});
assert.equal(p.currentTrack, episode);
assert.equal(p.currentTrack, placeholder);
assert.equal(p.currentTime, 1200);
assert.equal(p.isPlaying, false);
assert.equal(p.audio.src, '', 'the previous track is unloaded');
@@ -184,35 +198,35 @@ test('library tracks still report the audio position', () => {
test('resume on an unplayable item skips it, also with repeat one', () => {
for (const repeatMode of ['one', 'off', 'all']) {
const p = activePlayer([podcast], 0);
const p = activePlayer([placeholder], 0);
p.repeatMode = repeatMode;
p.currentTime = 30;
p.resume();
p.next();
assert.equal(p.currentTrack, podcast);
assert.equal(p.currentTrack, placeholder);
assert.equal(p.isPlaying, false);
assert.equal(p.currentTime, 30, 'the item keeps its position');
assert.deepEqual(p.audio.played, []);
}
const p = activePlayer([song(1), podcast, song(2)], 1);
const p = activePlayer([song(1), placeholder, song(2)], 1);
p.repeatMode = 'one';
p.resume();
assert.equal(p.currentTrack.id, 2);
assert.deepEqual(p.audio.played, ['/api/player/stream/2']);
// Repeat all wraps around to the first playable item.
const wrap = activePlayer([song(1), podcast], 1);
const wrap = activePlayer([song(1), placeholder], 1);
wrap.repeatMode = 'all';
wrap.resume();
assert.equal(wrap.currentTrack.id, 1);
});
test('an episode reached without its position reports it as unknown, never as 0', () => {
// Next from the last music track lands on a trailing episode.
const p = activePlayer([song(1), episode], 0, {currentTime: 200, src: '/api/player/stream/1'});
test('an unplayable item reached without its position reports it as unknown, never as 0', () => {
// Next from the last music track lands on a trailing placeholder.
const p = activePlayer([song(1), placeholder], 0, {currentTime: 200, src: '/api/player/stream/1'});
p.isPlaying = true;
p.currentTime = 200;
p.next();
assert.equal(p.currentTrack, episode);
assert.equal(p.currentTrack, placeholder);
assert.equal(p.isPlaying, false);
let reported = p._devicePlaybackStatePayload();
assert.equal(reported.index, 1);
@@ -230,29 +244,29 @@ test('an episode reached without its position reports it as unknown, never as 0'
assert.equal(p.currentTrack.id, 1);
assert.equal(p._devicePlaybackStatePayload().position_unknown, undefined);
// Another browser or a Jam guest plays the episode row (position 0 sent).
const remote = activePlayer([song(1), episode], 0, {currentTime: 30, src: '/api/player/stream/1'});
// Another browser or a Jam guest plays the placeholder row (position 0 sent).
const remote = activePlayer([song(1), placeholder], 0, {currentTime: 30, src: '/api/player/stream/1'});
remote._executeRemoteCommand({command: 'play_from_index', payload: {
tracks: [song(1), episode], index: 1, track: episode, position_seconds: 0, paused: false,
tracks: [song(1), placeholder], index: 1, track: placeholder, position_seconds: 0, paused: false,
}});
assert.equal(remote.currentTrack, episode);
assert.equal(remote.currentTrack, placeholder);
assert.equal(remote._devicePlaybackStatePayload().position_unknown, true);
// A transfer passes on what the previous device did not know.
const relay = activePlayer([song(1)], 0);
relay._executeRemoteCommand({command: 'transfer_state', payload: {
tracks: [song(1), episode], index: 1, track: episode, position_seconds: 0,
tracks: [song(1), placeholder], index: 1, track: placeholder, position_seconds: 0,
position_unknown: true, paused: true,
}});
assert.equal(relay._devicePlaybackStatePayload().position_unknown, true);
// A mirrored state with a known position keeps it.
const mirror = activePlayer([song(1), episode], 0);
mirror._syncLocalPlaybackState({tracks: [song(1), episode], index: 1, track: episode, position_seconds: 900, paused: true});
const mirror = activePlayer([song(1), placeholder], 0);
mirror._syncLocalPlaybackState({tracks: [song(1), placeholder], index: 1, track: placeholder, position_seconds: 900, paused: true});
assert.equal(mirror._devicePlaybackStatePayload().position_seconds, 900);
assert.equal(mirror._devicePlaybackStatePayload().position_unknown, undefined);
});
test('repeat all and shuffle continue past a trailing unplayable item', () => {
const wrap = activePlayer([song(1), episode], 0, {currentTime: 200, src: '/api/player/stream/1'});
const wrap = activePlayer([song(1), placeholder], 0, {currentTime: 200, src: '/api/player/stream/1'});
wrap.repeatMode = 'all';
wrap.isPlaying = true;
wrap.next();
@@ -260,49 +274,49 @@ test('repeat all and shuffle continue past a trailing unplayable item', () => {
assert.equal(wrap.queue.currentIndex, 0);
assert.deepEqual(wrap.audio.played, ['/api/player/stream/1']);
// Shuffle picks the episode (index 1 of 3) and continues with music
// Shuffle picks the placeholder (index 1 of 3) and continues with music
// (searching towards the pick from the current item).
const shuffled = activePlayer([song(1), episode, song(2)], 2, {src: '/api/player/stream/2'}, {random: 0.5});
const shuffled = activePlayer([song(1), placeholder, song(2)], 2, {src: '/api/player/stream/2'}, {random: 0.5});
shuffled.shuffle = true;
shuffled.next();
assert.equal(shuffled.currentTrack.id, 1);
assert.equal(shuffled.isPlaying, false, 'the stub audio does not fire play events');
assert.deepEqual(shuffled.audio.played, ['/api/player/stream/1']);
// A trailing episode picked by shuffle wraps to the first playable item.
const trailing = activePlayer([song(1), song(2), episode], 1, {src: '/api/player/stream/2'}, {random: 0.9});
// A trailing placeholder picked by shuffle wraps to the first playable item.
const trailing = activePlayer([song(1), song(2), placeholder], 1, {src: '/api/player/stream/2'}, {random: 0.9});
trailing.shuffle = true;
trailing.next();
assert.equal(trailing.currentTrack.id, 1);
// Without repeat the queue ends on the episode, as before.
const stop = activePlayer([song(1), episode], 0, {src: '/api/player/stream/1'});
// Without repeat the queue ends on the placeholder, as before.
const stop = activePlayer([song(1), placeholder], 0, {src: '/api/player/stream/1'});
stop.next();
assert.equal(stop.currentTrack, episode);
assert.equal(stop.currentTrack, placeholder);
assert.equal(stop.isPlaying, false);
});
test('prev and seek work on a handed-off episode', () => {
test('prev and seek work on a handed-off unplayable item', () => {
const p = activePlayer([song(1), song(3)], 0, {currentTime: 95, src: '/api/player/stream/1'});
p._executeRemoteCommand({command: 'transfer_state', payload: {
tracks: [song(1), episode], index: 1, track: episode,
tracks: [song(1), placeholder], index: 1, track: placeholder,
position_seconds: 1200, duration_seconds: 1800, paused: false,
}});
// Seeking moves the episode's own position (nothing is loaded in <audio>).
// Seeking moves the placeholder's own position (nothing is loaded in <audio>).
p.seek(1500);
assert.equal(p.currentTime, 1500);
assert.equal(p._devicePlaybackStatePayload().position_seconds, 1500);
// Prev goes to the previous item instead of restarting the episode.
// Prev goes to the previous item instead of restarting the placeholder.
p.prev();
assert.equal(p.currentTrack.id, 1);
assert.deepEqual(p.audio.played, ['/api/player/stream/1']);
// At the start of the queue Prev leaves the episode and its position alone.
const first = activePlayer([episode, song(1)], 0);
// At the start of the queue Prev leaves the placeholder and its position alone.
const first = activePlayer([placeholder, song(1)], 0);
first._executeRemoteCommand({command: 'transfer_state', payload: {
tracks: [episode, song(1)], index: 0, track: episode, position_seconds: 1200, paused: true,
tracks: [placeholder, song(1)], index: 0, track: placeholder, position_seconds: 1200, paused: true,
}});
first.prev();
assert.equal(first.currentTrack, episode);
assert.equal(first.currentTrack, placeholder);
assert.equal(first.currentTime, 1200);
});