Fix offline playback ownership and polish the artist list and desktop sidebar
Build and Publish / Build and Publish Docker Image (push) Successful in 2m44s
Build and Publish / Build and Publish Docker Image (push) Successful in 2m44s
This commit is contained in:
1 parent
656466b176
commit
a045ab4fbe
22 files changed
+724
-140
No files matched your search
@@ -29,6 +29,7 @@ const {chromium} = require(process.env.PLAYWRIGHT_MODULE || 'playwright');
|
||||
}
|
||||
const read = (path, init) => repo.respond(new Request(location.origin+api+path,init));
|
||||
const get = async (path,init) => (await read(path,init)).json();
|
||||
const emptyContentLikes = await get('tracks/content/like');
|
||||
await repo.observe(api+'me',{id:1,name:'One'});
|
||||
await repo.observe(api+'likes',{track_ids:[21,22,23]});
|
||||
await repo.observe(api+'artists?mine=true',{items:[{id:12,image_url:api+'cover/14/medium'}]});
|
||||
@@ -45,6 +46,7 @@ const {chromium} = require(process.env.PLAYWRIGHT_MODULE || 'playwright');
|
||||
const featured = await get('artists/11');
|
||||
const release = await get('releases/37');
|
||||
const unlikedCopy = (await get('playlists/-1')).tracks;
|
||||
const legacyContentLikes = await get('tracks/content/like');
|
||||
const playlist = (await get('playlists/9')).tracks;
|
||||
const search = await get('search?q=song+band');
|
||||
const lyrics = await get('lyrics/21');
|
||||
@@ -81,6 +83,13 @@ const {chromium} = require(process.env.PLAYWRIGHT_MODULE || 'playwright');
|
||||
throw new Error('Unexpected remote path '+path);
|
||||
}});
|
||||
const [local] = await repo.list();
|
||||
await repo.observe(api+'tracks/content/like',[content,'b3:'+'c'.repeat(64)]);
|
||||
const remoteLikes = {
|
||||
contents:await get('tracks/content/like'),
|
||||
ids:(await get('likes')).track_ids,
|
||||
playlist:(await get('playlists/-1')).tracks.map(t=>t.id),
|
||||
track:local.id,
|
||||
};
|
||||
const savedView = await get('releases/'+local.release_id);
|
||||
const remoteDetails = {
|
||||
rejected,identity:OfflineCatalog.trackId(federated.id) === local.id,
|
||||
@@ -129,7 +138,7 @@ const {chromium} = require(process.env.PLAYWRIGHT_MODULE || 'playwright');
|
||||
range:[range.status,range.headers.get('Content-Range'),rangeBytes],suffix:suffixBytes,
|
||||
invalidRange:invalidRange.status,head:[head.status,head.headers.get('Content-Length'),(await head.arrayBuffer()).byteLength],
|
||||
error,truncated,files:files.length,afterRemove,remainingBytes,cleared:await repo.stats(),
|
||||
mediaRequests,remoteDetails,notFound,cleanup};
|
||||
mediaRequests,remoteDetails,notFound,cleanup,emptyContentLikes,legacyContentLikes,remoteLikes};
|
||||
});
|
||||
assert.equal(results.queueBefore,1);
|
||||
assert.equal(results.queueAfter,0);
|
||||
@@ -141,6 +150,12 @@ const {chromium} = require(process.env.PLAYWRIGHT_MODULE || 'playwright');
|
||||
assert.deepEqual(results.guests,[21,22]);
|
||||
assert.deepEqual(results.albumTracks,[21]);
|
||||
assert.equal(results.unlikedCopy,1);
|
||||
assert.deepEqual(results.emptyContentLikes,[]);
|
||||
assert.deepEqual(results.legacyContentLikes,['b3:'+'1'.repeat(64)]);
|
||||
const liked = results.remoteLikes;
|
||||
assert.deepEqual(liked.contents,['b3:'+'f'.repeat(64)]);
|
||||
assert.deepEqual(liked.ids,[liked.track]);
|
||||
assert.deepEqual(liked.playlist,[liked.track]);
|
||||
assert.deepEqual(results.playlist,[22,21]);
|
||||
assert.equal(results.results,2);
|
||||
assert.equal(results.lyrics.versions[0].plain_text,'First line');
|
||||
|
||||
@@ -28,7 +28,7 @@ const assets = {'/offline-worker.js':'text/javascript','/offline-catalog.js':'te
|
||||
|
||||
(async () => {
|
||||
assert.ok(html.includes('data-offline-account="1"'),'render the current member player fixture first');
|
||||
let down = false;
|
||||
let down = false, remoteOwner = null;
|
||||
const log = [];
|
||||
const server = http.createServer(async (req,res) => {
|
||||
const p = new URL(req.url,'http://localhost').pathname;
|
||||
@@ -46,6 +46,11 @@ const assets = {'/offline-worker.js':'text/javascript','/offline-catalog.js':'te
|
||||
if (range) {res.statusCode=206; res.setHeader('Content-Range',`bytes ${first}-${last}/${wav.length}`);}
|
||||
return res.end(wav.subarray(first,last+1));
|
||||
}
|
||||
if (p === '/api/player/federation/artists/events') {
|
||||
res.writeHead(200, {'Content-Type':'text/event-stream'});
|
||||
res.write(': connected\n\n');
|
||||
return;
|
||||
}
|
||||
if (p.endsWith('/events')) {res.writeHead(204); return res.end();}
|
||||
const results = {
|
||||
'/api/player/me':{id:1,name:'Member',role:'user',stats:{}},
|
||||
@@ -55,8 +60,9 @@ const assets = {'/offline-worker.js':'text/javascript','/offline-catalog.js':'te
|
||||
'/api/player/follows':{artist_ids:[],artists:[]}, '/api/player/playlists':[], '/api/player/pins':[],
|
||||
'/api/player/state':{queue:[],repeat_mode:'off',volume:.5},'/api/player/lyrics/1':text,
|
||||
'/api/player/federation/tracks/lyrics':text,
|
||||
'/api/player/devices/heartbeat':{active_device_id:null,devices:[],jams:[]},
|
||||
'/api/player/devices/poll':{active_device_id:null,devices:[],commands:[]},
|
||||
'/api/player/devices/heartbeat':{active_device_id:remoteOwner,devices:[],jams:[]},
|
||||
'/api/player/devices/poll':{active_device_id:remoteOwner,devices:[],commands:[],
|
||||
playback_state:remoteOwner ? {track:tracks[0],tracks:[tracks[0]],index:0,position_seconds:6,paused:false} : null},
|
||||
};
|
||||
res.setHeader('Content-Type','application/json');
|
||||
if (p === '/api/player/tracks-by-ids') {
|
||||
@@ -69,7 +75,16 @@ const assets = {'/offline-worker.js':'text/javascript','/offline-catalog.js':'te
|
||||
await new Promise(resolve => server.listen(0,'127.0.0.1',resolve));
|
||||
const base = 'http://127.0.0.1:'+server.address().port;
|
||||
const browser = await chromium.launch({headless:true,...(process.env.CHROME_PATH ? {executablePath:process.env.CHROME_PATH} : {})});
|
||||
const page = await browser.newPage({viewport:{width:1280,height:860}});
|
||||
const context = await browser.newContext({viewport:{width:1280,height:860}});
|
||||
const page = await context.newPage();
|
||||
await context.addInitScript(() => {
|
||||
const play = HTMLMediaElement.prototype.play;
|
||||
window.audioPlayCalls = 0;
|
||||
HTMLMediaElement.prototype.play = function(...args) {
|
||||
if (this instanceof HTMLAudioElement) window.audioPlayCalls++;
|
||||
return play.apply(this,args);
|
||||
};
|
||||
});
|
||||
const errors = [];
|
||||
page.on('pageerror',e=>errors.push(e.message));
|
||||
try {
|
||||
@@ -90,9 +105,26 @@ const assets = {'/offline-worker.js':'text/javascript','/offline-catalog.js':'te
|
||||
await page.waitForFunction(() => Alpine.store('player').isPlaying && Alpine.store('player').currentTime > .1);
|
||||
await page.waitForFunction(() => Alpine.store('offline').items.some(t=>t.id===1));
|
||||
assert.equal(await page.evaluate(() => Alpine.store('offline').bytes),wav.length);
|
||||
// A second, forgotten tab sees the playing track through device sync.
|
||||
remoteOwner = await page.evaluate(() => Alpine.store('devices').id);
|
||||
const controller = await context.newPage();
|
||||
controller.on('pageerror',e=>errors.push(e.message));
|
||||
await controller.goto(base+'/#artist/7');
|
||||
await controller.waitForFunction(() => !Alpine.store('devices').isActive() &&
|
||||
Alpine.store('player').currentTrack?.id === 1 && Alpine.store('player').isPlaying);
|
||||
await account.click();
|
||||
await block.getByRole('switch').click();
|
||||
await page.waitForFunction(() => Alpine.store('offline').manual && Alpine.store('offline').active);
|
||||
await page.waitForFunction(() => {
|
||||
const player = Alpine.store('player');
|
||||
return player._offlineSession && player.isPlaying && player.currentTime > .3;
|
||||
});
|
||||
await controller.waitForFunction(() => Alpine.store('offline').active && Alpine.store('player')._offlineSession &&
|
||||
!Alpine.store('player').isPlaying);
|
||||
assert.equal(await controller.evaluate(() => window.audioPlayCalls),0,'only the original playback tab may continue');
|
||||
await controller.close();
|
||||
remoteOwner = null;
|
||||
await page.locator('.device-toggle-btn.active:visible').waitFor();
|
||||
const baseline = log.length;
|
||||
down = true;
|
||||
await page.goto(base+'/#artist/7');
|
||||
@@ -124,6 +156,35 @@ const assets = {'/offline-worker.js':'text/javascript','/offline-catalog.js':'te
|
||||
assert.equal(await page.locator('.track-row[data-shared-track-id]').count(),1);
|
||||
down = false;
|
||||
await page.waitForFunction(() => !Alpine.store('offline').active,null,{timeout:15000});
|
||||
// Lose the browser connection while viewing a live artist and controlling another device.
|
||||
remoteOwner = 'other-browser';
|
||||
await page.goto(base+'/#artist/7');
|
||||
await page.waitForFunction(() => !Alpine.store('devices').isActive() && Alpine.store('player').isPlaying &&
|
||||
Alpine.store('player').currentTrack?.id === 1 &&
|
||||
Alpine.store('library')._artistFederationSource?.readyState === EventSource.OPEN);
|
||||
const controllerPlayCalls = await page.evaluate(() => window.audioPlayCalls);
|
||||
await page.context().setOffline(true);
|
||||
await page.waitForFunction(() => Alpine.store('offline').automatic &&
|
||||
!Alpine.store('library')._artistFederationSource && Alpine.store('library').currentArtist?.top_tracks?.length === 1);
|
||||
await page.locator('.device-toggle-btn.active:visible').waitFor();
|
||||
await page.waitForFunction(() => Alpine.store('player')._offlineSession && !Alpine.store('player').isPlaying);
|
||||
assert.equal(await page.evaluate(() => window.audioPlayCalls),controllerPlayCalls,'a former controller must not start audio on disconnection');
|
||||
const disconnected = log.length;
|
||||
const savedRow = page.locator('.artist-appearance-row:visible').filter({hasText:'Recording 1'}).first();
|
||||
await savedRow.press('Enter');
|
||||
await page.waitForFunction(() => Alpine.store('player').currentTrack?.id === 1 &&
|
||||
Alpine.store('player').isPlaying && Alpine.store('player').currentTime > .3);
|
||||
assert.equal(await page.evaluate(() => Alpine.store('library').federationIsLiked({key:{content_id:'unknown'}})),false);
|
||||
const artistEvents = log.filter(r => r.p === '/api/player/federation/artists/events').length;
|
||||
await page.reload();
|
||||
await page.waitForFunction(() => Alpine.store('offline').automatic && Alpine.store('library').currentArtist?.id === 7);
|
||||
assert.equal(await page.evaluate(() => window.audioPlayCalls),0,'reloading offline must not autoplay');
|
||||
assert.deepEqual(log.slice(disconnected).filter(r => !['/offline-worker.js','/offline-catalog.js'].includes(r.p)),[]);
|
||||
remoteOwner = null;
|
||||
await page.context().setOffline(false);
|
||||
await page.waitForFunction(() => !Alpine.store('offline').active &&
|
||||
Alpine.store('library')._artistFederationSource?.readyState === EventSource.OPEN,null,{timeout:15000});
|
||||
assert.equal(log.filter(r => r.p === '/api/player/federation/artists/events').length,artistEvents+1);
|
||||
await page.evaluate(track => Alpine.store('player').play(track),prepared);
|
||||
await page.waitForFunction(() => Alpine.store('offline').items.some(t=>t.offline_remote));
|
||||
await page.evaluate(() => Alpine.store('offline').setManual(true));
|
||||
|
||||
@@ -100,6 +100,13 @@ const catalog = fs.readFileSync(path.join(player, 'offline-catalog.js'), 'utf8')
|
||||
await other.goto(base+'/#artists');
|
||||
assert.equal(await other.evaluate(() => document.documentElement.dataset.offlineMode),'manual');
|
||||
assert.equal(await other.evaluate(() => fetch('/api/player/me').then(r=>r.json()).then(p=>p.name)), 'Saved');
|
||||
for (const path of ['artists/events?name=Band', 'search/events?q=Band']) {
|
||||
const status = await page.evaluate(async path => {
|
||||
const response = await fetch('/api/player/federation/'+path, {headers:{Accept:'text/event-stream'}});
|
||||
return response.status;
|
||||
}, path);
|
||||
assert.equal(status, 204, 'a late EventSource handshake is answered locally without a reconnect');
|
||||
}
|
||||
for (const [url,method] of [['/offline-probe','GET'],['/api/player/history','POST'],['/logout','GET']]) {
|
||||
assert.equal(await page.evaluate(([u,m]) => fetch(u,{method:m}).then(r=>r.status),[url, method]),503);
|
||||
}
|
||||
|
||||
@@ -81,6 +81,43 @@ async function checkArtistPopularTracks(page) {
|
||||
await rows.nth(5).waitFor({state:'detached'});
|
||||
assert.equal(await section.locator('.artist-popular-overflow').evaluate(el=>el.getAnimations().length),0);
|
||||
}
|
||||
|
||||
async function checkArtistScrollReturn(page) {
|
||||
const tracks = Array.from({length:35}, (_, i) => local(i+1, 'Track '+i));
|
||||
const releases = Array.from({length:48}, (_, i) => ({id:i+1,title:'Album '+i,release_type:'album',track_count:8}));
|
||||
await page.route('**/api/player/artists/398', route => route.fulfill({json:{
|
||||
id:398,name:'Scorpions',top_tracks:tracks,featured_tracks:[],releases,total_track_count:tracks.length,
|
||||
}}));
|
||||
await page.evaluate(() => { location.hash = 'artist/398'; });
|
||||
const section = page.locator('.artist-top-tracks');
|
||||
const toggle = section.getByRole('button', {name:'Expand all',exact:true});
|
||||
const collapse = section.getByRole('button', {name:'Collapse',exact:true});
|
||||
await page.getByText('Album 47',{exact:true}).waitFor({state:'attached'});
|
||||
const scroller = page.locator('#center-scroll');
|
||||
for (const reducedMotion of ['no-preference','reduce']) {
|
||||
await page.emulateMedia({reducedMotion});
|
||||
// Expand midway down the viewport, then scroll the distant Collapse button into a different position.
|
||||
const offset = await scroller.evaluate(el => {
|
||||
const button = el.querySelector('.artist-top-tracks-toggle');
|
||||
el.scrollTop += button.getBoundingClientRect().top - el.getBoundingClientRect().top - el.clientHeight * .5;
|
||||
return el.scrollTop;
|
||||
});
|
||||
const expandY = (await toggle.boundingBox()).y;
|
||||
await toggle.click();
|
||||
await section.locator('.artist-appearance-row').last().getByText('Track 34',{exact:true}).waitFor({state:'attached'});
|
||||
await section.locator('.artist-popular-overflow').evaluate(el => Promise.all(el.getAnimations().map(a => a.finished)));
|
||||
const expandedOffset = await scroller.evaluate(el => {
|
||||
const button = el.querySelector('.artist-top-tracks-toggle');
|
||||
el.scrollTop += button.getBoundingClientRect().top - el.getBoundingClientRect().top - el.clientHeight * .25;
|
||||
return el.scrollTop;
|
||||
});
|
||||
assert.ok(expandedOffset > offset + 1000, 'the listener has scrolled through the expanded tracks');
|
||||
await collapse.click();
|
||||
await section.locator('.artist-appearance-row').nth(5).waitFor({state:'detached'});
|
||||
await page.waitForFunction(y => Math.abs(document.querySelector('.artist-top-tracks-toggle').getBoundingClientRect().top - y) < 12,
|
||||
expandY, {timeout:2500});
|
||||
}
|
||||
}
|
||||
data.remote[0].metadata.artists[0].local_id=1;
|
||||
data.remote[0].metadata.release.local_id=442;
|
||||
data.remote[0].metadata.featured_artists=[{name:'Guest & Co'}];
|
||||
@@ -246,6 +283,7 @@ data.remote[0].availability.local={track_id:111, stream_url:'/api/player/stream/
|
||||
assert.equal(await page.evaluate(()=>window.groupPlays.at(-1).id),'fed:'+remote(12).key.content_id);
|
||||
assert.equal(await page.evaluate(()=>Alpine.store('player').volume),0.37);
|
||||
await checkArtistPopularTracks(page);
|
||||
await checkArtistScrollReturn(page);
|
||||
assert.deepEqual(errors,[]);await page.close();
|
||||
}
|
||||
console.log('Search and artist version groups, expansion, playback and streaming checks passed.');
|
||||
|
||||
@@ -231,9 +231,22 @@ async function checkOfflineControls(page, trigger, panel) {
|
||||
await page.locator('.content-topbar').click({position:{x:1,y:1}});
|
||||
await panel.waitFor({state:'hidden'});
|
||||
await trigger.click();
|
||||
const manual = panel.getByRole('switch', {name:'Use saved music only'});
|
||||
const manual = panel.getByRole('switch', {name:'Offline mode'});
|
||||
const help = offlineAccount.getByRole('button', {name:'Info', exact:true});
|
||||
await help.hover();
|
||||
const hint = offlineAccount.getByRole('tooltip');
|
||||
await hint.waitFor();
|
||||
assert.match(await hint.innerText(), /only the local cache.*No network requests/);
|
||||
await help.click();
|
||||
assert.equal(await manual.getAttribute('aria-checked'), 'false', 'opening the hint leaves the mode unchanged');
|
||||
await help.press('Escape');
|
||||
await hint.waitFor({state:'hidden'});
|
||||
assert.ok(await panel.isVisible());
|
||||
await manual.click();
|
||||
assert.equal(await manual.getAttribute('aria-checked'), 'true');
|
||||
const offlineStatus = page.locator('.offline-topbar-state span');
|
||||
assert.equal(await offlineStatus.innerText(), 'Offline');
|
||||
assert.ok((await offlineStatus.boundingBox()).width > 20, 'the status text is visible even on a small phone');
|
||||
assert.ok(await panel.isVisible(), 'toggling saved music keeps the menu open');
|
||||
assert.equal(await panel.getByRole('link', {name:'My listening'}).isVisible(), false);
|
||||
assert.equal(await panel.getByRole('link', {name:'Followed'}).isVisible(), true);
|
||||
|
||||
@@ -13,6 +13,7 @@ function setup(hash, fetch) {
|
||||
const location = { hash };
|
||||
const replacements = [];
|
||||
const streams = [];
|
||||
const offline = {active: false, manual: false};
|
||||
let library;
|
||||
class EventSource {
|
||||
constructor(url) { this.url = url; this.events = {}; streams.push(this); }
|
||||
@@ -21,12 +22,17 @@ function setup(hash, fetch) {
|
||||
close() { this.closed = true; }
|
||||
}
|
||||
vm.runInNewContext(librarySource, {
|
||||
location, fetch, EventSource, GUEST: false, playerOffline: () => false, URLSearchParams, clearTimeout, setTimeout,
|
||||
Alpine: { store(_name, value) { library = value; } },
|
||||
location, fetch, EventSource, GUEST: false, playerOffline: () => offline.active, URLSearchParams, clearTimeout, setTimeout,
|
||||
window: {setTimeout, clearTimeout},
|
||||
Alpine: { store(name, value) {
|
||||
if (value) library = value;
|
||||
if (name === 'offline') return offline;
|
||||
if (name === 'library') return library;
|
||||
} },
|
||||
history: { replaceState(_state, _title, url) { location.hash = url; replacements.push(url); } },
|
||||
});
|
||||
library._afterNavigation = () => {};
|
||||
return { library, location, replacements, streams };
|
||||
return { library, location, replacements, streams, offline };
|
||||
}
|
||||
|
||||
function key(title, artist, year) {
|
||||
@@ -34,6 +40,43 @@ function key(title, artist, year) {
|
||||
}
|
||||
const link = releaseKey => '#releasefed?key=' + encodeURIComponent(JSON.stringify(releaseKey));
|
||||
|
||||
test('federation closes subscriptions and pending search batches when switching offline', async () => {
|
||||
const {library, streams, offline} = setup('#artist/1', () => assert.fail('no HTTP request expected'));
|
||||
const release = {title:'Album', artists:[{name:'Band'}], tracks:[]};
|
||||
const startStreams = () => {
|
||||
library.startArtistFederation('Band');
|
||||
library.startReleaseFederation(release);
|
||||
library.startFederationSearch('Band');
|
||||
};
|
||||
startStreams();
|
||||
const [artist, edition, search] = streams;
|
||||
const match = {entity:{key:{normalized_name:'band'}, name:'Band'}, score:1};
|
||||
search.emit('federation.artist', match);
|
||||
offline.manual = offline.busy = true; // The page closes these before awaiting the worker acknowledgement.
|
||||
library.stopFederation();
|
||||
startStreams();
|
||||
assert.equal(streams.length, 3);
|
||||
assert.ok(streams.every(stream => stream.closed));
|
||||
offline.active = true;
|
||||
offline.manual = offline.busy = false;
|
||||
startStreams();
|
||||
assert.equal(streams.length, 3);
|
||||
offline.active = false;
|
||||
startStreams();
|
||||
assert.equal(streams.length, 6);
|
||||
// Queued events from the previous subscription must not affect the recovered page.
|
||||
artist.emit('federation.artist.catalog', {entity:{name:'Old'}});
|
||||
edition.emit('artist.completed', {});
|
||||
search.emit('federation.artist', match);
|
||||
search.onerror();
|
||||
await new Promise(resolve => setTimeout(resolve, 65));
|
||||
assert.equal(library.currentArtist, null);
|
||||
assert.equal(library.releaseFederationLoading, true);
|
||||
assert.equal(library.federationSearch.artists.length, 0);
|
||||
assert.equal(library.federationSearch.loading, true);
|
||||
library.stopFederation();
|
||||
});
|
||||
|
||||
test('guest appearances add recordings, not owned releases, even across several catalogues', () => {
|
||||
const { library, streams } = setup('#artist/333', () => assert.fail('no request expected'));
|
||||
const wire = id => ({ item_id: id, content_id: id, title: 'Диагноз', artists: ['Трагедия Всей Жизни'], featured_artists: ['Кизиль'] });
|
||||
|
||||
@@ -0,0 +1,125 @@
|
||||
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');
|
||||
const storesSource = template.slice(template.indexOf(' let playbackConnection'), template.indexOf(" Alpine.store('queue', {"));
|
||||
const offline = readFileSync(__dirname + '/../templates/player/offline_scripts.html', 'utf8');
|
||||
const applySource = offline.slice(offline.indexOf(' apply(mode)'), offline.indexOf(' async captureLibrary()'));
|
||||
|
||||
function setup(fetch) {
|
||||
const stores = {offline: {active: true, saveState() {}, scheduleProbe() {}}};
|
||||
const window = new EventTarget();
|
||||
const audio = Object.assign(new EventTarget(), {
|
||||
paused: true, ended: false, playCalls: 0,
|
||||
async play() {
|
||||
++this.playCalls;
|
||||
this.paused = false;
|
||||
this.dispatchEvent(new Event('play'));
|
||||
this.dispatchEvent(new Event('playing'));
|
||||
},
|
||||
pause() { this.paused = true; },
|
||||
});
|
||||
const document = Object.assign(new EventTarget(), {title: 'Player', documentElement: {classList: {toggle() {}}}});
|
||||
const storage = new Map([['furu_player_device_id', 'here']]);
|
||||
const sessionStorage = {
|
||||
getItem: key => storage.get(key), setItem: (key, value) => storage.set(key, value),
|
||||
removeItem: key => storage.delete(key),
|
||||
};
|
||||
vm.runInNewContext(storesSource + "\nObject.assign(Alpine.store('offline'), {" + applySource + "});", {
|
||||
GUEST: false, SHARE_TOKEN: 'skip-restore', Alpine: {effect() {}, store(name, value) { if (value) stores[name] = value; return stores[name]; }},
|
||||
audio, navigator: {}, window, document, sessionStorage, AbortController, fetch, CustomEvent,
|
||||
retryTimer: 0, transfer: null, playbackSource: t => t.stream_url,
|
||||
playerOffline: () => stores.offline.active, OfflineCatalog: {trackId: t => t.id},
|
||||
setInterval: () => 0, setTimeout: () => 0, clearTimeout() {},
|
||||
});
|
||||
stores.player.init();
|
||||
stores.devices.init();
|
||||
return {stores, audio, mode: active => stores.offline.apply(active ? 'auto' : 'online')};
|
||||
}
|
||||
|
||||
for (const monitoring of [true, false]) test('a former remote controller stays silent offline, Jam monitoring ' + monitoring, async () => {
|
||||
const {stores, audio, mode} = setup(() => assert.fail('Unexpected network request'));
|
||||
const {devices, player} = stores;
|
||||
mode(false);
|
||||
devices.activeDeviceId = 'other';
|
||||
devices.currentJamId = 'mixed';
|
||||
devices.jams = [{id: 'mixed', is_member: true, is_owner: false}];
|
||||
assert.equal(player._shouldSendRemote(), true);
|
||||
const saved = {id: 3, title: 'Song', stream_url: '/api/player/stream/3'};
|
||||
stores.queue = {tracks: [saved], syncCurrentIndexToTrack() {}};
|
||||
player.currentTrack = saved;
|
||||
player.currentTime = 12;
|
||||
player.isPlaying = true;
|
||||
player._localSourceTrackId = monitoring ? saved.id : 17;
|
||||
audio.paused = !monitoring;
|
||||
player._cachePlayCounted = true;
|
||||
mode(true);
|
||||
assert.equal(audio.paused, true, 'stop the monitor synchronously before reading IndexedDB');
|
||||
assert.equal(player.isPlaying, false);
|
||||
let nextCalls = 0;
|
||||
player.next = () => { nextCalls++; };
|
||||
audio.dispatchEvent(new Event('ended'));
|
||||
audio.dispatchEvent(new Event('playing'));
|
||||
assert.equal(nextCalls, 0);
|
||||
player.useOfflineCatalog([saved]);
|
||||
assert.equal(devices.isActive(), true);
|
||||
assert.equal(devices.selectedJam(), null);
|
||||
assert.equal(player._shouldSendRemote(), false);
|
||||
assert.equal(player.isPlaying, false);
|
||||
assert.equal(audio.playCalls, 0);
|
||||
assert.equal(player._cachePlayCounted, false);
|
||||
player.resume();
|
||||
assert.equal(audio.paused, false);
|
||||
assert.equal(audio.playCalls, 1);
|
||||
player.useOfflineCatalog([saved]); // A cache refresh must preserve explicit offline playback.
|
||||
assert.equal(audio.paused, false);
|
||||
assert.equal(audio.playCalls, 1);
|
||||
assert.equal(await devices.sendCommand('pause'), false);
|
||||
});
|
||||
|
||||
test('only the online owner playing the displayed recording continues from cache', () => {
|
||||
for (const [owner, paused, source, continues] of [
|
||||
['here', false, 3, true], ['here', true, 3, false], ['here', false, 4, false], ['other', false, 3, false],
|
||||
]) {
|
||||
const {stores, audio, mode} = setup(() => assert.fail('Unexpected network request'));
|
||||
mode(false);
|
||||
const saved = {id: 3, stream_url: '/api/player/stream/3'};
|
||||
stores.queue = {tracks: [saved], syncCurrentIndexToTrack() {}};
|
||||
stores.devices.activeDeviceId = owner;
|
||||
stores.player.currentTrack = saved;
|
||||
stores.player.isPlaying = !paused;
|
||||
stores.player._localSourceTrackId = source;
|
||||
audio.paused = paused;
|
||||
mode(true);
|
||||
stores.player.useOfflineCatalog([saved]);
|
||||
assert.equal(!audio.paused, continues);
|
||||
assert.equal(audio.playCalls, continues ? 1 : 0);
|
||||
}
|
||||
});
|
||||
|
||||
test('late device polls and transfers cannot replace playback after going offline and reconnecting', async () => {
|
||||
const responses = [];
|
||||
const {stores, mode} = setup((url, {signal}) => new Promise(resolve => responses.push({
|
||||
url, signal, deliver: data => resolve({ok: true, json: async () => data}),
|
||||
})));
|
||||
const {devices, player} = stores;
|
||||
let remoteCommands = 0;
|
||||
player._executeRemoteCommand = () => { ++remoteCommands; };
|
||||
mode(false);
|
||||
const poll = devices.poll();
|
||||
const transfer = devices.select('here');
|
||||
assert.equal(responses.length, 2);
|
||||
mode(true);
|
||||
assert.ok(responses.every(r => r.signal.aborted));
|
||||
mode(false);
|
||||
const fresh = devices.heartbeat();
|
||||
responses[2].deliver({active_device_id: 'other', devices: [], jams: []});
|
||||
await fresh;
|
||||
for (const r of responses.slice(0, 2)) r.deliver({active_device_id: 'here', commands: [{command: 'play_track'}], playback_state: {}});
|
||||
await Promise.all([poll, transfer]);
|
||||
assert.equal(devices.activeDeviceId, 'other');
|
||||
assert.equal(devices.isActive(), false);
|
||||
assert.equal(remoteCommands, 0);
|
||||
});
|
||||
Reference in new issue
Block a user