Files
furumi-web/tests/browser-library-import.cjs
T
sanapachandClaude Opus 5.5 d275e7326b Add the Import library page and wizard to the web player
Import library sits between Followed and Settings in the account menu and
opens #imports: the sources, the history with statistics and links to the
created playlists, and #imports/N with progress, per-playlist results, a
deleted-playlist notice with Create again, and the entries with status and
playlist filters, search, paging and the candidates of doubtful entries to
choose from. Retry unmatched (with the federated search consent), Cancel,
Delete history and a new Spotify sign-in for waiting imports call the
existing /api/imports endpoints. The page polls every 3 s while an import
runs. It follows the player's views, skeletons, dialogs, switches and
phrase table in English and Russian.

The New import wizard picks a source, then the data export or the Spotify
sign-in, then the playlists: imported ones cannot be selected, similar ones
need an explicit confirmation, and federated search is off until the user
turns it on. A ZIP export is opened in the browser with fflate 0.8.2,
vendored with its MIT licence and served at /vendor/fflate-0.8.2.js only
when an archive is picked. Only Playlist*.json and YourLibrary.json are
extracted; archives over 256 MiB, with more than 2,000 entries, more than
256 playlist files or more than 32 MiB declared for them are refused before
anything is decompressed, and a request over 32 MiB is not sent.

Federated tracks can now be removed from a playlist in edit mode:
DELETE /api/player/tracks/content/playlist checks the owner and records the
existing PlaylistTrackRemoved operation. The body-level dialogs get an
Alpine root, which also makes Get app open again.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 19:05:30 +02:00

242 lines
20 KiB
JavaScript

