Files
furumi-web/tests/library_import.test.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

350 lines
20 KiB
JavaScript
Raw Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
const assert = require('node:assert/strict');
const {readFileSync} = require('node:fs');
const {test} = require('node:test');
const vm = require('node:vm');
const fflate = require('../src/player/vendor/fflate-0.8.2.min.js');
// Labels render as their phrase keys, so assertions name the message.
const source = readFileSync(`${__dirname}/../templates/player/imports_scripts.html`, 'utf8')
.replace(/<\/?script>/g, '').replace(/\{\{ t\.(\w+) \}\}/g, '$1');
const MiB = 1024 * 1024;
// Values from the script's realm are compared by structure.
const same = (actual, expected) => assert.deepEqual(JSON.parse(JSON.stringify(actual ?? null)), expected ?? null);
function setup(responder = () => ({json: {}})) {
const calls = [], timers = [], assigned = [], replaced = [];
const stores = {
library: {view: 'artists', _activeHash: '', _beginNavigation(hash) { this._activeHash = hash; }, _afterNavigation() {}},
mobile: {closeLibrary() {}},
user: {menuOpen: true},
playlists: {reloads: 0, reload() { this.reloads += 1; }},
};
const context = {
document: {documentElement: {lang: 'en'}, addEventListener(_, fn) { fn(); }, querySelector: () => null},
Alpine: {store(name, value) { if (value) stores[name] = value; return stores[name]; }},
fetch: async (url, options = {}) => {
const call = {url, method: options.method || 'GET', body: options.body === undefined ? undefined : JSON.parse(options.body)};
calls.push(call);
const {status = 200, json = {}} = responder(call) || {};
return {ok: status < 400, status, json: async () => json};
},
window: {fflate}, setTimeout: (fn, ms) => { timers.push({fn, ms}); return timers.length; },
clearTimeout: () => {}, confirm: () => true,
location: {assign: url => assigned.push(url)},
history: {state: null, replaceState: (_, __, hash) => replaced.push(hash)},
formatTime: seconds => `${Math.floor(seconds / 60)}:${String(Math.floor(seconds % 60)).padStart(2, '0')}`,
formatArtistCount: count => `${count} tracks`,
finishPlayerDialog: async (_, close) => close(),
Uint8Array, TextEncoder, TextDecoder, URLSearchParams,
};
vm.runInNewContext(source, context);
return {store: stores.imports, stores, calls, timers, assigned, replaced};
}
const exportFiles = {
'Spotify Account Data/Playlist1.json': {playlists: [{name: 'Road trip', items: [{track: {trackName: 'Song', artistName: 'Artist'}}]}]},
'Spotify Account Data/YourLibrary.json': {tracks: [{artist: 'Artist', track: 'Liked', album: 'Album'}]},
'Spotify Account Data/StreamingHistory_music_0.json': [{trackName: 'Private listening history'}],
'Spotify Account Data/Userdata.json': {email: 'person@example.test'},
'Spotify Account Data/Read Me First.pdf': 'not json',
};
function zipFile(entries, name = 'my_spotify_data.zip') {
const data = Object.fromEntries(Object.entries(entries).map(([path, value]) =>
[path, Buffer.from(typeof value === 'string' ? value : JSON.stringify(value, null, 2))]));
return new File([fflate.zipSync(data)], name, {type: 'application/zip'});
}
const preview = playlists => ({json: {provider: 'spotify', source: 'file', playlists, all_imported: false, federated_search_available: true}});
const playlist = (key, extra = {}) => ({source_key: key, kind: 'playlist', title: key, track_count: 2, available: true,
already_imported_in: null, similar_to: null, ...extra});
test('the browser unzips only playlist files and leaves listening history and account data behind', async () => {
const {store, calls} = setup(call => call.url === '/api/imports/preview' ? preview([playlist('a')]) : {json: {id: 7}});
store.chooseMethod('spotify', 'file');
await store.readFiles([zipFile(exportFiles)]);
assert.equal(store.wizard.error, '');
assert.equal(calls.length, 1);
const sent = calls[0].body;
assert.equal(sent.provider, 'spotify');
assert.equal(sent.source, 'file');
same(sent.files.map(file => file.name).sort(),
['Spotify Account Data/Playlist1.json', 'Spotify Account Data/YourLibrary.json']);
assert.equal(sent.files[0].data.playlists[0].name, 'Road trip');
assert.ok(!JSON.stringify(sent).includes('Private listening history'));
assert.ok(!JSON.stringify(sent).includes('person@example.test'));
assert.equal(store.wizard.step, 'select');
same(store.wizard.fileNames.sort(), ['Playlist1.json', 'YourLibrary.json']);
});
test('archive, entry, file and declared size limits stop a ZIP before anything is sent', async () => {
const {store, calls} = setup();
store.chooseMethod('spotify', 'file');
let read = false;
await store.readFiles([{name: 'huge.zip', type: 'application/zip', size: 257 * MiB, arrayBuffer: async () => { read = true; }}]);
assert.equal(store.wizard.error, 'player_import_archive_too_large');
assert.equal(read, false);
const entries = Object.fromEntries(Array.from({length: 2001}, (_, i) => [`misc/file${i}.txt`, 'x']));
await store.readFiles([zipFile(entries)]);
assert.equal(store.wizard.error, 'player_import_zip_too_many_entries');
const playlists = Object.fromEntries(Array.from({length: 257}, (_, i) => [`Playlist${i + 1}.json`, {playlists: []}]));
await store.readFiles([zipFile(playlists)]);
assert.equal(store.wizard.error, 'player_import_zip_too_many_files');
// A bomb declares a huge size; the declared sizes are checked before inflating.
const bomb = fflate.zipSync({'Playlist1.json': new Uint8Array(64 * 1024).fill(32)});
const view = new DataView(bomb.buffer);
for (let i = 0; i < bomb.length - 4; i++) {
if (view.getUint32(i, true) === 0x02014b50) view.setUint32(i + 24, 40 * MiB, true);
}
await store.readFiles([new File([bomb], 'bomb.zip')]);
assert.equal(store.wizard.error, 'player_import_export_too_large');
await store.readFiles([new File([Buffer.from('not a zip')], 'broken.zip')]);
assert.equal(store.wizard.error, 'player_import_zip_invalid');
await store.readFiles([new File(['{}'], 'StreamingHistory0.json')]);
assert.equal(store.wizard.error, 'player_import_no_files');
assert.equal(calls.length, 0);
same(store.wizard.files, []);
});
test('unzipped JSON files are accepted and an oversized request is refused in the browser', async () => {
const {store, calls} = setup(() => preview([playlist('a')]));
store.chooseMethod('spotify', 'file');
await store.readFiles([new File(['' + JSON.stringify(exportFiles['Spotify Account Data/Playlist1.json'])], 'Playlist1.json'),
new File(['[]'], 'StreamingHistory_music_0.json')]);
assert.equal(calls.length, 1);
same(calls[0].body.files.map(file => file.name), ['Playlist1.json']);
assert.equal(store.wizard.skipped, 1);
// Text that does not parse is sent as text; escaping can push it past the limit.
await store.readFiles([new File(['"'.repeat(20 * MiB)], 'Playlist1.json')]);
assert.equal(store.wizard.error, 'player_import_request_too_large');
assert.equal(calls.length, 1);
});
test('imported, unavailable and similar playlists need the right selection and confirmation', async () => {
const {store, calls, stores} = setup(call => call.url === '/api/imports'
? {json: {id: 12, status: 'queued'}}
: call.url.startsWith('/api/imports/12') ? {json: call.url.includes('items') ? {items: [], next: null} : {id: 12, status: 'queued', statistics: {}}} : {json: {}});
store.chooseMethod('spotify', 'file');
store.wizard.files = [{name: 'Playlist1.json', data: {}}];
store.applyPreview(preview([
playlist('fresh'), playlist('done', {already_imported_in: 3}),
playlist('similar', {similar_to: {import_id: 4, target_playlist_id: 40}}), playlist('locked', {available: false}),
]).json);
same(store.selection().map(p => p.source_key), ['fresh']);
store.selectAll(true);
same(store.selection().map(p => p.source_key), ['fresh']);
store.wizard.selected.done = true;
store.wizard.selected.locked = true;
same(store.selection().map(p => p.source_key), ['fresh']);
store.wizard.selected.similar = true;
assert.equal(store.canStart(), false);
await store.begin();
assert.equal(store.wizard.error, 'player_import_confirm_similar_needed');
assert.equal(calls.length, 0);
store.wizard.confirmed.similar = true;
store.wizard.federated = true;
await store.begin();
same(calls[0].body.selection, ['fresh', 'similar']);
same(calls[0].body.confirm_similar, ['similar']);
assert.equal(calls[0].body.federated_search, true);
assert.equal(calls[0].body.files.length, 1);
assert.equal(store.wizard.open, false);
same(store.wizard.files, []);
assert.equal(stores.library.view, 'import_detail');
assert.equal(stores.library._activeHash, '#imports/12');
});
test('federated search is never requested when the server has it turned off', async () => {
const {store, calls} = setup(() => ({json: {id: 1}}));
store.chooseMethod('spotify', 'file');
store.applyPreview({...preview([playlist('a')]).json, federated_search_available: false});
store.wizard.federated = true;
await store.begin();
assert.equal(calls[0].body.federated_search, false);
});
test('a conflict from the server marks playlists imported meanwhile', async () => {
const {store} = setup(() => ({status: 409, json: {error: 'some playlists were already imported',
conflicts: [{source_key: 'a', import_id: 9}]}}));
store.chooseMethod('spotify', 'file');
store.applyPreview(preview([playlist('a'), playlist('b')]).json);
await store.begin();
assert.equal(store.wizard.open, true);
assert.equal(store.wizard.error, 'player_import_conflicts');
assert.equal(store.wizard.preview.playlists[0].already_imported_in, 9);
same(store.selection().map(p => p.source_key), ['b']);
});
test('the history polls every 3 seconds only while an import is running', async () => {
let imports = [{id: 1, provider: 'spotify', status: 'running', statistics: {total: 4, published: 0}}];
const {store, stores, timers} = setup(call => call.url === '/api/imports/providers'
? {json: {providers: [{id: 'spotify', name: 'Spotify', methods: ['file', 'api']}], federated_search_available: true}}
: {json: {imports}});
await store.route(null, '', {fromHash: true});
assert.equal(stores.library.view, 'imports');
assert.equal(store.providerName('spotify'), 'Spotify');
assert.equal(timers.length, 1);
assert.equal(timers[0].ms, 3000);
imports = [{...imports[0], status: 'done', statistics: {total: 4, published: 3}}];
await timers[0].fn();
assert.equal(store.imports[0].status, 'done');
assert.equal(stores.playlists.reloads, 1);
assert.equal(timers.length, 1);
// Leaving the page stops polling.
imports = [{...imports[0], status: 'running'}];
store.schedule();
stores.library.view = 'artists';
const before = timers.length;
await timers.at(-1).fn();
assert.equal(timers.length, before);
});
test('details filter entries, choose candidates and retry with a new federated consent', async () => {
let detail = {id: 5, provider: 'spotify', status: 'done', federated_search: false, statistics: {total: 3, ambiguous: 1, unmatched: 1},
source_playlists: [{id: 50, title: 'Road trip', target_playlist_id: 500, target_deleted: false}]};
const item = {id: 80, playlist_id: 50, position: 0, metadata: {title: 'Song', artists: ['A']}, resolution_status: 'ambiguous',
candidates: [{origin: 'local', title: 'Song'}, {origin: 'federation', title: 'Song (Live)'}], publication_status: 'not_ready'};
const {store, calls, timers} = setup(call => {
if (call.url === '/api/imports/providers') return {json: {providers: [], federated_search_available: true}};
if (call.url.includes('/items/80/match')) return {json: {resolution_status: 'matched', publication_status: 'pending'}};
if (call.url.includes('/items')) return {json: {items: [item], next: null}};
if (call.url.endsWith('/resync')) { detail = {...detail, status: 'queued'}; return {json: {status: 'queued'}}; }
return {json: detail};
});
await store.route(5, '', {fromHash: true});
assert.equal(store.detail.id, 5);
assert.equal(store.items.length, 1);
same(store.statusFilters().map(f => f.status), ['', 'ambiguous', 'unmatched']);
store.setStatus('ambiguous');
await new Promise(resolve => setImmediate(resolve));
assert.ok(calls.some(call => call.url === '/api/imports/5/items?status=ambiguous'));
await store.choose(item, 1);
const chosen = calls.find(call => call.url === '/api/imports/5/items/80/match');
same(chosen.body, {candidate: 1});
assert.equal(item.match_origin, 'federation');
store.openRetry();
assert.equal(store.retryFederated, false);
store.retryFederated = true;
await store.retry(store.detail, store.retryFederated);
same(calls.find(call => call.url === '/api/imports/5/resync').body, {federated_search: true});
assert.equal(store.detail.status, 'queued');
assert.equal(store.message, 'player_import_retry_started');
assert.ok(timers.length >= 1);
});
test('history retry keeps the consent, and cancel and delete call the import endpoints', async () => {
const {store, calls} = setup(call => call.url === '/api/imports' ? {json: {imports: []}}
: call.url === '/api/imports/providers' ? {json: {providers: []}}
: call.url.endsWith('/cancel') ? {json: {status: 'cancelling'}} : {json: {id: 6, status: 'running', statistics: {}}});
await store.retry({id: 6});
same(calls[0], {url: '/api/imports/6/resync', method: 'POST', body: {}});
store.detailId = 6;
store.detail = {id: 6, status: 'running', statistics: {}};
await store.cancel();
assert.ok(calls.some(call => call.url === '/api/imports/6/cancel' && call.method === 'POST'));
assert.equal(store.message, 'player_import_cancel_requested');
await store.remove({id: 6, status: 'done'});
assert.ok(calls.some(call => call.url === '/api/imports/6' && call.method === 'DELETE'));
assert.equal(store.message, 'player_import_deleted');
});
test('the Spotify sign-in returns to the wizard or continues the waiting import', async () => {
const {store, calls, assigned, replaced} = setup(call => {
if (call.url === '/api/imports/providers/spotify/playlists') {
return {json: {provider: 'spotify', source: 'api', federated_search_available: true,
playlists: [playlist('spotify:playlist:1'), playlist('spotify:playlist:2', {available: false})]}};
}
if (call.url === '/api/imports') return {json: call.method === 'POST' ? {id: 3} : {imports: []}};
if (call.url === '/api/imports/providers') return {json: {providers: [{id: 'spotify', name: 'Spotify', methods: ['file', 'api']}]}};
if (call.url.includes('/items')) return {json: {items: [], next: null}};
return {json: {id: 3, provider: 'spotify', status: 'needs_reauth', statistics: {}}};
});
await store.route(null, 'connect=spotify', {fromHash: true});
await new Promise(resolve => setImmediate(resolve));
same(replaced, ['#imports']);
assert.equal(store.wizard.method, 'api');
assert.equal(store.wizard.step, 'select');
same(store.selection().map(p => p.source_key), ['spotify:playlist:1']);
await store.begin();
const created = calls.find(call => call.url === '/api/imports' && call.method === 'POST');
assert.equal(created.body.source, 'api');
assert.equal(created.body.files, undefined);
await store.route(null, 'connect=spotify&error=not_allowed', {fromHash: true});
assert.equal(store.wizard.error, 'player_import_oauth_not_allowed');
await store.route(3, 'error=account_mismatch', {fromHash: true});
assert.equal(store.notice, 'player_import_oauth_account_mismatch');
assert.equal(replaced.at(-1), '#imports/3');
assert.equal(store.hasActive(), false);
store.reauthorize();
same(assigned, ['/api/imports/providers/spotify/authorize?import_id=3']);
});
test('a sign-in from earlier in the session is used without asking again', async () => {
const {store} = setup(call => call.url.endsWith('/playlists')
? {status: 409, json: {error: 'sign in to Spotify first'}} : {json: {}});
await store.chooseMethod('spotify', 'api');
assert.equal(store.wizard.step, 'connect');
assert.equal(store.wizard.error, '');
});
test('progress follows the phase of a running import', () => {
const {store} = setup();
same(store.progress({status: 'running', phase: 'resolve_local', statistics: {total: 10, pending: 4}}), {value: 6, max: 10});
same(store.progress({status: 'running', phase: 'publish', statistics: {total: 10, published: 3, duplicate: 1, publication_pending: 4}}), {value: 4, max: 8});
same(store.progress({status: 'running', phase: 'fetching', statistics: {total: 0}}), {value: null, max: null});
assert.equal(store.statusText({status: 'running', cancel_requested: true}), 'player_import_status_cancelling');
assert.equal(store.noteText({resolution_note: 'write_failed'}), 'player_import_note_failed');
assert.equal(store.noteText({resolution_note: 'unknown_code'}), '');
assert.equal(store.text('foundOf', {found: 3, total: 9}), 'player_import_found_of');
});
const scripts = readFileSync(`${__dirname}/../templates/player/scripts.html`, 'utf8');
function playlistsStore(responder) {
const start = scripts.indexOf(" Alpine.store('playlists', {");
const end = scripts.indexOf('\n });\n', start) + '\n });\n'.length;
const calls = [];
const stores = {library: {currentPlaylist: null}, playlistHeader: {busy: false, reset() {}}, pins: {reload: async () => {}}};
vm.runInNewContext(scripts.slice(start, end), {
Alpine: {store: (name, value) => value ? (stores[name] = value) : stores[name]},
GUEST: false, T: new Proxy({}, {get: (_, key) => key}), console: {warn() {}},
fetch: async (url, options = {}) => {
calls.push({url, method: options.method || 'GET', body: options.body && JSON.parse(options.body)});
return responder(url);
},
});
return {store: stores.playlists, stores, calls};
}
test('a federated track is removed from a playlist by its content id', async () => {
const {store, stores, calls} = playlistsStore(url => ({ok: true, json: async () => url === '/api/player/playlists' ? [] : {ok: true}}));
const federated = {id: 'fed:b3:1', content_id: 'b3:1', federation_pending: true};
const local = {id: 4, playlist_track_id: 40, content_id: 'b3:4'};
stores.library.currentPlaylist = {id: 12, kind: 'user', is_own: true, tracks: [local, federated]};
store.editingPlaylistId = 12;
await store.removeCurrentTrack(federated, 1);
same(calls[0], {url: '/api/player/tracks/content/playlist', method: 'DELETE', body: {playlist_id: 12, content_id: 'b3:1'}});
same(stores.library.currentPlaylist.tracks, [local]);
await store.removeCurrentTrack(local, 0);
assert.equal(calls.filter(call => call.method === 'DELETE')[1].url, '/api/player/playlists/12/tracks');
});
test('a failed federated removal restores the track', async () => {
const {store, stores} = playlistsStore(() => ({ok: false, json: async () => ({})}));
const federated = {id: 'fed:b3:1', content_id: 'b3:1', federation_pending: true};
stores.library.currentPlaylist = {id: 12, kind: 'user', is_own: true, tracks: [federated]};
store.editingPlaylistId = 12;
await store.removeCurrentTrack(federated, 0);
same(stores.library.currentPlaylist.tracks, [federated]);
});
test('import templates parse without a browser', () => {
for (const file of ['templates/player/imports_scripts.html']) {
const html = readFileSync(`${__dirname}/../${file}`, 'utf8');
for (const match of html.matchAll(/<script>([\s\S]*?)<\/script>/g)) new vm.Script(match[1]);
}
});