Play saved audio and display artwork directly from browser storage
This commit is contained in:
1 parent
32057fd67b
commit
6a593ee1fb
16 files changed
+576
-115
No files matched your search
@@ -64,10 +64,15 @@
|
||||
const missing = () => json({error:'Unavailable offline'}, 404);
|
||||
function coverKey(url) {
|
||||
if (typeof url !== 'string') return null;
|
||||
if (url.startsWith(location.origin + '/')) url = url.slice(location.origin.length);
|
||||
// Serve the saved thumbnail for all resolutions of the same artwork.
|
||||
const match = url.match(/^\/api\/player\/cover\/(\d+)(?:\/(?:small|medium|large))?$/);
|
||||
if (match) return BASE + 'cover/' + match[1] + '/medium';
|
||||
return /^\/api\/player\/playlists\/\d+\/cover\?v=[a-f\d]+$/i.test(url) ? url : null;
|
||||
if (/^\/api\/player\/playlists\/\d+\/cover\?v=[a-f\d]+$/i.test(url)) return url;
|
||||
return /^\/api\/player\/federation\/(?:tracks\/artwork|catalog\/artwork(?:\/discover)?)\?[^#]+$/.test(url) ? url : null;
|
||||
}
|
||||
function savedTrack(row) {
|
||||
return row.track.cover_url || !row.release?.cover_url ? row.track : {...row.track, cover_url:row.release.cover_url};
|
||||
}
|
||||
function releaseInfo(release, track) {
|
||||
return {
|
||||
@@ -86,8 +91,12 @@
|
||||
function contentKey(track) {
|
||||
return /^b3:[\da-f]{64}$/.test(track.content_id) ? track.content_id : 'track:' + track.id;
|
||||
}
|
||||
function binary(file, request, mime) {
|
||||
const headers = new Headers({'Content-Type':mime || file.type || 'application/octet-stream', 'Accept-Ranges':'bytes'});
|
||||
const audioTypes = new Map(Object.entries({
|
||||
mp3:'audio/mpeg', flac:'audio/flac', wav:'audio/wav', ogg:'audio/ogg', oga:'audio/ogg',
|
||||
opus:'audio/ogg', mp4:'audio/mp4', m4a:'audio/mp4', alac:'audio/mp4', aac:'audio/aac', webm:'audio/webm',
|
||||
}));
|
||||
function binary(file, request) {
|
||||
const headers = new Headers({'Content-Type':file.type || 'application/octet-stream', 'Accept-Ranges':'bytes'});
|
||||
const range = request.headers.get('Range');
|
||||
let start = 0, end = file.size - 1;
|
||||
if (range) {
|
||||
@@ -119,6 +128,7 @@
|
||||
|
||||
class OfflineCatalog {
|
||||
static trackId(value) { return trackId(value); }
|
||||
static artworkKey(url) { return coverKey(url); }
|
||||
static canSave(track) {
|
||||
return !!track && !track.podcast && !track.federation_pending && (positiveId(track.id) !== null || preparedRemote(track));
|
||||
}
|
||||
@@ -185,13 +195,37 @@
|
||||
]);
|
||||
const mime = new Map(fileKeys.map((key,i) => [key, fileInfo[i].mime]));
|
||||
const counts = new Map(plays.map(p => [p.id, p]));
|
||||
return rows.map(r => ({...r.track, bytes:r.bytes, audio_mime:mime.get(r.file), downloaded_at:r.downloaded_at,
|
||||
return rows.map(r => ({...savedTrack(r), bytes:r.bytes, audio_mime:mime.get(r.file), downloaded_at:r.downloaded_at,
|
||||
last_played_at:counts.get(r.id)?.last_played_at || null, play_count:counts.get(r.id)?.play_count || 0}));
|
||||
}
|
||||
async has(value) {
|
||||
const id = trackId(value);
|
||||
return id !== null && Boolean(await this.read('tracks',id));
|
||||
}
|
||||
async openAudio(track) {
|
||||
const id = trackId(track);
|
||||
const row = id && await this.read('tracks', id);
|
||||
const source = track?.id ?? track;
|
||||
const requested = track?.content_id ?? (typeof source === 'string' && source.startsWith('fed:') ? source.slice(4) : null);
|
||||
const content = contentToken(requested) ? requested : null;
|
||||
const key = content || row?.file;
|
||||
let entry = key && await this.read('files', key);
|
||||
// Older recordings without a content hash are stored under their local track ID.
|
||||
if (!entry && content && row?.file === 'track:' + id) entry = await this.read('files', row.file);
|
||||
if (!entry) return null;
|
||||
try {
|
||||
const handle = await (await this.directory()).getFileHandle(entry.name);
|
||||
const file = await handle.getFile();
|
||||
const format = track?.audio_format || row?.track?.audio_format;
|
||||
const type = entry.mime && entry.mime !== 'application/octet-stream'
|
||||
? entry.mime : file.type || audioTypes.get(normalized(format));
|
||||
// OPFS filenames have no extension. Retype the disk-backed bytes without reading them into memory.
|
||||
return type && type !== file.type ? file.slice(0, file.size, type) : file;
|
||||
} catch (error) {
|
||||
if (error.name === 'NotFoundError') return null;
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
async enqueue(track) {
|
||||
if (!OfflineCatalog.canSave(track)) return;
|
||||
const id = trackId(track);
|
||||
@@ -516,10 +550,11 @@
|
||||
const revision = await this.read('meta','revision');
|
||||
if (this._catalog && this._revision === revision) return this._catalog;
|
||||
const rows = await this.all('tracks');
|
||||
const tracks = rows.map(row => row.track);
|
||||
const tracks = [];
|
||||
const artists = new Map(), releases = new Map();
|
||||
for (const row of rows) {
|
||||
const t = row.track;
|
||||
const t = savedTrack(row);
|
||||
tracks.push(t);
|
||||
const release = releases.get(t.release_id) || {...row.release, tracks:[]};
|
||||
release.tracks.push(t);
|
||||
releases.set(release.id, release);
|
||||
@@ -614,21 +649,13 @@
|
||||
const {ids} = await request.json().catch(() => ({}));
|
||||
if (!Array.isArray(ids)) return json({error:'Expected track IDs'},400);
|
||||
const rows = await Promise.all(ids.slice(0,500).map(trackId).filter(Boolean).map(id => this.read('tracks',id)));
|
||||
return json(rows.filter(Boolean).map(row => row.track));
|
||||
return json(rows.filter(Boolean).map(savedTrack));
|
||||
}
|
||||
if (!['GET','HEAD'].includes(request.method)) return null;
|
||||
let m;
|
||||
if ((m = /^(?:stream\/(\d+)|federation\/cache\/([a-f\d]{64}))$/.exec(path))) {
|
||||
const key = m[1] ? (await this.read('tracks',Number(m[1])))?.file : 'b3:'+m[2];
|
||||
const file = key && await this.read('files', key);
|
||||
if (!file) return missing();
|
||||
try {
|
||||
const handle = await (await this.directory()).getFileHandle(file.name);
|
||||
return binary(await handle.getFile(),request,file.mime);
|
||||
} catch(error) {
|
||||
if (error.name === 'NotFoundError') return missing();
|
||||
throw error;
|
||||
}
|
||||
const file = await this.openAudio(m[1] ? Number(m[1]) : {content_id:'b3:'+m[2]});
|
||||
return file ? binary(file,request) : missing();
|
||||
}
|
||||
const art = coverKey(url.pathname + url.search);
|
||||
if (art) {
|
||||
|
||||
@@ -286,7 +286,9 @@ async function handle(event) {
|
||||
const queueLookup = sameOrigin && request.method === 'POST' && url.pathname === '/api/player/tracks-by-ids';
|
||||
response = await fetch(queueLookup ? request.clone() : request, {signal:signal.signal});
|
||||
} catch {
|
||||
if (request.signal.aborted || state.mode === 'disabled' || probe || !sameOrigin) return Response.error();
|
||||
if (state.mode === 'disabled' || !sameOrigin) return Response.error();
|
||||
// Cancelled device polls and failed reachability probes have no local payload to replay.
|
||||
if (request.signal.aborted || probe) return unavailable();
|
||||
if (rootNavigation) await bind(event.resultingClientId, state.account);
|
||||
return fallback(request, state, rootNavigation);
|
||||
} finally {
|
||||
|
||||
@@ -13,7 +13,7 @@
|
||||
:title="track.release_title"
|
||||
aria-label="{{ t.player_release }}">
|
||||
<template x-if="track.cover_url">
|
||||
<img :src="track.cover_url" alt="" aria-hidden="true" loading="lazy">
|
||||
<img x-artwork="track.cover_url" alt="" aria-hidden="true" loading="lazy">
|
||||
</template>
|
||||
<template x-if="!track.cover_url">
|
||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"><rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="12" cy="12" r="4"/></svg>
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
<template x-for="artist in $store.follows.artists" :key="artist.id">
|
||||
<div class="collection-row">
|
||||
<a class="collection-link" :href="$store.library.artistHref(artist)">
|
||||
<span class="collection-art artist"><span aria-hidden="true">♫</span><template x-if="artist.image_url"><img :src="artist.image_url" alt="" loading="lazy"></template></span>
|
||||
<span class="collection-art artist"><span aria-hidden="true">♫</span><template x-if="artist.image_url"><img x-artwork="artist.image_url" alt="" loading="lazy"></template></span>
|
||||
<span><strong x-text="artist.name"></strong><small x-text="formatArtistCount(artist.track_count, 'tracks')"></small></span>
|
||||
</a>
|
||||
<div x-data="{ get target() { return $store.pins.target('artist', artist) } }">{% include "player/pin_button.html" %}</div>
|
||||
|
||||
@@ -123,7 +123,7 @@
|
||||
<li><span class="listening-rank-no" aria-hidden="true" x-text="index+1"></span>
|
||||
<div class="listening-rank-art" :class="{round:listens.kind === 'artists'}">
|
||||
<svg viewBox="0 0 24 24" aria-hidden="true"><circle cx="12" cy="12" r="7"/><circle cx="12" cy="12" r="2"/></svg>
|
||||
<template x-if="item.cover_url"><img :src="item.cover_url" alt="" loading="lazy"
|
||||
<template x-if="item.cover_url"><img x-artwork="item.cover_url" alt="" loading="lazy"
|
||||
@error="listens.coverFailed($el)" @load="$el.removeAttribute('data-unavailable')"></template>
|
||||
</div>
|
||||
<div class="listening-entry-info">
|
||||
@@ -158,7 +158,7 @@
|
||||
<time :datetime="new Date(item.started_at_ms).toISOString()" x-text="listens.clock(item.started_at_ms)"></time>
|
||||
<button class="listening-play-art" @click="listens.play(item)"
|
||||
:aria-label="listens.text('play') + ' ' + item.title">
|
||||
<template x-if="item.cover_url"><img :src="item.cover_url" alt="" loading="lazy"
|
||||
<template x-if="item.cover_url"><img x-artwork="item.cover_url" alt="" loading="lazy"
|
||||
@error="listens.coverFailed($el)" @load="$el.removeAttribute('data-unavailable')"></template>
|
||||
<svg viewBox="0 0 24 24" aria-hidden="true" :class="{placeholder: !item.cover_url}"><path d="M8 5v14l11-7z"/></svg>
|
||||
</button>
|
||||
|
||||
@@ -55,6 +55,7 @@ document.addEventListener('alpine:init', () => {
|
||||
clock(ms) { return times.format(new Date(ms)); },
|
||||
coverFailed(image) {
|
||||
image.setAttribute('data-unavailable', '');
|
||||
if (Alpine.store('offline')?.localArtworkOnly) return;
|
||||
const path = image.getAttribute('src') || '';
|
||||
if (/^\/api\/player\/cover\/\d+\/small$/.test(path)) {
|
||||
image.src = path.slice(0, -'/small'.length);
|
||||
|
||||
@@ -20,6 +20,58 @@ document.addEventListener('alpine:init', () => {
|
||||
let wakeQueue = false, blocked = false, retryDelay = 5000;
|
||||
let revision = 0, listVersion = 0, lastSuccess = Date.now(), channel;
|
||||
function catalog() { return repo || (repo = new globalThis.OfflineCatalog(account)); }
|
||||
// Share each disk-backed cover between visible tiles, the player and the OS media controls.
|
||||
// The final consumer releases the URL when a row disappears or changes its artwork.
|
||||
const covers = new Map();
|
||||
function acquireCover(key, display) {
|
||||
let entry = covers.get(key);
|
||||
if (!entry) {
|
||||
entry = {users:0, url:null};
|
||||
covers.set(key, entry);
|
||||
entry.ready = catalog().read('assets', key).then(blob => {
|
||||
if (blob?.size && covers.get(key) === entry) entry.url = URL.createObjectURL(blob);
|
||||
}).catch(() => {});
|
||||
}
|
||||
let live = true;
|
||||
++entry.users;
|
||||
entry.ready.then(() => { if (live) display(entry.url); });
|
||||
return () => {
|
||||
live = false;
|
||||
if (--entry.users) return;
|
||||
covers.delete(key);
|
||||
if (entry.url) URL.revokeObjectURL(entry.url);
|
||||
};
|
||||
}
|
||||
const lazyCovers = new WeakMap();
|
||||
const coverObserver = 'IntersectionObserver' in window && new IntersectionObserver(entries => {
|
||||
for (const entry of entries) lazyCovers.get(entry.target)?.(entry.isIntersecting);
|
||||
}, {rootMargin:'450px'});
|
||||
const missingCover = 'data:image/svg+xml,' + encodeURIComponent('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 48 48" fill="none" stroke="#747474" stroke-width="2"><circle cx="24" cy="24" r="13"/><circle cx="24" cy="24" r="3"/></svg>');
|
||||
Alpine.directive('artwork', (image, {expression}, {evaluateLater, effect, cleanup}) => {
|
||||
const read = evaluateLater(expression);
|
||||
let dispose;
|
||||
function clear() { dispose?.(); dispose = null; }
|
||||
effect(() => read(url => {
|
||||
clear();
|
||||
const offline = Alpine.store('offline');
|
||||
const show = src => {
|
||||
if (src) image.setAttribute('src', src);
|
||||
else image.removeAttribute('src');
|
||||
};
|
||||
if (!offline.localArtworkOnly || !url || /^(?:blob:|data:)/i.test(url)) { show(url); return; }
|
||||
show(null);
|
||||
const open = () => offline.bindArtwork(url, src => show(src || missingCover));
|
||||
if (image.loading !== 'lazy' || !coverObserver) { dispose = open(); return; }
|
||||
let release;
|
||||
lazyCovers.set(image, visible => {
|
||||
if (visible && !release) release = open();
|
||||
if (!visible && release) { show(null); release(); release = null; }
|
||||
});
|
||||
coverObserver.observe(image);
|
||||
dispose = () => { coverObserver.unobserve(image); lazyCovers.delete(image); release?.(); };
|
||||
}));
|
||||
cleanup(clear);
|
||||
});
|
||||
function eligible(track) {
|
||||
return globalThis.OfflineCatalog?.canSave(track) === true;
|
||||
}
|
||||
@@ -299,6 +351,17 @@ document.addEventListener('alpine:init', () => {
|
||||
}).catch(() => { this.error = label('storage'); });
|
||||
},
|
||||
localResponse(request) { return catalog().respond(request); },
|
||||
get localArtworkOnly() { return this.active || (this.enabled && navigator.onLine === false); },
|
||||
bindArtwork(url, display) {
|
||||
if (!this.localArtworkOnly || !url || /^(?:blob:|data:)/i.test(url)) {
|
||||
display(url);
|
||||
return;
|
||||
}
|
||||
const key = OfflineCatalog.artworkKey(url);
|
||||
if (key) return acquireCover(key, display);
|
||||
display(null);
|
||||
},
|
||||
openAudio(track) { return catalog().openAudio(track); },
|
||||
async played(track) {
|
||||
if (!this.enabled || !eligible(track)) return;
|
||||
try {
|
||||
|
||||
@@ -85,7 +85,7 @@
|
||||
:aria-pressed="header.selected.includes(option.cover_id)"
|
||||
:disabled="header.selected.length >= 4 && !header.selected.includes(option.cover_id)"
|
||||
@click="header.toggleRelease(option.cover_id)">
|
||||
<img :src="option.cover_url" alt="" loading="lazy" decoding="async">
|
||||
<img x-artwork="option.cover_url" alt="" loading="lazy" decoding="async">
|
||||
<span aria-hidden="true" x-show="header.selected.includes(option.cover_id)" x-text="header.selected.indexOf(option.cover_id) + 1"></span>
|
||||
</button>
|
||||
</template>
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
<template x-if="tiles.length">
|
||||
<span class="playlist-art-tiles" :data-tiles="tiles.length" aria-hidden="true">
|
||||
<template x-for="(url, index) in tiles" :key="index">
|
||||
<img :src="url" alt="" decoding="async" loading="lazy"
|
||||
<img x-artwork="url" alt="" decoding="async" loading="lazy"
|
||||
@error="$el.style.visibility = 'hidden'" @load="$el.style.visibility = ''">
|
||||
</template>
|
||||
</span>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<template x-if="$store.podcasts.artwork(pod)">
|
||||
<img
|
||||
:src="$store.podcasts.artwork(pod)"
|
||||
x-artwork="$store.podcasts.artwork(pod)"
|
||||
alt=""
|
||||
aria-hidden="true"
|
||||
loading="lazy"
|
||||
|
||||
+160
-55
@@ -11,18 +11,13 @@ function redirectOnUnauthorized(status) {
|
||||
|
||||
const playerFetch = window.fetch.bind(window);
|
||||
function playerOffline() { return window.Alpine?.store('offline')?.active === true; }
|
||||
function playbackSource(track) {
|
||||
const offline = Alpine.store('offline');
|
||||
if (!offline?.enabled || !offline.isSaved(track)) return track.stream_url;
|
||||
const remoteToken = track.federated_cache && track.content_id?.match(/^b3:([a-f0-9]{64})$/)?.[1];
|
||||
return track.stream_url === '/api/player/stream/' + track.id ||
|
||||
(remoteToken && track.stream_url === '/api/player/federation/cache/' + remoteToken)
|
||||
? track.stream_url + '?saved=1' : track.stream_url;
|
||||
}
|
||||
window.fetch = async (input, init) => {
|
||||
const url = new URL(input instanceof Request ? input.url : input, window.location.href);
|
||||
const offline = window.Alpine?.store('offline');
|
||||
if (offline?.active && !(offline.automatic && url.origin === location.origin && url.pathname === '/offline-probe')) {
|
||||
// The browser can disable networking before it delivers the offline event.
|
||||
const disconnected = offline?.enabled && offline.supported && navigator.onLine === false;
|
||||
const recoveryProbe = offline?.automatic && url.origin === location.origin && url.pathname === '/offline-probe';
|
||||
if (disconnected || (offline?.active && !recoveryProbe)) {
|
||||
if (url.origin === location.origin && url.pathname.startsWith('/api/player/')) {
|
||||
const request = new Request(input instanceof Request ? input : url.href, init);
|
||||
const local = await offline.localResponse(request);
|
||||
@@ -744,9 +739,24 @@ document.addEventListener('alpine:init', () => {
|
||||
// Player store
|
||||
// -----------------------------------------------------------------------
|
||||
let playbackConnection = new AbortController();
|
||||
let releaseSessionArtwork, sessionMetadataKey;
|
||||
let pendingMedia = null, audioObjectUrl = null, audibleTrackId = null;
|
||||
|
||||
// Firefox updates onLine before delivering the offline event that switches the catalog.
|
||||
function deviceSyncUnavailable() { return playerOffline() || navigator.onLine === false; }
|
||||
|
||||
function detachAudio() {
|
||||
if (audio.hasAttribute('src')) {
|
||||
audio.removeAttribute('src');
|
||||
audio.load();
|
||||
}
|
||||
if (audioObjectUrl) URL.revokeObjectURL(audioObjectUrl);
|
||||
audioObjectUrl = null;
|
||||
}
|
||||
window.addEventListener('furumusic:offline-mode', () => {
|
||||
playbackConnection.abort();
|
||||
playbackConnection = new AbortController();
|
||||
Alpine.store('player')._updateMediaSession();
|
||||
});
|
||||
|
||||
Alpine.store('player', {
|
||||
@@ -787,6 +797,8 @@ document.addEventListener('alpine:init', () => {
|
||||
});
|
||||
|
||||
audio.addEventListener('timeupdate', () => {
|
||||
// Loading or losing an HTTP source can report a zero position before cache recovery.
|
||||
if (pendingMedia || audio.error || !audio.readyState) return;
|
||||
this.currentTime = audio.currentTime;
|
||||
this.duration = audio.duration || 0;
|
||||
this.progress = this.duration > 0 ? (this.currentTime / this.duration) * 100 : 0;
|
||||
@@ -796,7 +808,8 @@ document.addEventListener('alpine:init', () => {
|
||||
});
|
||||
|
||||
audio.addEventListener('ended', () => {
|
||||
if (playerOffline() && this._offlinePlaybackHeld) return;
|
||||
if (pendingMedia || !audio.ended || (playerOffline() && this._offlinePlaybackHeld)) return;
|
||||
audibleTrackId = null;
|
||||
if (this.currentTrack?.podcast) {
|
||||
this.isPlaying = false;
|
||||
this.currentTrack.podcast_completed = true;
|
||||
@@ -813,20 +826,22 @@ document.addEventListener('alpine:init', () => {
|
||||
});
|
||||
|
||||
audio.addEventListener('playing', () => {
|
||||
if (audio.paused || (playerOffline() && this._offlinePlaybackHeld)) return;
|
||||
if (pendingMedia || audio.paused || (playerOffline() && this._offlinePlaybackHeld)) return;
|
||||
audibleTrackId = this._localSourceTrackId;
|
||||
if (!this._cachePlayCounted && Alpine.store('offline')?.enabled) {
|
||||
this._cachePlayCounted = true;
|
||||
Alpine.store('offline').played(this.currentTrack);
|
||||
}
|
||||
});
|
||||
audio.addEventListener('play', () => {
|
||||
if (audio.paused || (playerOffline() && this._offlinePlaybackHeld)) return;
|
||||
if (pendingMedia || audio.paused || (playerOffline() && this._offlinePlaybackHeld)) return;
|
||||
this.isPlaying = true;
|
||||
if (!this._playbackStartedAt) this._playbackStartedAt = Math.floor(Date.now() / 1000);
|
||||
this._lastAudioTime = audio.currentTime || 0;
|
||||
this._sendNowPlaying();
|
||||
});
|
||||
audio.addEventListener('pause', () => {
|
||||
if (pendingMedia || !audio.paused) return;
|
||||
if (this.currentTrack?.podcast) Alpine.store('podcasts')?.checkpoint(this, !!this.currentTrack.podcast_completed);
|
||||
this._trackListenedDelta();
|
||||
this.isPlaying = false;
|
||||
@@ -836,6 +851,16 @@ document.addEventListener('alpine:init', () => {
|
||||
audio.addEventListener('loadedmetadata', () => {
|
||||
this.duration = audio.duration || 0;
|
||||
});
|
||||
audio.addEventListener('error', () => {
|
||||
const offline = Alpine.store('offline'), track = this.currentTrack;
|
||||
if (!audio.error || pendingMedia || audioObjectUrl || !offline?.enabled || offline.active ||
|
||||
!track || track.id !== this._localSourceTrackId) return;
|
||||
// A native media load can fail before fetch or navigator notices the outage.
|
||||
offline.networkResult(false);
|
||||
if (!offline.active && this._isLocalPlaybackDevice() && audibleTrackId === track.id && offline.isSaved(track)) {
|
||||
this._loadSource(track, this.currentTime, false, true);
|
||||
}
|
||||
});
|
||||
|
||||
// Periodic state save
|
||||
this._saveTimer = setInterval(() => {
|
||||
@@ -851,11 +876,17 @@ document.addEventListener('alpine:init', () => {
|
||||
}
|
||||
|
||||
// Save state on page unload
|
||||
window.addEventListener('pagehide', () => {
|
||||
window.addEventListener('pagehide', (event) => {
|
||||
if (this._isLocalPlaybackDevice()) {
|
||||
this._saveStateSync();
|
||||
this._recordHistory('stopped', true);
|
||||
}
|
||||
if (!event.persisted) {
|
||||
releaseSessionArtwork?.();
|
||||
releaseSessionArtwork = sessionMetadataKey = null;
|
||||
pendingMedia = null;
|
||||
if (audioObjectUrl) detachAudio();
|
||||
}
|
||||
});
|
||||
window.addEventListener('pageshow', (event) => {
|
||||
if (event.persisted && this._historyRecorded) {
|
||||
@@ -946,19 +977,46 @@ document.addEventListener('alpine:init', () => {
|
||||
this._localSourceTrackId = track.id;
|
||||
this._historyRecorded = false;
|
||||
this._resetPlaybackTracking();
|
||||
audio.src = playbackSource(track);
|
||||
const seekSeconds = Number(options.position_seconds || 0);
|
||||
this.currentTime = seekSeconds;
|
||||
this.duration = Number(track.duration_seconds || 0);
|
||||
this.progress = this.duration > 0 ? seekSeconds / this.duration * 100 : 0;
|
||||
this._seekOnLoad(seekSeconds);
|
||||
if (options.paused) {
|
||||
this._updateMediaSession();
|
||||
return this._loadSource(track, seekSeconds, !!options.paused);
|
||||
},
|
||||
|
||||
async _loadSource(track, position, paused, recoverStream = false) {
|
||||
const offline = Alpine.store('offline');
|
||||
const localOnly = () => recoverStream || !!track.offline_remote || offline?.active || (offline?.enabled && navigator.onLine === false);
|
||||
this._seekOnLoad(0);
|
||||
pendingMedia = null;
|
||||
audibleTrackId = null;
|
||||
if (localOnly() || (offline?.enabled && offline.isSaved(track))) {
|
||||
// Media requests can fail in browser offline mode before reaching the service worker.
|
||||
// Keep the actual File in the media pipeline, with native seeking and streaming.
|
||||
const request = pendingMedia = {position, paused, recoverStream};
|
||||
detachAudio();
|
||||
this.isPlaying = false;
|
||||
const file = await offline.openAudio(track).catch(() => null);
|
||||
if (pendingMedia !== request) return;
|
||||
pendingMedia = null;
|
||||
if (file) audioObjectUrl = URL.createObjectURL(file);
|
||||
else if (localOnly()) {
|
||||
this._localSourceTrackId = null;
|
||||
return;
|
||||
}
|
||||
({position, paused} = request);
|
||||
} else if (audioObjectUrl) {
|
||||
detachAudio();
|
||||
}
|
||||
audio.src = audioObjectUrl || track.stream_url;
|
||||
this._seekOnLoad(position);
|
||||
if (paused) {
|
||||
audio.pause();
|
||||
this.isPlaying = false;
|
||||
} else {
|
||||
audio.play().catch(() => {});
|
||||
}
|
||||
this._updateMediaSession();
|
||||
},
|
||||
|
||||
_seekOnLoad(seconds) {
|
||||
@@ -974,6 +1032,9 @@ document.addEventListener('alpine:init', () => {
|
||||
},
|
||||
|
||||
_pauseLocal() {
|
||||
audibleTrackId = null;
|
||||
if (pendingMedia) pendingMedia.paused = true;
|
||||
if (playerOffline()) this._offlinePlaybackHeld = true;
|
||||
audio.pause();
|
||||
this.isPlaying = false;
|
||||
},
|
||||
@@ -982,7 +1043,9 @@ document.addEventListener('alpine:init', () => {
|
||||
// Read the online owner before offline mode makes this tab the active device.
|
||||
// Jam monitoring can play real local audio on a tab that only controls the owner.
|
||||
const ownedPlayback = this._isLocalPlaybackDevice();
|
||||
this._offlinePlaybackHeld = !ownedPlayback || !this.isPlaying || audio.paused || audio.ended ||
|
||||
const lostStream = (audio.error && audibleTrackId === this._localSourceTrackId) ||
|
||||
(pendingMedia?.recoverStream && !pendingMedia.paused);
|
||||
this._offlinePlaybackHeld = !ownedPlayback || ((!this.isPlaying || audio.paused) && !lostStream) || audio.ended ||
|
||||
!this.currentTrack || this.currentTrack.id !== this._localSourceTrackId;
|
||||
if (this._offlinePlaybackHeld) this._pauseLocal();
|
||||
if (!ownedPlayback) this._cachePlayCounted = false;
|
||||
@@ -991,28 +1054,38 @@ document.addEventListener('alpine:init', () => {
|
||||
useOfflineCatalog(saved) {
|
||||
const byId = new Map(saved.map(t => [Number(t.id), t]));
|
||||
const byContent = new Map(saved.filter(t => t.content_id).map(t => [t.content_id, t]));
|
||||
const lookup = t => t && (byId.get(OfflineCatalog.trackId(t)) || byContent.get(t.content_id));
|
||||
const lookup = track => {
|
||||
if (!track) return null;
|
||||
const local = byId.get(OfflineCatalog.trackId(track));
|
||||
return local && (!track.content_id || !local.content_id || local.content_id === track.content_id)
|
||||
? local : byContent.get(track.content_id);
|
||||
};
|
||||
const queue = Alpine.store('queue');
|
||||
queue.tracks = queue.tracks.map(lookup).filter(Boolean);
|
||||
const previous = this.currentTrack;
|
||||
const cached = lookup(previous);
|
||||
if (cached) {
|
||||
queue.syncCurrentIndexToTrack(cached);
|
||||
const playingHere = !this._offlinePlaybackHeld && !audio.paused && !audio.ended;
|
||||
if (!this._offlineSession || this._localSourceTrackId !== cached.id || this.isPlaying !== playingHere) {
|
||||
if ((audioObjectUrl || pendingMedia) && this._localSourceTrackId === previous.id) {
|
||||
// Already reading this recording locally. Keep its decoder, playhead and play count.
|
||||
this.currentTrack = this._historyTrack = cached;
|
||||
this._localSourceTrackId = cached.id;
|
||||
if (audibleTrackId === previous.id) audibleTrackId = cached.id;
|
||||
this._offlineSession = true;
|
||||
} else {
|
||||
const counted = this._cachePlayCounted;
|
||||
this._playLocal(cached, {paused:!playingHere, position_seconds:this.currentTime});
|
||||
this._playLocal(cached, {paused:this._offlinePlaybackHeld, position_seconds:this.currentTime});
|
||||
this._cachePlayCounted = counted;
|
||||
}
|
||||
} else if (previous) {
|
||||
this._offlineSession = true;
|
||||
this._seekOnLoad(0);
|
||||
this._pauseLocal();
|
||||
audio.removeAttribute('src');
|
||||
audio.load();
|
||||
pendingMedia = null;
|
||||
detachAudio();
|
||||
this.currentTrack = this._historyTrack = this._localSourceTrackId = null;
|
||||
this.currentTime = this.progress = this.duration = 0;
|
||||
if ('mediaSession' in navigator) navigator.mediaSession.metadata = null;
|
||||
this._updateMediaSession();
|
||||
}
|
||||
if (!cached) queue.currentIndex = -1;
|
||||
Alpine.store('offline').saveState(this._buildStatePayload(true));
|
||||
@@ -1038,22 +1111,29 @@ document.addEventListener('alpine:init', () => {
|
||||
this._remoteStateBaseTime = this.currentTime;
|
||||
this._remoteStateReceivedAt = Date.now();
|
||||
if (this._shouldMirrorRemoteLocally()) {
|
||||
audio.play().catch(() => {});
|
||||
this._resumeLocal();
|
||||
}
|
||||
this._sendRemote('resume');
|
||||
return;
|
||||
}
|
||||
this._offlinePlaybackHeld = false;
|
||||
if (playerOffline() && this.currentTrack && (!this._offlineSession || this._localSourceTrackId !== this.currentTrack.id)) {
|
||||
const offline = Alpine.store('offline');
|
||||
const retrySaved = audio.error && !audioObjectUrl && offline?.enabled && offline.isSaved(this.currentTrack);
|
||||
if (this.currentTrack && (retrySaved || (playerOffline() && (!this._offlineSession || this._localSourceTrackId !== this.currentTrack.id)))) {
|
||||
this._playLocal(this.currentTrack, {position_seconds:this.currentTime});
|
||||
return;
|
||||
}
|
||||
audio.play().catch(() => {});
|
||||
this._resumeLocal();
|
||||
},
|
||||
|
||||
_resumeLocal() {
|
||||
if (pendingMedia) pendingMedia.paused = false;
|
||||
else audio.play().catch(() => {});
|
||||
},
|
||||
|
||||
toggle() {
|
||||
if (!this.currentTrack) return;
|
||||
if (this.isPlaying) { this.pause(); }
|
||||
if (this.isPlaying || pendingMedia && !pendingMedia.paused) { this.pause(); }
|
||||
else { this.resume(); }
|
||||
},
|
||||
|
||||
@@ -1071,6 +1151,15 @@ document.addEventListener('alpine:init', () => {
|
||||
this._sendRemote('seek', { time: nextTime });
|
||||
return;
|
||||
}
|
||||
if (pendingMedia) {
|
||||
pendingMedia.position = this.currentTime = nextTime;
|
||||
return;
|
||||
}
|
||||
if (!audio.readyState) {
|
||||
this.currentTime = nextTime;
|
||||
this._seekOnLoad(nextTime);
|
||||
return;
|
||||
}
|
||||
audio.currentTime = nextTime;
|
||||
this._lastAudioTime = audio.currentTime || 0;
|
||||
},
|
||||
@@ -1078,7 +1167,7 @@ document.addEventListener('alpine:init', () => {
|
||||
seekRelative(delta) {
|
||||
if (!this.currentTrack) return;
|
||||
const duration = this.duration || audio.duration || 0;
|
||||
const current = this._shouldSendRemote() ? this.currentTime : audio.currentTime;
|
||||
const current = pendingMedia || !audio.readyState || this._shouldSendRemote() ? this.currentTime : audio.currentTime;
|
||||
const max = duration > 0 ? duration : Number.MAX_SAFE_INTEGER;
|
||||
this.seek(Math.max(0, Math.min(max, current + delta)));
|
||||
},
|
||||
@@ -1265,7 +1354,7 @@ document.addEventListener('alpine:init', () => {
|
||||
},
|
||||
|
||||
_applyRemotePlaybackState(state) {
|
||||
if (!state) return;
|
||||
if (!state || deviceSyncUnavailable()) return;
|
||||
const queue = Alpine.store('queue');
|
||||
const tracks = Array.isArray(state.tracks) ? state.tracks.filter(Boolean) : [];
|
||||
if (queue && tracks.length > 0) {
|
||||
@@ -1289,7 +1378,7 @@ document.addEventListener('alpine:init', () => {
|
||||
},
|
||||
|
||||
_syncLocalPlaybackState(state) {
|
||||
if (!state) return;
|
||||
if (!state || deviceSyncUnavailable()) return;
|
||||
const queue = Alpine.store('queue');
|
||||
const tracks = Array.isArray(state.tracks) ? state.tracks.filter(Boolean) : [];
|
||||
if (queue && tracks.length > 0) {
|
||||
@@ -1314,6 +1403,9 @@ document.addEventListener('alpine:init', () => {
|
||||
position_seconds: desiredTime,
|
||||
paused: !!state.paused,
|
||||
});
|
||||
} else if (pendingMedia) {
|
||||
pendingMedia.position = desiredTime;
|
||||
pendingMedia.paused = !!state.paused;
|
||||
} else {
|
||||
const drift = Math.abs((audio.currentTime || 0) - desiredTime);
|
||||
const driftLimit = state.paused ? 0.08 : 0.75;
|
||||
@@ -1351,7 +1443,7 @@ document.addEventListener('alpine:init', () => {
|
||||
},
|
||||
|
||||
_executeRemoteCommand(command) {
|
||||
if (!command || !command.command) return;
|
||||
if (!command?.command || deviceSyncUnavailable()) return;
|
||||
const payload = command.payload || {};
|
||||
const queue = Alpine.store('queue');
|
||||
this._remoteExecuting = true;
|
||||
@@ -1405,18 +1497,32 @@ document.addEventListener('alpine:init', () => {
|
||||
},
|
||||
|
||||
_updateMediaSession() {
|
||||
if (!('mediaSession' in navigator) || !this.currentTrack) return;
|
||||
if (!('mediaSession' in navigator)) return;
|
||||
const t = this.currentTrack;
|
||||
navigator.mediaSession.metadata = new MediaMetadata({
|
||||
title: t.title,
|
||||
artist: t.artists.map(a => a.name).join(', '),
|
||||
artwork: t.cover_url ? [{ src: coverVariantUrl(t.cover_url, 'large'), sizes: '512x512', type: 'image/jpeg' }] : [],
|
||||
});
|
||||
navigator.mediaSession.setActionHandler('play', () => this.resume());
|
||||
navigator.mediaSession.setActionHandler('pause', () => this.pause());
|
||||
navigator.mediaSession.setActionHandler('previoustrack', () => this.prev());
|
||||
navigator.mediaSession.setActionHandler('nexttrack', () => this.next());
|
||||
navigator.mediaSession.setActionHandler('seekto', (d) => { if (d.seekTime != null) this.seek(d.seekTime); });
|
||||
const artist = Array.isArray(t?.artists) ? t.artists.map(a => a?.name || a).join(', ') : '';
|
||||
const cover = typeof t?.cover_url === 'string' ? coverVariantUrl(t.cover_url, 'large') : null;
|
||||
const key = t && JSON.stringify([t.id, t.title, artist, cover, Alpine.store('offline').localArtworkOnly]);
|
||||
if (key === sessionMetadataKey) return;
|
||||
sessionMetadataKey = key;
|
||||
releaseSessionArtwork?.();
|
||||
releaseSessionArtwork = null;
|
||||
// OS media controls are optional. An unsupported action or image must never interrupt audio.
|
||||
try {
|
||||
const metadata = t ? new MediaMetadata({title:t.title, artist}) : null;
|
||||
navigator.mediaSession.metadata = metadata;
|
||||
if (!metadata) return;
|
||||
if (cover) releaseSessionArtwork = Alpine.store('offline').bindArtwork(cover, src => {
|
||||
try {
|
||||
// Firefox requires absolute URLs for MediaImage, including online covers.
|
||||
metadata.artwork = src ? [{src:new URL(src, document.baseURI).href}] : [];
|
||||
} catch { /* Keep the text if the platform rejects this artwork. */ }
|
||||
});
|
||||
navigator.mediaSession.setActionHandler('play', () => this.resume());
|
||||
navigator.mediaSession.setActionHandler('pause', () => this.pause());
|
||||
navigator.mediaSession.setActionHandler('previoustrack', () => this.prev());
|
||||
navigator.mediaSession.setActionHandler('nexttrack', () => this.next());
|
||||
navigator.mediaSession.setActionHandler('seekto', d => { if (d.seekTime != null) this.seek(d.seekTime); });
|
||||
} catch { /* Playback does not depend on Media Session support. */ }
|
||||
},
|
||||
|
||||
_buildStatePayload(forDeviceCache = false) {
|
||||
@@ -1518,9 +1624,8 @@ document.addEventListener('alpine:init', () => {
|
||||
this._localSourceTrackId = currentTrack.id;
|
||||
this._historyRecorded = false;
|
||||
this._resetPlaybackTracking();
|
||||
audio.src = playbackSource(currentTrack);
|
||||
// Seek to saved position once metadata is loaded
|
||||
this._seekOnLoad((state.position_ms || 0) / 1000);
|
||||
this.currentTime = (state.position_ms || 0) / 1000;
|
||||
this._loadSource(currentTrack, this.currentTime, true);
|
||||
this._updateMediaSession();
|
||||
}
|
||||
}
|
||||
@@ -1710,7 +1815,7 @@ document.addEventListener('alpine:init', () => {
|
||||
},
|
||||
|
||||
async _requestState(path, payload) {
|
||||
if (playerOffline()) return null;
|
||||
if (deviceSyncUnavailable()) return null;
|
||||
const {signal} = playbackConnection;
|
||||
const res = await fetch(path, {
|
||||
method: 'POST', headers: { 'Content-Type': 'application/json' },
|
||||
@@ -1718,11 +1823,11 @@ document.addEventListener('alpine:init', () => {
|
||||
});
|
||||
if (!res.ok) return null;
|
||||
const data = await res.json();
|
||||
return signal.aborted || playerOffline() ? null : data;
|
||||
return signal.aborted || deviceSyncUnavailable() ? null : data;
|
||||
},
|
||||
|
||||
async heartbeat() {
|
||||
if (playerOffline()) return;
|
||||
if (deviceSyncUnavailable()) return;
|
||||
try {
|
||||
const data = await this._requestState('/api/player/devices/heartbeat', this.requestPayload());
|
||||
if (data) this._apply(data);
|
||||
@@ -1730,7 +1835,7 @@ document.addEventListener('alpine:init', () => {
|
||||
},
|
||||
|
||||
async poll() {
|
||||
if (playerOffline()) return;
|
||||
if (deviceSyncUnavailable()) return;
|
||||
try {
|
||||
const data = await this._requestState('/api/player/devices/poll', this.requestPayload());
|
||||
if (!data) return;
|
||||
@@ -1758,7 +1863,7 @@ document.addEventListener('alpine:init', () => {
|
||||
},
|
||||
|
||||
_apply(data) {
|
||||
if (playerOffline()) return;
|
||||
if (deviceSyncUnavailable()) return;
|
||||
const previousJamId = this.currentJamId;
|
||||
this.activeDeviceId = data.active_device_id || null;
|
||||
this.devices = Array.isArray(data.devices) ? data.devices : [];
|
||||
@@ -1940,7 +2045,7 @@ document.addEventListener('alpine:init', () => {
|
||||
},
|
||||
|
||||
async loadFedDevices() {
|
||||
if (playerOffline()) return;
|
||||
if (deviceSyncUnavailable()) return;
|
||||
const {signal} = playbackConnection;
|
||||
try {
|
||||
const res = await fetch('/api/player/fed-devices', {signal});
|
||||
@@ -2062,7 +2167,7 @@ document.addEventListener('alpine:init', () => {
|
||||
},
|
||||
|
||||
async select(deviceId) {
|
||||
if (!deviceId || playerOffline()) return;
|
||||
if (!deviceId || deviceSyncUnavailable()) return;
|
||||
const player = Alpine.store('player');
|
||||
|
||||
try {
|
||||
@@ -2086,7 +2191,7 @@ document.addEventListener('alpine:init', () => {
|
||||
},
|
||||
|
||||
async sendCommand(command, payload = {}, targetDeviceId = null) {
|
||||
if (playerOffline()) return false;
|
||||
if (deviceSyncUnavailable()) return false;
|
||||
const jamId = this.isControllingRemoteJam() ? this.currentJamId : null;
|
||||
const target = jamId ? null : (targetDeviceId || this.activeDeviceId);
|
||||
if (!jamId && (!target || target === this.id)) return false;
|
||||
|
||||
+13
-13
@@ -214,7 +214,7 @@
|
||||
<div class="search-artist-img">
|
||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"><circle cx="12" cy="8" r="4"/><path d="M20 21a8 8 0 10-16 0"/></svg>
|
||||
<template x-if="$store.library.localSearchArtwork('artists', artist)">
|
||||
<img class="artwork-image" :src="$store.library.localSearchArtwork('artists', artist) || null" alt="" aria-hidden="true" loading="lazy" @load="$event.currentTarget.classList.add('artwork-loaded')" @error="$store.library.federationArtworkFailed($event.currentTarget)">
|
||||
<img class="artwork-image" x-artwork="$store.library.localSearchArtwork('artists', artist) || null" alt="" aria-hidden="true" loading="lazy" @load="$event.currentTarget.classList.add('artwork-loaded')" @error="$store.library.federationArtworkFailed($event.currentTarget)">
|
||||
</template>
|
||||
</div>
|
||||
<div class="search-artist-name"><a class="artist-link"
|
||||
@@ -239,7 +239,7 @@
|
||||
<div class="search-release-cover" style="position:relative">
|
||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"><rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="12" cy="12" r="4"/></svg>
|
||||
<template x-if="$store.library.localSearchArtwork('releases', release)">
|
||||
<img class="artwork-image" :src="$store.library.localSearchArtwork('releases', release) || null" alt="" aria-hidden="true" loading="lazy" @load="$event.currentTarget.classList.add('artwork-loaded')" @error="$store.library.federationArtworkFailed($event.currentTarget)">
|
||||
<img class="artwork-image" x-artwork="$store.library.localSearchArtwork('releases', release) || null" alt="" aria-hidden="true" loading="lazy" @load="$event.currentTarget.classList.add('artwork-loaded')" @error="$store.library.federationArtworkFailed($event.currentTarget)">
|
||||
</template>
|
||||
<button class="card-info-btn" @click.stop="$store.library.openReleaseInfo(release)" :title="$store.library.releaseInfo(release)" aria-label="{{ t.player_release_info }}">
|
||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="12" y1="16" x2="12" y2="12"/><line x1="12" y1="8" x2="12.01" y2="8"/></svg>
|
||||
@@ -348,7 +348,7 @@
|
||||
<div class="card" @click="$store.library.openArtist(artist.id)">
|
||||
<div class="card-img">
|
||||
<template x-if="artist.image_url">
|
||||
<img :src="artist.image_url" alt="" aria-hidden="true" loading="lazy">
|
||||
<img x-artwork="artist.image_url" alt="" aria-hidden="true" loading="lazy">
|
||||
</template>
|
||||
<template x-if="!artist.image_url">
|
||||
<span class="placeholder-icon"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"><circle cx="12" cy="8" r="4"/><path d="M20 21a8 8 0 10-16 0"/></svg></span>
|
||||
@@ -406,7 +406,7 @@
|
||||
<div class="artist-header">
|
||||
<div class="artist-img">
|
||||
<template x-if="$store.library.currentArtist.image_url">
|
||||
<img :src="$store.library.currentArtist.image_url"
|
||||
<img x-artwork="$store.library.currentArtist.image_url"
|
||||
alt="" aria-hidden="true"
|
||||
@error="$store.library.currentArtist.image_url = null">
|
||||
</template>
|
||||
@@ -465,7 +465,7 @@
|
||||
<div class="card" @click="$store.library.openRelease(release.id)">
|
||||
<div class="card-img">
|
||||
<template x-if="release.cover_url">
|
||||
<img :src="release.cover_url" alt="" aria-hidden="true"
|
||||
<img x-artwork="release.cover_url" alt="" aria-hidden="true"
|
||||
loading="lazy" @error="release.cover_url = null">
|
||||
</template>
|
||||
<template x-if="!release.cover_url">
|
||||
@@ -501,7 +501,7 @@
|
||||
@click="$store.library.openFederatedRelease(release)">
|
||||
<div class="card-img">
|
||||
<template x-if="release.cover_url">
|
||||
<img :src="release.cover_url" alt="" aria-hidden="true"
|
||||
<img x-artwork="release.cover_url" alt="" aria-hidden="true"
|
||||
loading="lazy" @error="release.cover_url = null">
|
||||
</template>
|
||||
<template x-if="!release.cover_url">
|
||||
@@ -618,7 +618,7 @@
|
||||
:title="track.release_title"
|
||||
aria-label="{{ t.player_release }}">
|
||||
<template x-if="track.cover_url">
|
||||
<img :src="track.cover_url" alt="" aria-hidden="true" loading="lazy">
|
||||
<img x-artwork="track.cover_url" alt="" aria-hidden="true" loading="lazy">
|
||||
</template>
|
||||
<template x-if="!track.cover_url">
|
||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"><rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="12" cy="12" r="4"/></svg>
|
||||
@@ -675,7 +675,7 @@
|
||||
<div class="release-header">
|
||||
<div class="release-cover">
|
||||
<template x-if="$store.library.currentRelease.cover_url">
|
||||
<img :src="$store.library.currentRelease.cover_url" alt="" aria-hidden="true"
|
||||
<img x-artwork="$store.library.currentRelease.cover_url" alt="" aria-hidden="true"
|
||||
@error="$store.library.releaseArtworkFailed($el)">
|
||||
</template>
|
||||
<template x-if="!$store.library.currentRelease.cover_url">
|
||||
@@ -921,7 +921,7 @@
|
||||
<div class="queue-track-cover">
|
||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"><path d="M9 18V5l12-2v13"/><circle cx="6" cy="18" r="3"/><circle cx="18" cy="16" r="3"/></svg>
|
||||
<template x-if="item.track.cover_url">
|
||||
<img class="artwork-image" :src="item.track.cover_url" alt="" aria-hidden="true" loading="lazy" @load="$event.currentTarget.classList.add('artwork-loaded')" @error="$event.currentTarget.classList.remove('artwork-loaded')">
|
||||
<img class="artwork-image" x-artwork="item.track.cover_url" alt="" aria-hidden="true" loading="lazy" @load="$event.currentTarget.classList.add('artwork-loaded')" @error="$event.currentTarget.classList.remove('artwork-loaded')">
|
||||
</template>
|
||||
<span class="queue-federation-status federation-track-status"
|
||||
x-show="item.track.federation_pending"
|
||||
@@ -1004,7 +1004,7 @@
|
||||
@pointerenter="hover($event)" @pointerleave="leave($event)"
|
||||
@keydown.space.stop @click.stop="activate($event)">
|
||||
<template x-if="$store.player.currentTrack.cover_url">
|
||||
<img :src="$store.player.currentTrack.cover_url" alt="" aria-hidden="true">
|
||||
<img x-artwork="$store.player.currentTrack.cover_url" alt="" aria-hidden="true">
|
||||
</template>
|
||||
<template x-if="!$store.player.currentTrack.cover_url">
|
||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"><path d="M9 18V5l12-2v13"/><circle cx="6" cy="18" r="3"/><circle cx="18" cy="16" r="3"/></svg>
|
||||
@@ -1015,8 +1015,8 @@
|
||||
:class="{ 'player-cover-preview-centered': $store.mobile.playerExpanded }"
|
||||
@pointerenter="hover($event)" @pointerleave="leave($event)" @click="pin()">
|
||||
<template x-if="visible && artwork">
|
||||
<img :src="coverVariantUrl(artwork, 'large')" :alt="$store.player.currentTrack?.release_title || $store.player.currentTrack?.title"
|
||||
@error="if ($el.getAttribute('src') !== artwork) $el.src = artwork; else closePreview()">
|
||||
<img x-artwork="coverVariantUrl(artwork, 'large')" :alt="$store.player.currentTrack?.release_title || $store.player.currentTrack?.title"
|
||||
@error="if (!$store.offline.localArtworkOnly && $el.getAttribute('src') !== artwork) $el.src = artwork; else closePreview()">
|
||||
</template>
|
||||
</div>
|
||||
</template>
|
||||
@@ -1314,7 +1314,7 @@
|
||||
<div class="mobile-expanded-queue-cover">
|
||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"><path d="M9 18V5l12-2v13"/><circle cx="6" cy="18" r="3"/><circle cx="18" cy="16" r="3"/></svg>
|
||||
<template x-if="item.track.cover_url">
|
||||
<img class="artwork-image" :src="item.track.cover_url" alt="" aria-hidden="true" loading="lazy" @load="$event.currentTarget.classList.add('artwork-loaded')" @error="$event.currentTarget.classList.remove('artwork-loaded')">
|
||||
<img class="artwork-image" x-artwork="item.track.cover_url" alt="" aria-hidden="true" loading="lazy" @load="$event.currentTarget.classList.add('artwork-loaded')" @error="$event.currentTarget.classList.remove('artwork-loaded')">
|
||||
</template>
|
||||
</div>
|
||||
<div class="mobile-expanded-queue-info">
|
||||
|
||||
@@ -17,6 +17,8 @@ const {chromium} = require(process.env.PLAYWRIGHT_MODULE || 'playwright');
|
||||
const tracks = [21,22,23].map((id,index) => ({id,title:'Song '+id,content_id:'b3:'+(id===23?'2':'1').repeat(64),
|
||||
artists:[owner],featured_artists:[artist],release_id:id===22?38:37,release_title:'Album '+index,
|
||||
stream_url:api+'stream/'+id,cover_url:api+'cover/13/small',file_size_bytes:6,has_lyrics:true}));
|
||||
// A recording without its own picture still has the already saved album cover.
|
||||
tracks[1].cover_url = null;
|
||||
const requests = [], bytes = new Uint8Array([0,1,2,3,4,5]);
|
||||
async function online(url, options = {}) {
|
||||
requests.push(url);
|
||||
@@ -40,6 +42,27 @@ const {chromium} = require(process.env.PLAYWRIGHT_MODULE || 'playwright');
|
||||
await Promise.all([repo.save(queueBefore[0],{fetch:online,limitBytes:100}),peerTab.save(tracks[1],{fetch:online,limitBytes:100})]);
|
||||
const queueAfter = await repo.pending();
|
||||
const afterSave = await repo.list();
|
||||
const inspectAudio = async (store, track) => {
|
||||
const blob = await store.openAudio(track);
|
||||
return blob && [blob.type, [...new Uint8Array(await blob.arrayBuffer())]];
|
||||
};
|
||||
const direct = {
|
||||
local:await inspectAudio(repo,21),
|
||||
alias:await inspectAudio(repo,{id:1234,content_id:tracks[0].content_id}),
|
||||
changedRecording:await inspectAudio(repo,{id:21,content_id:tracks[2].content_id}),
|
||||
otherAccount:await inspectAudio(otherAccount,tracks[0]),
|
||||
};
|
||||
// Old, unhashed downloads can have a generic MIME and an extensionless OPFS filename.
|
||||
const legacy = new OfflineCatalog(104);
|
||||
const oldTrack = {...tracks[0],content_id:null,audio_format:'MP3'};
|
||||
await legacy.save(oldTrack,{fetch:(url,options) => url === oldTrack.stream_url
|
||||
? new Response(bytes,{headers:{'Content-Type':'application/octet-stream'}}) : online(url,options)});
|
||||
direct.legacy = await inspectAudio(legacy,tracks[0]);
|
||||
direct.legacyById = await inspectAudio(legacy,oldTrack.id);
|
||||
const entry = await legacy.read('files','track:'+oldTrack.id);
|
||||
await (await legacy.directory()).removeEntry(entry.name);
|
||||
direct.missingFile = await inspectAudio(legacy,oldTrack);
|
||||
await legacy.clear();
|
||||
const beforeRemove = await repo.stats();
|
||||
const accountSeparated = await otherAccount.stats();
|
||||
const catalog = (await get('artists')).items;
|
||||
@@ -83,6 +106,9 @@ const {chromium} = require(process.env.PLAYWRIGHT_MODULE || 'playwright');
|
||||
throw new Error('Unexpected remote path '+path);
|
||||
}});
|
||||
const [local] = await repo.list();
|
||||
direct.federated = await inspectAudio(repo,federated);
|
||||
direct.synthetic = await inspectAudio(repo,local.id);
|
||||
direct.federatedId = await inspectAudio(repo,federated.id);
|
||||
await repo.observe(api+'tracks/content/like',[content,'b3:'+'c'.repeat(64)]);
|
||||
const remoteLikes = {
|
||||
contents:await get('tracks/content/like'),
|
||||
@@ -138,11 +164,15 @@ 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,emptyContentLikes,legacyContentLikes,remoteLikes};
|
||||
mediaRequests,remoteDetails,direct,notFound,cleanup,emptyContentLikes,legacyContentLikes,remoteLikes};
|
||||
});
|
||||
assert.equal(results.queueBefore,1);
|
||||
assert.equal(results.queueAfter,0);
|
||||
const bytes = [0,1,2,3,4,5], mp3 = ['audio/mpeg',bytes], wav = ['audio/wav',bytes];
|
||||
assert.deepEqual(results.direct,{local:mp3,alias:mp3,changedRecording:null,otherAccount:null,
|
||||
legacy:mp3,legacyById:mp3,missingFile:null,federated:wav,synthetic:wav,federatedId:wav});
|
||||
assert.equal(results.afterSave.find(t=>t.id===21).play_count,2);
|
||||
assert.equal(results.afterSave.find(t=>t.id===22).cover_url,'/api/player/cover/13/large');
|
||||
assert.ok(results.afterSave.every(t => t.downloaded_at>0));
|
||||
assert.deepEqual(results.beforeRemove,{tracks:2,bytes:8});
|
||||
assert.deepEqual(results.accountSeparated,{tracks:0,bytes:0});
|
||||
|
||||
@@ -9,16 +9,17 @@ const {chromium} = require(process.env.PLAYWRIGHT_MODULE || 'playwright');
|
||||
const player = path.resolve(__dirname, '../src/player');
|
||||
const html = fs.readFileSync('target/podcast-player-fixture.html','utf8');
|
||||
const rate = 8000, seconds = 24, wav = Buffer.alloc(44 + rate * 2 * seconds);
|
||||
const png = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+ip1sAAAAASUVORK5CYII=', 'base64');
|
||||
wav.write('RIFF'); wav.writeUInt32LE(wav.length-8,4); wav.write('WAVEfmt ',8);
|
||||
wav.writeUInt32LE(16,16); wav.writeUInt16LE(1,20); wav.writeUInt16LE(1,22);
|
||||
wav.writeUInt32LE(rate,24); wav.writeUInt32LE(rate*2,28); wav.writeUInt16LE(2,32);
|
||||
wav.writeUInt16LE(16,34); wav.write('data',36); wav.writeUInt32LE(wav.length-44,40);
|
||||
const artist = {id:7,name:'Offline band',image_url:null,release_count:1,track_count:2};
|
||||
const tracks = [1,2].map(id => ({id,content_id:'b3:'+String(id).repeat(64),title:'Recording '+id,
|
||||
const artist = {id:7,name:'Offline band',image_url:null,release_count:1,track_count:3};
|
||||
const tracks = [1,2,3].map(id => ({id,content_id:'b3:'+String(id).repeat(64),title:'Recording '+id,
|
||||
release_id:9,release_title:'Offline album',release_year:2010,artists:[{id:7,name:artist.name}],featured_artists:[],
|
||||
cover_url:null,track_number:id,duration_seconds:seconds,stream_url:'/api/player/stream/'+id,file_size_bytes:wav.length,
|
||||
cover_url:'/api/player/cover/'+id+'/small',track_number:id,duration_seconds:seconds,stream_url:'/api/player/stream/'+id,file_size_bytes:wav.length,
|
||||
has_lyrics:true,audio_format:'WAV'}));
|
||||
const release = {id:9,title:'Offline album',year:2010,artists:[artist],tracks,release_type:'Album',uploaders:[]};
|
||||
const release = {id:9,title:'Offline album',year:2010,cover_url:tracks[0].cover_url,artists:[artist],tracks,release_type:'Album',uploaders:[]};
|
||||
const token = 'd'.repeat(64), remoteUrl = '/api/player/federation/cache/'+token;
|
||||
const prepared = {id:'fed:b3:'+token,content_id:'b3:'+token,title:'Federated recording',release_title:'Remote release',
|
||||
artists:[{name:'Remote artist'}],duration_seconds:seconds,stream_url:remoteUrl,federated_cache:true};
|
||||
@@ -26,6 +27,21 @@ const text = {versions:[{id:'v1',label:'Words',plain_text:'Words from the saved
|
||||
const assets = {'/offline-worker.js':'text/javascript','/offline-catalog.js':'text/javascript',
|
||||
'/player.webmanifest':'application/manifest+json','/player-icon.svg':'image/svg+xml'};
|
||||
|
||||
async function waitForCachedAudio(page, trackId, after = .25) {
|
||||
await page.waitForFunction(([id, seconds]) => {
|
||||
const audio = window.playingAudio;
|
||||
return Alpine.store('player').currentTrack?.id === id && audio?.currentSrc.startsWith('blob:') &&
|
||||
!audio.paused && !audio.seeking && audio.currentTime > seconds;
|
||||
}, [trackId,after], {timeout: 8000});
|
||||
}
|
||||
|
||||
async function waitForCachedCovers(page, selectors) {
|
||||
await page.waitForFunction(selectors => selectors.every(selector => {
|
||||
const img = document.querySelector(selector);
|
||||
return img?.naturalWidth === 1 && /^(blob:|data:)/.test(img.currentSrc);
|
||||
}), selectors);
|
||||
}
|
||||
|
||||
(async () => {
|
||||
assert.ok(html.includes('data-offline-account="1"'),'render the current member player fixture first');
|
||||
let down = false, remoteOwner = null;
|
||||
@@ -38,6 +54,10 @@ const assets = {'/offline-worker.js':'text/javascript','/offline-catalog.js':'te
|
||||
if (down) {res.writeHead(503); return res.end();}
|
||||
if (p === '/') { res.setHeader('X-Furumusic-Player-Account','1'); res.setHeader('Content-Type','text/html'); return res.end(html); }
|
||||
if (p === '/offline-probe') {res.writeHead(204,{'X-Furumusic-Player-Account':'1'}); return res.end();}
|
||||
if (/^\/api\/player\/cover\/\d+\/(small|medium|large)$/.test(p)) {
|
||||
res.setHeader('Content-Type','image/png');
|
||||
return res.end(png);
|
||||
}
|
||||
if (p.includes('/stream/') || p === remoteUrl) {
|
||||
const range = /^bytes=(\d+)-(\d*)$/.exec(req.headers.range || '');
|
||||
const first = range ? Number(range[1]) : 0, last = range && range[2] ? Math.min(Number(range[2]),wav.length-1) : wav.length-1;
|
||||
@@ -55,8 +75,9 @@ const assets = {'/offline-worker.js':'text/javascript','/offline-catalog.js':'te
|
||||
const results = {
|
||||
'/api/player/me':{id:1,name:'Member',role:'user',stats:{}},
|
||||
'/api/player/artists':{items:[artist],page:1,total:1,per_page:80,has_more:false},
|
||||
'/api/player/artists/7':{...artist,releases:[release],top_tracks:tracks,featured_tracks:[],total_track_count:2},
|
||||
'/api/player/artists/7':{...artist,releases:[release],top_tracks:tracks,featured_tracks:[],total_track_count:tracks.length},
|
||||
'/api/player/releases/9':release, '/api/player/likes':{track_ids:[1]},
|
||||
'/api/player/playlists/-1':{id:-1,title:'Likes',kind:'likes',is_own:true,cover_urls:[tracks[0].cover_url],tracks:[tracks[0]]},
|
||||
'/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,
|
||||
@@ -81,12 +102,20 @@ const assets = {'/offline-worker.js':'text/javascript','/offline-catalog.js':'te
|
||||
const play = HTMLMediaElement.prototype.play;
|
||||
window.audioPlayCalls = 0;
|
||||
HTMLMediaElement.prototype.play = function(...args) {
|
||||
if (this instanceof HTMLAudioElement) window.audioPlayCalls++;
|
||||
if (this instanceof HTMLAudioElement) {
|
||||
window.audioPlayCalls++;
|
||||
window.playingAudio = this;
|
||||
}
|
||||
return play.apply(this,args);
|
||||
};
|
||||
});
|
||||
const errors = [];
|
||||
page.on('pageerror',e=>errors.push(e.message));
|
||||
const httpMedia = [], httpCovers = [];
|
||||
page.on('request', req => {
|
||||
if (req.resourceType() === 'media' && /^https?:/.test(req.url())) httpMedia.push(req.url());
|
||||
if (req.url().startsWith(base+'/api/player/cover/')) httpCovers.push(req.url());
|
||||
});
|
||||
try {
|
||||
const releaseRow = page.locator('.track-row[data-shared-track-id="1"]');
|
||||
const account = page.locator('.sidebar-account-trigger');
|
||||
@@ -104,7 +133,41 @@ const assets = {'/offline-worker.js':'text/javascript','/offline-catalog.js':'te
|
||||
await releaseRow.dblclick();
|
||||
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);
|
||||
assert.equal(await page.evaluate(() => Alpine.store('offline').bytes),wav.length+png.length);
|
||||
await page.evaluate(track => Alpine.store('offline').saveTrack(track),tracks[1]);
|
||||
await page.waitForFunction(() => Alpine.store('offline').items.length === 2);
|
||||
|
||||
// Disconnect during the first play, which started on HTTP before the cache was populated.
|
||||
await page.evaluate(() => Alpine.store('player').seek(12));
|
||||
await page.waitForFunction(() => window.playingAudio.currentTime > 12);
|
||||
const position = await page.evaluate(() => window.playingAudio.currentTime);
|
||||
const beforeDisconnect = httpMedia.length;
|
||||
const devtools = await context.newCDPSession(page);
|
||||
await devtools.send('Network.enable');
|
||||
await devtools.send('Network.setCacheDisabled', {cacheDisabled:true});
|
||||
await context.setOffline(true);
|
||||
await page.waitForFunction(() => Alpine.store('offline').automatic);
|
||||
await waitForCachedAudio(page, 1, position);
|
||||
await waitForCachedCovers(page, ['.release-cover img', '.player-cover img']);
|
||||
const coversAtDisconnect = httpCovers.length;
|
||||
await page.evaluate(() => Alpine.store('player').next());
|
||||
await waitForCachedAudio(page, 2);
|
||||
await page.evaluate(pos => Alpine.store('player').seek(pos),seconds / 2);
|
||||
await waitForCachedAudio(page, 2, seconds / 2);
|
||||
await page.goto(base+'/#playlist/-1');
|
||||
await page.waitForFunction(() => Alpine.store('library').currentPlaylist?.id === -1);
|
||||
await waitForCachedCovers(page, ['.playlist-heading-cover img', '.player-cover img']);
|
||||
await page.locator('.playlist-track-row[data-playlist-index="0"]').dblclick();
|
||||
await waitForCachedAudio(page, 1);
|
||||
assert.deepEqual(httpCovers.slice(coversAtDisconnect), [], 'opening likes and switching tracks do not request HTTP artwork');
|
||||
assert.deepEqual(httpMedia.slice(beforeDisconnect), [], 'playback and seeking use local files without HTTP media requests');
|
||||
await context.setOffline(false);
|
||||
await devtools.send('Network.setCacheDisabled', {cacheDisabled:false});
|
||||
await devtools.detach();
|
||||
await page.waitForFunction(() => !Alpine.store('offline').active);
|
||||
await page.goto(base+'/#release/9');
|
||||
await releaseRow.dblclick();
|
||||
await waitForCachedAudio(page, 1);
|
||||
// A second, forgotten tab sees the playing track through device sync.
|
||||
remoteOwner = await page.evaluate(() => Alpine.store('devices').id);
|
||||
const controller = await context.newPage();
|
||||
@@ -130,12 +193,12 @@ const assets = {'/offline-worker.js':'text/javascript','/offline-catalog.js':'te
|
||||
await page.goto(base+'/#artist/7');
|
||||
await page.reload();
|
||||
await page.waitForFunction(() => Alpine.store('offline').active && Alpine.store('library').currentArtist?.id === 7);
|
||||
assert.deepEqual(await page.evaluate(() => Alpine.store('library').currentArtist.releases.map(r=>[r.id,r.track_count])),[[9,1]]);
|
||||
assert.deepEqual(await page.evaluate(() => Alpine.store('library').currentArtist.releases.map(r=>[r.id,r.track_count])),[[9,2]]);
|
||||
await page.goto(base+'/#release/9');
|
||||
await releaseRow.waitFor();
|
||||
assert.equal(await page.locator('.track-row[data-shared-track-id]').count(),1);
|
||||
assert.equal(await page.locator('.track-row[data-shared-track-id]').count(),2);
|
||||
await releaseRow.dblclick();
|
||||
await page.waitForFunction(() => Alpine.store('player').isPlaying && Alpine.store('player').currentTime > .3);
|
||||
await waitForCachedAudio(page, 1);
|
||||
const offlineDetails = await page.evaluate(async () => {
|
||||
const response = await fetch('/api/player/stream/1',{headers:{Range:'bytes=0-3'}});
|
||||
return [response.status,await response.text(),(await (await fetch('/api/player/lyrics/1')).json()).versions[0].plain_text];
|
||||
@@ -153,7 +216,7 @@ const assets = {'/offline-worker.js':'text/javascript','/offline-catalog.js':'te
|
||||
down = true;
|
||||
await page.reload();
|
||||
await page.waitForFunction(() => Alpine.store('offline').automatic && Alpine.store('library').currentRelease?.id === 9);
|
||||
assert.equal(await page.locator('.track-row[data-shared-track-id]').count(),1);
|
||||
assert.equal(await page.locator('.track-row[data-shared-track-id]').count(),2);
|
||||
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.
|
||||
@@ -165,15 +228,14 @@ const assets = {'/offline-worker.js':'text/javascript','/offline-catalog.js':'te
|
||||
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);
|
||||
!Alpine.store('library')._artistFederationSource && Alpine.store('library').currentArtist?.top_tracks?.length === 2);
|
||||
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);
|
||||
await waitForCachedAudio(page, 1);
|
||||
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();
|
||||
|
||||
@@ -8,7 +8,7 @@ const player = path.join(__dirname, '..', 'src', 'player');
|
||||
const catalog = fs.readFileSync(path.join(player, 'offline-catalog.js'), 'utf8');
|
||||
|
||||
(async () => {
|
||||
let account = '17', unavailable = false, authOutage = false, hangingRequest;
|
||||
let account = '17', unavailable = false, authOutage = false, dropProbe = false, hangingRequest;
|
||||
const log = [];
|
||||
const server = http.createServer((req,res) => {
|
||||
const url = new URL(req.url, 'http://localhost');
|
||||
@@ -24,6 +24,7 @@ const catalog = fs.readFileSync(path.join(player, 'offline-catalog.js'), 'utf8')
|
||||
if (authOutage && url.pathname === '/offline-probe') { res.statusCode = 500; return res.end(); }
|
||||
if (url.pathname === '/logout') { account = ''; return res.end('logged out'); }
|
||||
if (url.pathname === '/offline-probe') {
|
||||
if (dropProbe) return req.socket.destroy();
|
||||
res.setHeader('X-Furumusic-Player-Account',account || '0');
|
||||
res.statusCode = account ? 204 : 401;
|
||||
return res.end();
|
||||
@@ -116,6 +117,10 @@ const catalog = fs.readFileSync(path.join(player, 'offline-catalog.js'), 'utf8')
|
||||
|
||||
await mode('auto');
|
||||
assert.equal(await page.evaluate(() => fetch('/offline-probe').then(r=>r.status)),204);
|
||||
dropProbe = true;
|
||||
assert.equal(await page.evaluate(() => fetch('/offline-probe').then(r=>r.status)),503,
|
||||
'a disconnected probe gets an unavailable response from the worker');
|
||||
dropProbe = false;
|
||||
await mode('online');
|
||||
assert.equal(await page.evaluate(() => fetch('/api/player/me').then(r=>r.json()).then(p=>p.name)), 'Network');
|
||||
authOutage = true;
|
||||
|
||||
@@ -8,11 +8,37 @@ const storesSource = template.slice(template.indexOf(' let playbackConnection
|
||||
const offline = readFileSync(__dirname + '/../templates/player/offline_scripts.html', 'utf8');
|
||||
const applySource = offline.slice(offline.indexOf(' apply(mode)'), offline.indexOf(' async captureLibrary()'));
|
||||
|
||||
test('catalog requests stay on the device as soon as the browser disables networking', async () => {
|
||||
const location = new URL('https://example.test/');
|
||||
const navigator = {onLine:false};
|
||||
const store = {enabled:true, supported:true, active:false, automatic:false, localResponse: async () => Response.json(['saved'])};
|
||||
const requests = [];
|
||||
const window = {location, Alpine:{store:() => store}, fetch: async input => {
|
||||
requests.push(input);
|
||||
return new Response(null, {status:204});
|
||||
}};
|
||||
const fetchSource = template.slice(template.indexOf('const playerFetch ='), template.indexOf('const T ='));
|
||||
vm.runInNewContext(fetchSource, {location, navigator, window, URL, Request, Response});
|
||||
assert.deepEqual(await (await window.fetch('/api/player/playlists/-1')).json(), ['saved']);
|
||||
store.active = store.automatic = true;
|
||||
assert.equal((await window.fetch('/offline-probe')).status, 503);
|
||||
assert.deepEqual(requests, []);
|
||||
navigator.onLine = true;
|
||||
assert.equal((await window.fetch('/offline-probe')).status, 204);
|
||||
assert.deepEqual(requests, ['/offline-probe']);
|
||||
});
|
||||
|
||||
function setup(fetch) {
|
||||
const stores = {offline: {active: true, saveState() {}, scheduleProbe() {}}};
|
||||
const stores = {offline: {active: true, saveState() {}, scheduleProbe() {}, played() {}, drain() {},
|
||||
isSaved: () => true, openAudio: async track => new Blob([String(track.id)])}};
|
||||
const created = [], revoked = [];
|
||||
const window = new EventTarget();
|
||||
const navigator = {onLine:true};
|
||||
const audio = Object.assign(new EventTarget(), {
|
||||
paused: true, ended: false, playCalls: 0,
|
||||
paused: true, ended: false, playCalls: 0, readyState: 0,
|
||||
hasAttribute(name) {return this[name] != null;},
|
||||
removeAttribute(name) {delete this[name];},
|
||||
load() {this.paused = true; this.readyState = 0; this.error = null;},
|
||||
async play() {
|
||||
++this.playCalls;
|
||||
this.paused = false;
|
||||
@@ -29,16 +55,21 @@ function setup(fetch) {
|
||||
};
|
||||
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,
|
||||
audio, navigator, window, document, sessionStorage, AbortController, fetch, CustomEvent,
|
||||
retryTimer: 0, transfer: null, URL: {
|
||||
createObjectURL(file) {created.push(file); return 'blob:test/' + created.length;},
|
||||
revokeObjectURL(url) {revoked.push(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')};
|
||||
return {stores, audio, created, revoked, navigator, mode: active => stores.offline.apply(active ? 'auto' : 'online')};
|
||||
}
|
||||
|
||||
const settle = () => new Promise(resolve => setImmediate(resolve));
|
||||
|
||||
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;
|
||||
@@ -64,6 +95,7 @@ for (const monitoring of [true, false]) test('a former remote controller stays s
|
||||
audio.dispatchEvent(new Event('playing'));
|
||||
assert.equal(nextCalls, 0);
|
||||
player.useOfflineCatalog([saved]);
|
||||
await settle();
|
||||
assert.equal(devices.isActive(), true);
|
||||
assert.equal(devices.selectedJam(), null);
|
||||
assert.equal(player._shouldSendRemote(), false);
|
||||
@@ -79,7 +111,7 @@ for (const monitoring of [true, false]) test('a former remote controller stays s
|
||||
assert.equal(await devices.sendCommand('pause'), false);
|
||||
});
|
||||
|
||||
test('only the online owner playing the displayed recording continues from cache', () => {
|
||||
test('only the online owner playing the displayed recording continues from cache', async () => {
|
||||
for (const [owner, paused, source, continues] of [
|
||||
['here', false, 3, true], ['here', true, 3, false], ['here', false, 4, false], ['other', false, 3, false],
|
||||
]) {
|
||||
@@ -94,11 +126,113 @@ test('only the online owner playing the displayed recording continues from cache
|
||||
audio.paused = paused;
|
||||
mode(true);
|
||||
stores.player.useOfflineCatalog([saved]);
|
||||
await settle();
|
||||
assert.equal(!audio.paused, continues);
|
||||
assert.equal(audio.playCalls, continues ? 1 : 0);
|
||||
}
|
||||
});
|
||||
|
||||
test('cached online playback keeps the same blob and position when entering offline mode', async () => {
|
||||
const {stores, audio, created, revoked, mode} = setup(() => assert.fail('Unexpected network request'));
|
||||
const saved = {id:3, content_id:'recording', stream_url:'/api/player/stream/3'};
|
||||
const duplicate = {...saved, id:4};
|
||||
stores.queue = {tracks:[saved, duplicate], syncCurrentIndexToTrack() {}};
|
||||
mode(false);
|
||||
stores.offline.enabled = true;
|
||||
await stores.player._playLocal(saved);
|
||||
assert.equal(audio.src, 'blob:test/1');
|
||||
audio.currentTime = 9;
|
||||
mode(true);
|
||||
stores.player.useOfflineCatalog([saved, duplicate]);
|
||||
assert.equal(stores.player.currentTrack.id, 3);
|
||||
assert.deepEqual(stores.queue.tracks.map(track => track.id), [3,4]);
|
||||
assert.equal(audio.currentTime, 9);
|
||||
assert.equal(audio.playCalls, 1);
|
||||
assert.equal(created.length, 1);
|
||||
assert.deepEqual(revoked, []);
|
||||
stores.player.useOfflineCatalog([]);
|
||||
assert.equal(audio.src, undefined);
|
||||
assert.deepEqual(revoked, ['blob:test/1']);
|
||||
});
|
||||
|
||||
test('a failed HTTP source resumes from cache only if it was playing when the network failed', async () => {
|
||||
for (const paused of [false, true]) {
|
||||
const {stores, audio, mode} = setup(() => assert.fail('Unexpected network request'));
|
||||
const saved = {id:3, stream_url:'/api/player/stream/3'};
|
||||
stores.queue = {tracks:[saved], syncCurrentIndexToTrack() {}};
|
||||
mode(false);
|
||||
await stores.player._playLocal(saved);
|
||||
audio.readyState = 4;
|
||||
audio.currentTime = 9;
|
||||
audio.dispatchEvent(new Event('timeupdate'));
|
||||
if (paused) stores.player.pause();
|
||||
audio.error = {code:2};
|
||||
audio.currentTime = 0;
|
||||
audio.paused = true;
|
||||
audio.dispatchEvent(new Event('pause'));
|
||||
audio.dispatchEvent(new Event('timeupdate'));
|
||||
mode(true);
|
||||
stores.player.useOfflineCatalog([saved]);
|
||||
await settle();
|
||||
audio.dispatchEvent(new Event('loadedmetadata'));
|
||||
assert.equal(audio.src, 'blob:test/1');
|
||||
assert.equal(audio.currentTime, 9);
|
||||
assert.equal(audio.paused, paused);
|
||||
}
|
||||
});
|
||||
|
||||
test('only the latest file read can attach audio, and pause and seek apply while it opens', async () => {
|
||||
const {stores, audio, revoked} = setup(() => assert.fail('Unexpected network request'));
|
||||
const files = new Map();
|
||||
stores.offline.openAudio = track => new Promise(resolve => files.set(track.id, resolve));
|
||||
const track = id => ({id, stream_url:'/api/player/stream/'+id});
|
||||
const first = stores.player._playLocal(track(1));
|
||||
const second = stores.player._playLocal(track(2));
|
||||
stores.player.seek(12);
|
||||
stores.player.pause();
|
||||
files.get(2)(new Blob(['second']));
|
||||
await second;
|
||||
files.get(1)(new Blob(['first']));
|
||||
await first;
|
||||
audio.dispatchEvent(new Event('loadedmetadata'));
|
||||
assert.equal(audio.src, 'blob:test/1');
|
||||
assert.equal(audio.paused, true);
|
||||
assert.equal(audio.currentTime, 12);
|
||||
const third = stores.player._playLocal(track(3));
|
||||
files.get(3)(null);
|
||||
await third;
|
||||
assert.equal(audio.src, undefined, 'a missing offline file cannot fall through to HTTP');
|
||||
assert.deepEqual(revoked, ['blob:test/1']);
|
||||
});
|
||||
|
||||
test('a native stream error switches to the file even before the browser announces offline', async () => {
|
||||
const {stores, audio, created, mode} = setup(() => assert.fail('Unexpected network request'));
|
||||
const track = {id:5, stream_url:'/api/player/stream/5'};
|
||||
stores.queue = {tracks:[track], syncCurrentIndexToTrack() {}};
|
||||
mode(false);
|
||||
await stores.player._playLocal(track);
|
||||
audio.readyState = 4;
|
||||
audio.currentTime = 12;
|
||||
audio.dispatchEvent(new Event('timeupdate'));
|
||||
// The download completed during HTTP playback. Firefox can fail the media request first.
|
||||
let finishRead;
|
||||
Object.assign(stores.offline, {
|
||||
enabled:true, networkResult() {}, openAudio:() => new Promise(resolve => {finishRead = resolve;}),
|
||||
});
|
||||
audio.paused = true;
|
||||
audio.error = {code:2};
|
||||
audio.dispatchEvent(new Event('error'));
|
||||
mode(true);
|
||||
stores.player.useOfflineCatalog([track]);
|
||||
finishRead(new Blob(['recording']));
|
||||
await settle();
|
||||
audio.dispatchEvent(new Event('loadedmetadata'));
|
||||
assert.equal(audio.src, 'blob:test/1');
|
||||
assert.equal(audio.currentTime, 12);
|
||||
assert.equal(audio.paused, false);
|
||||
assert.equal(created.length, 1);
|
||||
});
|
||||
|
||||
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({
|
||||
@@ -123,3 +257,35 @@ test('late device polls and transfers cannot replace playback after going offlin
|
||||
assert.equal(devices.isActive(), false);
|
||||
assert.equal(remoteCommands, 0);
|
||||
});
|
||||
|
||||
test('a poll finishing after browser disconnect cannot replace the playing file before the offline event', async () => {
|
||||
let requests = 0, deliverPoll;
|
||||
const {stores, audio, navigator, mode} = setup(() => {
|
||||
requests++;
|
||||
return {ok:true, json:() => new Promise(resolve => {deliverPoll = resolve;})};
|
||||
});
|
||||
const {player, devices, offline} = stores;
|
||||
mode(false);
|
||||
offline.enabled = true;
|
||||
const saved = {id:1, stream_url:'/api/player/stream/1'};
|
||||
const other = {id:2, stream_url:'/api/player/stream/2'};
|
||||
stores.queue = {tracks:[saved], syncCurrentIndexToTrack() {}, _tracksWithJamDefaults: tracks => tracks};
|
||||
devices.activeDeviceId = devices.id;
|
||||
await player._playLocal(saved);
|
||||
const poll = devices.poll();
|
||||
await settle();
|
||||
navigator.onLine = false;
|
||||
const payload = {track:other, tracks:[other], position_seconds:3};
|
||||
const command = {command:'play_track', payload};
|
||||
deliverPoll({active_device_id:'other', commands:[command], playback_state:payload});
|
||||
await poll;
|
||||
player._executeRemoteCommand(command);
|
||||
await devices.poll();
|
||||
await devices.heartbeat();
|
||||
assert.equal(requests, 1);
|
||||
assert.equal(devices.activeDeviceId, devices.id);
|
||||
assert.equal(player.currentTrack.id, saved.id);
|
||||
assert.equal(audio.paused, false);
|
||||
assert.equal(audio.src, 'blob:test/1');
|
||||
assert.equal(audio.playCalls, 1);
|
||||
});
|
||||
Reference in new issue
Block a user