diff --git a/docs/administration.md b/docs/administration.md index cf3d333..b75ecc1 100644 --- a/docs/administration.md +++ b/docs/administration.md @@ -97,7 +97,11 @@ for unplayed, started and played episodes, and the recent listening history. is shorter. - The web player saves the position about every 20 seconds and when you pause, seek, switch items, close the page or hand playback to another - device, without interrupting the audio. + device, without interrupting the audio. Reloading the page, or pressing + Play after a pause while another player went on with the episode, + continues from the newest saved position. Previous on an episode goes + back 15 seconds instead of to the start. Marking the episode that is + playing played or unplayed pauses it. - Handing playback to another device keeps the episode, its position and whether it was paused. A later save of an older listening session never moves the position back after you seek or start over elsewhere. diff --git a/docs/development.md b/docs/development.md index 84d3670..e3f5d13 100644 --- a/docs/development.md +++ b/docs/development.md @@ -160,13 +160,24 @@ post with the session cookie. In the browser (`templates/player/scripts.html`), `_playEpisodeLocal` asks for the playback, loads the publisher URL (or the proxy: mixed content, or a failed direct load) and seeks before playing; when the source cannot seek to -the saved position it shows that instead of playing from elsewhere. Writes of -one session run in order (`_reportEpisode`), read the session generation at -send time, stop after `superseded`, and carry the position of their own -episode. A browser that stops being the active device ends its session -without a report; a handoff from it reports first. Jam guests never play or -save episodes (they only ever see placeholders). The `podcasts` store backs -the Podcasts views in `shell.html`. +the saved position it shows that instead of playing from elsewhere. Only a +handoff or the user's own seek sends a position (`explicitPosition`); an +ordinary Play, including after a reload, resumes from the register, and Play +after a pause first checks that the register is still this session's +(`register_session_id`). A seek made while the source is being prepared is +applied when it arrives. Writes of one session run in order +(`_reportEpisode`), read the session generation at send time and carry the +position of their own episode. After `superseded`, checkpoints stop; if the +user keeps listening here, the next write (one checkpoint interval later, or +at once on pause, stop or the end of the stream) records the old session and +starts a new explicit one (`_takeOverEpisode`). A browser that loses the +active role sends one final `stop` at its session generation (it records the +listening; the new device's start keeps the register), unless it handed off +itself. Marking the loaded episode played or unplayed in the same tab saves +and closes its session and pauses it. Prev on an episode goes back 15 s +locally instead of resetting it. Jam guests never play or save episodes +(they only ever see placeholders). The `podcasts` store backs the Podcasts +views in `shell.html`. Tests never reach the internet: `test_server.rs` serves on 127.0.0.1 and provides a scripted resolver. Loopback is reachable only through diff --git a/templates/player/scripts.html b/templates/player/scripts.html index e022339..34f8975 100644 --- a/templates/player/scripts.html +++ b/templates/player/scripts.html @@ -790,6 +790,7 @@ document.addEventListener('alpine:init', () => { _episodeToken: 0, _episodeSeekTimer: null, _episodeCheckpointMs: 20000, + _episodeRewindSeconds: 15, _remoteExecuting: false, _remoteStateBaseTime: 0, _remoteStateReceivedAt: 0, @@ -1187,7 +1188,11 @@ document.addEventListener('alpine:init', () => { // is nothing to restart: Prev goes to the previous item. const restartable = !this._isUnplayableQueueItem(this.currentTrack); if (restartable && this.currentTime > 3) { - this.seek(0); + // An episode goes back a little: Prev (also a headset or + // lock-screen button) must not reset its saved position; + // "Start over" does that. + if (this._isPodcastEpisode(this.currentTrack)) this._rewindEpisode(this._episodeRewindSeconds); + else this.seek(0); return; } const queue = Alpine.store('queue'); @@ -1763,7 +1768,17 @@ document.addEventListener('alpine:init', () => { sessionId: null, pendingSessionId: start ? this._newEpisodeSessionId() : null, generation: null, startedAtMs: null, startPositionSeconds: position, lastPosition: known ? position : null, + // A position that is not the register's: a handoff or the + // user's own seek. Only such a position is sent with a + // start; otherwise the server resumes from the register. + explicitPosition: known, + // A seek made while the source is still being prepared. + pendingSeek: null, superseded: false, completed: false, closed: false, + // Superseded while this player kept playing: its next write + // starts a new session (see _takeOverEpisode). + takeOverPending: false, takingOver: false, handedOff: false, + reportedListenedMs: 0, lastWriteAt: 0, writes: Promise.resolve(), }; const body = { @@ -1787,7 +1802,11 @@ document.addEventListener('alpine:init', () => { episode.startedAtMs = Date.now(); episode.lastWriteAt = Date.now(); } - const at = Math.max(0, Number(info.position_ms || 0) / 1000); + const served = Math.max(0, Number(info.position_ms || 0) / 1000); + // The user moved the position while this was prepared. + const pending = episode.pendingSeek; + episode.pendingSeek = null; + const at = pending != null ? pending : served; episode.startPositionSeconds = at; episode.lastPosition = at; if (Number(info.duration_ms) > 0 && !(this.duration > 0)) this.duration = Number(info.duration_ms) / 1000; @@ -1795,8 +1814,15 @@ document.addEventListener('alpine:init', () => { this.currentTime = at; this._remoteStateBaseTime = at; this.progress = this.duration > 0 ? (at / this.duration) * 100 : 0; - // Play was pressed while a paused episode was being prepared. - if (!info.session_id && episode.wantPlay) this._startEpisodeSession(at); + if (!info.session_id && episode.wantPlay) { + // Play was pressed while a paused episode was being prepared. + this._startEpisodeSession(episode.explicitPosition ? at : null); + } else if (info.session_id && pending != null && Math.abs(pending - served) >= 1) { + // The session started where the server said; the + // user's seek is the explicit action that follows. + clearTimeout(this._episodeSeekTimer); + this._reportEpisode('seek', { position: pending }); + } this._loadEpisodeAudio(at, episode.wantPlay); }) .catch(error => { @@ -1826,6 +1852,9 @@ document.addEventListener('alpine:init', () => { const token = episode.token; const url = this._episodeAudioUrl(episode); episode.url = url; + // Where the audio starts once loaded (_moveEpisodeAudio may + // change it before that). + episode.loadPosition = position; episode.ready = false; episode.seekBlocked = false; episode.wantPlay = !!play; @@ -1847,6 +1876,7 @@ document.addEventListener('alpine:init', () => { audio.removeEventListener('loadedmetadata', onLoaded); const now = current(); if (!now) return; + const position = Number(now.loadPosition ?? 0); if (Number.isFinite(audio.duration) && audio.duration > 0) this.duration = audio.duration; now.ready = true; this.episodeLoading = false; @@ -1905,42 +1935,128 @@ document.addEventListener('alpine:init', () => { // A new listening session (explicit action) while the episode stays // loaded: Play after a paused load, after another device took over // or after the end, and the choice to listen from the start when - // the source cannot seek. + // the source cannot seek. `positionSeconds` null: where the + // register says (an ordinary Play). Resolves with the server's + // answer (null when it failed or is stale). const episode = this._episode; - if (!episode) return Promise.resolve(); + if (!episode) return Promise.resolve(null); const token = episode.token; const sessionId = this._newEpisodeSessionId(); + const known = positionSeconds != null; const at = Math.max(0, Number(positionSeconds || 0)); episode.sessionId = null; episode.generation = null; episode.pendingSessionId = sessionId; episode.startPositionSeconds = at; + episode.takeOverPending = false; + episode.reportedListenedMs = 0; this._resetPlaybackTracking(); - return this._episodeRequest(episode.episodeId, 'playback', { + const body = { episode: episode.ref, start: true, session_id: sessionId, - position_ms: Math.round(at * 1000), carried_generation: episode.carried, - }).then(info => { + }; + if (known) body.position_ms = Math.round(at * 1000); + return this._episodeRequest(episode.episodeId, 'playback', body).then(info => { const current = this._episode; - if (!current || current.token !== token || current.pendingSessionId !== sessionId) return; + if (!current || current.token !== token || current.pendingSessionId !== sessionId) return null; current.sessionId = info.session_id; current.pendingSessionId = null; current.generation = info.generation; current.startedAtMs = Date.now(); current.lastWriteAt = Date.now(); + current.startPositionSeconds = Math.max(0, Number(info.position_ms || 0) / 1000); current.superseded = false; current.completed = false; - }).catch(() => {}); + return info; + }).catch(() => null); + }, + + _resumeFromRegister(episode) { + // Ordinary Play of an episode whose register this player no + // longer holds: a new session where the register says, the + // audio moved there, then played. + const token = episode.token; + return this._startEpisodeSession(null).then(info => { + const current = this._episode; + if (!info || !current || current.token !== token) return; + this._moveEpisodeAudio(Number(info.position_ms || 0) / 1000); + if (current.ready && current.wantPlay && !current.seekBlocked) audio.play().catch(() => {}); + }); + }, + + _continuePausedEpisode(episode) { + // Play after a pause: the session continues only while the + // register is still its own; if another device or an action + // wrote the episode meanwhile, Play resumes from the register. + const token = episode.token; + const sessionId = episode.sessionId; + return this._episodeRequest(episode.episodeId, 'playback', { episode: episode.ref, start: false }) + .then(info => { + const current = this._episode; + if (!current || current.token !== token || !current.wantPlay) return; + if (current.sessionId === sessionId && info.register_session_id === sessionId) { + if (current.ready) audio.play().catch(() => {}); + return; + } + if (current.sessionId !== sessionId) return; + current.superseded = true; + return this._resumeFromRegister(current); + }) + .catch(() => { + const current = this._episode; + if (current && current.token === token && current.wantPlay && current.ready) audio.play().catch(() => {}); + }); + }, + + _moveEpisodeAudio(seconds) { + // Moves the loaded episode without an explicit write (the + // session's next report carries the position). + const episode = this._episode; + const at = Math.max(0, Number(seconds || 0)); + if (episode) episode.lastPosition = at; + this.currentTime = at; + this._remoteStateBaseTime = at; + this._remoteStateReceivedAt = Date.now(); + this.progress = this.duration > 0 ? (at / this.duration) * 100 : 0; + this._positionUnknown = false; + if (episode && !episode.ready) episode.loadPosition = at; + if (!episode?.ready || episode.seekBlocked) return; + if (Math.abs((audio.currentTime || 0) - at) < 1) return; + if (at > 1 && !this._episodeCanSeek(at)) { + episode.seekBlocked = true; + this.episodeNotice = T.podcastCannotSeek; + audio.pause(); + this.isPlaying = false; + return; + } + audio.currentTime = at; + this._lastAudioTime = audio.currentTime || at; + }, + + _rewindEpisode(seconds) { + // Prev on an episode: back a little, never to 0. Inside a + // session this is not an explicit action; the next checkpoint + // saves it. Without one, the next Play starts there. + const episode = this._episode; + const now = this._episodePosition() ?? this.currentTime ?? 0; + const at = Math.max(0, Number(now || 0) - seconds); + if (episode?.sessionId && !episode.superseded) { + this._moveEpisodeAudio(at); + return; + } + this._seekEpisode(at); }, _resumeEpisode() { const episode = this._episode; if (!episode || episode.failed) { - // Not prepared, or the source failed: prepare it again. + // Not prepared, or the source failed: prepare it again (from + // the register unless a handoff or a seek set the position). this.episodeNotice = ''; - this._playEpisodeLocal(this.currentTrack, { position_seconds: this._knownPosition(), paused: false }); + const position = episode?.explicitPosition ? this._knownPosition() : null; + this._playEpisodeLocal(this.currentTrack, { position_seconds: position, paused: false }); return; } episode.wantPlay = true; @@ -1952,16 +2068,34 @@ document.addEventListener('alpine:init', () => { this.episodeNotice = ''; this.currentTime = audio.currentTime || 0; this._startEpisodeSession(this.currentTime); - } else if ((!episode.sessionId && !episode.pendingSessionId) || episode.superseded || episode.completed) { - // Play at the end of the stream starts the audio over. + } else if (episode.completed) { + // Listening again: from the start after the end of the stream. this._startEpisodeSession(audio.ended ? 0 : this._episodePosition()); + } else if (episode.pendingSessionId) { + // A session is being started already. + } else if (!episode.sessionId && episode.explicitPosition) { + // A handoff or the user's seek chose the position. + this._startEpisodeSession(this._episodePosition()); + } else if (!episode.sessionId || episode.superseded) { + // Ordinary Play: from the register, wherever it was written. + this._resumeFromRegister(episode); + return; + } else if (!this.isPlaying && !episode.seekPending) { + // (A pending seek is an explicit write of its own.) + this._continuePausedEpisode(episode); + return; } if (episode.ready) audio.play().catch(() => {}); }, _seekEpisode(time) { const episode = this._episode; - if (episode) episode.lastPosition = time; + if (episode) { + episode.lastPosition = time; + episode.explicitPosition = true; + // Applied when the source arrives (see _playEpisodeLocal). + if (!episode.source) episode.pendingSeek = time; + } this.currentTime = time; this._remoteStateBaseTime = time; this._remoteStateReceivedAt = Date.now(); @@ -1975,9 +2109,11 @@ document.addEventListener('alpine:init', () => { if (episode.seekBlocked) return; // An explicit action, written once the user stops dragging. clearTimeout(this._episodeSeekTimer); + episode.seekPending = true; this._episodeSeekTimer = setTimeout(() => { const current = this._episode; if (!current || current.token !== episode.token) return; + current.seekPending = false; if (current.completed && current.wantPlay) { // Listening again after the end is a new session. this._startEpisodeSession(time); @@ -2013,20 +2149,13 @@ document.addEventListener('alpine:init', () => { this._reportEpisode('pause'); }, - _reportEpisode(event, options = {}) { - const episode = this._episode; - if (!episode?.sessionId || episode.generation == null || episode.closed) return Promise.resolve(); - // Another device or an explicit action elsewhere took over: only - // a new explicit action of this player writes again. - if (episode.superseded && event !== 'seek') return Promise.resolve(); - // The audio is not where the register says (source cannot seek). - if (episode.seekBlocked) return Promise.resolve(); - // After a handoff the new device writes; this one stays quiet. - if (event !== 'handoff' && !this._isLocalPlaybackDevice()) return Promise.resolve(); + _episodeReportBody(episode, event, options = {}) { + // A progress report of `episode`'s session, or null when its + // position is unknown here. const position = options.position != null ? options.position : this._episodePosition(episode); - if (position == null) return Promise.resolve(); + if (position == null) return null; const duration = episode.ready && Number.isFinite(audio.duration) && audio.duration > 0 ? audio.duration : null; - const body = { + return { session_id: episode.sessionId, generation: episode.generation, event, @@ -2036,6 +2165,39 @@ document.addEventListener('alpine:init', () => { started_at_ms: episode.startedAtMs, start_position_ms: Math.round(Math.max(0, Number(episode.startPositionSeconds || 0)) * 1000), }; + }, + + _reportEpisode(event, options = {}) { + // `options.final`: the last report of a player that just lost + // the playback role (it records the listening; a newer explicit + // action of the new device keeps the register). + const episode = this._episode; + if (!episode?.sessionId || episode.generation == null || episode.closed) return Promise.resolve(); + // The audio is not where the register says (source cannot seek). + if (episode.seekBlocked) return Promise.resolve(); + const local = this._isLocalPlaybackDevice(); + // After a handoff the new device writes; this one stays quiet. + if (event !== 'handoff' && !options.final && !local) return Promise.resolve(); + if (episode.superseded && event !== 'seek') { + // The user kept listening here after another device or an + // action wrote the episode: the next write is an explicit + // action of this player (a new session). + if (episode.takeOverPending && local && !options.final && !options.beacon && event !== 'handoff') { + const body = this._episodeReportBody(episode, event, options); + return body ? this._takeOverEpisode(episode, body, false) : Promise.resolve(); + } + // Otherwise only closing reports are sent: the register + // refuses them, but the listening session is recorded. + if (event === 'checkpoint') return Promise.resolve(); + } + const body = this._episodeReportBody(episode, event, options); + if (!body) return Promise.resolve(); + const listenedMore = body.listened_ms - (episode.reportedListenedMs || 0) >= 1000; + episode.reportedListenedMs = Math.max(episode.reportedListenedMs || 0, body.listened_ms); + // Superseded while this player was playing it: the user keeps + // listening here (not after a handoff or the loss of the role). + const keepsListening = listenedMore && local && !options.final && event !== 'handoff' && event !== 'seek'; + if (event === 'handoff') episode.handedOff = true; episode.lastWriteAt = Date.now(); if (options.beacon && navigator.sendBeacon) { const url = `/api/podcasts/episodes/${episode.episodeId}/progress`; @@ -2050,7 +2212,18 @@ document.addEventListener('alpine:init', () => { try { const data = await this._episodeRequest(episode.episodeId, 'progress', body, { keepalive: !!options.keepalive }); if (data.outcome === 'superseded') { + const first = !episode.superseded; episode.superseded = true; + if (first && keepsListening) { + if (event === 'checkpoint') { + // Periodic: wait one interval, so a handoff + // that caused it can end this session first. + episode.takeOverPending = true; + } else { + // Pause, stop, end of stream: the user acted here. + await this._takeOverEpisode(episode, body, true); + } + } } else { episode.generation = Math.max(Number(episode.generation || 0), Number(data.generation || 0)); if (event === 'seek') episode.superseded = false; @@ -2063,14 +2236,92 @@ document.addEventListener('alpine:init', () => { return episode.writes; }, - _endEpisode(event = 'stop') { + async _takeOverEpisode(episode, report, recorded) { + // The episode's register was written elsewhere while the user + // kept listening here: write this player's position as an + // explicit action (a new session above everything seen) and + // keep reporting with it. `report`: the refused report of the + // old session; `recorded`: it was sent (pause/stop/ended record + // the listening); a checkpoint is resent as 'stop' to record it. + if (episode.takingOver) return; + episode.takingOver = true; + const sessionId = this._newEpisodeSessionId(); + try { + if (!recorded || report.event === 'checkpoint') { + const event = report.event === 'checkpoint' ? 'stop' : report.event; + await this._episodeRequest(episode.episodeId, 'progress', { ...report, event }, { keepalive: true }).catch(() => null); + } + const info = await this._episodeRequest(episode.episodeId, 'playback', { + episode: episode.ref, + start: true, + session_id: sessionId, + position_ms: report.position_ms, + carried_generation: episode.carried, + }, { keepalive: true }); + let completed = false; + if (report.event === 'ended') { + // The end of the stream completes the episode; the + // listening was recorded with the old session. + const done = await this._episodeRequest(episode.episodeId, 'progress', { + session_id: sessionId, + generation: info.generation, + event: 'ended', + position_ms: report.position_ms, + duration_ms: report.duration_ms, + }, { keepalive: true }); + completed = done?.status === 'completed'; + Alpine.store('podcasts')?.episodeProgressChanged?.(episode.episodeId, done); + } + if (this._episode === episode && !episode.closed) { + episode.sessionId = info.session_id; + episode.pendingSessionId = null; + episode.generation = info.generation; + episode.startedAtMs = Date.now(); + episode.lastWriteAt = Date.now(); + episode.startPositionSeconds = Math.max(0, Number(report.position_ms || 0) / 1000); + episode.superseded = false; + episode.takeOverPending = false; + episode.completed = completed; + episode.reportedListenedMs = 0; + this._resetPlaybackTracking(); + } + } catch { + } finally { + episode.takingOver = false; + } + }, + + async _releaseEpisodeSession(episodeId) { + // The user marks the episode loaded here played or unplayed from + // the list: the listening so far is saved, the audio stops and + // the session closes, so nothing written here overrides the + // mark; the next Play starts from the register. + const episode = this._episode; + if (!episode || episode.episodeId !== episodeId) return; + clearTimeout(this._episodeSeekTimer); + episode.seekPending = false; + episode.pendingSeek = null; + episode.wantPlay = false; + // `final`: recorded even when superseded, and never taken over. + if (episode.sessionId) await this._reportEpisode('stop', { keepalive: true, final: true }); + Object.assign(episode, { + sessionId: null, pendingSessionId: null, generation: null, + superseded: false, takeOverPending: false, completed: false, + explicitPosition: false, reportedListenedMs: 0, + }); + this._pauseLocal(); + }, + + _endEpisode(event = 'stop', options = {}) { // The current episode is replaced or playback stops here: report // the final position (kept alive past a page change) and close - // the session. + // the session. `options.final`: this player lost the playback + // role; it still records the listening unless it handed off. const episode = this._episode; if (!episode) return; clearTimeout(this._episodeSeekTimer); - if (!episode.closed) this._reportEpisode(event, { keepalive: true }); + const report = !episode.closed && !(options.final && episode.handedOff); + if (report) this._reportEpisode(event, { keepalive: true, final: !!options.final }); episode.closed = true; this._episode = null; this._episodeToken += 1; @@ -2184,12 +2435,13 @@ document.addEventListener('alpine:init', () => { queue.currentIndex = idx; const currentTrack = restored.tracks[idx]; if (this._isPodcastEpisode(currentTrack) && !this._isUnplayableQueueItem(currentTrack)) { - // Paused, at the saved position; a saved 0 means - // "resume from the progress register". + // Paused, where the progress register says: this + // page's saved position may be older than what + // other devices (or a mark) wrote since. const position = state.position_ms ? state.position_ms / 1000 : null; const prepared = this._episode?.episodeId === this._episodeRef(currentTrack)?.episode_id; if (!prepared && this._isLocalPlaybackDevice()) { - this._playEpisodeLocal(currentTrack, { position_seconds: position, paused: true }); + this._playEpisodeLocal(currentTrack, { position_seconds: null, paused: true }); } else if (!prepared) { this.currentTrack = currentTrack; this.currentTime = position || 0; @@ -2507,10 +2759,11 @@ document.addEventListener('alpine:init', () => { } if (!this.isActive() && !this.shouldPlayJamLocally()) { Alpine.store('player')?._pauseLocal(); - // Another device plays now and writes the episode's progress; - // the session here ends without a report (a handoff from - // here already sent its final position). - Alpine.store('player')?._endEpisode('stop'); + // Another device plays now and writes the episode's progress. + // A final report records the listening done here (at this + // session's generation, so the new device's start wins); + // after a handoff from here it was already sent. + Alpine.store('player')?._endEpisode('stop', { final: true }); } if (wasControllingJam && !this.isControllingRemoteJam()) { Alpine.store('player')?._dropJamPlaceholders(); @@ -3652,7 +3905,14 @@ document.addEventListener('alpine:init', () => { this.busy = { ...this.busy, [id]: true }; this.actionError = ''; try { + // The episode loaded in this player: its session must not + // write over the mark (see _releaseEpisodeSession). + const player = Alpine.store('player'); + if (action !== 'restart') await player?._releaseEpisodeSession?.(id); const updated = await this._json(`/api/podcasts/episodes/${id}/${action}`, { method: 'POST' }); + if (player?._episode?.episodeId === id && !player._episode.sessionId) { + player._moveEpisodeAudio(Number(updated?.resume_position_ms || 0) / 1000); + } this._replaceEpisode(updated); this.loadDetail(); return true; diff --git a/tests/player_podcasts.test.cjs b/tests/player_podcasts.test.cjs index 775fdf5..5a3cf2a 100644 --- a/tests/player_podcasts.test.cjs +++ b/tests/player_podcasts.test.cjs @@ -44,7 +44,9 @@ const PLAYER_METHODS = [ '_episodeRef', '_newEpisodeSessionId', '_episodeRequest', '_playEpisodeLocal', '_episodeAudioUrl', '_loadEpisodeAudio', '_episodeCanSeek', '_onEpisodeAudioError', '_startEpisodeSession', '_resumeEpisode', '_seekEpisode', '_episodePosition', '_episodeTick', '_onEpisodePaused', - '_reportEpisode', '_endEpisode', + '_reportEpisode', '_endEpisode', '_episodeReportBody', '_takeOverEpisode', '_releaseEpisodeSession', + '_resumeFromRegister', '_continuePausedEpisode', '_moveEpisodeAudio', '_rewindEpisode', 'prev', + '_restoreState', '_restoredQueueTracks', ]; function eventAudio(extra = {}) { @@ -97,7 +99,7 @@ function episodePlayer(queueTracks, currentIndex, options = {}) { 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, + 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; }}, @@ -114,7 +116,7 @@ function episodePlayer(queueTracks, currentIndex, options = {}) { _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, + _episodeSeekTimer: null, _episodeCheckpointMs: 20000, _episodeRewindSeconds: 15, _isLocalPlaybackDevice: () => env.local, _shouldSendRemote: () => false, _shouldMirrorRemoteLocally: () => false, _setVolumeLocal(v) { this.volume = v; }, _updateMediaSession() {}, _saveState() {}, @@ -200,21 +202,35 @@ test('an episode plays from its resume position and saves progress in the backgr 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. + // 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(); - 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.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[4]; - assert.deepEqual([again.body.start, again.body.position_ms], [true, 300000]); + 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.progress.map(([, data]) => data.outcome), ['written', 'written', 'superseded']); + 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 () => { @@ -442,6 +458,304 @@ test('a report always carries the position of its own episode', async () => { 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});