// Run only against a fresh disposable instance: federation disabled, no Spotify client id, // FURU_AGENT_STORAGE_DIR equal to FURU_TEST_STORAGE_DIR. The test seeds the library over psql // and writes small media files into the storage directory. const {chromium}=require(process.env.PLAYWRIGHT_MODULE||'playwright'); const assert=require('node:assert/strict'); const fs=require('node:fs'),path=require('node:path'); const {spawnSync}=require('node:child_process'); const fflate=require('../src/player/vendor/fflate-0.8.2.min.js'); const base=process.env.FURU_TEST_URL||'http://127.0.0.1:3020'; const container=process.env.FURU_TEST_PG_CONTAINER||'furumi-libimport-test-pg'; const database=process.env.FURU_TEST_DATABASE||'furumi_libimport_live'; const storage=process.env.FURU_TEST_STORAGE_DIR; const shots=process.env.FURU_SCREENSHOT_DIR||path.resolve(__dirname,'../target'); assert.ok(storage&&path.isAbsolute(storage),'FURU_TEST_STORAGE_DIR must be the absolute FURU_AGENT_STORAGE_DIR of the instance'); function sql(statement) { const result=spawnSync('docker',['exec','-i',container,'psql','-U','postgres','-d',database,'-At','-v','ON_ERROR_STOP=1'],{input:statement,encoding:'utf8'}); assert.equal(result.status,0,result.stderr);return result.stdout.trim(); } const quote=value=>`'${String(value).replace(/'/g,"''")}'`; const stamp="'2026-11-26T00:00:00Z'"; // One library track with its artist, release and audio file in the storage directory. function seedTrack({artist,release,title,duration}) { const file=`library-import-live/${title.replace(/\W+/g,'-').toLowerCase()}.flac`; fs.mkdirSync(path.join(storage,'library-import-live'),{recursive:true}); fs.writeFileSync(path.join(storage,file),`live import fixture: ${artist} - ${title}`); return sql(`WITH a AS ( INSERT INTO furumusic__artist (name,name_sort,is_hidden,created_at,updated_at) SELECT ${quote(artist)},${quote(artist.toLowerCase())},false,${stamp},${stamp} WHERE NOT EXISTS (SELECT 1 FROM furumusic__artist WHERE name=${quote(artist)}) RETURNING id), artist AS (SELECT id FROM a UNION ALL SELECT id FROM furumusic__artist WHERE name=${quote(artist)}), r AS (INSERT INTO furumusic__release (title,title_sort,release_type,is_hidden,created_at,updated_at) VALUES (${quote(release)},${quote(release.toLowerCase())},'album',false,${stamp},${stamp}) RETURNING id), ra AS (INSERT INTO furumusic__release_artist (release_id,artist_id,position) SELECT r.id,artist.id,0 FROM r,artist), m AS (INSERT INTO furumusic__media_file (file_type,file_path,original_filename,mime_type,file_size_bytes,sha256_hash,created_at) VALUES ('audio',${quote(file)},${quote(path.basename(file))},'audio/flac',64,${quote('live-'+file)},${stamp}) RETURNING id), t AS (INSERT INTO furumusic__track (title,title_sort,release_id,duration_seconds,audio_file_id,is_hidden,created_at,updated_at) SELECT ${quote(title)},${quote(title.toLowerCase())},r.id,${duration},m.id,false,${stamp},${stamp} FROM r,m RETURNING id), ta AS (INSERT INTO furumusic__track_artist (track_id,artist_id,role,position) SELECT t.id,artist.id,'main',0 FROM t,artist) SELECT id FROM t;`); } const track=(trackName,artistName,albumName)=>({track:{trackName,artistName,albumName,trackUri:'spotify:track:'+Buffer.from(trackName).toString('hex').slice(0,22)}, episode:null,audiobook:null,localTrack:null,addedDate:'2026-11-01'}); const exportFiles={ 'Spotify Account Data/Playlist1.json':{playlists:[ {name:'Road trip',lastModifiedDate:'2026-11-01',collaborators:[],items:[ track('Paranoid Android','Radiohead','OK Computer'), track('Come Together - Remastered 2009','The Beatles','Abbey Road (Remastered)'), {track:null,episode:{episodeName:'Episode 12: Tour stories',showName:'Example Music Podcast',episodeUri:'spotify:episode:4rOoJ6Egrf8K2IrywzwOMk'},audiobook:null,localTrack:null,addedDate:'2026-11-02'}, track('Teardrop','Massive Attack','Mezzanine'), track('A track nobody has','Unknown Artist','Nowhere'), {track:null,episode:null,audiobook:null,localTrack:{uri:'spotify:local:My+Band:Garage+Tapes:Demo+Song:215'},addedDate:'2026-11-03'}, track('Paranoid Android','Radiohead','OK Computer'), ]}, {name:'Rainy day',lastModifiedDate:'2026-11-01',collaborators:[],items:[ track('Late Arrival','Night Owls','Moonlight'), track('Teardrop','Massive Attack','Mezzanine'), ]}, ]}, 'Spotify Account Data/YourLibrary.json':{tracks:[ {artist:'Björk',album:'Homogenic',track:'Jóga',uri:'spotify:track:4eeeeeeeeeeeeeeeeeeeee'}, {artist:'Кино',album:'Группа крови',track:'Группа крови',uri:'spotify:track:5fffffffffffffffffffff'}, ],albums:[],shows:[],episodes:[],bannedTracks:[],artists:[],bannedArtists:[],other:[]}, 'Spotify Account Data/StreamingHistory0.json':[{endTime:'2026-11-01 10:00',artistName:'Private Artist',trackName:'Private listening history entry',msPlayed:1000}], }; const exportZip=Buffer.from(fflate.zipSync(Object.fromEntries(Object.entries(exportFiles) .map(([name,value])=>[name,Buffer.from(JSON.stringify(value,null,2))])))); (async()=>{ const browser=await chromium.launch({headless:true,executablePath:process.env.CHROME_PATH||'/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'}); try{ const context=await browser.newContext({viewport:{width:1440,height:1000},locale:'en-US'}); const page=await context.newPage();const errors=[];page.on('pageerror',error=>errors.push(error.message)); const posts=[]; page.on('request',request=>{if(request.method()==='POST'&&new URL(request.url()).pathname.startsWith('/api/imports')) posts.push({path:new URL(request.url()).pathname,body:request.postData()});}); const api=async(url,options)=>{const response=await context.request.fetch(base+url,options); assert.ok(response.ok(),`${url}: ${response.status()} ${await response.text()}`);return response.json();}; const view=name=>page.waitForFunction(value=>window.Alpine?.store('library')?.view===value,name); const waitDone=async id=>{ for(let attempt=0;attempt<120;attempt++){ const record=await api(`/api/imports/${id}`); if(record.status==='done'&&record.statistics.pending===0&&record.statistics.publication_pending===0)return record; assert.ok(['queued','running','done'].includes(record.status),JSON.stringify(record)); await new Promise(resolve=>setTimeout(resolve,500)); } throw new Error(`import ${id} did not finish`); }; const playlistTitles=async id=>(await api(`/api/player/playlists/${id}`)).tracks.map(entry=>entry.title); const noHorizontalScroll=()=>page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth); // Administrator and library: exact matches, a remaster-only-on-one-side doubt, the rest missing. await page.goto(base+'/admin/setup'); assert.equal(await page.locator('[name=confirm_password]').count(),1,'the instance already has an administrator; start a fresh one'); await page.locator('[name=username]').fill('importer'); await page.locator('[name=password]').fill('library-import-password'); await page.locator('[name=confirm_password]').fill('library-import-password'); await page.locator('form button[type=submit]').click();await page.waitForURL('**/admin/v2'); const paranoid=seedTrack({artist:'Radiohead',release:'OK Computer',title:'Paranoid Android',duration:387}); const together=seedTrack({artist:'The Beatles',release:'Abbey Road',title:'Come Together',duration:259}); const teardrop=seedTrack({artist:'Massive Attack',release:'Mezzanine',title:'Teardrop',duration:330}); const joga=seedTrack({artist:'Björk',release:'Homogenic',title:'Jóga',duration:305}); assert.ok([paranoid,together,teardrop,joga].every(id=>Number(id)>0)); // The account menu leads to the page: Followed, Import library, Settings. await page.goto(base+'/');await page.waitForFunction(()=>window.Alpine?.store('library')); await page.locator('.sidebar-account-trigger').click(); const labels=(await page.locator('#sidebar-account-actions .account-action-list > *').allInnerTexts()).map(text=>text.trim()); const at=label=>labels.indexOf(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.getByText('No imports yet. Start with New import.').waitFor(); // Wizard: Spotify data export; only Playlist*.json and YourLibrary.json leave the browser. const upload=async()=>{ await page.getByRole('button',{name:'New import'}).click(); const dialog=page.locator('dialog#import-wizard');await dialog.waitFor(); 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(2).waitFor(); return dialog; }; const dialog=await upload(); const previews=posts.filter(post=>post.path==='/api/imports/preview'); assert.equal(previews.length,1); const preview=JSON.parse(previews[0].body); assert.deepEqual(preview.files.map(file=>file.name).sort(),['Spotify Account Data/Playlist1.json','Spotify Account Data/YourLibrary.json']); assert.ok(!previews[0].body.includes('Private listening history'),'listening history reached the server'); await dialog.getByText('Files read: 2.',{exact:true}).waitFor(); const rows=dialog.locator('.import-select-list li'); assert.deepEqual((await rows.locator('.import-select-copy strong').allInnerTexts()).map(text=>text.trim()),['Liked Songs','Road trip','Rainy day']); const boxes=rows.locator('input[type=checkbox]'); for(let index=0;index<3;index++)assert.equal(await boxes.nth(index).isChecked(),true); await dialog.getByText('not supported: 2').waitFor(); assert.equal(await dialog.getByRole('switch').isDisabled(),true,'federation is off on this server'); await dialog.getByText('Federation is turned off on this server.').waitFor(); await page.screenshot({path:path.join(shots,'library-import-live-wizard.png')}); await dialog.getByRole('button',{name:'Start import'}).click(); await view('import_detail');await dialog.waitFor({state:'detached'}); const start=posts.find(post=>post.path==='/api/imports'); const started=JSON.parse(start.body); assert.equal(started.selection.length,3);assert.equal(started.federated_search,false); assert.ok(!start.body.includes('Private listening history')); const id=Number(page.url().match(/#imports\/(\d+)$/)[1]);assert.ok(id>0); // The real worker resolves and publishes; the page shows the statistics. const record=await waitDone(id); const stats=record.statistics; assert.deepEqual({total:stats.total,matched_local:stats.matched_local,matched_federation:stats.matched_federation,ambiguous:stats.ambiguous, unmatched:stats.unmatched,unsupported:stats.unsupported,failed:stats.failed,published:stats.published,duplicate:stats.duplicate}, {total:11,matched_local:5,matched_federation:0,ambiguous:1,unmatched:3,unsupported:2,failed:0,published:4,duplicate:1},JSON.stringify(stats)); await page.locator('.import-heading .import-status',{hasText:'Done'}).waitFor({timeout:10000}); const shown=async()=>(await page.locator('.import-stats dd').allInnerTexts()).map(text=>text.trim()); await page.waitForFunction(()=>document.querySelector('.import-stats dd')?.textContent.trim()==='11'); assert.deepEqual(await shown(),['11','5','4','1','3','2']); // Private playlists in source order without repeats, in the API and the sidebar. const detail=await api(`/api/imports/${id}`); const targets=Object.fromEntries(detail.source_playlists.map(playlist=>[playlist.title,playlist.target_playlist_id])); assert.deepEqual(Object.keys(targets).sort(),['Liked Songs','Rainy day','Road trip']); assert.ok(Object.values(targets).every(target=>target>0)); const own=await api('/api/player/playlists'); const names={'Road trip':'Road trip','Rainy day':'Rainy day','Liked Songs':'Liked Songs (Spotify)'}; for(const [title,target] of Object.entries(targets)){ const playlist=own.find(entry=>entry.id===target); assert.ok(playlist,`${title} is not among the user's playlists`); assert.equal(playlist.title,names[title]);assert.equal(playlist.is_public,false,JSON.stringify(playlist)); } assert.deepEqual(await playlistTitles(targets['Road trip']),['Paranoid Android','Teardrop']); assert.deepEqual(await playlistTitles(targets['Rainy day']),['Teardrop']); assert.deepEqual(await playlistTitles(targets['Liked Songs']),['Jóga']); await page.reload();await view('import_detail'); for(const title of Object.values(names))await page.locator('.sidebar-left').getByText(title,{exact:true}).first().waitFor(); await page.locator('.import-item').first().waitFor(); await page.screenshot({path:path.join(shots,'library-import-live-detail.png'),fullPage:true}); // The detail page links to the playlist, which the player shows in source order. await page.locator('.import-playlists a',{hasText:'Road trip'}).click(); await view('playlist_detail');assert.ok(page.url().endsWith(`#playlist/${targets['Road trip']}`)); await page.waitForFunction(()=>Alpine.store('library').currentPlaylist?.tracks?.length===2); const rowTitles=page.locator('.playlist-track-row .track-title'); assert.deepEqual((await rowTitles.allInnerTexts()).map(text=>text.trim()),['Paranoid Android','Teardrop']); await page.goBack();await view('import_detail');await page.locator('.import-item').first().waitFor(); // Filters list the unmatched and unsupported entries. const filter=async(label,count)=>{ await page.locator('.import-filters button',{hasText:label}).click(); await page.waitForFunction(n=>{const store=Alpine.store('imports');return store.itemsLoaded&&!store.itemsLoading&&store.items.length===n;},count); return (await page.locator('.import-item > .import-item-copy > strong').allInnerTexts()).map(text=>text.trim()); }; assert.deepEqual((await filter('Not found',3)).sort(),['A track nobody has','Late Arrival','Группа крови'].sort()); assert.deepEqual(await filter('Not supported',2),['Episode 12: Tour stories','Demo Song']); await page.locator('.import-item',{hasText:'Podcast episode'}).waitFor(); await page.locator('.import-item',{hasText:'Local file'}).waitFor(); assert.equal((await filter('All',11)).length,11); // A manual choice for the remaster doubt is published by the next pass. assert.deepEqual(await filter('Needs a choice',1),['Come Together - Remastered 2009']); const candidate=page.locator('.import-candidate',{hasText:'Come Together'}).first(); await candidate.getByText('Abbey Road',{exact:false}).waitFor(); await candidate.getByRole('button',{name:'Choose'}).click(); await page.getByRole('status').filter({hasText:'The track will be added to the playlist.'}).waitFor(); const chosen=posts.find(post=>/\/items\/\d+\/match$/.test(post.path));assert.deepEqual(JSON.parse(chosen.body),{candidate:0}); const afterChoice=(await waitDone(id)).statistics; assert.equal(afterChoice.ambiguous,0);assert.equal(afterChoice.matched_local,6);assert.equal(afterChoice.published,5); assert.deepEqual(await playlistTitles(targets['Road trip']),['Paranoid Android','Teardrop','Come Together']); const choice=(await api(`/api/imports/${id}/items?status=matched&q=Come`)).items; assert.equal(choice.length,1);assert.equal(choice[0].publication_status,'published'); // Importing the same export again: every playlist is flagged as already imported. await page.goto(base+'/#imports');await view('imports'); await page.locator('.import-history-row').first().waitFor(); const again=await upload(); await again.getByText('This export was already imported.').waitFor(); assert.equal(await again.getByText(`Already imported in #${id}`).count(),3); for(let index=0;index<3;index++)assert.equal(await again.locator('.import-select-list li input[type=checkbox]').nth(index).isDisabled(),true); assert.equal(await again.getByRole('button',{name:'Start import'}).isDisabled(),true); await page.screenshot({path:path.join(shots,'library-import-live-again.png')}); await again.locator('.player-dialog-close').click();await again.waitFor({state:'detached'}); // Retry unmatched finds a track added to the library meanwhile and appends it. seedTrack({artist:'Night Owls',release:'Moonlight',title:'Late Arrival',duration:200}); await page.goto(`${base}/#imports/${id}`);await view('import_detail'); await page.locator('.import-heading .import-status',{hasText:'Done'}).waitFor(); await page.getByRole('button',{name:'Retry unmatched'}).click(); const panel=page.locator('#import-retry-panel');await panel.waitFor(); assert.equal(await panel.getByRole('switch').isDisabled(),true); await panel.getByRole('button',{name:'Retry',exact:true}).click(); await page.getByRole('status').filter({hasText:'Unmatched tracks will be searched again.'}).waitFor(); const retry=posts.find(post=>post.path===`/api/imports/${id}/resync`);assert.ok(retry,'Retry unmatched was not sent'); const afterRetry=(await waitDone(id)).statistics; assert.equal(afterRetry.unmatched,2);assert.equal(afterRetry.matched_local,7);assert.equal(afterRetry.published,6); assert.deepEqual(await playlistTitles(targets['Rainy day']),['Teardrop','Late Arrival']); await page.waitForFunction(()=>document.querySelector('.import-stats dd')?.textContent.trim()==='11' &&document.querySelectorAll('.import-stats dd')[2]?.textContent.trim()==='6',null,{timeout:10000}); // Mobile: the history and the details fit the screen. await page.setViewportSize({width:390,height:844}); await page.goto(base+'/#imports');await view('imports');await page.locator('.import-history-row').first().waitFor(); assert.equal(await noHorizontalScroll(),true,'the import history scrolls horizontally'); await page.screenshot({path:path.join(shots,'library-import-live-mobile.png')}); await page.goto(`${base}/#imports/${id}`);await view('import_detail');await page.locator('.import-item').first().waitFor(); assert.equal(await noHorizontalScroll(),true,'the import details scroll horizontally'); await page.screenshot({path:path.join(shots,'library-import-live-mobile-detail.png'),fullPage:true}); await page.setViewportSize({width:1440,height:1000}); // Delete history keeps the created playlists and their tracks. page.once('dialog',prompt=>{assert.match(prompt.message(),/Created playlists stay/);prompt.accept();}); await page.getByRole('button',{name:'Delete history'}).click(); await view('imports'); await page.getByText('No imports yet. Start with New import.').waitFor(); assert.deepEqual((await api('/api/imports')).imports,[]); assert.equal((await context.request.get(`${base}/api/imports/${id}`)).status(),404); assert.deepEqual(await playlistTitles(targets['Road trip']),['Paranoid Android','Teardrop','Come Together']); assert.deepEqual(await playlistTitles(targets['Rainy day']),['Teardrop','Late Arrival']); assert.deepEqual(await playlistTitles(targets['Liked Songs']),['Jóga']); assert.deepEqual(errors,[]); console.log('PASS: menu order, ZIP with playlist files only, real worker, statistics, private playlists in source order, filters, manual choice, already imported, Retry unmatched, Delete history, mobile'); } finally {await browser.close();} })().catch(error=>{console.error(error);process.exitCode=1;});