diff --git a/templates/player/scripts.html b/templates/player/scripts.html
index 34f8975..a2b9485 100644
--- a/templates/player/scripts.html
+++ b/templates/player/scripts.html
@@ -3048,11 +3048,16 @@ document.addEventListener('alpine:init', () => {
async select(deviceId) {
if (!deviceId) return;
const player = Alpine.store('player');
+ // The episode reported as handed off, until the transfer succeeds.
+ let handedOff = null;
try {
// Handing an episode to another device: save its position at
// this session's generation first; the new device continues.
- if (deviceId !== this.id && this.isActive()) await player?._reportEpisode('handoff');
+ if (deviceId !== this.id && this.isActive()) {
+ handedOff = player?._episode || null;
+ await player?._reportEpisode('handoff');
+ }
this.clearJamSelection();
const res = await fetch('/api/player/devices/active', {
method: 'POST',
@@ -3067,6 +3072,7 @@ document.addEventListener('alpine:init', () => {
this.selectError = res.status === 409 ? await this._errorText(res) : '';
return;
}
+ handedOff = null;
this.selectError = '';
const data = await res.json();
this._apply(data);
@@ -3080,7 +3086,13 @@ document.addEventListener('alpine:init', () => {
} else if (deviceId !== this.id && player && this.id !== this.activeDeviceId) {
player._applyRemotePlaybackState(data.playback_state);
}
- } catch {}
+ } catch {
+ } finally {
+ // The transfer failed and this tab keeps playing: what it
+ // listens from here on is recorded when it stops or loses
+ // the playback role (see _endEpisode).
+ if (handedOff) handedOff.handedOff = false;
+ }
},
async sendCommand(command, payload = {}, targetDeviceId = null) {
diff --git a/tests/player_podcasts.test.cjs b/tests/player_podcasts.test.cjs
index 5a3cf2a..67cdd08 100644
--- a/tests/player_podcasts.test.cjs
+++ b/tests/player_podcasts.test.cjs
@@ -109,6 +109,8 @@ function episodePlayer(queueTracks, currentIndex, options = {}) {
Alpine: {store: name => stores[name]},
});
vm.runInContext('this.methods = {' + PLAYER_METHODS.map(method).join('\n') + '};', context);
+ env.context = context;
+ env.stores = stores;
env.queue = queue;
env.player = Object.assign(context.methods, {
currentTrack: queueTracks[currentIndex] || null, currentTime: 0, duration: 0, progress: 0,
@@ -123,9 +125,24 @@ function episodePlayer(queueTracks, currentIndex, options = {}) {
_recordHistory() {}, _resetPlaybackTracking() { this._listenedSeconds = 0; },
_mirrorRemoteTrack() {}, _sendRemote() {},
});
+ stores.player = env.player;
return env;
}
+// The devices store's select() (the device picker), on the same stubs.
+function devicesStore(env, id = 'web-a') {
+ vm.runInContext('this.devicesMethods = {' + method('select') + '};', env.context);
+ const devices = Object.assign(env.context.devicesMethods, {
+ id, activeDeviceId: id, open: true, selectError: '', applied: [],
+ isActive() { return this.activeDeviceId === this.id; },
+ clearJamSelection() {},
+ async _errorText(res) { return (await res.json()).error; },
+ _apply(data) { this.applied.push(data); this.activeDeviceId = data.active_device_id; },
+ });
+ env.stores.devices = Object.assign(env.stores.devices, devices);
+ return devices;
+}
+
const flush = async () => {
for (let i = 0; i < 20; i++) await new Promise(resolve => setImmediate(resolve));
};
@@ -844,3 +861,83 @@ test('playing an episode from the list puts it next in the queue', () => {
assert.equal(queue.tracks.length, 3);
assert.equal(store.actionError, 'jam blocked');
});
+
+test('a handoff that does not go through still records the listening when the role is lost later', async () => {
+ const env = episodePlayer([episode()], 0);
+ const p = env.player;
+ const devices = devicesStore(env);
+ p.playQueueIndex(0);
+ answer(env.calls[0], {generation: 3});
+ await flush();
+ env.audio.fire('loadedmetadata');
+ p.isPlaying = true;
+ env.audio.currentTime = 700;
+ p._listenedSeconds = 100;
+ // The user picks a device that needs an update for podcast episodes.
+ const selecting = devices.select('tui-b');
+ await flush();
+ const handoff = env.calls[1];
+ assert.equal(handoff.body.event, 'handoff');
+ handoff.respond({outcome: 'written', generation: 3, status: 'in_progress', position_ms: 700000, session_recorded: true});
+ await flush();
+ const transfer = env.calls[2];
+ assert.equal(transfer.url, '/api/player/devices/active');
+ transfer.respond({error: 'the device needs an update'}, 409);
+ await selecting;
+ assert.equal(devices.selectError, 'the device needs an update');
+ assert.equal(devices.isActive(), true, 'this tab keeps playing');
+ // Ten more minutes here, then another device pulls playback.
+ env.audio.currentTime = 1300;
+ p._listenedSeconds = 700;
+ env.local = false;
+ p._endEpisode('stop', {final: true});
+ await flush();
+ assert.equal(env.calls.length, 4, 'a final report after the failed handoff');
+ const stop = env.calls[3];
+ assert.deepEqual(
+ [stop.body.event, stop.body.generation, stop.body.position_ms, stop.body.listened_ms],
+ ['stop', 3, 1300000, 700000],
+ );
+
+ // A network error during the transfer is the same.
+ const lost = episodePlayer([episode()], 0);
+ const lostDevices = devicesStore(lost);
+ lost.player.playQueueIndex(0);
+ answer(lost.calls[0], {generation: 3});
+ await flush();
+ lost.audio.fire('loadedmetadata');
+ lost.player.isPlaying = true;
+ lost.player._listenedSeconds = 30;
+ const failing = lostDevices.select('tui-b');
+ await flush();
+ lost.calls[1].respond({outcome: 'written', generation: 3, status: 'in_progress', position_ms: 600000});
+ await flush();
+ lost.calls[2].fail(new Error('offline'));
+ await failing;
+ lost.player._listenedSeconds = 90;
+ lost.local = false;
+ lost.player._endEpisode('stop', {final: true});
+ await flush();
+ assert.deepEqual(lost.calls.slice(1).map(call => call.body?.event ?? call.url), ['handoff', '/api/player/devices/active', 'stop']);
+
+ // A transfer that goes through: the new device writes, this one is quiet.
+ const moved = episodePlayer([episode()], 0);
+ const movedDevices = devicesStore(moved);
+ moved.player.playQueueIndex(0);
+ answer(moved.calls[0], {generation: 3});
+ await flush();
+ moved.audio.fire('loadedmetadata');
+ moved.player.isPlaying = true;
+ moved.player._listenedSeconds = 30;
+ const moving = movedDevices.select('tui-b');
+ await flush();
+ moved.calls[1].respond({outcome: 'written', generation: 3, status: 'in_progress', position_ms: 600000});
+ await flush();
+ moved.calls[2].respond({active_device_id: 'tui-b', playback_state: null});
+ await moving;
+ assert.equal(movedDevices.isActive(), false);
+ moved.local = false;
+ moved.player._endEpisode('stop', {final: true});
+ await flush();
+ assert.deepEqual(moved.calls.slice(1).map(call => call.body?.event ?? call.url), ['handoff', '/api/player/devices/active']);
+});