feat: unify local and federated search results
Build and Publish / Build and Publish Docker Image (push) Successful in 2m33s

This commit is contained in:
ab committed 2026-11-23 05:41:25 +02:00
1 parent 07864a1a36
commit 12f21583f8
24 files changed
+2076 -982

No files matched your search

+145 -17
View File
@@ -5,8 +5,8 @@ const { chromium } = require(process.env.PLAYWRIGHT_MODULE || 'playwright');
const html = fs.readFileSync('target/podcast-player-fixture.html', 'utf8');
const alpine = fs.readFileSync('target/podcast-alpine.min.js', 'utf8');
function stream(events) {
return events.map(([kind, entity], index) => {
const data = JSON.stringify({ kind, sequence: index + 1, entity });
return events.map(([kind, entity, score], index) => {
const data = JSON.stringify({ kind, sequence: index + 1, entity, score });
return `event: ${kind}\ndata: ${data}\n\n`;
}).join('');
}
@@ -47,15 +47,33 @@ const burst = stream([
}
};
});
let sendBurst, sendOnLeave;
let sendBurst, sendOnLeave, sendLocal, sendRemote;
const delayedLocal = new Promise(resolve => { sendLocal = resolve; });
const canonicalTrack = track(442, 'Song title');
canonicalTrack.availability.local = { track_id: 42 };
const canonicalArtist = { key: { normalized_name: 'song band' }, name: 'Song Band', peers: ['peer'], local_id: 7 };
const canonicalRelease = { key: { normalized_title: 'album', primary_artists: ['band'], year: 2014 }, local_id: 442,
title: 'Album', artists: ['Band'], sources: [{ owner: 'peer' }] };
const canonicalEvents = stream([
['federation.track', canonicalTrack, 800], ['federation.track', track(443, 'Remote exact title'), 1000],
['federation.artist', canonicalArtist, 800], ['federation.release', canonicalRelease, 800],
['search.completed', {}],
]);
const localResult = {
artists: [{ id: 7, name: 'Song Band', image_url: '/test/local-artist' }],
releases: [{ id: 442, title: 'Album', cover_url: '/test/local-cover' }],
tracks: [{ id: 42, title: 'Song title', artists: [{ id: 7, name: 'Song Band' }], release_id: 442, release_title: 'Album' }],
podcasts: [], scores: { tracks: { 42: 900 } },
};
const responses = new Map([
['Song', new Promise(resolve => { sendBurst = resolve; })],
['leave', new Promise(resolve => { sendOnLeave = resolve; })],
['late-local', canonicalEvents],
['early-local', new Promise(resolve => { sendRemote = resolve; })],
['partial', stream([
['federation.track', track(1, 'Other song')],
['federation.track', track(2, 'Partial match')],
['federation.track', track(3, 'Provisional title')],
['federation.track', track(3, 'Partial')],
['federation.track', track(2, 'A partial match'), 950],
['federation.track', track(3, 'Partial (live)'), 950],
['federation.track', track(3, 'Partial'), 1000],
['search.failed', { message: 'Peer disconnected' }],
])],
]);
@@ -68,6 +86,9 @@ const burst = stream([
return route.fulfill({ contentType: 'application/javascript', body: alpine });
}
if (url.pathname === '/api/player/search') {
const q = url.searchParams.get('q');
if (q === 'late-local') await delayedLocal;
if (q === 'early-local' || q === 'late-local') return route.fulfill({ json: localResult });
return route.fulfill({ json: { tracks: [], artists: [], releases: [], podcasts: [] } });
}
if (url.pathname === '/api/player/artists') {
@@ -77,7 +98,7 @@ const burst = stream([
const body = await responses.get(url.searchParams.get('q'));
return route.fulfill({ contentType: 'text/event-stream', body });
}
if (url.pathname === '/test/local-artist') return route.fulfill({
if (url.pathname === '/test/local-artist' || url.pathname === '/test/local-cover') return route.fulfill({
contentType: 'image/svg+xml', body: '<svg xmlns="http://www.w3.org/2000/svg" width="1" height="1"/>',
});
if (route.request().resourceType() === 'image') return route.fulfill({ status: 404, body: '' });
@@ -89,7 +110,7 @@ const burst = stream([
const library = Alpine.store('library');
window.imageErrors = 0;
document.addEventListener('error', event => {
if (event.target instanceof HTMLImageElement && event.target.closest('.federation-entity-card')) {
if (event.target instanceof HTMLImageElement && event.target.closest('.search-federation-only')) {
window.imageErrors++;
}
}, true);
@@ -97,7 +118,7 @@ const burst = stream([
await library.search('Song');
window.trackUpdates = 0;
Alpine.effect(() => {
void library.federationSearch.tracks;
void library.unifiedSearch.tracks;
window.trackUpdates++;
});
window.started = performance.now();
@@ -117,22 +138,78 @@ const burst = stream([
console.log('Federation search burst', { ...first, imageErrors: final.errors, settledUpdates: final.updates });
assert.equal(first.sourceTracks, trackCount);
assert.equal(first.mountedRows, groupCount);
assert.equal(await page.locator('.federation-entity-card img').count(), 0);
assert.equal(await page.locator('.search-federation-only img').count(), 0);
assert.equal(await page.locator('.search-artist-card.search-federation-only:visible').count(), 1);
assert.equal(await page.locator('.search-release-card.search-federation-only:visible').count(), 1);
const released = page.locator('.search-release-card.search-federation-only').first();
const visual = await released.evaluate(card => {
const style = getComputedStyle(card);
const corner = getComputedStyle(card, '::before');
return { radius: style.borderTopLeftRadius, corner: corner.clipPath, color: corner.backgroundColor,
duration: style.animationDuration, pointer: corner.pointerEvents };
});
assert.equal(visual.radius, '0px');
assert.match(visual.corner, /^polygon\(/);
const [red, green, blue] = visual.color.match(/\d+/g).map(Number);
assert.ok(green > red && green > blue, 'remote-only corner uses the green accent');
for (const selector of ['.search-artist-card', '.search-release-card', '.track-row']) {
const png = await page.locator(selector + '.search-federation-only').first().screenshot({ animations: 'disabled' });
const samples = await page.evaluate(async base64 => {
const img = new Image();
img.src = 'data:image/png;base64,' + base64;
await img.decode();
const canvas = document.createElement('canvas');
const context = canvas.getContext('2d');
context.drawImage(img, 0, 0);
return [[0, 0], [1, 1], [1, 10], [10, 1], [14, 14]].map(([x, y]) =>
Array.from(context.getImageData(x, y, 1, 1).data).slice(0, 3));
}, png.toString('base64'));
// The outermost pixel can straddle a fractional row boundary.
const [r, g, b] = samples[0];
assert.ok(g > r && g > b && g > green * .5, selector);
assert.deepEqual(samples.slice(1, 4), Array(3).fill([red, green, blue]), selector);
assert.notDeepEqual(samples[4], [red, green, blue], 'the mark is triangular');
}
assert.equal(visual.pointer, 'none');
assert.ok(parseFloat(visual.duration) > 0 && parseFloat(visual.duration) <= .15);
await page.emulateMedia({ reducedMotion: 'reduce' });
assert.equal(await released.evaluate(card => getComputedStyle(card).animationName), 'none');
await page.emulateMedia({ reducedMotion: 'no-preference' });
assert.equal(await page.locator('.federation-search-section:visible').count(), 0);
assert.equal(final.errors, 3, 'each of the three missing artwork URLs is tried once');
assert.ok(first.updates < trackCount / 2, 'the event stream is published in batches');
assert.equal(final.updates, first.updates, 'artwork failures do not invalidate track results');
// A local image arriving after the missing federation image still gets a chance to load.
await page.evaluate(() => {
Alpine.store('library').searchResults.artists = [{ id: 1, name: 'Band', image_url: '/test/local-artist' }];
});
await page.waitForSelector('.federation-entity-card img.artwork-loaded[src="/test/local-artist"]');
// The local HTTP request and the SSE response can complete in either order.
for (const query of ['late-local', 'early-local']) {
await page.evaluate(q => { window.pendingSearch = Alpine.store('library').search(q); }, query);
if (query === 'late-local') {
await page.waitForFunction(() => !Alpine.store('library').federationSearch.loading);
} else {
await page.waitForFunction(() => !Alpine.store('library').searchLoading);
}
await page.locator('[data-search-source="local"]').waitFor();
await page.evaluate(() => { window.canonicalRow = document.querySelector('[data-search-source="local"]'); });
if (query === 'late-local') sendLocal(); else sendRemote(canonicalEvents);
await page.evaluate(() => window.pendingSearch);
await page.waitForFunction(() => !Alpine.store('library').federationSearch.loading);
assert.equal(await page.locator('[data-search-source="local"]').count(), 1);
assert.equal(await page.evaluate(() => document.querySelector('[data-search-source="local"]') === window.canonicalRow), true);
assert.deepEqual(await page.locator('[data-search-source] .search-track-name:visible').allTextContents(),
['Remote exact title', 'Song title'], 'ranking combines both sources');
assert.equal(await page.locator('[data-search-source="federation"]').count(), 1, 'another recording survives');
assert.equal(await page.locator('.search-release-card:visible').count(), 1);
assert.equal(await page.locator('.search-artist-card:visible').count(), 1);
assert.equal(await page.locator('.search-release-card.search-federation-only:visible').count(), 0);
assert.equal(await page.locator('[data-search-source="local"] .federation-source-count:visible').count(), 0);
await page.waitForSelector('.search-release-card img.artwork-loaded[src="/test/local-cover"]');
}
// A failing stream publishes its last batch, including replacements for existing content IDs.
await page.evaluate(() => Alpine.store('library').search('partial'));
await page.waitForFunction(() => Alpine.store('library').federationSearch.error === 'Peer disconnected');
assert.deepEqual(await page.locator('[data-search-source="federation"] .search-track-name').allTextContents(),
['Partial', 'Partial match', 'Other song']);
['Partial', 'A partial match']);
// Leave after the first SSE event has been buffered but before its batch is published.
await page.evaluate(async () => {
@@ -146,8 +223,59 @@ const burst = stream([
assert.equal(await page.evaluate(() => window.searchStream.readyState === EventSource.CLOSED), true);
assert.deepEqual(await page.evaluate(() => Alpine.store('library').federationSearch),
{ loading: false, error: '', artists: [], releases: [], tracks: [] });
await verifyReleaseNavigation(page);
assert.deepEqual(errors, []);
} finally {
await browser.close();
}
})().catch(error => { console.error(error); process.exitCode = 1; });
async function verifyReleaseNavigation(page) {
const local = {
id: 442, title: 'Вино из цикуты', artists: [{ id: 21, name: 'Саша Скул' }], year: 2014,
release_type: 'album', cover_url: '/test/local-cover', tracks: [], uploaders: [],
};
function releaseUrl(title, name, year) {
const key = { normalized_title: title, primary_artists: [name], release_type: null, year };
return `http://groups.test/#releasefed?key=${encodeURIComponent(JSON.stringify(key))}`;
}
await page.route('**/api/player/releases/442', route => route.fulfill({ json: local }));
await page.route('**/api/player/federation/release/resolve?*', route => {
const key = JSON.parse(new URL(route.request().url()).searchParams.get('key'));
const matched = key.normalized_title === 'вино из цикуты'
&& key.primary_artists.join() === 'саша скул' && key.year === 2014;
return route.fulfill({ json: { local_id: matched ? 442 : null } });
});
const remote = { name: 'AC/DC', releases: [{
title: 'Across Borders', year: 2017, release_type: 'album',
tracks: [{ title: 'Remote song', item_id: 'abc', content_id: 'content-id', artists: ['AC/DC'] }],
}] };
await page.route('**/api/player/federation/artists/events?*', route => {
const name = new URL(route.request().url()).searchParams.get('name');
const entity = name === 'ac dc' ? remote : {
name: local.artists[0].name, releases: [{ title: local.title, year: local.year, release_type: 'album', tracks: [] }],
};
const payload = JSON.stringify({ peer: 'peer', entity });
return route.fulfill({ contentType: 'text/event-stream', body:
`event: federation.artist.catalog\ndata: ${payload}\n\nevent: artist.completed\ndata: {}\n\n` });
});
// Leave the application so no in-memory search result can help with either lookup.
await page.goto('about:blank');
await page.goto(releaseUrl('вино из цикуты', 'саша скул', 2014));
await page.waitForURL('**/#release/442');
await page.locator('.release-cover img[src="/test/local-cover"]').waitFor();
await page.reload();
await page.waitForFunction(() => Alpine.store('library').currentRelease?.id === 442);
const remoteUrl = releaseUrl('across borders', 'ac dc', 2017);
await page.goto(remoteUrl);
await page.getByText('Remote song', { exact: true }).first().waitFor();
assert.equal(page.url(), remoteUrl);
await page.reload();
await page.getByText('Remote song', { exact: true }).first().waitFor();
assert.equal(await page.locator('.release-artists a').first().innerText(), 'AC/DC');
await page.goBack();
await page.waitForURL('**/#release/442');
await page.locator('.release-cover img[src="/test/local-cover"]').waitFor();
}
+102 -15
View File
@@ -1,37 +1,60 @@
const {chromium}=require(process.env.PLAYWRIGHT_MODULE||'playwright');
const fs=require('node:fs'),assert=require('node:assert/strict');
const http=require('node:http');
const html=fs.readFileSync('target/podcast-player-fixture.html','utf8'),alpine=fs.readFileSync('target/podcast-alpine.min.js','utf8');
const local=(id,title='Still Loving You',artist='Scorpions')=>({id,title,artists:[{id:1,name:artist}],featured_artists:[],release_title:'Release '+id,release_id:id,duration_seconds:300+id,audio_format:'flac',lastfm_rating:87});
const remote=(id,title='Still Loving You')=>({key:{content_id:'b3:'+String(id).padStart(64,'0')},metadata:{title,artists:[{name:'Scorpions'}],featured_artists:[],release:{title:'Remote release '+id},duration_seconds:300+id},availability:{state:'federated',local:null,federation:[{owner:'peer',item_id:String(id)}]}});
const data={local:[local(1),local(2,'Another song'),local(3),local(4,'Still Loving You','Other artist'),local(5)],remote:[remote(11),remote(12),remote(13,'Other remote song')]};
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'}];
data.remote[0].availability.local={track_id:111, stream_url:'/api/player/stream/111'};
(async()=>{
const browser=await chromium.launch({headless:true,...(process.env.CHROME_PATH?{executablePath:process.env.CHROME_PATH}:{})});
const server=http.createServer((_req,res)=>{res.writeHead(200,{'Content-Type':'text/html; charset=utf-8'});res.end(html);});
try{
await new Promise((resolve,reject)=>server.once('error',reject).listen(0,'127.0.0.1',resolve));
const origin='http://127.0.0.1:'+server.address().port;
for(const width of [1440,390,320]){
const page=await browser.newPage({viewport:{width,height:1000}}),errors=[];page.on('pageerror',e=>errors.push(e.message));
await page.route('**/*',route=>{
let finishSimilarity;
const peersReady=new Promise(resolve=>{finishSimilarity=resolve;});
await page.context().route('**/*',async route=>{
const u=new URL(route.request().url());
if(u.hostname==='groups.test'&&u.pathname==='/')return route.fulfill({contentType:'text/html',body:html});
if(u.origin===origin&&u.pathname==='/')return route.continue();
if(u.hostname==='cdn.jsdelivr.net'&&u.pathname.includes('alpine'))return route.fulfill({contentType:'application/javascript',body:alpine});
if(u.pathname==='/api/player/artists')return route.fulfill({json:{items:[],total:0,has_more:false}});
if(u.pathname==='/api/player/releases/442')return route.fulfill({json:{id:442,title:'Remote release 11',artists:[],tracks:[],uploaders:[]}});
if(u.pathname==='/api/player/similarity/42'){
if(u.searchParams.get('local_only'))return route.fulfill({json:{label:'Seed',tracks:[
{...local(1),similarity_score:0.9},{...local(2,'Another song'),similarity_score:0.7},
]}});
await peersReady;
return route.fulfill({json:{queried_peers:1,federation_tracks:[{...remote(12),similarity_score:0.95}]}});
}
return route.fulfill({json:[]});
});
await page.goto('http://groups.test/');await page.waitForFunction(()=>window.Alpine?.store('searchGroups')&&Alpine.store('library'));
await page.goto(origin);await page.waitForFunction(()=>window.Alpine?.store('searchGroups')&&Alpine.store('library'));
await page.evaluate(data=>{
window.groupPlays=[];
const library=Alpine.store('library');library.view='search';library.searchQuery='Still';library.searchLoading=false;library.similaritySearchLabel='';
library.searchResults={artists:[],releases:[],tracks:data.local,podcasts:[]};library.federationSearch={loading:false,error:'',artists:[],releases:[],tracks:data.remote};
library.updateUnifiedSearch('tracks');
Alpine.store('queue').playRelease=(tracks,index)=>window.groupPlays.push({source:'local',ids:tracks.map(t=>t.id),id:tracks[index].id});
library.playFederatedTrack=track=>window.groupPlays.push({source:'federation',id:track.key.content_id});
library.toggleFederationLike=track=>window.likedContent=track.key.content_id;
Alpine.store('playlists').showFederationPicker=track=>window.playlistContent=track.key.content_id;
},data);
const localRows=page.locator('[data-search-source="local"]'),remoteRows=page.locator('[data-search-source="federation"]');
await page.waitForFunction(()=>document.querySelectorAll('[data-search-source="local"]').length===3);
assert.equal(await localRows.count(),3);assert.equal(await remoteRows.count(),2);
assert.equal(await localRows.count(),3);assert.equal(await remoteRows.count(),1);
assert.equal(await localRows.first().locator('.search-federation-only').count(),0);
assert.equal(await remoteRows.first().locator('.search-federation-only').count(),1);
assert.equal(await page.locator('.federation-search-section:visible').count(),0);
assert.equal(await localRows.locator('.search-version-toggle:visible').count(),1);
assert.equal(await localRows.locator('.search-track-variant').count(),0,'collapsed versions are unmounted');
assert.equal(await localRows.first().locator('.search-version-toggle').getAttribute('aria-expanded'),'false');
await localRows.first().locator('.search-track-name').click();
assert.deepEqual(await page.evaluate(()=>window.groupPlays.at(-1)),{source:'local',ids:[1,2,4],id:1});
assert.deepEqual(await page.evaluate(()=>window.groupPlays.at(-1)),{source:'local',ids:[1,2,4,'fed:'+remote(13,'Other remote song').key.content_id],id:1});
await page.evaluate(()=>{window.groupPlays=[];window.groupNodes=[...document.querySelectorAll('[data-search-source="local"]')];});
const animation=await page.evaluate(()=>new Promise(resolve=>{
const [head,next]=window.groupNodes,positions=[],start=performance.now();
@@ -43,7 +66,9 @@ const data={local:[local(1),local(2,'Another song'),local(3),local(4,'Still Lovi
assert.equal(await page.evaluate(()=>window.groupPlays.length),0,'branch toggle does not play');
assert.equal(await localRows.first().locator('.search-version-toggle').getAttribute('aria-expanded'),'true');
assert.equal(await localRows.nth(1).getAttribute('inert'),null);
assert.equal(await localRows.count(),5);
assert.equal(await localRows.count(),6);assert.equal(await remoteRows.count(),2);
assert.equal(await localRows.nth(1).getByRole('link',{name:'Scorpions'}).getAttribute('href'),'#artist/1');
assert.equal(await localRows.nth(1).getByRole('link',{name:'Release 3'}).getAttribute('href'),'#release/3');
assert.equal(await page.evaluate(()=>window.groupNodes.every(node=>document.getElementById(node.id)===node)),true,'representatives keep their DOM identities');
for(let index=0;index<3;index++){
const row=localRows.nth(index),box=await row.boundingBox(),actions=await row.locator('.track-actions').boundingBox();
@@ -53,7 +78,7 @@ const data={local:[local(1),local(2,'Another song'),local(3),local(4,'Still Lovi
await page.screenshot({path:`target/search-groups-expanded-${width}.png`});
const closing=await page.evaluate(()=>new Promise(resolve=>{
const rows=document.querySelectorAll('[data-search-source="local"]'),positions=[],start=performance.now();rows[0].querySelector('.search-version-toggle').click();
function sample(){positions.push(rows[3].getBoundingClientRect().top);if(performance.now()-start<230)requestAnimationFrame(sample);else resolve(positions);}requestAnimationFrame(sample);
function sample(){positions.push(rows[4].getBoundingClientRect().top);if(performance.now()-start<230)requestAnimationFrame(sample);else resolve(positions);}requestAnimationFrame(sample);
}));
assert.ok(new Set(closing.map(y=>Math.round(y))).size>2,'collapse also moves siblings smoothly');
await page.waitForFunction(()=>document.querySelectorAll('[data-search-source="local"]').length===3);
@@ -63,16 +88,78 @@ const data={local:[local(1),local(2,'Another song'),local(3),local(4,'Still Lovi
await page.evaluate(()=>new Promise(resolve=>{const button=document.querySelector('[data-search-source="local"] .search-version-toggle');[0,20,40,60,80].forEach(delay=>setTimeout(()=>button.click(),delay));setTimeout(resolve,280);}));
assert.equal(await localRows.first().locator('.search-version-toggle').getAttribute('aria-expanded'),'false');
assert.equal(await localRows.count(),3,'rapid toggles settle in the final state');
const remoteHead=remoteRows.first();await remoteHead.locator('.search-version-toggle').click();
await page.evaluate(track=>Alpine.store('library').federationSearch.tracks.push(track),remote(14));
await page.waitForFunction(()=>document.querySelectorAll('[data-search-source="federation"]').length===4);
assert.equal(await remoteHead.locator('.search-version-toggle').getAttribute('aria-expanded'),'true');
assert.equal(await remoteHead.locator('.search-version-toggle span').textContent(),'3');
await remoteRows.nth(1).locator('.search-track-name').click();assert.equal(await page.evaluate(()=>window.groupPlays.at(-1).id),remote(12).key.content_id);
await localRows.first().locator('.search-version-toggle').click();
await page.evaluate(track=>{
const lib=Alpine.store('library');lib.federationSearch.tracks.push(track);lib.updateUnifiedSearch('tracks');
},remote(14));
await page.waitForFunction(()=>document.querySelectorAll('[data-search-source="federation"]').length===3);
assert.equal(await localRows.first().locator('.search-version-toggle').getAttribute('aria-expanded'),'true');
assert.equal(await localRows.first().locator('.search-version-toggle span').textContent(),'6');
const remoteVersion=remoteRows.filter({has:page.getByRole('link',{name:'Remote release 12',exact:true})});
await remoteVersion.locator('.search-track-name').click();
assert.equal(await page.evaluate(()=>window.groupPlays.at(-1).id),'fed:'+remote(12).key.content_id);
assert.equal(await remoteVersion.locator('.track-share-btn').isDisabled(),true);
await remoteVersion.locator('.like-btn').click();
await remoteVersion.locator('.playlist-add-btn').click();
assert.deepEqual(await page.evaluate(()=>[window.likedContent,window.playlistContent]),[remote(12).key.content_id,remote(12).key.content_id]);
await remoteVersion.locator('.queue-next-btn').click();
assert.equal(await page.evaluate(()=>Alpine.store('queue').tracks.some(track=>track.federation_pending && track.content_id===window.groupPlays.at(-1).id.slice(4))),true);
const remoteRelease=await remoteVersion.getByRole('link',{name:'Remote release 12'}).getAttribute('href');
assert.ok(remoteRelease.startsWith('#releasefed?key='));
assert.equal(JSON.parse(decodeURIComponent(remoteRelease.split('=')[1])).normalized_title,'remote release 12');
assert.equal(await remoteVersion.getByRole('link',{name:'Scorpions'}).getAttribute('href'),'#artistfed?name=Scorpions');
await remoteVersion.locator('.info-btn').click();
assert.equal(await page.locator('.info-table').getByRole('link',{name:'Remote release 12'}).getAttribute('href'),remoteRelease);
await page.locator('.info-modal-head button').click();
const queued=await page.evaluate(()=>Alpine.store('library').federationQueueTrack(Alpine.store('library').federationSearch.tracks[0]));
assert.equal(queued.id,111);
assert.equal(queued.stream_url,'/api/player/stream/111');
assert.equal(queued.release_id,442);
assert.equal(queued.artists[0].id,1);
assert.equal(await page.evaluate(()=>{
const lib=Alpine.store('library');
const track=lib.federationQueueTrack(lib.federationSearch.tracks[0]);
return lib.releaseHref(lib.trackRelease({...track,release_id:1364,release_title:'Different local edition'}));
}),'#release/1364','a local edition takes precedence over another release containing the same audio');
assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth>innerWidth),false);
await page.emulateMedia({reducedMotion:'reduce'});assert.equal(await localRows.first().evaluate(el=>getComputedStyle(el).transitionDuration),'0s');
const plays=await page.evaluate(()=>window.groupPlays.length);
const promoted=localRows.filter({has:page.getByRole('link',{name:'Remote release 11',exact:true})});
assert.equal(await promoted.locator('.search-federation-only').count(),0);
await promoted.locator('.info-btn').click();
const info=page.locator('.info-table');
assert.equal(await info.getByRole('link',{name:'Scorpions'}).getAttribute('href'),'#artist/1');
assert.equal(await info.getByRole('link',{name:'ft. Guest & Co'}).getAttribute('href'),'#artistfed?name=Guest%20%26%20Co');
assert.equal(await info.getByText('1',{exact:true}).count(),1,'the local track info retains its federation peer count');
if(width===1440){
const [tab]=await Promise.all([page.context().waitForEvent('page'),info.getByRole('link',{name:'Remote release 11'}).click({modifiers:['Control']})]);
await tab.waitForURL('**/#release/442');
await tab.close();
assert.equal(await info.count(),1,'modified click keeps the original result and modal open');
}
await info.getByRole('link',{name:'Remote release 11'}).click();
await page.waitForURL('**/#release/442');
assert.equal(await info.count(),0);
assert.equal(await page.evaluate(()=>window.groupPlays.length),plays);
await page.evaluate(()=>{
Alpine.store('player').setVolume(0.37);
Alpine.store('library').searchSimilar(42);
});
await page.waitForFunction(()=>Alpine.store('library').similaritySearchStats.loading && document.querySelectorAll('.search-standard-entry').length===2);
assert.equal(await page.locator('.similarity-search-inline-progress').isVisible(),true);
finishSimilarity();
await page.waitForFunction(()=>!Alpine.store('library').similaritySearchStats.loading);
const similar=page.locator('.search-standard-entry');
assert.equal(await similar.count(),3,'similarity keeps versions ungrouped');
assert.deepEqual(await similar.evaluateAll(rows=>rows.map(row=>row.dataset.searchSource)),['federation','local','local']);
assert.equal(await similar.first().locator('.search-federation-only').count(),1);
assert.equal(await similar.locator('.search-version-toggle:visible').count(),0);
await similar.first().locator('.search-track-name').click();
assert.deepEqual(await page.evaluate(()=>window.groupPlays.at(-1).ids),['fed:'+remote(12).key.content_id,1,2]);
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);
assert.deepEqual(errors,[]);await page.close();
}
console.log('Grouped local/federation search, animation, playback and streaming checks passed.');
}finally{await browser.close();}
}finally{await browser.close();server.close();}
})().catch(error=>{console.error(error);process.exitCode=1;});
+130
View File
@@ -0,0 +1,130 @@
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 start = template.indexOf("Alpine.store('library', {");
const librarySource = template.slice(start, template.indexOf('\n });', start) + 8);
const flush = () => new Promise(resolve => setImmediate(resolve));
const json = value => ({ ok: true, json: async () => value });
function setup(hash, fetch) {
const location = { hash };
const replacements = [];
const streams = [];
let library;
class EventSource {
constructor(url) { this.url = url; this.events = {}; streams.push(this); }
addEventListener(kind, fn) { this.events[kind] = fn; }
emit(kind, data) { this.events[kind]({ data: JSON.stringify(data) }); }
close() { this.closed = true; }
}
vm.runInNewContext(librarySource, {
location, fetch, EventSource, GUEST: false, URLSearchParams, clearTimeout, setTimeout,
Alpine: { store(_name, value) { library = value; } },
history: { replaceState(_state, _title, url) { location.hash = url; replacements.push(url); } },
});
library._afterNavigation = () => {};
return { library, location, replacements, streams };
}
function key(title, artist, year) {
return { normalized_title: title, primary_artists: [artist], release_type: null, year };
}
const link = releaseKey => '#releasefed?key=' + encodeURIComponent(JSON.stringify(releaseKey));
test('existing release deep links replace their own history entry with the local edition', async () => {
for (const [id, title, artist, year] of [
[442, 'вино из цикуты', 'саша скул', 2014],
[1364, 'рэп из под стола remastered', 'гнойный', 2013],
]) {
const releaseKey = key(title, artist, year);
const calls = [];
const { library, replacements } = setup(link(releaseKey), async input => {
const url = new URL(input, 'https://player.test');
calls.push(url.pathname);
if (url.pathname.endsWith('/resolve')) {
assert.deepEqual(JSON.parse(url.searchParams.get('key')), releaseKey);
return json({ local_id: id });
}
return json({ id, title, year, artists: [{ id: 1, name: artist }], tracks: [], cover_url: '/covers/local' });
});
library._navigateFromHash({ fromHash: true });
await flush();
assert.deepEqual(calls, ['/api/player/federation/release/resolve', '/api/player/releases/' + id]);
assert.deepEqual(replacements, ['#release/' + id]);
assert.equal(library.currentRelease.cover_url, '/covers/local');
assert.equal(library.currentRelease.id, id);
}
});
test('a cold remote release loads its edition from a peer and rejects other years and types', async () => {
const releaseKey = key('some album', 'ac dc', 1990);
const { library, streams, location, replacements } = setup(link(releaseKey), () => json({ local_id: null }));
library._navigateFromHash({ fromHash: true });
await flush();
const [source] = streams;
assert.equal(location.hash, link(releaseKey));
assert.equal(library.releaseFederationLoading, true);
const candidate = (year, type, id) => ({ title: 'Some Album', year, release_type: type,
tracks: [{ title: id, content_id: id, item_id: id, artists: ['AC/DC'] }] });
const catalog = (...releases) => source.emit('federation.artist.catalog', { peer: 'peer', entity: { name: 'AC/DC', releases } });
catalog(candidate(1992, 'album', 'wrong-year'));
catalog(candidate(1990, 'album', 'ambiguous-album'), candidate(1990, 'ep', 'ambiguous-ep'));
assert.equal(library.currentRelease, null);
catalog(candidate(1990, 'album', 'right'));
source.emit('federation.artist.catalog', {
peer: 'second', entity: { name: 'AC/DC', releases: [candidate(1990, 'album', 'right')] },
});
catalog(candidate(1990, 'ep', 'wrong-type'));
catalog(candidate(1990, 'album', 'right'));
source.emit('artist.completed', {});
assert.deepEqual(replacements, []);
assert.equal(library.currentRelease.title, 'Some Album');
assert.equal(library.currentRelease.artists[0].name, 'AC/DC');
assert.deepEqual(Array.from(library.currentRelease.tracks, row => row.content_id), ['right']);
assert.deepEqual(Array.from(library.currentRelease.federationPeers).sort(), ['peer', 'second']);
assert.equal(library.currentRelease.tracks[0].release_key.release_type, 'album');
assert.equal(library.releaseUnavailable, false);
assert.equal(source.closed, true);
});
test('published release keys preserve protocol spelling and include all primary artists', () => {
const { library } = setup('#artists', () => assert.fail('no request expected'));
const releaseKey = library.federationReleaseKey('РЭП – Ремастер!', ['Гнойный', 'Björk', 'BJÖRK'], 2013, 'EP');
assert.deepEqual(JSON.parse(JSON.stringify(releaseKey)), {
normalized_title: 'рэп ремастер', primary_artists: ['björk', 'гнойный'], release_type: 'ep', year: 2013,
});
});
test('unavailable and malformed release links stay on the requested page', async () => {
for (const hash of ['#releasefed?key=%XX', link(key('unavailable', 'peer', 2002))]) {
const { library, location, streams } = setup(hash, () => json({ local_id: null }));
library._navigateFromHash({ fromHash: true });
await flush();
streams[0]?.emit('artist.completed', {});
assert.equal(library.view, 'release_detail');
assert.equal(library.currentRelease, null);
assert.equal(library.releaseUnavailable, true);
assert.equal(location.hash, hash);
}
});
test('late resolution cannot redirect away from a subsequent artist deep link', async () => {
let resolveRelease;
const { library, location, replacements } = setup(link(key('release', 'artist', 2000)), async input => {
if (input.includes('/release/resolve')) return new Promise(resolve => { resolveRelease = resolve; });
if (input.includes('/artist/resolve')) return json({ local_id: 37 });
return json({ id: 37, name: 'Artist', releases: [], image_url: '/artists/37' });
});
library._navigateFromHash({ fromHash: true });
location.hash = '#artistfed?name=Artist';
library._navigateFromHash({ fromHash: true });
await flush();
resolveRelease(json({ local_id: 442 }));
await flush();
assert.equal(library.currentArtist.id, 37);
assert.deepEqual(replacements, ['#artist/37']);
assert.equal(library.currentRelease, null);
});
+3 -3
View File
@@ -25,9 +25,9 @@ test('audio similarity keeps its original ungrouped ranking',()=>{
test('playing a grouped search uses the selected source identity and only visible versions',()=>{
const {groups,stores,context}=setup(),template=fs.readFileSync(`${__dirname}/../templates/player/scripts.html`,'utf8');
const method=template.slice(template.indexOf(' playSearchTrack(idx)'),template.indexOf(' _setupScroll()',template.indexOf(' playSearchTrack(idx)')));
vm.runInContext('this.library={'+method+'};',context);const library=context.library;library.searchResults={tracks:[local(1),local(2,'Other'),local(3)]};
vm.runInContext('this.library={'+method+'};',context);const library=context.library;library.displaySearchResults={tracks:[local(1),local(2,'Other'),{...local('fed:3'),federation_only:true}]};
library.playSearchTrack(0);assert.deepEqual(ids(stores.queue.tracks),[1,2]);assert.equal(stores.queue.index,0);
library.playSearchTrack(1);assert.equal(stores.queue.tracks[stores.queue.index].id,2);
groups.toggle(groups.rows(library.searchResults.tracks,'local')[0]);library.playSearchTrack(2);
assert.deepEqual(ids(stores.queue.tracks),[1,3,2]);assert.equal(stores.queue.tracks[stores.queue.index].id,3);
groups.toggle(groups.rows(library.displaySearchResults.tracks,'search')[0]);library.playSearchTrack(2);
assert.deepEqual(ids(stores.queue.tracks),[1,'fed:3',2]);assert.equal(stores.queue.tracks[stores.queue.index].id,'fed:3');
});