// Render first: FURU_LIBRARY_IMPORT_RENDER_FIXTURE=1 cargo test library_import::tests::web
// Uses the real rendered player with isolated API fixtures; no service or user data.
const {chromium}=require(process.env.PLAYWRIGHT_MODULE||'playwright');
const fs=require('node:fs'),path=require('node:path'),assert=require('node:assert/strict');
const root=path.resolve(__dirname,'..');
const fflate=require('../src/player/vendor/fflate-0.8.2.min.js');
const html=fs.readFileSync(path.join(root,'target/library-import-player-fixture.html'),'utf8');
const zipReader=fs.readFileSync(path.join(root,'src/player/vendor/fflate-0.8.2.min.js'),'utf8');
const shots=process.env.FURU_SCREENSHOT_DIR||path.join(root,'target');
const host='http://library-import.test';
const stats=(extra={})=>({total:6,pending:0,matched_local:2,matched_federation:1,ambiguous:1,unmatched:1,unsupported:1,failed:0,
published:3,publication_pending:0,duplicate:0,already_present:0,no_content_id:0,deferred_sync_limit:0,paused:0,publication_failed:0,catalog_errors:0,...extra});
const history=[
{id:4,provider:'spotify',source_type:'file',status:'running',phase:'resolve_local',federated_search:false,cancel_requested:false,
statistics:stats({pending:3,published:0}),error:null,created_at:'2026-11-26T10:00:00Z',updated_at:'2026-11-26T10:00:00Z',last_resync_at:null,playlists:[]},
{id:3,provider:'spotify',source_type:'api',status:'needs_reauth',phase:'fetching',federated_search:false,cancel_requested:false,
statistics:stats({total:0,matched_local:0,matched_federation:0,ambiguous:0,unmatched:0,unsupported:0,published:0}),error:null,
created_at:'2026-11-25T10:00:00Z',updated_at:'2026-11-25T10:00:00Z',last_resync_at:null,playlists:[]},
{id:2,provider:'spotify',source_type:'file',status:'done',phase:null,federated_search:false,cancel_requested:false,statistics:stats(),error:null,
created_at:'2026-11-24T10:00:00Z',updated_at:'2026-11-24T10:00:00Z',last_resync_at:null,
playlists:[{id:20,title:'Road trip',target_playlist_id:500,target_deleted:false},{id:21,title:'Liked Songs (Spotify)',target_playlist_id:501,target_deleted:false}]},
];
const detail=id=>({...history.find(record=>record.id===id),source_playlists:[
{id:20,kind:'playlist',ordinal:0,title:'Road trip',description:null,target_playlist_id:500,target_created_at:null,target_deleted:false,publication_paused:false,total:4,matched:2,published:2},
{id:21,kind:'favorites',ordinal:1,title:'Liked Songs (Spotify)',description:null,target_playlist_id:501,target_created_at:null,target_deleted:true,publication_paused:true,total:2,matched:1,published:1},
],attempt:null});
const items=[
{id:90,playlist_id:20,position:0,metadata:{kind:'track',title:'Northern Lights',artists:['Aurora Band'],album:'Skies',duration_ms:215000},
resolution_status:'matched',resolution_note:null,match_origin:'local',publication_status:'published',candidates:null},
{id:91,playlist_id:20,position:1,metadata:{kind:'track',title:'Harbour (Live)',artists:['Sea Choir'],album:'Live at the Pier',duration_ms:301000},
resolution_status:'ambiguous',resolution_note:null,match_origin:null,publication_status:'not_ready',
candidates:[{origin:'local',title:'Harbour',artists:['Sea Choir'],album:'Pier',duration_seconds:300,content_id:null,track_id:7},
{origin:'federation',title:'Harbour (Live)',artists:['Sea Choir'],album:'Live at the Pier',duration_seconds:302,content_id:'b3:'+'1'.repeat(64)}]},
{id:92,playlist_id:20,position:2,metadata:{kind:'track',title:'A track nobody has',artists:['Unknown Artist']},
resolution_status:'unmatched',resolution_note:'not_found',publication_status:'not_ready',candidates:null},
{id:93,playlist_id:21,position:0,metadata:{kind:'episode',title:'A podcast episode',artists:[]},
resolution_status:'unsupported',resolution_note:'episode',publication_status:'not_ready',candidates:null},
];
const exportZip=Buffer.from(fflate.zipSync({
'Spotify Account Data/Playlist1.json':Buffer.from(JSON.stringify({playlists:[{name:'Road trip',items:[{track:{trackName:'Northern Lights',artistName:'Aurora Band'}}]}]},null,2)),
'Spotify Account Data/YourLibrary.json':Buffer.from(JSON.stringify({tracks:[{artist:'Sea Choir',track:'Harbour',album:'Pier'}]})),
'Spotify Account Data/StreamingHistory_music_0.json':Buffer.from(JSON.stringify([{trackName:'Private listening history entry'}])),
'Spotify Account Data/Userdata.json':Buffer.from(JSON.stringify({email:'listener@example.test'})),
}));
const fedTrack={content_id:'b3:'+'2'.repeat(64),position:1,federation:{content_id:'b3:'+'2'.repeat(64),owner:'peer-a',item_id:'item-2',
title:'Peer song',artist_names:['Peer Artist'],featured_artist_names:[],duration_seconds:200,release_title:'Peer album'}};
(async()=>{
const browser=await chromium.launch({headless:true,...(process.env.CHROME_PATH?{executablePath:process.env.CHROME_PATH}:{})});
try{
const requests=[],errors=[];
const context=await browser.newContext({viewport:{width:1440,height:1000}});
const fixture=async route=>{
const request=route.request(),url=new URL(request.url()),method=request.method();
if(url.origin!==host)return route.fulfill({status:404,body:''});
if(url.pathname==='/')return route.fulfill({contentType:'text/html',body:html});
if(url.pathname==='/vendor/fflate-0.8.2.js'){requests.push({method,path:url.pathname});return route.fulfill({contentType:'text/javascript',body:zipReader});}
if(!url.pathname.startsWith('/api/'))return route.fulfill({status:404,body:''});
const body=request.postData()?JSON.parse(request.postData()):undefined;
requests.push({method,path:url.pathname,search:url.search,body});
const json=data=>route.fulfill({json:data});
if(url.pathname==='/api/player/me')return json({id:1,name:'Listener',username:'listener',role:'user'});
if(url.pathname==='/api/imports/providers')return json({providers:[{id:'spotify',name:'Spotify',methods:['file','api']}],federated_search_available:true});
if(url.pathname==='/api/imports'&&method==='GET')return json({imports:history});
if(url.pathname==='/api/imports/preview')return json({provider:'spotify',source:'file',all_imported:false,federated_search_available:true,playlists:[
{source_key:'sha256:road',kind:'playlist',title:'Road trip',description:null,track_count:1,unsupported_count:0,available:true,already_imported_in:null,similar_to:null},
{source_key:'sha256:old',kind:'playlist',title:'Old mix',description:null,track_count:12,unsupported_count:0,available:true,already_imported_in:2,similar_to:null},
{source_key:'sha256:gym',kind:'playlist',title:'Gym',description:null,track_count:40,unsupported_count:2,available:true,already_imported_in:null,similar_to:{import_id:2,target_playlist_id:500}},
{source_key:'sha256:liked',kind:'favorites',title:'Liked Songs',description:null,track_count:1,unsupported_count:0,available:true,already_imported_in:null,similar_to:null},
]});
if(url.pathname==='/api/imports'&&method==='POST')return json({id:2,status:'queued'});
let match=url.pathname.match(/^\/api\/imports\/(\d+)(\/.*)?$/);
if(match){
const id=Number(match[1]),rest=match[2]||'';
if(rest==='/items'){
const status=url.searchParams.get('status');
return json({items:items.filter(item=>!status||item.resolution_status===status),next:null});
}
if(rest.endsWith('/match'))return json({resolution_status:'matched',publication_status:'pending'});
if(rest==='/resync')return json({status:'queued'});
if(rest==='/cancel')return json({status:'cancelling'});
if(rest.endsWith('/recreate'))return json({status:'requested'});
if(method==='DELETE')return json({ok:true});
return json(detail(id));
}
if(url.pathname.startsWith('/api/imports/providers/spotify/authorize'))return route.fulfill({contentType:'text/html',body:'<p>Spotify sign-in</p>'});
if(url.pathname==='/api/player/playlists/500')return json({id:500,title:'Road trip',kind:'user',is_own:true,is_public:false,owner_name:'Listener',tracks:[
{id:7,playlist_track_id:70,content_id:'b3:'+'3'.repeat(64),title:'Northern Lights',artists:[{id:1,name:'Aurora Band'}],featured_artists:[],duration_seconds:215,release_title:'Skies',stream_url:'/api/player/stream/7'}]});
if(url.pathname==='/api/player/playlists/500/federation-tracks')return json([fedTrack]);
if(url.pathname==='/api/player/tracks/content/playlist')return json({ok:true});
if(url.pathname==='/api/player/playlists')return json([{id:500,title:'Road trip',kind:'user',is_own:true,track_count:2}]);
return json([]);
};
await context.route('**/*',fixture);
const page=await context.newPage();
page.on('pageerror',error=>errors.push(error.message));
if(process.env.DEBUG)page.on('console',message=>console.log('console:',message.text()));
const view=async name=>page.waitForFunction(v=>window.Alpine?.store('library')?.view===v,name);
// The menu entry sits between Followed and Settings and opens the page.
await page.goto(host+'/#artists');await view('artists');
await page.locator('.sidebar-account-trigger').click();
const labels=await page.locator('#sidebar-account-actions .account-action-list > *').allInnerTexts();
const at=label=>labels.findIndex(text=>text.trim()===label);
assert.ok(at('Followed')>=0&&at('Import library')===at('Followed')+1&&at('Settings')===at('Import library')+1,JSON.stringify(labels));
await page.locator('#sidebar-account-actions').getByRole('link',{name:'Import library'}).click();
await view('imports');assert.ok(page.url().endsWith('#imports'));
await page.getByRole('heading',{name:'Import library',level:1}).waitFor();
await page.locator('.import-history-row').nth(2).waitFor();
assert.equal(await page.locator('#sidebar-account-actions a[href="#imports"]').getAttribute('aria-current'),'page');
assert.equal(await page.locator('.import-history-row').count(),3);
assert.equal(await page.locator('.import-history-row').first().locator('.import-status').innerText(),'Running');
assert.equal(await page.locator('.import-history-playlists a').first().getAttribute('href'),'#playlist/500');
await page.screenshot({path:path.join(shots,'library-import-history.png')});
// The running import is polled every 3 seconds.
const lists=()=>requests.filter(r=>r.path==='/api/imports'&&r.method==='GET').length;
const before=lists();await page.waitForTimeout(3400);assert.ok(lists()>before,'history was not polled');
// Wizard: Data export ZIP; only playlist files reach the server.
await page.getByRole('button',{name:'New import'}).click();
const dialog=page.locator('dialog#import-wizard');await dialog.waitFor();
assert.equal(await dialog.evaluate(element=>element.open&&element.matches('.player-dialog')),true);
assert.equal(requests.filter(r=>r.path==='/vendor/fflate-0.8.2.js').length,0,'the ZIP reader must load lazily');
await dialog.getByRole('button',{name:/Data export/}).click();
await dialog.locator('input[type=file]').setInputFiles({name:'my_spotify_data.zip',mimeType:'application/zip',buffer:exportZip});
await dialog.locator('.import-select-list li').nth(3).waitFor();
const preview=requests.find(r=>r.path==='/api/imports/preview');
assert.deepEqual(preview.body.files.map(file=>file.name).sort(),['Spotify Account Data/Playlist1.json','Spotify Account Data/YourLibrary.json']);
assert.ok(!JSON.stringify(preview.body).includes('Private listening history'));
assert.ok(!JSON.stringify(preview.body).includes('listener@example.test'));
assert.equal(requests.filter(r=>r.path==='/vendor/fflate-0.8.2.js').length,1);
const boxes=dialog.locator('.import-select-list li input[type=checkbox]');
assert.equal(await boxes.nth(0).isChecked(),true);
assert.equal(await boxes.nth(1).isDisabled(),true);
assert.equal(await boxes.nth(2).isChecked(),false);
await dialog.getByText('Already imported in #2').waitFor();
await boxes.nth(2).check();
await dialog.getByText('Create a new playlist').waitFor();
const consent=dialog.getByRole('switch');
assert.equal(await consent.getAttribute('aria-checked'),'false');
await dialog.getByText('Participants receive only artist names.',{exact:false}).waitFor();
await page.screenshot({path:path.join(shots,'library-import-wizard.png')});
await dialog.getByRole('button',{name:'Start import'}).click();
await dialog.getByText('Confirm creating new playlists',{exact:false}).waitFor();
assert.equal(requests.filter(r=>r.path==='/api/imports'&&r.method==='POST').length,0);
await dialog.locator('.import-select-note label input').check();
await consent.click();assert.equal(await consent.getAttribute('aria-checked'),'true');
await dialog.getByRole('button',{name:'Start import'}).click();
await view('import_detail');await dialog.waitFor({state:'detached'});
const created=requests.find(r=>r.path==='/api/imports'&&r.method==='POST');
assert.deepEqual(created.body.selection,['sha256:road','sha256:gym','sha256:liked']);
assert.deepEqual(created.body.confirm_similar,['sha256:gym']);
assert.equal(created.body.federated_search,true);
assert.equal(created.body.files.length,2);
assert.ok(page.url().endsWith('#imports/2'));
// Details: statistics, playlists, filters, a manual choice and Retry with consent.
await page.locator('.import-item').nth(3).waitFor();
assert.equal(await page.locator('.import-stats dd').first().innerText(),'6');
await page.getByText('The playlist was deleted').waitFor();
await page.getByRole('button',{name:'Create again'}).click();
await page.waitForFunction(()=>Alpine.store('imports').message==='The playlist will be created again.');
assert.ok(requests.some(r=>r.path==='/api/imports/2/playlists/21/recreate'&&r.method==='POST'));
await page.screenshot({path:path.join(shots,'library-import-detail.png'),fullPage:true});
await page.locator('.import-filters button',{hasText:'Needs a choice'}).click();
await page.waitForFunction(()=>Alpine.store('imports').items.length===1);
assert.ok(requests.some(r=>r.path==='/api/imports/2/items'&&r.search==='?status=ambiguous'));
await page.locator('.import-candidate').nth(1).getByRole('button',{name:'Choose'}).click();
await page.waitForFunction(()=>Alpine.store('imports').message==='The track will be added to the playlist.'||Alpine.store('imports').items.every(item=>item.resolution_status!=='ambiguous'));
assert.deepEqual(requests.find(r=>r.path==='/api/imports/2/items/91/match').body,{candidate:1});
await page.getByRole('button',{name:'Retry unmatched'}).click();
const panel=page.locator('#import-retry-panel');await panel.waitFor();
await panel.getByRole('switch').click();
await panel.getByRole('button',{name:'Retry'}).click();
await page.waitForFunction(()=>Alpine.store('imports').message==='Unmatched tracks will be searched again.');
assert.deepEqual(requests.find(r=>r.path==='/api/imports/2/resync').body,{federated_search:true});
// Delete history keeps playlists; the page returns to the list.
page.once('dialog',prompt=>{assert.match(prompt.message(),/Created playlists stay/);prompt.accept();});
await page.getByRole('button',{name:'Delete history'}).click();
await view('imports');
assert.ok(requests.some(r=>r.path==='/api/imports/2'&&r.method==='DELETE'));
// A Spotify import waiting for a sign-in continues through the provider.
await page.goto(host+'/#imports/3?error=account_mismatch');await view('import_detail');
await page.getByText('Sign in with the Spotify account used for this import.').waitFor();
assert.ok(page.url().endsWith('#imports/3'));
await Promise.all([page.waitForURL('**/api/imports/providers/spotify/authorize?import_id=3'),
page.getByRole('button',{name:'Sign in to Spotify again'}).click()]);
// A federated track can be removed from the playlist in edit mode.
await page.goto(host+'/#playlist/500');await view('playlist_detail');
await page.waitForFunction(()=>Alpine.store('library').currentPlaylist?.tracks?.length===2);
await page.evaluate(()=>Alpine.store('playlists').toggleEditCurrent());
await page.locator('.playlist-track-row').nth(1).locator('.playlist-track-remove').click();
await page.waitForFunction(()=>Alpine.store('library').currentPlaylist.tracks.length===1);
assert.deepEqual(requests.find(r=>r.path==='/api/player/tracks/content/playlist'&&r.method==='DELETE').body,
{playlist_id:500,content_id:fedTrack.content_id});
// Mobile: the popover menu, the page and the wizard fit the screen.
await page.setViewportSize({width:390,height:844});
await page.goto(host+'/#artists');await view('artists');
await page.locator('.mobile-account-chip').click();
const mobileMenu=page.locator('#mobile-account-actions');
await mobileMenu.getByRole('link',{name:'Import library'}).waitFor({state:'visible'});
const mobileLabels=await mobileMenu.locator('.account-action-list > *').allInnerTexts();
assert.equal(mobileLabels.findIndex(text=>text.trim()==='Import library'),mobileLabels.findIndex(text=>text.trim()==='Followed')+1);
await page.waitForTimeout(250);await page.screenshot({path:path.join(shots,'library-import-mobile-menu.png')});
await mobileMenu.getByRole('link',{name:'Import library'}).click();await view('imports');
await page.locator('.import-history-row').first().waitFor();
assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth>innerWidth),false);
await page.waitForTimeout(250);await page.screenshot({path:path.join(shots,'library-import-mobile.png')});
await page.goto(host+'/#imports/2');await view('import_detail');await page.locator('.import-item').first().waitFor();
assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth>innerWidth),false);
await page.screenshot({path:path.join(shots,'library-import-mobile-detail.png'),fullPage:true});
await page.evaluate(()=>Alpine.store('imports').startWizard('spotify'));
await page.locator('dialog#import-wizard').waitFor();
const surface=await page.locator('dialog#import-wizard .player-dialog-surface').boundingBox();
assert.ok(surface.width<=390,'the wizard fits the mobile screen');
await page.waitForTimeout(200);await page.screenshot({path:path.join(shots,'library-import-mobile-wizard.png')});
await page.locator('dialog#import-wizard .player-dialog-close').click();
await page.locator('dialog#import-wizard').waitFor({state:'detached'});
await page.close();
// With reduced motion the wizard opens and closes without animations.
const still=await browser.newContext({viewport:{width:1024,height:800},reducedMotion:'reduce'});
await still.route('**/*',fixture);
const calm=await still.newPage();calm.on('pageerror',error=>errors.push(error.message));
await calm.goto(host+'/#imports');
await calm.waitForFunction(()=>Alpine.store('library').view==='imports'&&Alpine.store('imports').loaded);
await calm.getByRole('button',{name:'New import'}).click();
const calmDialog=calm.locator('dialog#import-wizard');await calmDialog.waitFor();
assert.equal(await calmDialog.locator('.player-dialog-surface').evaluate(element=>getComputedStyle(element).animationName),'none');
await calm.keyboard.press('Escape');
await calmDialog.waitFor({state:'detached',timeout:500});
await still.close();
assert.deepEqual(errors,[]);
console.log('PASS: menu order, history polling, lazy ZIP reader with playlist files only, similar confirmation and consent, details, manual choice, Retry, Delete, Spotify sign-in continuation, federated track removal, mobile');
} finally {await browser.close();}
})().catch(error=>{console.error(error);process.exitCode=1;});