diff --git a/docs/administration.md b/docs/administration.md index 9fff163..278d5d3 100644 --- a/docs/administration.md +++ b/docs/administration.md @@ -101,11 +101,18 @@ its destination for its remaining files. ## Spotify library import +Users start an import from **Import library** in the account menu. The page +lists the available sources, the history of imports with their statistics and +links to the created playlists, and the entries of each import. + Spotify playlists and Liked Songs are imported from the account data export -("Download your data") without any server configuration. The browser sends -only `Playlist*.json` and `YourLibrary.json`; the server parses them in memory -and stores the entries of the selected playlists. An import request may not -exceed 32 MiB. Importing a playlist a second time is refused; a playlist with +("Download your data") without any server configuration. The browser opens the +ZIP archive itself and sends only `Playlist*.json` and `YourLibrary.json`; +listening history and account details never leave it. Before anything is +decompressed the browser refuses archives over 256 MiB, archives with more than +2,000 entries, more than 256 playlist files, or playlist files declaring more +than 32 MiB in total. The server parses the files in memory and stores the +entries of the selected playlists. An import request may not exceed 32 MiB. Importing a playlist a second time is refused; a playlist with the same title and changed contents is imported as a new playlist only after confirmation. diff --git a/docs/development.md b/docs/development.md index c702da0..577fd77 100644 --- a/docs/development.md +++ b/docs/development.md @@ -172,7 +172,8 @@ extension; the tests install it into `public`. The publisher tests (`src/library_import/tests/publisher.rs`) run against the Device Sync tables of the same schema. They cover source order, repeats, empty playlists, a second pass that adds nothing, Resync appending at the end, tracks -removed by the user or by a committed but not yet applied operation, deleted +removed by the user or by a committed but not yet applied operation, a +federated track removed in the web player by its content id, deleted target playlists and recreation, an entry failing after its operation was recorded, registers written concurrently, deletions from the web and from another device during a batch, older operations that arrive during a batch, @@ -189,6 +190,32 @@ requests. The matcher's reference table (`src/library_import/matcher/tests.rs`) runs without a database and documents the matching rules case by case. +The import page has browser-store tests and a browser scenario on the rendered +player with isolated API fixtures; neither needs a server or a database: + +```bash +node --test tests/library_import.test.cjs +FURU_LIBRARY_IMPORT_RENDER_FIXTURE=1 cargo test library_import::tests::web +node tests/browser-library-import.cjs +``` + +The store tests unzip real archives with the vendored fflate and cover the +archive limits (size, entries, playlist files and declared sizes, checked +before decompression), the request limit, the selection of repeated, similar +and unavailable playlists, federated consent, polling, the Spotify sign-in +return and removing a federated track from a playlist. The browser scenario +checks the menu order on desktop and mobile, history polling, that only +`Playlist*.json` and `YourLibrary.json` from a ZIP with listening history reach +the server, the wizard, details, a manual choice, Retry unmatched, history +deletion, continuing a Spotify import after a new sign-in, federated track +removal in a playlist and reduced motion. Set `PLAYWRIGHT_MODULE` and +`CHROME_PATH` as for the other browser tests; `FURU_SCREENSHOT_DIR` chooses +where screenshots go (default `target/`). + +`src/player/vendor/fflate-0.8.2.min.js` is `umd/index.js` of the npm package +`fflate@0.8.2` (MIT, `src/player/vendor/fflate-LICENSE`), served unchanged at +`/vendor/fflate-0.8.2.js` and loaded only when a user picks an archive. + The Spotify export fixture in `src/library_import/adapters/fixtures/spotify_export/` is synthetic. Add a fresh anonymized real export next to it before relying on the parser for a new export format. diff --git a/src/i18n/phrases.rs b/src/i18n/phrases.rs index 5ab5e65..4e8382d 100644 --- a/src/i18n/phrases.rs +++ b/src/i18n/phrases.rs @@ -759,4 +759,143 @@ translations! { player_open_torrent_failed: "Could not open torrent" , "Не удалось открыть торрент"; player_delete_torrent_failed: "Could not remove torrent from history" , "Не удалось удалить торрент из истории"; player_load_ai_queue_failed: "Could not load AI queue" , "Не удалось загрузить очередь ИИ"; + // Library import + player_import_library: "Import library" , "Импорт библиотеки"; + player_import_new: "New import" , "Новый импорт"; + player_import_sources: "Sources" , "Источники"; + player_import_history: "History" , "История"; + player_import_history_empty: "No imports yet. Start with New import." , "Импортов пока нет. Начните с кнопки «Новый импорт»."; + player_import_load_failed: "Could not load imports." , "Не удалось загрузить импорты."; + player_import_request_failed: "The request failed. Try again." , "Запрос не выполнен. Попробуйте ещё раз."; + player_import_retry: "Retry" , "Повторить"; + player_import_method_file: "Data export" , "Выгрузка данных"; + player_import_method_file_hint: "ZIP archive from Download your data, or its playlist JSON files" , "ZIP-архив из «Скачать данные» или JSON-файлы плейлистов из него"; + player_import_method_api: "Sign in with Spotify" , "Войти через Spotify"; + player_import_method_api_hint: "Reads your own and collaborative playlists directly" , "Читает ваши и совместные плейлисты напрямую"; + player_import_upload_help: "In Spotify, open Account, then Privacy settings, and request Account data. When the email arrives, choose the downloaded ZIP archive, or its Playlist1.json, Playlist2.json and YourLibrary.json files." , "В Spotify откройте «Аккаунт», затем «Настройки конфиденциальности» и запросите данные аккаунта. Когда придёт письмо, выберите скачанный ZIP-архив или файлы Playlist1.json, Playlist2.json и YourLibrary.json из него."; + player_import_privacy: "The archive is opened in your browser. Only playlists and saved tracks are sent to the server; listening history stays on this device." , "Архив открывается в браузере. На сервер уходят только плейлисты и сохранённые треки; история прослушиваний остаётся на этом устройстве."; + player_import_api_help: "Spotify asks you to allow read access to your playlists and saved tracks. In Development Mode only your own and collaborative playlists can be read; import other playlists from the data export." , "Spotify попросит разрешить чтение плейлистов и сохранённых треков. В режиме разработки читаются только ваши и совместные плейлисты; остальные импортируйте из выгрузки данных."; + player_import_choose_files: "Choose files" , "Выбрать файлы"; + player_import_reading: "Reading the export…" , "Читаю выгрузку…"; + player_import_files_read: "Files read: {count}." , "Прочитано файлов: {count}."; + player_import_files_skipped: "Other files were skipped: {count}." , "Другие файлы пропущены: {count}."; + player_import_no_files: "No playlist files found. Choose the export archive or its Playlist*.json and YourLibrary.json files." , "Файлы плейлистов не найдены. Выберите архив выгрузки или файлы Playlist*.json и YourLibrary.json."; + player_import_archive_too_large: "The archive is larger than 256 MB. Choose the account data export." , "Архив больше 256 МБ. Выберите выгрузку данных аккаунта."; + player_import_zip_too_many_entries: "The archive contains too many files." , "В архиве слишком много файлов."; + player_import_zip_too_many_files: "The export contains more than 256 playlist files." , "В выгрузке больше 256 файлов плейлистов."; + player_import_export_too_large: "The playlist files are larger than 32 MB in total." , "Файлы плейлистов в сумме больше 32 МБ."; + player_import_zip_invalid: "The file is not a valid ZIP archive." , "Файл не является корректным ZIP-архивом."; + player_import_zip_load_failed: "Could not load the archive reader. Check the connection and try again." , "Не удалось загрузить модуль чтения архивов. Проверьте соединение и попробуйте ещё раз."; + player_import_request_too_large: "The export is too large to send (32 MB at most)." , "Выгрузка слишком большая для отправки (не больше 32 МБ)."; + player_import_sign_in: "Sign in with Spotify" , "Войти через Spotify"; + player_import_sign_in_again: "Sign in to Spotify again" , "Войти в Spotify снова"; + player_import_loading_playlists: "Loading playlists…" , "Загружаю плейлисты…"; + player_import_select_playlists: "Playlists to import" , "Плейлисты для импорта"; + player_import_select_all: "Select all" , "Выбрать все"; + player_import_select_none: "Clear" , "Снять выбор"; + player_import_selected_count: "Selected {count} of {total}" , "Выбрано {count} из {total}"; + player_import_favorites: "Liked Songs" , "Любимые треки"; + player_import_unsupported_count: "not supported: {count}" , "не поддерживается: {count}"; + player_import_already_imported: "Already imported in #{id}" , "Уже импортирован в №{id}"; + player_import_all_imported: "This export was already imported." , "Эта выгрузка уже импортирована."; + player_import_similar: "A similar playlist was imported in #{id}. A new playlist will be created." , "Похожий плейлист уже импортирован в №{id}. Будет создан новый плейлист."; + player_import_confirm_similar: "Create a new playlist" , "Создать новый плейлист"; + player_import_confirm_similar_needed: "Confirm creating new playlists for the similar ones, or clear them." , "Подтвердите создание новых плейлистов для похожих или снимите их выбор."; + player_import_unavailable: "Only through the data export" , "Только через выгрузку данных"; + player_import_federated: "Search in the federation" , "Искать в федерации"; + player_import_federated_consent: "Tracks missing here are searched for in the catalogues of Furumi network participants. Participants receive only artist names." , "Недостающие треки ищутся в каталогах участников сети Furumi. Участникам сети будут отправлены только имена исполнителей."; + player_import_federated_off: "Federation is turned off on this server." , "Федерация на этом сервере выключена."; + player_import_start: "Start import" , "Начать"; + player_import_starting: "Starting the import…" , "Запускаю импорт…"; + player_import_back: "Back" , "Назад"; + player_import_conflicts: "Some playlists were imported meanwhile and are no longer selected." , "Некоторые плейлисты уже импортированы, их выбор снят."; + player_import_similar_conflicts: "Similar playlists were imported before. Confirm creating new playlists for them." , "Похожие плейлисты уже импортированы. Подтвердите создание новых плейлистов."; + player_import_status_queued: "Queued" , "В очереди"; + player_import_status_running: "Running" , "Выполняется"; + player_import_status_done: "Done" , "Готово"; + player_import_status_cancelled: "Cancelled" , "Отменён"; + player_import_status_failed: "Failed" , "Ошибка"; + player_import_status_needs_reauth: "Sign-in needed" , "Нужен вход"; + player_import_status_cancelling: "Cancelling" , "Отменяется"; + player_import_phase_fetching: "Reading playlists from Spotify" , "Чтение плейлистов из Spotify"; + player_import_phase_resolve_local: "Matching with the library" , "Поиск в библиотеке"; + player_import_phase_resolve_federation: "Searching the federation" , "Поиск в федерации"; + player_import_phase_publish: "Adding tracks to playlists" , "Добавление треков в плейлисты"; + player_import_phase_waiting: "Waiting to start" , "Ожидает запуска"; + player_import_found_of: "{found} of {total} found" , "Найдено {found} из {total}"; + player_import_number: "#{id}" , "№{id}"; + player_import_playlists_more: "and {count} more" , "и ещё {count}"; + player_import_retry_unmatched: "Retry unmatched" , "Искать ненайденные"; + player_import_retry_started: "Unmatched tracks will be searched again." , "Ненайденные треки будут найдены заново."; + player_import_cancel: "Cancel" , "Отменить"; + player_import_cancel_requested: "The import stops after the current step. Added tracks stay." , "Импорт остановится после текущего шага. Добавленные треки останутся."; + player_import_delete_history: "Delete history" , "Удалить историю"; + player_import_delete_confirm: "Delete this import history? Created playlists stay." , "Удалить историю этого импорта? Созданные плейлисты останутся."; + player_import_deleted: "Import history deleted. Playlists stay." , "История импорта удалена. Плейлисты остались."; + player_import_reauth_needed: "The Spotify sign-in has expired. Sign in again to continue this import." , "Вход в Spotify истёк. Войдите снова, чтобы продолжить этот импорт."; + player_import_stat_total: "Entries" , "Записей"; + player_import_stat_found: "Found" , "Найдено"; + player_import_stat_published: "Added to playlists" , "Добавлено в плейлисты"; + player_import_stat_ambiguous: "Needs a choice" , "Нужен выбор"; + player_import_stat_unmatched: "Not found" , "Не найдено"; + player_import_stat_unsupported: "Not supported" , "Не поддерживается"; + player_import_stat_failed: "Errors" , "Ошибки"; + player_import_stat_deferred: "Deferred by the sync limit" , "Отложено из-за лимита синхронизации"; + player_import_stat_duplicate: "Repeats" , "Повторы"; + player_import_stat_already_present: "Already in the playlist or removed" , "Уже в плейлисте или удалены"; + player_import_stat_paused: "Paused" , "Приостановлено"; + player_import_stat_no_content: "No content id" , "Без идентификатора содержимого"; + player_import_stat_publish_failed: "Not added" , "Не добавлено"; + player_import_playlists: "Playlists" , "Плейлисты"; + player_import_playlist_deleted: "The playlist was deleted" , "Плейлист удалён"; + player_import_playlist_pending: "Not created yet" , "Ещё не создан"; + player_import_recreate: "Create again" , "Создать заново"; + player_import_recreate_started: "The playlist will be created again." , "Плейлист будет создан заново."; + player_import_entries: "Entries" , "Записи"; + player_import_filter_all: "All" , "Все"; + player_import_all_playlists: "All playlists" , "Все плейлисты"; + player_import_search: "Search entries" , "Поиск по записям"; + player_import_no_entries: "No entries to show." , "Записей нет."; + player_import_load_more: "Load more" , "Загрузить ещё"; + player_import_loading: "Loading…" , "Загрузка…"; + player_import_candidates: "Possible matches" , "Возможные совпадения"; + player_import_choose: "Choose" , "Выбрать"; + player_import_chosen: "The track will be added to the playlist." , "Трек будет добавлен в плейлист."; + player_import_origin_local: "Library" , "Библиотека"; + player_import_origin_federation: "Federation" , "Федерация"; + player_import_res_pending: "Waiting" , "Ожидает"; + player_import_res_matched: "Found" , "Найден"; + player_import_res_ambiguous: "Needs a choice" , "Нужен выбор"; + player_import_res_unmatched: "Not found" , "Не найден"; + player_import_res_unsupported: "Not supported" , "Не поддерживается"; + player_import_res_failed: "Error" , "Ошибка"; + player_import_pub_pending: "Waiting to be added" , "Ожидает добавления"; + player_import_pub_published: "Added" , "Добавлен"; + player_import_pub_duplicate: "Repeat in the source" , "Повтор в источнике"; + player_import_pub_already_present: "Already in the playlist or removed" , "Уже в плейлисте или удалён"; + player_import_pub_no_content_id: "No content id" , "Нет идентификатора содержимого"; + player_import_pub_deferred: "Deferred by the sync limit" , "Отложен из-за лимита синхронизации"; + player_import_pub_paused: "Playlist deleted" , "Плейлист удалён"; + player_import_pub_failed: "Not added" , "Не добавлен"; + player_import_note_not_found: "No such track" , "Такого трека нет"; + player_import_note_version_mismatch: "Only other versions" , "Есть только другие версии"; + player_import_note_duration_mismatch: "Duration differs" , "Длительность отличается"; + player_import_note_federation_error: "Federation search failed" , "Поиск в федерации не удался"; + player_import_note_federation_budget: "Federation search limit reached" , "Исчерпан лимит поиска в федерации"; + player_import_note_federation_unavailable: "Federation unavailable" , "Федерация недоступна"; + player_import_note_episode: "Podcast episode" , "Выпуск подкаста"; + player_import_note_audiobook: "Audiobook" , "Аудиокнига"; + player_import_note_local_file: "Local file" , "Локальный файл"; + player_import_note_unknown_kind: "Unknown item" , "Неизвестная запись"; + player_import_note_missing_title: "No title" , "Нет названия"; + player_import_note_failed: "Processing error" , "Ошибка обработки"; + player_import_oauth_state: "The sign-in could not be verified. Try again." , "Не удалось проверить вход. Попробуйте ещё раз."; + player_import_oauth_expired: "The sign-in took too long. Try again." , "Вход занял слишком много времени. Попробуйте ещё раз."; + player_import_oauth_denied: "Access was not granted." , "Доступ не предоставлен."; + player_import_oauth_not_configured: "Spotify sign-in is not configured on this server." , "Вход через Spotify на этом сервере не настроен."; + player_import_oauth_exchange: "Spotify did not confirm the sign-in. Try again." , "Spotify не подтвердил вход. Попробуйте ещё раз."; + player_import_oauth_not_allowed: "This Spotify account is not on the application user list. Ask the administrator, or use the data export." , "Этого аккаунта Spotify нет в списке пользователей приложения. Обратитесь к администратору или используйте выгрузку данных."; + player_import_oauth_unavailable: "Spotify is unavailable. Try again later." , "Spotify недоступен. Попробуйте позже."; + player_import_oauth_not_waiting: "This import is not waiting for a sign-in." , "Этот импорт не ожидает входа."; + player_import_oauth_account_mismatch: "Sign in with the Spotify account used for this import." , "Войдите в тот аккаунт Spotify, из которого делался этот импорт."; } diff --git a/src/library_import/tests.rs b/src/library_import/tests.rs index 384c856..f7018c3 100644 --- a/src/library_import/tests.rs +++ b/src/library_import/tests.rs @@ -34,6 +34,7 @@ use crate::federation::client::{CatalogPeers, CatalogStream}; use crate::scheduler::JobLog; mod publisher; +mod web; /// Workers share a process-wide slot counter, so database tests run one at a time. static SERIAL: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(()); diff --git a/src/library_import/tests/publisher.rs b/src/library_import/tests/publisher.rs index 3453e8a..87b6cc8 100644 --- a/src/library_import/tests/publisher.rs +++ b/src/library_import/tests/publisher.rs @@ -650,6 +650,81 @@ async fn library_import_entry_failing_in_its_transaction_leaves_nothing_behind() fixture.drop().await; } +#[tokio::test] +#[ignore = "requires FURU_LIBRARY_IMPORT_TEST_DATABASE_URL pointing to a disposable PostgreSQL database"] +async fn library_import_federated_track_removed_in_the_web_stays_removed() { + use crate::player::{ContentRemoval, remove_content_from_playlist}; + + let (_serial, fixture) = setup().await; + let pool = &fixture.pool; + library(pool, 1).await; + let import_id = matched_import( + pool, + "web-removal", + &[("Web removal", vec![Entry::Local(1), Entry::Fed(2)])], + ) + .await; + publish(pool, 826).await; + let road = target(pool, import_id, 0).await.unwrap(); + assert!(register(pool, road, 2).await.unwrap().0); + + // Only the owner can remove, and only a valid content id. + assert_eq!( + remove_content_from_playlist(pool, 2, road, &cid(2)) + .await + .unwrap(), + ContentRemoval::NotOwned + ); + assert_eq!( + remove_content_from_playlist(pool, USER, road, "not-a-content-id") + .await + .unwrap(), + ContentRemoval::InvalidContentId + ); + assert!(register(pool, road, 2).await.unwrap().0); + + // The web removes the federated track with the existing operation. + assert_eq!( + remove_content_from_playlist(pool, USER, road, &cid(2)) + .await + .unwrap(), + ContentRemoval::Removed + ); + assert!(!register(pool, road, 2).await.unwrap().0); + assert_eq!( + own_ops(pool, "playlist_track_removed", Some(&cid(2))).await, + 1 + ); + assert_eq!(rows(pool, road).await, [(1001, 0)]); + + // Even without its receipt, a later pass does not add it back. + sqlx::query( + "DELETE FROM furumusic__library_import_publication WHERE target_playlist_id = $1 AND content_id = $2", + ) + .bind(road) + .bind(cid(2)) + .execute(pool) + .await + .unwrap(); + sqlx::query("UPDATE furumusic__library_import_item SET publication_status = 'pending' WHERE source_position = 1") + .execute(pool) + .await + .unwrap(); + resync(pool, import_id).await; + publish(pool, 827).await; + assert_eq!( + statuses(pool, import_id).await, + ["published", "already_present"] + ); + assert!(!register(pool, road, 2).await.unwrap().0); + assert_eq!( + own_ops(pool, "playlist_track_added", Some(&cid(2))).await, + 1 + ); + assert_consistent(pool, road).await; + fixture.drop().await; +} + #[tokio::test] #[ignore = "requires FURU_LIBRARY_IMPORT_TEST_DATABASE_URL pointing to a disposable PostgreSQL database"] async fn library_import_rolls_back_when_a_register_is_written_concurrently() { diff --git a/src/library_import/tests/web.rs b/src/library_import/tests/web.rs new file mode 100644 index 0000000..70a86e2 --- /dev/null +++ b/src/library_import/tests/web.rs @@ -0,0 +1,76 @@ +//! Rendering of the import page, menu entry and wizard in the player. Set +//! `FURU_LIBRARY_IMPORT_RENDER_FIXTURE=1` to write the rendered player for +//! `tests/browser-library-import.cjs`. + +use cot::Template; + +use crate::i18n::{Lang, Translations}; +use crate::player::PlayerPageTemplate; + +fn render(lang: Lang, guest: bool) -> String { + PlayerPageTemplate { + t: Translations::for_lang(lang), + guest, + account_id: if guest { 0 } else { 1 }, + share_token: if guest { "share".into() } else { String::new() }, + downloads_enabled: true, + torrent_downloads_enabled: true, + youtube_downloads_enabled: true, + } + .render() + .unwrap() +} + +#[test] +fn library_import_page_menu_and_wizard_render_in_the_player() { + let html = render(Lang::En, false); + // The menu entry sits between Followed and Settings in both account menus. + let menus: Vec<&str> = html + .split("
Spotify sign-in
'}); + 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;}); diff --git a/tests/library_import.test.cjs b/tests/library_import.test.cjs new file mode 100644 index 0000000..65c0bb5 --- /dev/null +++ b/tests/library_import.test.cjs @@ -0,0 +1,349 @@ +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(/