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>
This commit is contained in:
sanapachandClaude Opus 5.5 committed 2026-11-26 19:05:30 +02:00
1 parent 4d6a1513d9
commit d275e7326b
21 files changed
+2421 -14

No files matched your search

+11 -4
View File
@@ -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.
+28 -1
View File
@@ -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.
+139
View File
@@ -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, из которого делался этот импорт.";
}
+1
View File
@@ -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(());
+75
View File
@@ -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() {
+76
View File
@@ -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("<div class=\"account-action-list\"")
.skip(1)
.collect();
assert_eq!(menus.len(), 2);
for menu in menus {
let followed = menu.find("href=\"#followed\"").unwrap();
let imports = menu.find("href=\"#imports\"").unwrap();
let settings = menu.find("$store.user.openSettings()").unwrap();
assert!(followed < imports && imports < settings);
assert!(menu[imports..settings].contains("Import library"));
}
assert!(html.contains("x-if=\"$store.library.view === 'imports'\""));
assert!(html.contains("x-if=\"$store.library.view === 'import_detail'\""));
assert!(html.contains("id=\"import-wizard\" class=\"player-dialog import-wizard\""));
assert!(
html.find("Alpine.store('imports',").unwrap()
< html.find("Alpine.store('library',").unwrap(),
"the import store must exist before library.init restores the hash"
);
// The archive reader is loaded on demand, not embedded in the page.
assert!(html.contains("/vendor/fflate-0.8.2.js"));
assert!(!html.contains("_e.unzipSync="));
// Every label of the store is rendered from the phrase table.
assert!(!html.contains("{{ t."));
let russian = render(Lang::Ru, false);
assert!(russian.contains("Импорт библиотеки"));
assert!(russian.contains("Участникам сети будут отправлены только имена исполнителей."));
let shared = render(Lang::En, true);
assert!(!shared.contains("Alpine.store('imports',"));
assert!(!shared.contains("import-wizard"));
if std::env::var_os("FURU_LIBRARY_IMPORT_RENDER_FIXTURE").is_some() {
std::fs::create_dir_all("target").unwrap();
std::fs::write("target/library-import-player-fixture.html", &html).unwrap();
std::fs::write("target/library-import-player-fixture-ru.html", &russian).unwrap();
}
}
#[test]
fn library_import_vendored_zip_reader_is_fflate_0_8_2() {
let source = include_str!("../../player/vendor/fflate-0.8.2.min.js");
assert!(source.starts_with("!function(f){typeof module!='undefined'"));
assert!(source.contains("_e.unzip=") && source.contains("_e.unzipSync="));
let license = include_str!("../../player/vendor/fflate-LICENSE");
assert!(license.starts_with("MIT License") && license.contains("Arjun Barrett"));
}
+5
View File
@@ -327,6 +327,11 @@ impl App for FuruApp {
Route::with_handler_and_name("/offline-probe", get(offline::probe), "offline_probe"),
Route::with_handler_and_name("/player.webmanifest", get(offline::manifest), "player_manifest"),
Route::with_handler_and_name("/player-icon.svg", get(offline::icon), "player_icon"),
Route::with_handler_and_name(
"/vendor/fflate-0.8.2.js",
get(offline::fflate),
"vendor_fflate",
),
Route::with_handler_and_name(
"/metrics",
get({
+9
View File
@@ -43,6 +43,15 @@ pub(crate) async fn icon() -> cot::Result<Response<Body>> {
asset("image/svg+xml", include_str!("player/player-icon.svg"))
}
/// The ZIP reader of the library import wizard, loaded only when a user picks
/// an export archive. The version is part of the path.
pub(crate) async fn fflate() -> cot::Result<Response<Body>> {
asset(
"text/javascript; charset=utf-8",
include_str!("player/vendor/fflate-0.8.2.min.js"),
)
}
pub(crate) async fn probe(session: Session, db: Database) -> cot::Result<Response<Body>> {
let identity = crate::auth::checked_session_identity(&session, &db).await?;
let user = identity.filter(|user| user.is_active());
+103
View File
@@ -7292,6 +7292,85 @@ async fn content_playlist_add_handler(
Json(serde_json::json!({ "ok": true })).into_response()
}
/// Result of removing a federated track from a playlist.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum ContentRemoval {
Removed,
NotOwned,
InvalidContentId,
}
/// Removes a track identified by its content id from the user's own playlist
/// with the existing `PlaylistTrackRemoved` operation: the register becomes
/// `present = false` and a materialized row, if any, is deleted. Federated
/// tracks have no `playlist_track` row, so this is how the web removes them.
pub(crate) async fn remove_content_from_playlist(
pool: &sqlx::PgPool,
user_id: i64,
playlist_id: i64,
content_id: &str,
) -> anyhow::Result<ContentRemoval> {
let Some(content_id) = music_dht::normalize_content_id(content_id) else {
return Ok(ContentRemoval::InvalidContentId);
};
let owns: bool = sqlx::query_scalar(
"SELECT EXISTS (
SELECT 1 FROM furumusic__playlist WHERE id = $1 AND owner_id = $2
)",
)
.bind(playlist_id)
.bind(user_id)
.fetch_one(pool)
.await?;
if !owns {
return Ok(ContentRemoval::NotOwned);
}
crate::federation::devices::record_playlist_tracks_removed(
pool,
user_id,
playlist_id,
&[content_id],
)
.await?;
Ok(ContentRemoval::Removed)
}
// ---------------------------------------------------------------------------
// DELETE /api/player/tracks/content/playlist — remove a federated track
// ---------------------------------------------------------------------------
async fn content_playlist_remove_handler(
auth_ctx: auth::AuthContext,
session: Session,
db: Database,
pool: &sqlx::PgPool,
Json(body): Json<ContentTrackMutation>,
) -> cot::Result<cot::response::Response> {
let Some(user) = auth::get_request_user(&auth_ctx, &session, &db).await else {
return Ok(json_error(StatusCode::UNAUTHORIZED, "not authenticated"));
};
let Some(playlist_id) = body.playlist_id else {
return Ok(json_error(StatusCode::BAD_REQUEST, "missing playlist id"));
};
match remove_content_from_playlist(pool, user.id, playlist_id, &body.content_id).await {
Ok(ContentRemoval::Removed) => Json(serde_json::json!({ "ok": true })).into_response(),
Ok(ContentRemoval::NotOwned) => Ok(json_error(StatusCode::FORBIDDEN, "not your playlist")),
Ok(ContentRemoval::InvalidContentId) => {
Ok(json_error(StatusCode::BAD_REQUEST, "invalid content id"))
}
Err(err) => {
tracing::warn!(
playlist_id,
"fed device playlist remove op was not recorded: {err:#}"
);
Ok(json_error(
StatusCode::INTERNAL_SERVER_ERROR,
"could not remove the track",
))
}
}
}
async fn federation_playlist_tracks_handler(
auth_ctx: auth::AuthContext,
session: Session,
@@ -10696,6 +10775,30 @@ impl App for PlayerApp {
content_playlist_add_handler(auth_ctx, session, db, pg_pool, json).await
}
}
})
.delete({
let pool = Arc::clone(&pool);
let pool_config = Arc::clone(&pool_config);
move |auth_ctx: auth::AuthContext,
session: Session,
db: Database,
json: Json<ContentTrackMutation>| {
let pool = Arc::clone(&pool);
let pool_config = Arc::clone(&pool_config);
async move {
let pg_pool = pool
.get_or_init(|| async {
sqlx::postgres::PgPoolOptions::new()
.max_connections(5)
.connect(&pool_config.database_url)
.await
.expect("player pool")
})
.await;
content_playlist_remove_handler(auth_ctx, session, db, pg_pool, json)
.await
}
}
}),
"player_content_playlist",
),
+1
View File
@@ -0,0 +1 @@
!function(f){typeof module!='undefined'&&typeof exports=='object'?module.exports=f():typeof define!='undefined'&&define.amd?define(f):(typeof self!='undefined'?self:this).fflate=f()}(function(){var _e={};"use strict";var t=(typeof module!='undefined'&&typeof exports=='object'?function(_f){"use strict";var e,t=";var __w=require('worker_threads');__w.parentPort.on('message',function(m){onmessage({data:m})}),postMessage=function(m,t){__w.parentPort.postMessage(m,t)},close=process.exit;self=global";try{e=require("worker_threads").Worker}catch(e){}exports.default=e?function(r,n,o,a,s){var u=!1,i=new e(r+t,{eval:!0}).on("error",(function(e){return s(e,null)})).on("message",(function(e){return s(null,e)})).on("exit",(function(e){e&&!u&&s(Error("exited with code "+e),null)}));return i.postMessage(o,a),i.terminate=function(){return u=!0,e.prototype.terminate.call(i)},i}:function(e,t,r,n,o){setImmediate((function(){return o(Error("async operations unsupported - update to Node 12+ (or Node 10-11 with the --experimental-worker CLI flag)"),null)}));var a=function(){};return{terminate:a,postMessage:a}};return _f}:function(_f){"use strict";var e={};_f.default=function(r,t,s,a,n){var o=new Worker(e[t]||(e[t]=URL.createObjectURL(new Blob([r+';addEventListener("error",function(e){e=e.error;postMessage({$e$:[e.message,e.code,e.stack]})})'],{type:"text/javascript"}))));return o.onmessage=function(e){var r=e.data,t=r.$e$;if(t){var s=Error(t[0]);s.code=t[1],s.stack=t[2],n(s,null)}else n(null,r)},o.postMessage(s,a),o};return _f})({}),n=Uint8Array,r=Uint16Array,e=Int32Array,i=new n([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),o=new n([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),s=new n([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),a=function(t,n){for(var i=new r(31),o=0;o<31;++o)i[o]=n+=1<<t[o-1];var s=new e(i[30]);for(o=1;o<30;++o)for(var a=i[o];a<i[o+1];++a)s[a]=a-i[o]<<5|o;return{b:i,r:s}},u=a(i,2),h=u.b,f=u.r;h[28]=258,f[258]=28;for(var l=a(o,0),c=l.b,p=l.r,v=new r(32768),d=0;d<32768;++d){var g=(43690&d)>>1|(21845&d)<<1;v[d]=((65280&(g=(61680&(g=(52428&g)>>2|(13107&g)<<2))>>4|(3855&g)<<4))>>8|(255&g)<<8)>>1}var y=function(t,n,e){for(var i=t.length,o=0,s=new r(n);o<i;++o)t[o]&&++s[t[o]-1];var a,u=new r(n);for(o=1;o<n;++o)u[o]=u[o-1]+s[o-1]<<1;if(e){a=new r(1<<n);var h=15-n;for(o=0;o<i;++o)if(t[o])for(var f=o<<4|t[o],l=n-t[o],c=u[t[o]-1]++<<l,p=c|(1<<l)-1;c<=p;++c)a[v[c]>>h]=f}else for(a=new r(i),o=0;o<i;++o)t[o]&&(a[o]=v[u[t[o]-1]++]>>15-t[o]);return a},m=new n(288);for(d=0;d<144;++d)m[d]=8;for(d=144;d<256;++d)m[d]=9;for(d=256;d<280;++d)m[d]=7;for(d=280;d<288;++d)m[d]=8;var b=new n(32);for(d=0;d<32;++d)b[d]=5;var w=y(m,9,0),x=y(m,9,1),z=y(b,5,0),k=y(b,5,1),M=function(t){for(var n=t[0],r=1;r<t.length;++r)t[r]>n&&(n=t[r]);return n},S=function(t,n,r){var e=n/8|0;return(t[e]|t[e+1]<<8)>>(7&n)&r},A=function(t,n){var r=n/8|0;return(t[r]|t[r+1]<<8|t[r+2]<<16)>>(7&n)},T=function(t){return(t+7)/8|0},D=function(t,r,e){return(null==r||r<0)&&(r=0),(null==e||e>t.length)&&(e=t.length),new n(t.subarray(r,e))};_e.FlateErrorCode={UnexpectedEOF:0,InvalidBlockType:1,InvalidLengthLiteral:2,InvalidDistance:3,StreamFinished:4,NoStreamHandler:5,InvalidHeader:6,NoCallback:7,InvalidUTF8:8,ExtraFieldTooLong:9,InvalidDate:10,FilenameTooLong:11,StreamFinishing:12,InvalidZipData:13,UnknownCompressionMethod:14};var C=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"],I=function(t,n,r){var e=Error(n||C[t]);if(e.code=t,Error.captureStackTrace&&Error.captureStackTrace(e,I),!r)throw e;return e},U=function(t,r,e,a){var u=t.length,f=a?a.length:0;if(!u||r.f&&!r.l)return e||new n(0);var l=!e,p=l||2!=r.i,v=r.i;l&&(e=new n(3*u));var d=function(t){var r=e.length;if(t>r){var i=new n(Math.max(2*r,t));i.set(e),e=i}},g=r.f||0,m=r.p||0,b=r.b||0,w=r.l,z=r.d,C=r.m,U=r.n,F=8*u;do{if(!w){g=S(t,m,1);var E=S(t,m+1,3);if(m+=3,!E){var Z=t[(J=T(m)+4)-4]|t[J-3]<<8,q=J+Z;if(q>u){v&&I(0);break}p&&d(b+Z),e.set(t.subarray(J,q),b),r.b=b+=Z,r.p=m=8*q,r.f=g;continue}if(1==E)w=x,z=k,C=9,U=5;else if(2==E){var O=S(t,m,31)+257,G=S(t,m+10,15)+4,L=O+S(t,m+5,31)+1;m+=14;for(var H=new n(L),j=new n(19),N=0;N<G;++N)j[s[N]]=S(t,m+3*N,7);m+=3*G;var P=M(j),B=(1<<P)-1,Y=y(j,P,1);for(N=0;N<L;){var J,K=Y[S(t,m,B)];if(m+=15&K,(J=K>>4)<16)H[N++]=J;else{var Q=0,R=0;for(16==J?(R=3+S(t,m,3),m+=2,Q=H[N-1]):17==J?(R=3+S(t,m,7),m+=3):18==J&&(R=11+S(t,m,127),m+=7);R--;)H[N++]=Q}}var V=H.subarray(0,O),W=H.subarray(O);C=M(V),U=M(W),w=y(V,C,1),z=y(W,U,1)}else I(1);if(m>F){v&&I(0);break}}p&&d(b+131072);for(var X=(1<<C)-1,$=(1<<U)-1,_=m;;_=m){var tt=(Q=w[A(t,m)&X])>>4;if((m+=15&Q)>F){v&&I(0);break}if(Q||I(2),tt<256)e[b++]=tt;else{if(256==tt){_=m,w=null;break}var nt=tt-254;tt>264&&(nt=S(t,m,(1<<(it=i[N=tt-257]))-1)+h[N],m+=it);var rt=z[A(t,m)&$],et=rLine truncated
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2023 Arjun Barrett
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+9 -1
View File
@@ -26,6 +26,7 @@ if ('serviceWorker' in navigator) {
<style>{% include "player/dialog_styles.css" %}</style>
{% if !guest %}
<style>{% include "player/get_app.css" %}</style>
{% include "player/imports_styles.html" %}
{% endif %}
{% if downloads_enabled %}
<style>
@@ -39,11 +40,18 @@ if ('serviceWorker' in navigator) {
{% block body %}
{% include "player/shell.html" %}
{% include "player/modals.html" %}
{% if !guest %}{% include "player/get_app.html" %}{% endif %}
{% if !guest %}
{# Body-level dialogs need an Alpine root, like the modals above. #}
<div x-data>
{% include "player/get_app.html" %}
{% include "player/imports_wizard.html" %}
</div>
{% endif %}
{% include "player/lyrics_modal.html" %}
{% include "player/offline_scripts.html" %}
{% include "player/offline_manager_scripts.html" %}
{% include "player/podcast_scripts.html" %}
{% if !guest %}{% include "player/imports_scripts.html" %}{% endif %}
{% include "player/lyrics_scripts.html" %}
{% include "player/lyrics_search_scripts.html" %}
{% include "player/search_group_scripts.html" %}
+4
View File
@@ -38,6 +38,10 @@
<svg viewBox="0 0 24 24" aria-hidden="true"><circle cx="9" cy="8" r="3.5"/><path d="M2.5 20a6.5 6.5 0 0 1 13 0m.5-9 2.5 2.5L23 9"/></svg>
{{ t.player_followed_page }}
</a>
<a data-online-only href="#imports" :aria-current="['imports', 'import_detail'].includes($store.library.view) ? 'page' : null">
<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M12 3v11m-4-4 4 4 4-4M5 14v6h14v-6"/></svg>
{{ t.player_import_library }}
</a>
<button type="button" @click="$store.user.openSettings()">
<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M4 6h9m4 0h3M4 12h2m4 0h10M4 18h8m4 0h4"/><circle cx="15" cy="6" r="2"/><circle cx="8" cy="12" r="2"/><circle cx="14" cy="18" r="2"/></svg>
{{ t.nav_settings }}
+263
View File
@@ -0,0 +1,263 @@
<template x-if="$store.library.view === 'imports'">
<section class="library-imports" x-data="{ get imports() { return $store.imports } }"
@keydown.space="if ($event.target.closest('button,a,input,select,label')) $event.stopPropagation()">
<header class="import-heading">
<h1 class="section-title">{{ t.player_import_library }}</h1>
<button type="button" class="release-action-btn primary" data-online-only @click="imports.startWizard()"
aria-haspopup="dialog" aria-controls="import-wizard">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" aria-hidden="true"><path d="M12 5v14M5 12h14"/></svg>
{{ t.player_import_new }}
</button>
</header>
<p class="import-notice" role="status" aria-live="polite" x-show="imports.message" x-text="imports.message"></p>
<div class="import-notice error" role="alert" x-show="imports.error" x-cloak>
<span x-text="imports.error"></span>
<button type="button" class="import-text-action" @click="imports.enter()">{{ t.player_import_retry }}</button>
</div>
<template x-if="!imports.loaded && !imports.error">
<div class="page-skeleton" role="status">
<span class="loading-label">{{ t.player_loading_content }}</span>
<div aria-hidden="true">
<div class="import-source-grid">
<div class="import-source skeleton-card"><i class="skeleton-bar"></i><i class="skeleton-bar"></i></div>
</div>
</div>
{% include "player/skeleton_tracks.html" %}
</div>
</template>
<template x-if="imports.loaded">
<div>
<h2 class="import-subtitle">{{ t.player_import_sources }}</h2>
<div class="import-source-grid">
<template x-for="provider in imports.providers" :key="provider.id">
<button type="button" class="import-source" data-online-only @click="imports.startWizard(provider.id)"
aria-haspopup="dialog" aria-controls="import-wizard">
<strong x-text="provider.name"></strong>
<small x-text="provider.methods.map(method => imports.text(method === 'api' ? 'methodApi' : 'methodFile')).join(' · ')"></small>
</button>
</template>
</div>
<h2 class="import-subtitle">{{ t.player_import_history }}</h2>
<p class="empty-state" x-show="!imports.imports.length">{{ t.player_import_history_empty }}</p>
<ul class="import-history" x-show="imports.imports.length">
<template x-for="record in imports.imports" :key="record.id">
<li class="import-history-row">
<a class="import-history-link" :href="'#imports/' + record.id">
<span class="import-history-title">
<strong x-text="imports.title(record)"></strong>
<small x-text="imports.date(record.created_at)"></small>
</span>
<span class="import-status" :data-status="record.status" x-text="imports.statusText(record)"></span>
<span class="import-history-count"
x-text="imports.text('foundOf', {found: imports.number(imports.found(record)), total: imports.number(imports.stats(record).total)})"></span>
</a>
<div class="import-history-playlists" x-show="imports.playlistLinks(record).length">
<template x-for="link in imports.playlistLinks(record).slice(0, 3)" :key="link.id">
<a :href="'#playlist/' + link.target_playlist_id" x-text="link.title"></a>
</template>
<span x-show="imports.playlistLinks(record).length > 3"
x-text="imports.text('playlistsMore', {count: imports.playlistLinks(record).length - 3})"></span>
</div>
<div class="import-history-actions" data-online-only>
<button type="button" class="import-text-action" x-show="imports.isFinished(record)"
:disabled="imports.busy" @click="imports.retry(record)">{{ t.player_import_retry_unmatched }}</button>
<button type="button" class="import-text-action" x-show="record.status === 'needs_reauth'"
@click="imports.reauthorize(record)">{{ t.player_import_sign_in_again }}</button>
</div>
</li>
</template>
</ul>
</div>
</template>
</section>
</template>
<template x-if="$store.library.view === 'import_detail'">
<section class="library-imports" x-data="{ get imports() { return $store.imports }, get detail() { return $store.imports.detail } }"
@keydown.space="if ($event.target.closest('button,a,input,select,label')) $event.stopPropagation()">
<nav class="breadcrumb" aria-label="{{ t.player_import_library }}">
<a href="#imports">{{ t.player_import_library }}</a>
</nav>
<div class="import-notice error" role="alert" x-show="imports.detailError" x-cloak>
<span x-text="imports.detailError"></span>
<button type="button" class="import-text-action" @click="imports.open(imports.detailId)">{{ t.player_import_retry }}</button>
</div>
<template x-if="!detail && !imports.detailError">
<div class="page-skeleton" role="status">
<span class="loading-label">{{ t.player_loading_content }}</span>
<div aria-hidden="true">
<i class="skeleton-bar skeleton-title"></i>
<i class="skeleton-bar skeleton-byline"></i>
<div class="import-stats import-stats-skeleton">
{% for _ in 0..4 %}<div><i class="skeleton-bar"></i><i class="skeleton-bar"></i></div>{% endfor %}
</div>
</div>
{% include "player/skeleton_tracks.html" %}
</div>
</template>
<template x-if="detail">
<div>
<header class="import-heading">
<div class="import-heading-copy">
<h1 class="section-title" x-text="imports.title(detail)"></h1>
<p>
<span class="import-status" :data-status="detail.status" x-text="imports.statusText(detail)"></span>
<span x-text="imports.date(detail.created_at)"></span>
</p>
</div>
<div class="import-actions" data-online-only>
<button type="button" class="release-action-btn primary" x-show="detail.status === 'needs_reauth'"
@click="imports.reauthorize()">{{ t.player_import_sign_in_again }}</button>
<button type="button" class="release-action-btn secondary" x-show="imports.isFinished(detail)"
:disabled="imports.busy" :aria-expanded="imports.retryPanel" aria-controls="import-retry-panel"
@click="imports.openRetry()">{{ t.player_import_retry_unmatched }}</button>
<button type="button" class="release-action-btn secondary" x-show="imports.isActive(detail) || detail.status === 'needs_reauth'"
:disabled="imports.busy || detail.cancel_requested" @click="imports.cancel()">{{ t.player_import_cancel }}</button>
<button type="button" class="release-action-btn secondary" x-show="!imports.isActive(detail)"
:disabled="imports.busy" @click="imports.remove()">{{ t.player_import_delete_history }}</button>
</div>
</header>
<div id="import-retry-panel" class="import-retry-panel" x-show="imports.retryPanel" x-cloak
x-transition.opacity.duration.140ms>
<div class="import-consent">
<button type="button" role="switch" class="offline-switch-row" :aria-checked="imports.retryFederated"
:disabled="!imports.federatedAvailable" aria-labelledby="import-retry-federated"
aria-describedby="import-retry-consent" @click="imports.retryFederated = !imports.retryFederated">
<span class="offline-switch" aria-hidden="true"></span>
</button>
<span>
<strong id="import-retry-federated">{{ t.player_import_federated }}</strong>
<small id="import-retry-consent" x-text="imports.federatedAvailable ? imports.text('federatedConsent') : imports.text('federatedOff')"></small>
</span>
</div>
<button type="button" class="release-action-btn primary" :disabled="imports.busy"
@click="imports.retry(detail, imports.federatedAvailable ? imports.retryFederated : undefined)">{{ t.player_import_retry }}</button>
</div>
<p class="import-notice" role="status" aria-live="polite" x-show="imports.message || imports.notice"
x-text="imports.message || imports.notice"></p>
<p class="import-notice" x-show="detail.status === 'needs_reauth'">{{ t.player_import_reauth_needed }}</p>
<p class="import-notice error" x-show="detail.error" x-text="detail.error"></p>
<div class="import-progress" x-show="imports.isActive(detail)" x-cloak>
<span x-text="imports.phaseText(detail)"></span>
<template x-if="imports.progress(detail).max">
<progress :max="imports.progress(detail).max" :value="imports.progress(detail).value"
:aria-label="imports.phaseText(detail)"></progress>
</template>
<template x-if="!imports.progress(detail).max">
<progress :aria-label="imports.phaseText(detail)"></progress>
</template>
</div>
<dl class="import-stats">
<div><dt>{{ t.player_import_stat_total }}</dt><dd x-text="imports.number(imports.stats(detail).total)"></dd></div>
<div>
<dt>{{ t.player_import_stat_found }}</dt>
<dd x-text="imports.number(imports.found(detail))"></dd>
<small x-text="imports.text('local') + ' ' + imports.number(imports.stats(detail).matched_local) + ' · ' + imports.text('federation') + ' ' + imports.number(imports.stats(detail).matched_federation)"></small>
</div>
<div><dt>{{ t.player_import_stat_published }}</dt><dd x-text="imports.number(imports.stats(detail).published)"></dd></div>
<div><dt>{{ t.player_import_stat_ambiguous }}</dt><dd x-text="imports.number(imports.stats(detail).ambiguous)"></dd></div>
<div><dt>{{ t.player_import_stat_unmatched }}</dt><dd x-text="imports.number(imports.stats(detail).unmatched)"></dd></div>
<div><dt>{{ t.player_import_stat_unsupported }}</dt><dd x-text="imports.number(imports.stats(detail).unsupported)"></dd></div>
</dl>
<ul class="import-extra-stats" x-show="imports.extraStats().length">
<template x-for="stat in imports.extraStats()" :key="stat.key">
<li><span x-text="stat.label"></span> <strong x-text="imports.number(stat.value)"></strong></li>
</template>
</ul>
<h2 class="import-subtitle">{{ t.player_import_playlists }}</h2>
<ul class="import-playlists">
<template x-for="playlist in detail.source_playlists" :key="playlist.id">
<li class="collection-row">
<template x-if="playlist.target_playlist_id && !playlist.target_deleted">
<a class="collection-link" :href="'#playlist/' + playlist.target_playlist_id">
<span class="collection-art" :class="{likes: playlist.kind === 'favorites'}" aria-hidden="true"
x-text="playlist.kind === 'favorites' ? '♥' : '♫'"></span>
<span><strong x-text="playlist.title"></strong>
<small x-text="imports.text('foundOf', {found: imports.number(playlist.matched), total: imports.number(playlist.total)}) + ' · ' + imports.text('statPublished') + ' ' + imports.number(playlist.published)"></small></span>
</a>
</template>
<template x-if="!playlist.target_playlist_id || playlist.target_deleted">
<div class="collection-link">
<span class="collection-art" aria-hidden="true" x-text="playlist.kind === 'favorites' ? '♥' : '♫'"></span>
<span><strong x-text="playlist.title"></strong>
<small x-text="playlist.target_deleted ? imports.text('playlistDeleted') : imports.text('playlistPending')"></small></span>
</div>
</template>
<button type="button" class="import-text-action" data-online-only x-show="playlist.target_deleted && !imports.isActive(detail)"
:disabled="imports.busy" @click="imports.recreate(playlist)">{{ t.player_import_recreate }}</button>
</li>
</template>
</ul>
<h2 class="import-subtitle">{{ t.player_import_entries }}</h2>
<div class="import-filters">
<div class="collection-tabs" role="group" aria-label="{{ t.player_import_entries }}">
<template x-for="option in imports.statusFilters()" :key="option.status">
<button type="button" :aria-pressed="imports.filter.status === option.status"
@click="imports.setStatus(option.status)"
x-text="option.label + ' ' + imports.number(option.count)"></button>
</template>
</div>
<div class="import-filter-fields">
<select aria-label="{{ t.player_import_playlists }}" x-show="detail.source_playlists.length > 1"
:value="imports.filter.playlist" @change="imports.setPlaylist($event.target.value)">
<option value="">{{ t.player_import_all_playlists }}</option>
<template x-for="playlist in detail.source_playlists" :key="playlist.id">
<option :value="String(playlist.id)" x-text="playlist.title"></option>
</template>
</select>
<input type="search" placeholder="{{ t.player_import_search }}" aria-label="{{ t.player_import_search }}"
maxlength="200" x-model="imports.filter.q" @input="imports.searchChanged()">
</div>
</div>
<template x-if="!imports.itemsLoaded">
<div class="page-skeleton" role="status">
<span class="loading-label">{{ t.player_loading_content }}</span>
{% include "player/skeleton_tracks.html" %}
</div>
</template>
<p class="empty-state" x-show="imports.itemsLoaded && !imports.items.length">{{ t.player_import_no_entries }}</p>
<ol class="import-items" x-show="imports.items.length" :aria-busy="imports.itemsLoading">
<template x-for="item in imports.items" :key="item.id">
<li class="import-item" :data-status="item.resolution_status">
<span class="import-item-position" x-text="item.position + 1"></span>
<div class="import-item-copy">
<strong x-text="imports.meta(item).title || '—'"></strong>
<small x-text="[imports.artists(imports.meta(item).artists), imports.meta(item).album].filter(Boolean).join(' · ')"></small>
<small class="import-item-note" x-show="!imports.filter.playlist && detail.source_playlists.length > 1"
x-text="imports.playlistTitle(item.playlist_id)"></small>
</div>
<span class="import-item-duration" x-text="imports.duration(imports.meta(item).duration_ms)"></span>
<span class="import-item-status">
<span class="import-status" :data-status="item.resolution_status" x-text="imports.resolutionText(item)"></span>
<small x-show="imports.noteText(item) || imports.publicationText(item)"
x-text="imports.noteText(item) || imports.publicationText(item)"></small>
</span>
<template x-if="item.resolution_status === 'ambiguous' && item.candidates?.length">
<div class="import-candidates">
<span class="import-candidates-title">{{ t.player_import_candidates }}</span>
<template x-for="(candidate, index) in item.candidates" :key="index">
<div class="import-candidate">
<div class="import-item-copy">
<strong x-text="candidate.title"></strong>
<small x-text="[imports.artists(candidate.artists), candidate.album].filter(Boolean).join(' · ')"></small>
</div>
<span class="import-item-duration" x-text="candidate.duration_seconds ? formatTime(candidate.duration_seconds) : ''"></span>
<span class="import-origin" x-text="imports.text(candidate.origin === 'federation' ? 'federation' : 'local')"></span>
<button type="button" class="import-text-action" data-online-only
:disabled="!!imports.choosing || imports.isActive(detail)"
@click="imports.choose(item, index)">{{ t.player_import_choose }}</button>
</div>
</template>
</div>
</template>
</li>
</template>
</ol>
<div class="import-more" x-show="imports.itemsNext">
<button type="button" class="release-action-btn secondary" :disabled="imports.itemsLoading"
@click="imports.loadItems(true).catch(error => { imports.message = error.message })"
x-text="imports.itemsLoading ? imports.text('loading') : imports.text('loadMore')"></button>
</div>
</div>
</template>
</section>
</template>
+791
View File
@@ -0,0 +1,791 @@
<script>
document.addEventListener('alpine:init', () => {
const labels = {
title: "{{ t.player_import_library }}",
newImport: "{{ t.player_import_new }}",
sources: "{{ t.player_import_sources }}",
history: "{{ t.player_import_history }}",
historyEmpty: "{{ t.player_import_history_empty }}",
loadFailed: "{{ t.player_import_load_failed }}",
failed: "{{ t.player_import_request_failed }}",
retry: "{{ t.player_import_retry }}",
methodFile: "{{ t.player_import_method_file }}",
methodFileHint: "{{ t.player_import_method_file_hint }}",
methodApi: "{{ t.player_import_method_api }}",
methodApiHint: "{{ t.player_import_method_api_hint }}",
chooseFiles: "{{ t.player_import_choose_files }}",
reading: "{{ t.player_import_reading }}",
filesRead: "{{ t.player_import_files_read }}",
filesSkipped: "{{ t.player_import_files_skipped }}",
noFiles: "{{ t.player_import_no_files }}",
archiveTooLarge: "{{ t.player_import_archive_too_large }}",
zipTooManyEntries: "{{ t.player_import_zip_too_many_entries }}",
zipTooManyFiles: "{{ t.player_import_zip_too_many_files }}",
exportTooLarge: "{{ t.player_import_export_too_large }}",
zipInvalid: "{{ t.player_import_zip_invalid }}",
zipLoadFailed: "{{ t.player_import_zip_load_failed }}",
requestTooLarge: "{{ t.player_import_request_too_large }}",
signIn: "{{ t.player_import_sign_in }}",
signInAgain: "{{ t.player_import_sign_in_again }}",
loadingPlaylists: "{{ t.player_import_loading_playlists }}",
selectPlaylists: "{{ t.player_import_select_playlists }}",
selectAll: "{{ t.player_import_select_all }}",
selectNone: "{{ t.player_import_select_none }}",
selectedCount: "{{ t.player_import_selected_count }}",
favorites: "{{ t.player_import_favorites }}",
unsupportedCount: "{{ t.player_import_unsupported_count }}",
alreadyImported: "{{ t.player_import_already_imported }}",
allImported: "{{ t.player_import_all_imported }}",
similar: "{{ t.player_import_similar }}",
confirmSimilar: "{{ t.player_import_confirm_similar }}",
confirmSimilarNeeded: "{{ t.player_import_confirm_similar_needed }}",
unavailable: "{{ t.player_import_unavailable }}",
federated: "{{ t.player_import_federated }}",
federatedConsent: "{{ t.player_import_federated_consent }}",
federatedOff: "{{ t.player_import_federated_off }}",
start: "{{ t.player_import_start }}",
starting: "{{ t.player_import_starting }}",
back: "{{ t.player_import_back }}",
conflicts: "{{ t.player_import_conflicts }}",
similarConflicts: "{{ t.player_import_similar_conflicts }}",
status_queued: "{{ t.player_import_status_queued }}",
status_running: "{{ t.player_import_status_running }}",
status_done: "{{ t.player_import_status_done }}",
status_cancelled: "{{ t.player_import_status_cancelled }}",
status_failed: "{{ t.player_import_status_failed }}",
status_needs_reauth: "{{ t.player_import_status_needs_reauth }}",
status_cancelling: "{{ t.player_import_status_cancelling }}",
phase_fetching: "{{ t.player_import_phase_fetching }}",
phase_resolve_local: "{{ t.player_import_phase_resolve_local }}",
phase_resolve_federation: "{{ t.player_import_phase_resolve_federation }}",
phase_publish: "{{ t.player_import_phase_publish }}",
phase_waiting: "{{ t.player_import_phase_waiting }}",
foundOf: "{{ t.player_import_found_of }}",
number: "{{ t.player_import_number }}",
playlistsMore: "{{ t.player_import_playlists_more }}",
retryUnmatched: "{{ t.player_import_retry_unmatched }}",
retryStarted: "{{ t.player_import_retry_started }}",
cancel: "{{ t.player_import_cancel }}",
cancelRequested: "{{ t.player_import_cancel_requested }}",
deleteHistory: "{{ t.player_import_delete_history }}",
deleteConfirm: "{{ t.player_import_delete_confirm }}",
deleted: "{{ t.player_import_deleted }}",
reauthNeeded: "{{ t.player_import_reauth_needed }}",
statTotal: "{{ t.player_import_stat_total }}",
statFound: "{{ t.player_import_stat_found }}",
statPublished: "{{ t.player_import_stat_published }}",
statAmbiguous: "{{ t.player_import_stat_ambiguous }}",
statUnmatched: "{{ t.player_import_stat_unmatched }}",
statUnsupported: "{{ t.player_import_stat_unsupported }}",
statFailed: "{{ t.player_import_stat_failed }}",
statDeferred: "{{ t.player_import_stat_deferred }}",
statDuplicate: "{{ t.player_import_stat_duplicate }}",
statAlreadyPresent: "{{ t.player_import_stat_already_present }}",
statPaused: "{{ t.player_import_stat_paused }}",
statNoContent: "{{ t.player_import_stat_no_content }}",
statPublishFailed: "{{ t.player_import_stat_publish_failed }}",
playlists: "{{ t.player_import_playlists }}",
playlistDeleted: "{{ t.player_import_playlist_deleted }}",
playlistPending: "{{ t.player_import_playlist_pending }}",
recreate: "{{ t.player_import_recreate }}",
recreateStarted: "{{ t.player_import_recreate_started }}",
entries: "{{ t.player_import_entries }}",
filterAll: "{{ t.player_import_filter_all }}",
allPlaylists: "{{ t.player_import_all_playlists }}",
search: "{{ t.player_import_search }}",
noEntries: "{{ t.player_import_no_entries }}",
loadMore: "{{ t.player_import_load_more }}",
loading: "{{ t.player_import_loading }}",
candidates: "{{ t.player_import_candidates }}",
choose: "{{ t.player_import_choose }}",
chosen: "{{ t.player_import_chosen }}",
local: "{{ t.player_import_origin_local }}",
federation: "{{ t.player_import_origin_federation }}",
res_pending: "{{ t.player_import_res_pending }}",
res_matched: "{{ t.player_import_res_matched }}",
res_ambiguous: "{{ t.player_import_res_ambiguous }}",
res_unmatched: "{{ t.player_import_res_unmatched }}",
res_unsupported: "{{ t.player_import_res_unsupported }}",
res_failed: "{{ t.player_import_res_failed }}",
pub_pending: "{{ t.player_import_pub_pending }}",
pub_published: "{{ t.player_import_pub_published }}",
pub_duplicate: "{{ t.player_import_pub_duplicate }}",
pub_already_present: "{{ t.player_import_pub_already_present }}",
pub_no_content_id: "{{ t.player_import_pub_no_content_id }}",
pub_deferred_sync_limit: "{{ t.player_import_pub_deferred }}",
pub_paused: "{{ t.player_import_pub_paused }}",
pub_failed: "{{ t.player_import_pub_failed }}",
note_not_found: "{{ t.player_import_note_not_found }}",
note_version_mismatch: "{{ t.player_import_note_version_mismatch }}",
note_duration_mismatch: "{{ t.player_import_note_duration_mismatch }}",
note_federation_error: "{{ t.player_import_note_federation_error }}",
note_federation_budget: "{{ t.player_import_note_federation_budget }}",
note_federation_unavailable: "{{ t.player_import_note_federation_unavailable }}",
note_episode: "{{ t.player_import_note_episode }}",
note_audiobook: "{{ t.player_import_note_audiobook }}",
note_local_file: "{{ t.player_import_note_local_file }}",
note_unknown_kind: "{{ t.player_import_note_unknown_kind }}",
note_missing_title: "{{ t.player_import_note_missing_title }}",
note_failed: "{{ t.player_import_note_failed }}",
oauth_state: "{{ t.player_import_oauth_state }}",
oauth_expired: "{{ t.player_import_oauth_expired }}",
oauth_denied: "{{ t.player_import_oauth_denied }}",
oauth_not_configured: "{{ t.player_import_oauth_not_configured }}",
oauth_exchange: "{{ t.player_import_oauth_exchange }}",
oauth_not_allowed: "{{ t.player_import_oauth_not_allowed }}",
oauth_unavailable: "{{ t.player_import_oauth_unavailable }}",
oauth_not_waiting: "{{ t.player_import_oauth_not_waiting }}",
oauth_account_mismatch: "{{ t.player_import_oauth_account_mismatch }}",
};
const MiB = 1024 * 1024;
// The request limit of /api/imports. The wizard checks it before sending,
// and the archive limits keep a ZIP bomb from filling the browser memory:
// fflate never inflates an entry beyond its declared size, so the declared
// sizes of the extracted files bound what is decompressed.
const LIMITS = {archiveBytes: 256 * MiB, entries: 2000, files: 256, exportBytes: 32 * MiB, requestBytes: 32 * MiB};
// Only these files of an export are read; listening history stays in the browser.
const EXPORT_FILES = {spotify: /(^|\/)(Playlist\d*|YourLibrary)\.json$/};
const POLL_MS = 3000;
const ACTIVE = ['queued', 'running'];
const FINISHED = ['done', 'failed', 'cancelled'];
const NOTES_FAILED = ['invalid_metadata', 'resolve_failed', 'write_failed', 'content_id_failed'];
const locale = document.documentElement.lang || 'en';
const numbers = new Intl.NumberFormat(locale);
const dates = new Intl.DateTimeFormat(locale, {dateStyle:'medium', timeStyle:'short'});
const fill = (template, values) => template.replace(/\{(\w+)\}/g, (_, key) => values[key] ?? '');
let fflateLoading = null;
function emptyWizard() {
return {
open: false, step: 'source', provider: '', method: '', busy: false, error: '', notice: '',
files: [], fileNames: [], skipped: 0, preview: null, selected: {}, confirmed: {}, federated: false,
};
}
Alpine.store('imports', {
providers: [], federatedAvailable: false, providersLoaded: false,
imports: [], loaded: false, loading: false, error: '', message: '',
detail: null, detailId: null, detailError: '', notice: '',
items: [], itemsNext: null, itemsLoading: false, itemsLoaded: false,
filter: {status: '', playlist: '', q: ''},
retryPanel: false, retryFederated: false,
busy: false, choosing: null,
wizard: emptyWizard(),
_navigation: 0, _items: 0, _timer: null, _search: null, _signature: '',
text(key, values) {
const label = labels[key] ?? key;
return values ? fill(label, values) : label;
},
number(value) { return numbers.format(Number(value) || 0); },
date(value) {
const date = value ? new Date(value) : null;
return date && !isNaN(date) ? dates.format(date) : '';
},
duration(ms) { return ms ? formatTime(Number(ms) / 1000) : ''; },
stats(record) { return record?.statistics || {}; },
found(record) {
const stats = this.stats(record);
return (stats.matched_local || 0) + (stats.matched_federation || 0);
},
title(record) {
return this.providerName(record?.provider) + ' · ' + this.text('number', {id: record?.id});
},
providerName(id) {
return this.providers.find(provider => provider.id === id)?.name || (id ? id[0].toUpperCase() + id.slice(1) : '');
},
isActive(record) { return ACTIVE.includes(record?.status); },
isFinished(record) { return FINISHED.includes(record?.status); },
statusText(record) {
if (record?.cancel_requested && this.isActive(record)) return this.text('status_cancelling');
return this.text('status_' + record?.status);
},
phaseText(record) {
if (record?.status === 'queued') return this.text('phase_waiting');
return record?.phase ? this.text('phase_' + record.phase) : '';
},
// Progress of the current phase; `null` max means an indeterminate bar.
progress(record) {
const stats = this.stats(record);
if (record?.status !== 'running' || record.phase === 'fetching' || !stats.total) return {value: null, max: null};
if (record.phase === 'publish') {
const done = ['published', 'duplicate', 'already_present', 'no_content_id', 'deferred_sync_limit', 'paused', 'publication_failed']
.reduce((sum, key) => sum + (stats[key] || 0), 0);
const max = done + (stats.publication_pending || 0);
return max ? {value: done, max} : {value: null, max: null};
}
return {value: stats.total - (stats.pending || 0), max: stats.total};
},
noteText(item) {
const note = item?.resolution_note;
if (!note) return '';
if (NOTES_FAILED.includes(note)) return this.text('note_failed');
return labels['note_' + note] || '';
},
resolutionText(item) {
if (item.resolution_status === 'matched') {
return this.text(item.match_origin === 'federation' ? 'federation' : 'local');
}
return this.text('res_' + item.resolution_status);
},
publicationText(item) {
const status = item?.publication_status;
return status && status !== 'not_ready' ? this.text('pub_' + status) : '';
},
meta(item) { return item?.metadata || {}; },
artists(list) { return (list || []).filter(Boolean).join(', '); },
async api(url, options = {}) {
const init = {...options};
if (options.body !== undefined) init.headers = {'Content-Type': 'application/json'};
const response = await fetch(url, init);
const data = await response.json().catch(() => ({}));
if (!response.ok) {
const message = response.status === 413 ? this.text('requestTooLarge') : data.error || this.text('failed');
throw Object.assign(new Error(message), {status: response.status, data});
}
return data;
},
// ---------------------------------------------------------------
// Navigation and polling
// ---------------------------------------------------------------
visible() { return ['imports', 'import_detail'].includes(Alpine.store('library').view); },
navigate(hash, view, options = {}) {
const library = Alpine.store('library');
library._beginNavigation(hash, options);
library.searchQuery = '';
library.searchResults = null;
library.view = view;
library.currentArtist = null;
library.currentRelease = null;
library.currentPlaylist = null;
library._previousView = view;
Alpine.store('mobile')?.closeLibrary();
},
// `#imports`, `#imports?connect=spotify[&error=CODE]` and `#imports/N[?error=CODE]`.
route(id, params, options = {}) {
const query = new URLSearchParams(params || '');
const error = query.get('error');
if (id > 0) return this.open(id, {...options, error});
const connect = query.get('connect');
const entered = this.enter(options);
if (connect) this.returnFromSignIn(connect, error);
return entered;
},
async enter(options = {}) {
const token = ++this._navigation;
this.navigate('#imports', 'imports', options);
this.detail = null;
this.detailId = null;
this.message = '';
this.error = '';
this.loading = true;
try {
await Promise.all([this.loadProviders(), this.load()]);
} catch (error) {
if (token === this._navigation) this.error = error.message || this.text('loadFailed');
} finally {
if (token === this._navigation) {
this.loading = false;
Alpine.store('library')._afterNavigation(options);
this.schedule();
}
}
},
async open(id, options = {}) {
const token = ++this._navigation;
this.navigate('#imports/' + id, 'import_detail', options);
if (this.detailId !== id) {
this.detail = null;
this.items = [];
this.itemsLoaded = false;
this.itemsNext = null;
this.filter = {status: '', playlist: '', q: ''};
}
this.detailId = id;
this.detailError = '';
this.message = '';
this.retryPanel = false;
this.notice = options.error ? this.text('oauth_' + options.error) : '';
if (options.error) {
history.replaceState(history.state, '', '#imports/' + id);
Alpine.store('library')._activeHash = '#imports/' + id;
}
try {
if (!this.providersLoaded) this.loadProviders().catch(() => {});
await Promise.all([this.loadDetail(id), this.loadItems()]);
} catch (error) {
if (token === this._navigation) this.detailError = error.status === 404 ? this.text('loadFailed') : error.message;
} finally {
if (token === this._navigation) {
Alpine.store('library')._afterNavigation(options);
this.schedule();
}
}
},
hasActive() {
if (Alpine.store('library').view === 'import_detail') return this.isActive(this.detail);
return this.imports.some(record => this.isActive(record));
},
// Polls every 3 s while the page is open and an import is in progress.
schedule() {
if (this._timer || !this.visible() || !this.hasActive()) return;
this._timer = setTimeout(() => this.tick(), POLL_MS);
},
stopPolling() {
if (this._timer) clearTimeout(this._timer);
this._timer = null;
},
async tick() {
this._timer = null;
if (!this.visible()) return;
const token = this._navigation;
try {
if (Alpine.store('library').view === 'import_detail' && this.detailId) await this.refreshDetail();
else await this.load();
} catch {}
if (token === this._navigation) this.schedule();
},
// ---------------------------------------------------------------
// History
// ---------------------------------------------------------------
async loadProviders() {
const data = await this.api('/api/imports/providers');
this.providers = data.providers || [];
this.federatedAvailable = !!data.federated_search_available;
this.providersLoaded = true;
},
async load() {
const data = await this.api('/api/imports');
const before = this.loaded ? this.published(this.imports) : null;
this.imports = data.imports || [];
this.loaded = true;
if (before !== null && this.published(this.imports) !== before) Alpine.store('playlists')?.reload?.();
},
published(records) {
return records.reduce((sum, record) => sum + (this.stats(record).published || 0), 0);
},
playlistLinks(record) {
return (record?.playlists || []).filter(link => link.target_playlist_id && !link.target_deleted);
},
async retry(record, federated) {
if (this.busy) return;
this.busy = true;
this.message = '';
try {
const body = federated === undefined ? {} : {federated_search: !!federated};
await this.api(`/api/imports/${record.id}/resync`, {method: 'POST', body: JSON.stringify(body)});
this.message = this.text('retryStarted');
this.retryPanel = false;
if (this.detail?.id === record.id) await this.refreshDetail(true);
else await this.load();
} catch (error) {
this.message = error.message;
} finally {
this.busy = false;
this.schedule();
}
},
// ---------------------------------------------------------------
// Details
// ---------------------------------------------------------------
async loadDetail(id) {
const detail = await this.api(`/api/imports/${id}`);
if (this.detailId !== id) return false;
const changed = this._signature !== this.signature(detail);
const published = this.stats(this.detail).published;
this.detail = detail;
this._signature = this.signature(detail);
if (published !== undefined && this.stats(detail).published !== published) Alpine.store('playlists')?.reload?.();
return changed;
},
signature(detail) {
return JSON.stringify([detail?.status, detail?.phase, detail?.statistics]);
},
// A background refresh keeps the entry list; it reloads only an
// unpaginated first page when the counters changed.
async refreshDetail(force = false) {
const id = this.detailId;
const changed = await this.loadDetail(id);
if ((changed || force) && this.detailId === id && this.items.length <= 50 && !this.choosing) await this.loadItems();
},
itemsUrl(after) {
const params = new URLSearchParams();
if (this.filter.status) params.set('status', this.filter.status);
if (this.filter.playlist) params.set('playlist', this.filter.playlist);
if (this.filter.q.trim()) params.set('q', this.filter.q.trim());
if (after) params.set('after', after);
const query = params.toString();
return `/api/imports/${this.detailId}/items` + (query ? '?' + query : '');
},
async loadItems(append = false) {
const id = this.detailId;
const token = ++this._items;
this.itemsLoading = true;
try {
const page = await this.api(this.itemsUrl(append ? this.itemsNext : null));
if (token !== this._items || id !== this.detailId) return;
this.items = append ? [...this.items, ...(page.items || [])] : page.items || [];
this.itemsNext = page.next || null;
this.itemsLoaded = true;
} finally {
if (token === this._items) this.itemsLoading = false;
}
},
setStatus(status) {
if (this.filter.status === status) return;
this.filter.status = status;
this.loadItems().catch(error => { this.message = error.message; });
},
setPlaylist(playlist) {
this.filter.playlist = playlist;
this.loadItems().catch(error => { this.message = error.message; });
},
searchChanged() {
clearTimeout(this._search);
this._search = setTimeout(() => this.loadItems().catch(error => { this.message = error.message; }), 300);
},
statusFilters() {
const stats = this.stats(this.detail);
return [
{status: '', label: this.text('filterAll'), count: stats.total},
{status: 'matched', label: this.text('statFound'), count: (stats.matched_local || 0) + (stats.matched_federation || 0)},
{status: 'ambiguous', label: this.text('statAmbiguous'), count: stats.ambiguous},
{status: 'unmatched', label: this.text('statUnmatched'), count: stats.unmatched},
{status: 'unsupported', label: this.text('statUnsupported'), count: stats.unsupported},
{status: 'failed', label: this.text('statFailed'), count: stats.failed},
{status: 'pending', label: this.text('res_pending'), count: stats.pending},
].filter(filter => !filter.status || filter.count || filter.status === this.filter.status);
},
// The secondary counters appear only when they are not zero.
extraStats() {
const stats = this.stats(this.detail);
return [
['deferred_sync_limit', 'statDeferred'], ['duplicate', 'statDuplicate'],
['already_present', 'statAlreadyPresent'], ['paused', 'statPaused'],
['no_content_id', 'statNoContent'], ['publication_failed', 'statPublishFailed'], ['failed', 'statFailed'],
].filter(([key]) => stats[key]).map(([key, label]) => ({key, label: this.text(label), value: stats[key]}));
},
playlistTitle(id) {
return this.detail?.source_playlists?.find(playlist => playlist.id === id)?.title || '';
},
async cancel() {
if (this.busy || !this.detail) return;
this.busy = true;
this.message = '';
try {
const data = await this.api(`/api/imports/${this.detail.id}/cancel`, {method: 'POST', body: '{}'});
this.message = data.status === 'cancelling' ? this.text('cancelRequested') : '';
await this.refreshDetail(true);
} catch (error) {
this.message = error.message;
} finally {
this.busy = false;
this.schedule();
}
},
async remove(record = this.detail) {
if (this.busy || !record || !confirm(this.text('deleteConfirm'))) return;
this.busy = true;
this.message = '';
try {
await this.api(`/api/imports/${record.id}`, {method: 'DELETE'});
this.imports = this.imports.filter(entry => entry.id !== record.id);
if (this.detailId === record.id) {
this.detail = null;
this.detailId = null;
await this.enter();
}
this.message = this.text('deleted');
} catch (error) {
this.message = error.message;
} finally {
this.busy = false;
}
},
async recreate(playlist) {
if (this.busy || !this.detail) return;
this.busy = true;
this.message = '';
try {
await this.api(`/api/imports/${this.detail.id}/playlists/${playlist.id}/recreate`, {method: 'POST', body: '{}'});
this.message = this.text('recreateStarted');
await this.refreshDetail(true);
} catch (error) {
this.message = error.message;
} finally {
this.busy = false;
this.schedule();
}
},
reauthorize(record = this.detail) {
if (!record) return;
location.assign(`/api/imports/providers/${encodeURIComponent(record.provider)}/authorize?import_id=${record.id}`);
},
openRetry() {
this.retryFederated = !!this.detail?.federated_search && this.federatedAvailable;
this.retryPanel = !this.retryPanel;
},
async choose(item, index) {
if (this.choosing || !this.detail) return;
this.choosing = item.id;
this.message = '';
try {
const result = await this.api(`/api/imports/${this.detail.id}/items/${item.id}/match`, {
method: 'POST', body: JSON.stringify({candidate: index}),
});
const candidate = item.candidates?.[index] || {};
Object.assign(item, {
resolution_status: result.resolution_status || 'matched',
publication_status: result.publication_status || item.publication_status,
match_origin: candidate.origin || item.match_origin,
candidates: null,
});
this.message = this.text('chosen');
this.choosing = null;
await this.refreshDetail();
} catch (error) {
this.message = error.message;
} finally {
this.choosing = null;
this.schedule();
}
},
// ---------------------------------------------------------------
// New import wizard
// ---------------------------------------------------------------
startWizard(provider = '') {
Alpine.store('user').menuOpen = false;
this.wizard = {...emptyWizard(), open: true, provider};
if (!this.providersLoaded) this.loadProviders().catch(error => { this.wizard.error = error.message; });
},
async closeWizard(dialog) {
const close = () => {
this.wizard = emptyWizard();
};
if (dialog) await finishPlayerDialog(dialog, close);
else close();
},
chooseMethod(provider, method) {
this.wizard = {...emptyWizard(), open: true, provider, method, step: method === 'api' ? 'connect' : 'upload'};
// A sign-in from earlier in this session may still be valid.
if (method === 'api') return this.loadApiPlaylists(true);
},
back() {
const {provider} = this.wizard;
this.wizard = {...emptyWizard(), open: true, provider};
},
signIn(provider = this.wizard.provider) {
location.assign(`/api/imports/providers/${encodeURIComponent(provider)}/authorize`);
},
// The browser returns here from the provider's sign-in page.
returnFromSignIn(provider, error) {
history.replaceState(history.state, '', '#imports');
Alpine.store('library')._activeHash = '#imports';
this.wizard = {...emptyWizard(), open: true, provider, method: 'api', step: 'connect'};
if (error) {
this.wizard.error = this.text('oauth_' + error);
return;
}
return this.loadApiPlaylists();
},
async loadApiPlaylists(quiet = false) {
const wizard = this.wizard;
wizard.busy = true;
wizard.error = '';
wizard.notice = this.text('loadingPlaylists');
try {
const preview = await this.api(`/api/imports/providers/${encodeURIComponent(wizard.provider)}/playlists`);
if (this.wizard !== wizard) return;
this.applyPreview(preview);
} catch (error) {
if (this.wizard === wizard && !(quiet && error.status === 409)) wizard.error = error.message;
} finally {
wizard.busy = false;
wizard.notice = '';
}
},
async zipLibrary() {
if (window.fflate) return window.fflate;
fflateLoading ??= new Promise((resolve, reject) => {
const script = document.createElement('script');
script.src = '/vendor/fflate-0.8.2.js';
script.onload = () => window.fflate ? resolve(window.fflate) : reject(new Error(this.text('zipLoadFailed')));
script.onerror = () => reject(new Error(this.text('zipLoadFailed')));
document.head.appendChild(script);
}).catch(error => {
fflateLoading = null;
throw error;
});
return fflateLoading;
},
// Extracts only the export's playlist files. Archive entries, files and
// declared sizes are limited before anything is decompressed.
async readArchive(file, pattern, budget) {
if (file.size > LIMITS.archiveBytes) throw new Error(this.text('archiveTooLarge'));
const fflate = await this.zipLibrary();
const bytes = new Uint8Array(await file.arrayBuffer());
let entries = 0;
let problem = '';
const extracted = await new Promise((resolve, reject) => {
try {
fflate.unzip(bytes, {filter: entry => {
entries += 1;
if (problem) return false;
if (entries > LIMITS.entries) problem = 'zipTooManyEntries';
if (problem || !pattern.test(entry.name)) return false;
const size = Number(entry.originalSize);
budget.files += 1;
budget.bytes += Number.isFinite(size) && size >= 0 ? size : Infinity;
if (budget.files > LIMITS.files) problem = 'zipTooManyFiles';
else if (budget.bytes > LIMITS.exportBytes) problem = 'exportTooLarge';
return !problem;
}}, (error, files) => error ? reject(error) : resolve(files));
} catch (error) {
reject(error);
}
}).catch(error => {
throw problem ? new Error(this.text(problem)) : new Error(this.text('zipInvalid'));
});
if (problem) throw new Error(this.text(problem));
const decoder = new TextDecoder();
return Object.entries(extracted).map(([name, data]) => ({name, text: decoder.decode(data)}));
},
async readFiles(list) {
const wizard = this.wizard;
const pattern = EXPORT_FILES[wizard.provider];
const files = Array.from(list || []);
if (!pattern || !files.length) return;
wizard.busy = true;
wizard.error = '';
wizard.notice = this.text('reading');
wizard.preview = null;
try {
const budget = {files: 0, bytes: 0};
const read = [];
let skipped = 0;
for (const file of files) {
if (/\.zip$/i.test(file.name) || /zip/.test(file.type || '')) {
read.push(...await this.readArchive(file, pattern, budget));
} else if (pattern.test(file.name)) {
budget.files += 1;
budget.bytes += file.size;
if (budget.files > LIMITS.files) throw new Error(this.text('zipTooManyFiles'));
if (budget.bytes > LIMITS.exportBytes) throw new Error(this.text('exportTooLarge'));
read.push({name: file.name, text: await file.text()});
} else {
skipped += 1;
}
}
if (this.wizard !== wizard) return;
if (!read.length) throw new Error(this.text('noFiles'));
// Parsed JSON is sent compact; text that does not parse goes as is,
// so the server can name the file and line that is broken.
wizard.files = read.map(file => {
const text = file.text.replace(/^/, '');
try {
return {name: file.name, data: JSON.parse(text)};
} catch {
return {name: file.name, data: text};
}
});
wizard.fileNames = read.map(file => file.name.split('/').pop());
wizard.skipped = skipped;
wizard.notice = '';
const preview = await this.api('/api/imports/preview', {method: 'POST', body: this.requestBody({})});
if (this.wizard === wizard) this.applyPreview(preview);
} catch (error) {
if (this.wizard === wizard) {
wizard.error = error.message || this.text('failed');
wizard.files = [];
}
} finally {
wizard.busy = false;
wizard.notice = '';
}
},
requestBody(extra) {
const wizard = this.wizard;
const body = JSON.stringify({provider: wizard.provider, source: wizard.method || 'file',
...(wizard.method === 'api' ? {} : {files: wizard.files}), ...extra});
if (new TextEncoder().encode(body).length > LIMITS.requestBytes) throw new Error(this.text('requestTooLarge'));
return body;
},
applyPreview(preview) {
const wizard = this.wizard;
wizard.preview = preview;
wizard.step = 'select';
wizard.selected = {};
wizard.confirmed = {};
for (const playlist of preview.playlists || []) {
wizard.selected[playlist.source_key] = this.selectable(playlist) && !playlist.similar_to;
}
if (!preview.federated_search_available) wizard.federated = false;
this.federatedAvailable = !!preview.federated_search_available;
},
selectable(playlist) { return playlist.available !== false && !playlist.already_imported_in; },
selectAll(value) {
for (const playlist of this.wizard.preview?.playlists || []) {
if (this.selectable(playlist)) this.wizard.selected[playlist.source_key] = value && !playlist.similar_to;
}
},
selection() {
return (this.wizard.preview?.playlists || [])
.filter(playlist => this.selectable(playlist) && this.wizard.selected[playlist.source_key]);
},
unconfirmed() {
return this.selection().filter(playlist => playlist.similar_to && !this.wizard.confirmed[playlist.source_key]);
},
canStart() {
return !this.wizard.busy && this.selection().length > 0 && !this.unconfirmed().length;
},
async begin() {
const wizard = this.wizard;
if (!this.canStart()) {
if (this.unconfirmed().length) wizard.error = this.text('confirmSimilarNeeded');
return;
}
wizard.busy = true;
wizard.error = '';
wizard.notice = this.text('starting');
try {
const selection = this.selection();
const result = await this.api('/api/imports', {method: 'POST', body: this.requestBody({
selection: selection.map(playlist => playlist.source_key),
federated_search: wizard.federated && this.federatedAvailable,
confirm_similar: selection.filter(playlist => playlist.similar_to).map(playlist => playlist.source_key),
})});
await this.closeWizard(document.querySelector('.import-wizard[open]'));
return this.open(result.id);
} catch (error) {
if (this.wizard !== wizard) return;
this.applyConflicts(error.data || {});
wizard.error = error.data?.conflicts ? this.text('conflicts')
: error.data?.similar ? this.text('similarConflicts') : error.message;
} finally {
wizard.busy = false;
wizard.notice = '';
}
},
// A 409 names playlists imported meanwhile; the wizard marks them.
applyConflicts(data) {
const playlists = this.wizard.preview?.playlists || [];
for (const conflict of data.conflicts || []) {
const playlist = playlists.find(entry => entry.source_key === conflict.source_key);
if (playlist) {
playlist.already_imported_in = conflict.import_id;
this.wizard.selected[playlist.source_key] = false;
}
}
for (const similar of data.similar || []) {
const playlist = playlists.find(entry => entry.source_key === similar.source_key);
if (playlist) playlist.similar_to = {import_id: similar.import_id, target_playlist_id: similar.target_playlist_id};
}
},
});
});
</script>
+140
View File
@@ -0,0 +1,140 @@
<style>
.library-imports { max-width: 1050px; margin: 0 auto; padding: 0 0 24px; }
:where(.library-imports, .import-wizard) :where(button, select, input) { font-family: inherit; }
.library-imports :is(a, button, select, input):focus-visible, .import-wizard :is(a, button, input):focus-visible,
.import-file-button:focus-within { outline: 2px solid var(--accent); outline-offset: 2px; }
.import-heading { display: flex; align-items: flex-start; justify-content: space-between; flex-wrap: wrap; gap: 12px; margin-bottom: 16px; }
.import-heading .section-title { margin: 0; }
.import-heading-copy { min-width: 0; }
.import-heading-copy p { display: flex; align-items: center; flex-wrap: wrap; gap: 8px; margin: 8px 0 0; color: var(--text-secondary); font-size: 13px; }
.import-actions { display: flex; flex-wrap: wrap; gap: 8px; }
.import-subtitle { margin: 26px 0 12px; font-size: 18px; letter-spacing: -.015em; }
.import-notice { margin: 0 0 12px; color: var(--text-secondary); font-size: 13px; overflow-wrap: anywhere; }
.import-notice.error { display: flex; align-items: center; flex-wrap: wrap; gap: 10px; color: #ffaeab; }
.import-text-action { padding: 6px 10px; border: 1px solid var(--border-color); border-radius: 5px; background: transparent; color: var(--text-secondary); font-size: 13px; cursor: pointer; transition: color 120ms, background-color 120ms; }
.import-text-action:hover:not(:disabled) { color: var(--text-primary); background: var(--bg-elevated); }
.import-text-action:disabled { opacity: .45; cursor: default; }
.import-source-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(210px, 1fr)); gap: 12px; }
.import-source, .import-method {
display: grid; gap: 6px; min-width: 0; padding: 14px 16px; border: 1px solid var(--border-color); border-radius: 8px;
background: var(--bg-secondary); color: var(--text-primary); text-align: left; cursor: pointer; transition: background-color 140ms, border-color 140ms;
}
.import-source:hover, .import-method:hover { background: var(--bg-elevated); border-color: var(--bg-active); }
.import-source strong, .import-method strong { font-size: 15px; }
.import-source small, .import-method small { color: var(--text-secondary); font-size: 12px; line-height: 1.4; }
.import-source.skeleton-card { min-height: 46px; cursor: default; }
.import-source.skeleton-card .skeleton-bar:first-child { width: 40%; }
.import-history { list-style: none; margin: 0; padding: 0; }
.import-history-row { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 4px 12px; padding: 10px 6px; border-bottom: 1px solid var(--border-color); }
.import-history-row:hover, .import-history-row:focus-within { background: var(--bg-elevated); border-radius: 6px; }
.import-history-link, .import-history-playlists { grid-column: 1; }
.import-history-link { display: grid; grid-template-columns: minmax(0, 1fr) auto auto; align-items: center; gap: 12px; min-width: 0; color: inherit; text-decoration: none; }
.import-history-title { min-width: 0; }
.import-history-title strong, .import-history-title small { display: block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.import-history-title strong { font-size: 14px; }
.import-history-title small, .import-history-count { color: var(--text-subdued); font-size: 12px; }
.import-history-count { font-variant-numeric: tabular-nums; white-space: nowrap; }
.import-history-actions { display: flex; gap: 6px; align-items: center; grid-column: 2; grid-row: 1 / span 2; }
.import-history-playlists { display: flex; flex-wrap: wrap; gap: 4px 10px; min-width: 0; color: var(--text-subdued); font-size: 12px; }
.import-history-playlists a { color: var(--text-secondary); text-decoration: none; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; max-width: 220px; }
.import-history-playlists a:hover { color: var(--text-primary); text-decoration: underline; }
.import-status { display: inline-flex; align-items: center; padding: 2px 8px; border-radius: 10px; background: var(--bg-active); color: var(--text-secondary); font-size: 12px; white-space: nowrap; }
.import-status:is([data-status=done], [data-status=matched]) { background: #183426; color: var(--accent); }
.import-status:is([data-status=running], [data-status=queued], [data-status=pending]) { color: var(--text-primary); }
.import-status:is([data-status=failed], [data-status=needs_reauth]) { background: #3a1f1f; color: #ffaeab; }
.import-status[data-status=ambiguous] { background: #3a321a; color: #f0d58a; }
.import-progress { display: grid; gap: 6px; margin: 0 0 16px; color: var(--text-secondary); font-size: 13px; }
.import-progress progress { width: 100%; height: 6px; accent-color: var(--accent); }
.import-stats { display: grid; grid-template-columns: repeat(6, minmax(0, 1fr)); margin: 0 0 10px; padding: 16px 0; border: 1px solid var(--border-color); border-radius: 8px; background: var(--bg-secondary); }
.import-stats > div { min-width: 0; padding: 0 clamp(8px, 1.6vw, 18px); }
.import-stats > div + div { border-left: 1px solid var(--border-color); }
.import-stats dt, .import-stats small { color: var(--text-secondary); font-size: 12px; }
.import-stats dd { margin: 6px 0 0; font-size: clamp(18px, 2vw, 26px); font-weight: 650; font-variant-numeric: tabular-nums; }
.import-stats small { display: block; margin-top: 4px; overflow-wrap: anywhere; }
.import-stats-skeleton { grid-template-columns: repeat(5, minmax(0, 1fr)); margin-top: 18px; }
.import-stats-skeleton .skeleton-bar + .skeleton-bar { width: 50%; margin-top: 10px; height: 16px; }
.import-extra-stats { display: flex; flex-wrap: wrap; gap: 6px 16px; list-style: none; margin: 0; padding: 0; color: var(--text-secondary); font-size: 13px; }
.import-extra-stats strong { color: var(--text-primary); font-variant-numeric: tabular-nums; }
.import-playlists { list-style: none; margin: 0; padding: 0; max-width: 840px; }
.import-filters { display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: 10px; margin-bottom: 10px; }
.import-filters .collection-tabs { margin: 0; }
.import-filters .collection-tabs button { display: inline-flex; align-items: center; min-height: 32px; padding: 6px 12px; border: 0; border-radius: 18px; background: var(--bg-elevated); color: var(--text-secondary); font-size: 13px; cursor: pointer; transition: color 120ms, background-color 120ms; }
.import-filters .collection-tabs button:hover { color: var(--text-primary); }
.import-filters .collection-tabs button[aria-pressed=true] { background: var(--text-primary); color: var(--bg-primary); }
.import-filter-fields { display: flex; flex-wrap: wrap; gap: 8px; }
.import-filter-fields :is(select, input) { min-width: 0; max-width: 260px; padding: 7px 10px; border: 1px solid var(--border-color); border-radius: 6px; background: var(--bg-secondary); color: var(--text-primary); color-scheme: dark; font-size: 13px; }
.import-items { list-style: none; margin: 0; padding: 0; transition: opacity 140ms; }
.import-items[aria-busy=true] { opacity: .7; }
.import-item { display: grid; grid-template-columns: 34px minmax(0, 1fr) 48px minmax(120px, auto); align-items: center; gap: 4px 12px; padding: 8px 6px; border-bottom: 1px solid var(--border-color); }
.import-item-position, .import-item-duration { color: var(--text-subdued); font-size: 12px; font-variant-numeric: tabular-nums; }
.import-item-position { text-align: right; }
.import-item-copy { min-width: 0; }
.import-item-copy strong, .import-item-copy small { display: block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.import-item-copy strong { font-size: 14px; font-weight: 600; }
.import-item-copy small { margin-top: 2px; color: var(--text-subdued); font-size: 12px; }
.import-item-status { display: grid; justify-items: end; gap: 3px; text-align: right; }
.import-item-status small { color: var(--text-subdued); font-size: 12px; }
.import-candidates { grid-column: 2 / -1; display: grid; gap: 4px; margin-top: 4px; padding: 8px 10px; border-radius: 6px; background: var(--bg-secondary); }
.import-candidates-title { color: var(--text-secondary); font-size: 12px; }
.import-candidate { display: grid; grid-template-columns: minmax(0, 1fr) 48px auto auto; align-items: center; gap: 10px; }
.import-origin { color: var(--text-secondary); font-size: 12px; }
.import-more { display: flex; justify-content: center; margin-top: 14px; }
.import-retry-panel { display: flex; align-items: center; justify-content: space-between; flex-wrap: wrap; gap: 12px; margin: 0 0 14px; padding: 12px 14px; border: 1px solid var(--border-color); border-radius: 8px; background: var(--bg-secondary); }
.import-consent { display: flex; align-items: flex-start; gap: 10px; min-width: 0; flex: 1; }
.import-consent .offline-switch-row { flex: none; min-height: 22px; border: 0; background: none; cursor: pointer; }
.import-consent strong, .import-consent small { display: block; }
.import-consent strong { font-size: 14px; }
.import-consent small { margin-top: 3px; color: var(--text-secondary); font-size: 12px; line-height: 1.4; }
.import-wizard-body { display: grid; gap: 14px; padding: 16px var(--dialog-gutter) var(--dialog-gutter); }
.import-wizard-body .import-notice { margin: 0; }
.import-step { display: grid; gap: 14px; min-width: 0; }
.import-provider h3 { margin: 0 0 10px; font-size: 15px; }
.import-methods { display: grid; grid-template-columns: repeat(auto-fit, minmax(220px, 1fr)); gap: 10px; }
.import-help, .import-privacy { margin: 0; color: var(--text-secondary); font-size: 13px; line-height: 1.5; }
.import-privacy { color: var(--text-subdued); font-size: 12px; }
.import-file-button { position: relative; justify-self: start; }
.import-file-button.disabled { opacity: .45; pointer-events: none; }
.import-file-input { position: absolute; width: 1px; height: 1px; opacity: 0; overflow: hidden; clip-path: inset(50%); }
.import-select-head { display: flex; align-items: center; justify-content: space-between; flex-wrap: wrap; gap: 8px; font-size: 13px; }
.import-select-head span { display: flex; gap: 6px; }
.import-select-list { list-style: none; max-height: min(46vh, 420px); margin: 0; padding: 0; overflow: auto; overscroll-behavior: contain; border: 1px solid var(--border-color); border-radius: 8px; scrollbar-width: thin; }
.import-select-list li { padding: 8px 12px; border-bottom: 1px solid var(--border-color); }
.import-select-list li:last-child { border-bottom: 0; }
.import-select-list li.disabled .import-select-copy { opacity: .55; }
.import-select-row { display: flex; align-items: center; gap: 10px; min-width: 0; cursor: pointer; }
.import-select-row input, .import-select-note input { flex: none; width: 16px; height: 16px; accent-color: var(--accent); }
.import-select-copy { min-width: 0; }
.import-select-copy strong, .import-select-copy small { display: block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.import-select-copy strong { font-size: 14px; font-weight: 600; }
.import-select-copy small { color: var(--text-subdued); font-size: 12px; }
.import-select-note { display: grid; gap: 6px; margin: 6px 0 0 26px; color: var(--text-secondary); font-size: 12px; }
.import-select-note a { color: var(--text-secondary); }
.import-select-note.warning > span { color: #f0d58a; }
.import-select-note label { display: flex; align-items: center; gap: 8px; color: var(--text-primary); cursor: pointer; }
.import-wizard-footer { display: flex; justify-content: space-between; gap: 10px; padding-top: 4px; }
@media (max-width: 760px) {
.import-stats { grid-template-columns: repeat(3, minmax(0, 1fr)); row-gap: 14px; }
.import-stats > div:nth-child(3n + 1) { border-left: 0; }
.import-stats-skeleton { grid-template-columns: repeat(3, minmax(0, 1fr)); }
}
@media (max-width: 600px) {
.import-history-row { grid-template-columns: minmax(0, 1fr); }
.import-history-link { grid-template-columns: minmax(0, 1fr) auto; }
.import-history-count { grid-column: 1 / -1; }
.import-history-actions { grid-column: 1; grid-row: auto; }
.import-item { grid-template-columns: 26px minmax(0, 1fr) auto; }
.import-item-duration { display: none; }
.import-item-status { grid-column: 2 / -1; justify-items: start; text-align: left; }
.import-candidates { grid-column: 1 / -1; }
.import-candidate { grid-template-columns: minmax(0, 1fr) auto; }
.import-candidate .import-origin { grid-column: 1; }
.import-candidate .import-text-action { grid-column: 2; grid-row: 1 / span 2; min-height: 36px; }
.import-filter-fields, .import-filter-fields :is(select, input) { flex: 1; max-width: none; }
.import-text-action, .import-filters .collection-tabs button { min-height: 36px; }
.import-actions .release-action-btn { flex: 1; justify-content: center; }
}
@media (prefers-reduced-motion: reduce) {
.import-source, .import-method, .import-text-action, .import-items, .import-filters .collection-tabs button { transition: none; }
.import-retry-panel, .import-select-note label { transition-duration: 0s !important; }
}
</style>
+134
View File
@@ -0,0 +1,134 @@
<template x-if="$store.imports.wizard.open">
<dialog id="import-wizard" class="player-dialog import-wizard" aria-labelledby="import-wizard-title" style="--dialog-width: 640px"
x-data="{ get imports() { return $store.imports }, get wizard() { return $store.imports.wizard } }"
x-init="$nextTick(() => { if ($el.isConnected) { $el.showModal(); document.getElementById('import-wizard-title').focus() } })"
@dismiss-player-dialog.stop="imports.closeWizard($el)"
@cancel.prevent="imports.closeWizard($el)" @click.self="imports.closeWizard($el)" @keydown.space.stop>
<div class="player-dialog-surface">
{% let dialog_head_class = "" %}
{% let dialog_title_id = "import-wizard-title" %}
{% let dialog_title = t.player_import_new %}
{% let dialog_icon = "M12 3v12m-4-4 4 4 4-4M5 21h14" %}
{% let show_version = false %}
{% include "player/dialog_header.html" %}
<div class="import-wizard-body" :aria-busy="wizard.busy">
<p class="import-notice error" role="alert" x-show="wizard.error" x-text="wizard.error"></p>
<p class="import-notice" role="status" aria-live="polite" x-show="wizard.notice" x-text="wizard.notice"></p>
<template x-if="wizard.step === 'source'">
<div class="import-step">
<template x-if="!imports.providersLoaded && !wizard.error">
<div class="page-skeleton" role="status">
<span class="loading-label">{{ t.player_loading_content }}</span>
<div class="import-source skeleton-card" aria-hidden="true"><i class="skeleton-bar"></i><i class="skeleton-bar"></i></div>
</div>
</template>
<template x-for="provider in imports.providers.filter(entry => !wizard.provider || entry.id === wizard.provider)" :key="provider.id">
<section class="import-provider">
<h3 x-text="provider.name"></h3>
<div class="import-methods">
<button type="button" class="import-method" x-show="provider.methods.includes('file')"
@click="imports.chooseMethod(provider.id, 'file')">
<strong>{{ t.player_import_method_file }}</strong>
<small>{{ t.player_import_method_file_hint }}</small>
</button>
<button type="button" class="import-method" x-show="provider.methods.includes('api')"
@click="imports.chooseMethod(provider.id, 'api')">
<strong>{{ t.player_import_method_api }}</strong>
<small>{{ t.player_import_method_api_hint }}</small>
</button>
</div>
</section>
</template>
</div>
</template>
<template x-if="wizard.step === 'upload'">
<div class="import-step">
<p class="import-help">{{ t.player_import_upload_help }}</p>
<label class="release-action-btn primary import-file-button" :class="{disabled: wizard.busy}">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" aria-hidden="true"><path d="M12 16V4m-4 4 4-4 4 4M5 20h14"/></svg>
<span>{{ t.player_import_choose_files }}</span>
<input type="file" class="import-file-input" multiple accept=".zip,.json,application/zip,application/json"
:disabled="wizard.busy" @change="imports.readFiles($event.target.files); $event.target.value = ''">
</label>
<p class="import-privacy">{{ t.player_import_privacy }}</p>
</div>
</template>
<template x-if="wizard.step === 'connect'">
<div class="import-step">
<p class="import-help">{{ t.player_import_api_help }}</p>
<button type="button" class="release-action-btn primary" :disabled="wizard.busy" @click="imports.signIn()">
{{ t.player_import_sign_in }}
</button>
</div>
</template>
<template x-if="wizard.step === 'select' && wizard.preview">
<div class="import-step">
<p class="import-help" x-show="wizard.fileNames.length"
x-text="imports.text('filesRead', {count: wizard.fileNames.length}) + (wizard.skipped ? ' ' + imports.text('filesSkipped', {count: wizard.skipped}) : '')"></p>
<p class="import-notice" x-show="wizard.preview.all_imported">{{ t.player_import_all_imported }}</p>
<div class="import-select-head">
<strong x-text="imports.text('selectedCount', {count: imports.selection().length, total: wizard.preview.playlists.length})"></strong>
<span>
<button type="button" class="import-text-action" @click="imports.selectAll(true)">{{ t.player_import_select_all }}</button>
<button type="button" class="import-text-action" @click="imports.selectAll(false)">{{ t.player_import_select_none }}</button>
</span>
</div>
<ul class="import-select-list" aria-label="{{ t.player_import_select_playlists }}">
<template x-for="playlist in wizard.preview.playlists" :key="playlist.source_key">
<li :class="{disabled: !imports.selectable(playlist)}">
<label class="import-select-row">
<input type="checkbox" :disabled="!imports.selectable(playlist)"
x-model="wizard.selected[playlist.source_key]">
<span class="import-select-copy">
<strong x-text="playlist.kind === 'favorites' ? imports.text('favorites') : playlist.title"></strong>
<small x-text="formatArtistCount(playlist.track_count, 'tracks') + (playlist.unsupported_count ? ' · ' + imports.text('unsupportedCount', {count: playlist.unsupported_count}) : '')"></small>
</span>
</label>
<template x-if="playlist.already_imported_in">
<p class="import-select-note">
<a :href="'#imports/' + playlist.already_imported_in" @click="imports.closeWizard($el.closest('dialog'))"
x-text="imports.text('alreadyImported', {id: playlist.already_imported_in})"></a>
</p>
</template>
<template x-if="playlist.available === false">
<p class="import-select-note">{{ t.player_import_unavailable }}</p>
</template>
<template x-if="playlist.similar_to && imports.selectable(playlist)">
<div class="import-select-note warning">
<span x-text="imports.text('similar', {id: playlist.similar_to.import_id})"></span>
<label x-show="wizard.selected[playlist.source_key]" x-transition.opacity.duration.120ms>
<input type="checkbox" x-model="wizard.confirmed[playlist.source_key]">
{{ t.player_import_confirm_similar }}
</label>
</div>
</template>
</li>
</template>
</ul>
<div class="import-consent">
<button type="button" role="switch" class="offline-switch-row" :aria-checked="wizard.federated && imports.federatedAvailable"
:disabled="!imports.federatedAvailable" aria-labelledby="import-federated-title"
aria-describedby="import-federated-consent" @click="wizard.federated = !wizard.federated">
<span class="offline-switch" aria-hidden="true"></span>
</button>
<span>
<strong id="import-federated-title">{{ t.player_import_federated }}</strong>
<small id="import-federated-consent" x-text="imports.federatedAvailable ? imports.text('federatedConsent') : imports.text('federatedOff')"></small>
</span>
</div>
</div>
</template>
<footer class="import-wizard-footer" x-show="wizard.step !== 'source'">
<button type="button" class="release-action-btn secondary" :disabled="wizard.busy" @click="imports.back()">{{ t.player_import_back }}</button>
<button type="button" class="release-action-btn primary" x-show="wizard.step === 'select'"
:disabled="!imports.canStart() && !imports.unconfirmed().length" @click="imports.begin()">{{ t.player_import_start }}</button>
</footer>
</div>
</div>
</dialog>
</template>
+20 -8
View File
@@ -2852,7 +2852,7 @@ document.addEventListener('alpine:init', () => {
if (GUEST) return;
if (this._hashNav) return;
const hash = location.hash || '#artists';
if (playerOffline() && (/^#(?:listening|podcasts?|artistfed|releasefed|similar|share)(?:[/?]|$)/.test(hash) ||
if (playerOffline() && (/^#(?:listening|podcasts?|imports|artistfed|releasefed|similar|share)(?:[/?]|$)/.test(hash) ||
(hash.startsWith('#search?') && new URLSearchParams(hash.slice(8)).get('mode') === 'lyrics'))) {
return this.openCollectionView('offline_unavailable', hash, options);
}
@@ -2877,6 +2877,8 @@ document.addEventListener('alpine:init', () => {
return this._navigateFromHash({...options, fromHash:true});
} else if (view === 'followed') {
this.openCollectionView('followed', '#followed', options);
} else if (view === 'imports') {
Alpine.store('imports').route(id, params, options);
} else if (view === 'artists' && new URLSearchParams(params).get('tab') === 'playlists') {
this.openCollectionView('playlists', '#artists?tab=playlists', options);
} else if (view === 'artists' && !id) {
@@ -6109,19 +6111,29 @@ document.addEventListener('alpine:init', () => {
const playlist = this.currentPlaylist();
const playlistId = Number(playlist.id);
const playlistTrackId = Number(track.playlist_track_id || 0);
// Federated tracks have no playlist row; they are removed by content id.
const contentId = playlistTrackId ? '' : String(track.content_id || '');
const previous = (playlist.tracks || []).slice();
if (!playlistTrackId) return;
if (!playlistTrackId && !contentId) return;
const finish = this._startTrackChange(playlistId);
playlist.tracks = previous.filter(item => Number(item.playlist_track_id || 0) !== playlistTrackId);
playlist.tracks = previous.filter(item => playlistTrackId
? Number(item.playlist_track_id || 0) !== playlistTrackId
: item.playlist_track_id || item.content_id !== contentId);
this._updateListTrackCount(playlistId, playlist.tracks.length);
try {
const res = await fetch(`/api/player/playlists/${playlistId}/tracks`, {
method: 'DELETE',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ playlist_track_id: playlistTrackId }),
});
const res = playlistTrackId
? await fetch(`/api/player/playlists/${playlistId}/tracks`, {
method: 'DELETE',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ playlist_track_id: playlistTrackId }),
})
: await fetch('/api/player/tracks/content/playlist', {
method: 'DELETE',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ playlist_id: playlistId, content_id: contentId }),
});
if (!res.ok) throw new Error('remove failed');
await this._refreshAfterTrackChange(playlist, res);
} catch (err) {
+1
View File
@@ -168,6 +168,7 @@
{% include "player/podcasts.html" %}
{% if !guest %}
{% include "player/collection.html" %}
{% include "player/imports.html" %}
{% endif %}
{% include "player/listening.html" %}
<template x-if="$store.library.pendingDetail">
+241
View File
@@ -0,0 +1,241 @@
// Render first: FURU_LIBRARY_IMPORT_RENDER_FIXTURE=1 cargo test library_import::tests::web
// Uses the real rendered player with isolated API fixtures; no service or user data.
const {chromium}=require(process.env.PLAYWRIGHT_MODULE||'playwright');
const fs=require('node:fs'),path=require('node:path'),assert=require('node:assert/strict');
const root=path.resolve(__dirname,'..');
const fflate=require('../src/player/vendor/fflate-0.8.2.min.js');
const html=fs.readFileSync(path.join(root,'target/library-import-player-fixture.html'),'utf8');
const zipReader=fs.readFileSync(path.join(root,'src/player/vendor/fflate-0.8.2.min.js'),'utf8');
const shots=process.env.FURU_SCREENSHOT_DIR||path.join(root,'target');
const host='http://library-import.test';
const stats=(extra={})=>({total:6,pending:0,matched_local:2,matched_federation:1,ambiguous:1,unmatched:1,unsupported:1,failed:0,
published:3,publication_pending:0,duplicate:0,already_present:0,no_content_id:0,deferred_sync_limit:0,paused:0,publication_failed:0,catalog_errors:0,...extra});
const history=[
{id:4,provider:'spotify',source_type:'file',status:'running',phase:'resolve_local',federated_search:false,cancel_requested:false,
statistics:stats({pending:3,published:0}),error:null,created_at:'2026-11-26T10:00:00Z',updated_at:'2026-11-26T10:00:00Z',last_resync_at:null,playlists:[]},
{id:3,provider:'spotify',source_type:'api',status:'needs_reauth',phase:'fetching',federated_search:false,cancel_requested:false,
statistics:stats({total:0,matched_local:0,matched_federation:0,ambiguous:0,unmatched:0,unsupported:0,published:0}),error:null,
created_at:'2026-11-25T10:00:00Z',updated_at:'2026-11-25T10:00:00Z',last_resync_at:null,playlists:[]},
{id:2,provider:'spotify',source_type:'file',status:'done',phase:null,federated_search:false,cancel_requested:false,statistics:stats(),error:null,
created_at:'2026-11-24T10:00:00Z',updated_at:'2026-11-24T10:00:00Z',last_resync_at:null,
playlists:[{id:20,title:'Road trip',target_playlist_id:500,target_deleted:false},{id:21,title:'Liked Songs (Spotify)',target_playlist_id:501,target_deleted:false}]},
];
const detail=id=>({...history.find(record=>record.id===id),source_playlists:[
{id:20,kind:'playlist',ordinal:0,title:'Road trip',description:null,target_playlist_id:500,target_created_at:null,target_deleted:false,publication_paused:false,total:4,matched:2,published:2},
{id:21,kind:'favorites',ordinal:1,title:'Liked Songs (Spotify)',description:null,target_playlist_id:501,target_created_at:null,target_deleted:true,publication_paused:true,total:2,matched:1,published:1},
],attempt:null});
const items=[
{id:90,playlist_id:20,position:0,metadata:{kind:'track',title:'Northern Lights',artists:['Aurora Band'],album:'Skies',duration_ms:215000},
resolution_status:'matched',resolution_note:null,match_origin:'local',publication_status:'published',candidates:null},
{id:91,playlist_id:20,position:1,metadata:{kind:'track',title:'Harbour (Live)',artists:['Sea Choir'],album:'Live at the Pier',duration_ms:301000},
resolution_status:'ambiguous',resolution_note:null,match_origin:null,publication_status:'not_ready',
candidates:[{origin:'local',title:'Harbour',artists:['Sea Choir'],album:'Pier',duration_seconds:300,content_id:null,track_id:7},
{origin:'federation',title:'Harbour (Live)',artists:['Sea Choir'],album:'Live at the Pier',duration_seconds:302,content_id:'b3:'+'1'.repeat(64)}]},
{id:92,playlist_id:20,position:2,metadata:{kind:'track',title:'A track nobody has',artists:['Unknown Artist']},
resolution_status:'unmatched',resolution_note:'not_found',publication_status:'not_ready',candidates:null},
{id:93,playlist_id:21,position:0,metadata:{kind:'episode',title:'A podcast episode',artists:[]},
resolution_status:'unsupported',resolution_note:'episode',publication_status:'not_ready',candidates:null},
];
const exportZip=Buffer.from(fflate.zipSync({
'Spotify Account Data/Playlist1.json':Buffer.from(JSON.stringify({playlists:[{name:'Road trip',items:[{track:{trackName:'Northern Lights',artistName:'Aurora Band'}}]}]},null,2)),
'Spotify Account Data/YourLibrary.json':Buffer.from(JSON.stringify({tracks:[{artist:'Sea Choir',track:'Harbour',album:'Pier'}]})),
'Spotify Account Data/StreamingHistory_music_0.json':Buffer.from(JSON.stringify([{trackName:'Private listening history entry'}])),
'Spotify Account Data/Userdata.json':Buffer.from(JSON.stringify({email:'listener@example.test'})),
}));
const fedTrack={content_id:'b3:'+'2'.repeat(64),position:1,federation:{content_id:'b3:'+'2'.repeat(64),owner:'peer-a',item_id:'item-2',
title:'Peer song',artist_names:['Peer Artist'],featured_artist_names:[],duration_seconds:200,release_title:'Peer album'}};
(async()=>{
const browser=await chromium.launch({headless:true,...(process.env.CHROME_PATH?{executablePath:process.env.CHROME_PATH}:{})});
try{
const requests=[],errors=[];
const context=await browser.newContext({viewport:{width:1440,height:1000}});
const fixture=async route=>{
const request=route.request(),url=new URL(request.url()),method=request.method();
if(url.origin!==host)return route.fulfill({status:404,body:''});
if(url.pathname==='/')return route.fulfill({contentType:'text/html',body:html});
if(url.pathname==='/vendor/fflate-0.8.2.js'){requests.push({method,path:url.pathname});return route.fulfill({contentType:'text/javascript',body:zipReader});}
if(!url.pathname.startsWith('/api/'))return route.fulfill({status:404,body:''});
const body=request.postData()?JSON.parse(request.postData()):undefined;
requests.push({method,path:url.pathname,search:url.search,body});
const json=data=>route.fulfill({json:data});
if(url.pathname==='/api/player/me')return json({id:1,name:'Listener',username:'listener',role:'user'});
if(url.pathname==='/api/imports/providers')return json({providers:[{id:'spotify',name:'Spotify',methods:['file','api']}],federated_search_available:true});
if(url.pathname==='/api/imports'&&method==='GET')return json({imports:history});
if(url.pathname==='/api/imports/preview')return json({provider:'spotify',source:'file',all_imported:false,federated_search_available:true,playlists:[
{source_key:'sha256:road',kind:'playlist',title:'Road trip',description:null,track_count:1,unsupported_count:0,available:true,already_imported_in:null,similar_to:null},
{source_key:'sha256:old',kind:'playlist',title:'Old mix',description:null,track_count:12,unsupported_count:0,available:true,already_imported_in:2,similar_to:null},
{source_key:'sha256:gym',kind:'playlist',title:'Gym',description:null,track_count:40,unsupported_count:2,available:true,already_imported_in:null,similar_to:{import_id:2,target_playlist_id:500}},
{source_key:'sha256:liked',kind:'favorites',title:'Liked Songs',description:null,track_count:1,unsupported_count:0,available:true,already_imported_in:null,similar_to:null},
]});
if(url.pathname==='/api/imports'&&method==='POST')return json({id:2,status:'queued'});
let match=url.pathname.match(/^\/api\/imports\/(\d+)(\/.*)?$/);
if(match){
const id=Number(match[1]),rest=match[2]||'';
if(rest==='/items'){
const status=url.searchParams.get('status');
return json({items:items.filter(item=>!status||item.resolution_status===status),next:null});
}
if(rest.endsWith('/match'))return json({resolution_status:'matched',publication_status:'pending'});
if(rest==='/resync')return json({status:'queued'});
if(rest==='/cancel')return json({status:'cancelling'});
if(rest.endsWith('/recreate'))return json({status:'requested'});
if(method==='DELETE')return json({ok:true});
return json(detail(id));
}
if(url.pathname.startsWith('/api/imports/providers/spotify/authorize'))return route.fulfill({contentType:'text/html',body:'<p>Spotify sign-in</p>'});
if(url.pathname==='/api/player/playlists/500')return json({id:500,title:'Road trip',kind:'user',is_own:true,is_public:false,owner_name:'Listener',tracks:[
{id:7,playlist_track_id:70,content_id:'b3:'+'3'.repeat(64),title:'Northern Lights',artists:[{id:1,name:'Aurora Band'}],featured_artists:[],duration_seconds:215,release_title:'Skies',stream_url:'/api/player/stream/7'}]});
if(url.pathname==='/api/player/playlists/500/federation-tracks')return json([fedTrack]);
if(url.pathname==='/api/player/tracks/content/playlist')return json({ok:true});
if(url.pathname==='/api/player/playlists')return json([{id:500,title:'Road trip',kind:'user',is_own:true,track_count:2}]);
return json([]);
};
await context.route('**/*',fixture);
const page=await context.newPage();
page.on('pageerror',error=>errors.push(error.message));
if(process.env.DEBUG)page.on('console',message=>console.log('console:',message.text()));
const view=async name=>page.waitForFunction(v=>window.Alpine?.store('library')?.view===v,name);
// The menu entry sits between Followed and Settings and opens the page.
await page.goto(host+'/#artists');await view('artists');
await page.locator('.sidebar-account-trigger').click();
const labels=await page.locator('#sidebar-account-actions .account-action-list > *').allInnerTexts();
const at=label=>labels.findIndex(text=>text.trim()===label);
assert.ok(at('Followed')>=0&&at('Import library')===at('Followed')+1&&at('Settings')===at('Import library')+1,JSON.stringify(labels));
await page.locator('#sidebar-account-actions').getByRole('link',{name:'Import library'}).click();
await view('imports');assert.ok(page.url().endsWith('#imports'));
await page.getByRole('heading',{name:'Import library',level:1}).waitFor();
await page.locator('.import-history-row').nth(2).waitFor();
assert.equal(await page.locator('#sidebar-account-actions a[href="#imports"]').getAttribute('aria-current'),'page');
assert.equal(await page.locator('.import-history-row').count(),3);
assert.equal(await page.locator('.import-history-row').first().locator('.import-status').innerText(),'Running');
assert.equal(await page.locator('.import-history-playlists a').first().getAttribute('href'),'#playlist/500');
await page.screenshot({path:path.join(shots,'library-import-history.png')});
// The running import is polled every 3 seconds.
const lists=()=>requests.filter(r=>r.path==='/api/imports'&&r.method==='GET').length;
const before=lists();await page.waitForTimeout(3400);assert.ok(lists()>before,'history was not polled');
// Wizard: Data export ZIP; only playlist files reach the server.
await page.getByRole('button',{name:'New import'}).click();
const dialog=page.locator('dialog#import-wizard');await dialog.waitFor();
assert.equal(await dialog.evaluate(element=>element.open&&element.matches('.player-dialog')),true);
assert.equal(requests.filter(r=>r.path==='/vendor/fflate-0.8.2.js').length,0,'the ZIP reader must load lazily');
await dialog.getByRole('button',{name:/Data export/}).click();
await dialog.locator('input[type=file]').setInputFiles({name:'my_spotify_data.zip',mimeType:'application/zip',buffer:exportZip});
await dialog.locator('.import-select-list li').nth(3).waitFor();
const preview=requests.find(r=>r.path==='/api/imports/preview');
assert.deepEqual(preview.body.files.map(file=>file.name).sort(),['Spotify Account Data/Playlist1.json','Spotify Account Data/YourLibrary.json']);
assert.ok(!JSON.stringify(preview.body).includes('Private listening history'));
assert.ok(!JSON.stringify(preview.body).includes('listener@example.test'));
assert.equal(requests.filter(r=>r.path==='/vendor/fflate-0.8.2.js').length,1);
const boxes=dialog.locator('.import-select-list li input[type=checkbox]');
assert.equal(await boxes.nth(0).isChecked(),true);
assert.equal(await boxes.nth(1).isDisabled(),true);
assert.equal(await boxes.nth(2).isChecked(),false);
await dialog.getByText('Already imported in #2').waitFor();
await boxes.nth(2).check();
await dialog.getByText('Create a new playlist').waitFor();
const consent=dialog.getByRole('switch');
assert.equal(await consent.getAttribute('aria-checked'),'false');
await dialog.getByText('Participants receive only artist names.',{exact:false}).waitFor();
await page.screenshot({path:path.join(shots,'library-import-wizard.png')});
await dialog.getByRole('button',{name:'Start import'}).click();
await dialog.getByText('Confirm creating new playlists',{exact:false}).waitFor();
assert.equal(requests.filter(r=>r.path==='/api/imports'&&r.method==='POST').length,0);
await dialog.locator('.import-select-note label input').check();
await consent.click();assert.equal(await consent.getAttribute('aria-checked'),'true');
await dialog.getByRole('button',{name:'Start import'}).click();
await view('import_detail');await dialog.waitFor({state:'detached'});
const created=requests.find(r=>r.path==='/api/imports'&&r.method==='POST');
assert.deepEqual(created.body.selection,['sha256:road','sha256:gym','sha256:liked']);
assert.deepEqual(created.body.confirm_similar,['sha256:gym']);
assert.equal(created.body.federated_search,true);
assert.equal(created.body.files.length,2);
assert.ok(page.url().endsWith('#imports/2'));
// Details: statistics, playlists, filters, a manual choice and Retry with consent.
await page.locator('.import-item').nth(3).waitFor();
assert.equal(await page.locator('.import-stats dd').first().innerText(),'6');
await page.getByText('The playlist was deleted').waitFor();
await page.getByRole('button',{name:'Create again'}).click();
await page.waitForFunction(()=>Alpine.store('imports').message==='The playlist will be created again.');
assert.ok(requests.some(r=>r.path==='/api/imports/2/playlists/21/recreate'&&r.method==='POST'));
await page.screenshot({path:path.join(shots,'library-import-detail.png'),fullPage:true});
await page.locator('.import-filters button',{hasText:'Needs a choice'}).click();
await page.waitForFunction(()=>Alpine.store('imports').items.length===1);
assert.ok(requests.some(r=>r.path==='/api/imports/2/items'&&r.search==='?status=ambiguous'));
await page.locator('.import-candidate').nth(1).getByRole('button',{name:'Choose'}).click();
await page.waitForFunction(()=>Alpine.store('imports').message==='The track will be added to the playlist.'||Alpine.store('imports').items.every(item=>item.resolution_status!=='ambiguous'));
assert.deepEqual(requests.find(r=>r.path==='/api/imports/2/items/91/match').body,{candidate:1});
await page.getByRole('button',{name:'Retry unmatched'}).click();
const panel=page.locator('#import-retry-panel');await panel.waitFor();
await panel.getByRole('switch').click();
await panel.getByRole('button',{name:'Retry'}).click();
await page.waitForFunction(()=>Alpine.store('imports').message==='Unmatched tracks will be searched again.');
assert.deepEqual(requests.find(r=>r.path==='/api/imports/2/resync').body,{federated_search:true});
// Delete history keeps playlists; the page returns to the list.
page.once('dialog',prompt=>{assert.match(prompt.message(),/Created playlists stay/);prompt.accept();});
await page.getByRole('button',{name:'Delete history'}).click();
await view('imports');
assert.ok(requests.some(r=>r.path==='/api/imports/2'&&r.method==='DELETE'));
// A Spotify import waiting for a sign-in continues through the provider.
await page.goto(host+'/#imports/3?error=account_mismatch');await view('import_detail');
await page.getByText('Sign in with the Spotify account used for this import.').waitFor();
assert.ok(page.url().endsWith('#imports/3'));
await Promise.all([page.waitForURL('**/api/imports/providers/spotify/authorize?import_id=3'),
page.getByRole('button',{name:'Sign in to Spotify again'}).click()]);
// A federated track can be removed from the playlist in edit mode.
await page.goto(host+'/#playlist/500');await view('playlist_detail');
await page.waitForFunction(()=>Alpine.store('library').currentPlaylist?.tracks?.length===2);
await page.evaluate(()=>Alpine.store('playlists').toggleEditCurrent());
await page.locator('.playlist-track-row').nth(1).locator('.playlist-track-remove').click();
await page.waitForFunction(()=>Alpine.store('library').currentPlaylist.tracks.length===1);
assert.deepEqual(requests.find(r=>r.path==='/api/player/tracks/content/playlist'&&r.method==='DELETE').body,
{playlist_id:500,content_id:fedTrack.content_id});
// Mobile: the popover menu, the page and the wizard fit the screen.
await page.setViewportSize({width:390,height:844});
await page.goto(host+'/#artists');await view('artists');
await page.locator('.mobile-account-chip').click();
const mobileMenu=page.locator('#mobile-account-actions');
await mobileMenu.getByRole('link',{name:'Import library'}).waitFor({state:'visible'});
const mobileLabels=await mobileMenu.locator('.account-action-list > *').allInnerTexts();
assert.equal(mobileLabels.findIndex(text=>text.trim()==='Import library'),mobileLabels.findIndex(text=>text.trim()==='Followed')+1);
await page.waitForTimeout(250);await page.screenshot({path:path.join(shots,'library-import-mobile-menu.png')});
await mobileMenu.getByRole('link',{name:'Import library'}).click();await view('imports');
await page.locator('.import-history-row').first().waitFor();
assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth>innerWidth),false);
await page.waitForTimeout(250);await page.screenshot({path:path.join(shots,'library-import-mobile.png')});
await page.goto(host+'/#imports/2');await view('import_detail');await page.locator('.import-item').first().waitFor();
assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth>innerWidth),false);
await page.screenshot({path:path.join(shots,'library-import-mobile-detail.png'),fullPage:true});
await page.evaluate(()=>Alpine.store('imports').startWizard('spotify'));
await page.locator('dialog#import-wizard').waitFor();
const surface=await page.locator('dialog#import-wizard .player-dialog-surface').boundingBox();
assert.ok(surface.width<=390,'the wizard fits the mobile screen');
await page.waitForTimeout(200);await page.screenshot({path:path.join(shots,'library-import-mobile-wizard.png')});
await page.locator('dialog#import-wizard .player-dialog-close').click();
await page.locator('dialog#import-wizard').waitFor({state:'detached'});
await page.close();
// With reduced motion the wizard opens and closes without animations.
const still=await browser.newContext({viewport:{width:1024,height:800},reducedMotion:'reduce'});
await still.route('**/*',fixture);
const calm=await still.newPage();calm.on('pageerror',error=>errors.push(error.message));
await calm.goto(host+'/#imports');
await calm.waitForFunction(()=>Alpine.store('library').view==='imports'&&Alpine.store('imports').loaded);
await calm.getByRole('button',{name:'New import'}).click();
const calmDialog=calm.locator('dialog#import-wizard');await calmDialog.waitFor();
assert.equal(await calmDialog.locator('.player-dialog-surface').evaluate(element=>getComputedStyle(element).animationName),'none');
await calm.keyboard.press('Escape');
await calmDialog.waitFor({state:'detached',timeout:500});
await still.close();
assert.deepEqual(errors,[]);
console.log('PASS: menu order, history polling, lazy ZIP reader with playlist files only, similar confirmation and consent, details, manual choice, Retry, Delete, Spotify sign-in continuation, federated track removal, mobile');
} finally {await browser.close();}
})().catch(error=>{console.error(error);process.exitCode=1;});
+349
View File
@@ -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(/<script>([\s\S]*?)<\/script>/g)) new vm.Script(match[1]);
}
});