diff --git a/docs/administration.md b/docs/administration.md index 9fff163..278d5d3 100644 --- a/docs/administration.md +++ b/docs/administration.md @@ -101,11 +101,18 @@ its destination for its remaining files. ## Spotify library import +Users start an import from **Import library** in the account menu. The page +lists the available sources, the history of imports with their statistics and +links to the created playlists, and the entries of each import. + Spotify playlists and Liked Songs are imported from the account data export -("Download your data") without any server configuration. The browser sends -only `Playlist*.json` and `YourLibrary.json`; the server parses them in memory -and stores the entries of the selected playlists. An import request may not -exceed 32 MiB. Importing a playlist a second time is refused; a playlist with +("Download your data") without any server configuration. The browser opens the +ZIP archive itself and sends only `Playlist*.json` and `YourLibrary.json`; +listening history and account details never leave it. Before anything is +decompressed the browser refuses archives over 256 MiB, archives with more than +2,000 entries, more than 256 playlist files, or playlist files declaring more +than 32 MiB in total. The server parses the files in memory and stores the +entries of the selected playlists. An import request may not exceed 32 MiB. Importing a playlist a second time is refused; a playlist with the same title and changed contents is imported as a new playlist only after confirmation. diff --git a/docs/development.md b/docs/development.md index c702da0..577fd77 100644 --- a/docs/development.md +++ b/docs/development.md @@ -172,7 +172,8 @@ extension; the tests install it into `public`. The publisher tests (`src/library_import/tests/publisher.rs`) run against the Device Sync tables of the same schema. They cover source order, repeats, empty playlists, a second pass that adds nothing, Resync appending at the end, tracks -removed by the user or by a committed but not yet applied operation, deleted +removed by the user or by a committed but not yet applied operation, a +federated track removed in the web player by its content id, deleted target playlists and recreation, an entry failing after its operation was recorded, registers written concurrently, deletions from the web and from another device during a batch, older operations that arrive during a batch, @@ -189,6 +190,32 @@ requests. The matcher's reference table (`src/library_import/matcher/tests.rs`) runs without a database and documents the matching rules case by case. +The import page has browser-store tests and a browser scenario on the rendered +player with isolated API fixtures; neither needs a server or a database: + +```bash +node --test tests/library_import.test.cjs +FURU_LIBRARY_IMPORT_RENDER_FIXTURE=1 cargo test library_import::tests::web +node tests/browser-library-import.cjs +``` + +The store tests unzip real archives with the vendored fflate and cover the +archive limits (size, entries, playlist files and declared sizes, checked +before decompression), the request limit, the selection of repeated, similar +and unavailable playlists, federated consent, polling, the Spotify sign-in +return and removing a federated track from a playlist. The browser scenario +checks the menu order on desktop and mobile, history polling, that only +`Playlist*.json` and `YourLibrary.json` from a ZIP with listening history reach +the server, the wizard, details, a manual choice, Retry unmatched, history +deletion, continuing a Spotify import after a new sign-in, federated track +removal in a playlist and reduced motion. Set `PLAYWRIGHT_MODULE` and +`CHROME_PATH` as for the other browser tests; `FURU_SCREENSHOT_DIR` chooses +where screenshots go (default `target/`). + +`src/player/vendor/fflate-0.8.2.min.js` is `umd/index.js` of the npm package +`fflate@0.8.2` (MIT, `src/player/vendor/fflate-LICENSE`), served unchanged at +`/vendor/fflate-0.8.2.js` and loaded only when a user picks an archive. + The Spotify export fixture in `src/library_import/adapters/fixtures/spotify_export/` is synthetic. Add a fresh anonymized real export next to it before relying on the parser for a new export format. diff --git a/src/i18n/phrases.rs b/src/i18n/phrases.rs index 5ab5e65..4e8382d 100644 --- a/src/i18n/phrases.rs +++ b/src/i18n/phrases.rs @@ -759,4 +759,143 @@ translations! { player_open_torrent_failed: "Could not open torrent" , "Не удалось открыть торрент"; player_delete_torrent_failed: "Could not remove torrent from history" , "Не удалось удалить торрент из истории"; player_load_ai_queue_failed: "Could not load AI queue" , "Не удалось загрузить очередь ИИ"; + // Library import + player_import_library: "Import library" , "Импорт библиотеки"; + player_import_new: "New import" , "Новый импорт"; + player_import_sources: "Sources" , "Источники"; + player_import_history: "History" , "История"; + player_import_history_empty: "No imports yet. Start with New import." , "Импортов пока нет. Начните с кнопки «Новый импорт»."; + player_import_load_failed: "Could not load imports." , "Не удалось загрузить импорты."; + player_import_request_failed: "The request failed. Try again." , "Запрос не выполнен. Попробуйте ещё раз."; + player_import_retry: "Retry" , "Повторить"; + player_import_method_file: "Data export" , "Выгрузка данных"; + player_import_method_file_hint: "ZIP archive from Download your data, or its playlist JSON files" , "ZIP-архив из «Скачать данные» или JSON-файлы плейлистов из него"; + player_import_method_api: "Sign in with Spotify" , "Войти через Spotify"; + player_import_method_api_hint: "Reads your own and collaborative playlists directly" , "Читает ваши и совместные плейлисты напрямую"; + player_import_upload_help: "In Spotify, open Account, then Privacy settings, and request Account data. When the email arrives, choose the downloaded ZIP archive, or its Playlist1.json, Playlist2.json and YourLibrary.json files." , "В Spotify откройте «Аккаунт», затем «Настройки конфиденциальности» и запросите данные аккаунта. Когда придёт письмо, выберите скачанный ZIP-архив или файлы Playlist1.json, Playlist2.json и YourLibrary.json из него."; + player_import_privacy: "The archive is opened in your browser. Only playlists and saved tracks are sent to the server; listening history stays on this device." , "Архив открывается в браузере. На сервер уходят только плейлисты и сохранённые треки; история прослушиваний остаётся на этом устройстве."; + player_import_api_help: "Spotify asks you to allow read access to your playlists and saved tracks. In Development Mode only your own and collaborative playlists can be read; import other playlists from the data export." , "Spotify попросит разрешить чтение плейлистов и сохранённых треков. В режиме разработки читаются только ваши и совместные плейлисты; остальные импортируйте из выгрузки данных."; + player_import_choose_files: "Choose files" , "Выбрать файлы"; + player_import_reading: "Reading the export…" , "Читаю выгрузку…"; + player_import_files_read: "Files read: {count}." , "Прочитано файлов: {count}."; + player_import_files_skipped: "Other files were skipped: {count}." , "Другие файлы пропущены: {count}."; + player_import_no_files: "No playlist files found. Choose the export archive or its Playlist*.json and YourLibrary.json files." , "Файлы плейлистов не найдены. Выберите архив выгрузки или файлы Playlist*.json и YourLibrary.json."; + player_import_archive_too_large: "The archive is larger than 256 MB. Choose the account data export." , "Архив больше 256 МБ. Выберите выгрузку данных аккаунта."; + player_import_zip_too_many_entries: "The archive contains too many files." , "В архиве слишком много файлов."; + player_import_zip_too_many_files: "The export contains more than 256 playlist files." , "В выгрузке больше 256 файлов плейлистов."; + player_import_export_too_large: "The playlist files are larger than 32 MB in total." , "Файлы плейлистов в сумме больше 32 МБ."; + player_import_zip_invalid: "The file is not a valid ZIP archive." , "Файл не является корректным ZIP-архивом."; + player_import_zip_load_failed: "Could not load the archive reader. Check the connection and try again." , "Не удалось загрузить модуль чтения архивов. Проверьте соединение и попробуйте ещё раз."; + player_import_request_too_large: "The export is too large to send (32 MB at most)." , "Выгрузка слишком большая для отправки (не больше 32 МБ)."; + player_import_sign_in: "Sign in with Spotify" , "Войти через Spotify"; + player_import_sign_in_again: "Sign in to Spotify again" , "Войти в Spotify снова"; + player_import_loading_playlists: "Loading playlists…" , "Загружаю плейлисты…"; + player_import_select_playlists: "Playlists to import" , "Плейлисты для импорта"; + player_import_select_all: "Select all" , "Выбрать все"; + player_import_select_none: "Clear" , "Снять выбор"; + player_import_selected_count: "Selected {count} of {total}" , "Выбрано {count} из {total}"; + player_import_favorites: "Liked Songs" , "Любимые треки"; + player_import_unsupported_count: "not supported: {count}" , "не поддерживается: {count}"; + player_import_already_imported: "Already imported in #{id}" , "Уже импортирован в №{id}"; + player_import_all_imported: "This export was already imported." , "Эта выгрузка уже импортирована."; + player_import_similar: "A similar playlist was imported in #{id}. A new playlist will be created." , "Похожий плейлист уже импортирован в №{id}. Будет создан новый плейлист."; + player_import_confirm_similar: "Create a new playlist" , "Создать новый плейлист"; + player_import_confirm_similar_needed: "Confirm creating new playlists for the similar ones, or clear them." , "Подтвердите создание новых плейлистов для похожих или снимите их выбор."; + player_import_unavailable: "Only through the data export" , "Только через выгрузку данных"; + player_import_federated: "Search in the federation" , "Искать в федерации"; + player_import_federated_consent: "Tracks missing here are searched for in the catalogues of Furumi network participants. Participants receive only artist names." , "Недостающие треки ищутся в каталогах участников сети Furumi. Участникам сети будут отправлены только имена исполнителей."; + player_import_federated_off: "Federation is turned off on this server." , "Федерация на этом сервере выключена."; + player_import_start: "Start import" , "Начать"; + player_import_starting: "Starting the import…" , "Запускаю импорт…"; + player_import_back: "Back" , "Назад"; + player_import_conflicts: "Some playlists were imported meanwhile and are no longer selected." , "Некоторые плейлисты уже импортированы, их выбор снят."; + player_import_similar_conflicts: "Similar playlists were imported before. Confirm creating new playlists for them." , "Похожие плейлисты уже импортированы. Подтвердите создание новых плейлистов."; + player_import_status_queued: "Queued" , "В очереди"; + player_import_status_running: "Running" , "Выполняется"; + player_import_status_done: "Done" , "Готово"; + player_import_status_cancelled: "Cancelled" , "Отменён"; + player_import_status_failed: "Failed" , "Ошибка"; + player_import_status_needs_reauth: "Sign-in needed" , "Нужен вход"; + player_import_status_cancelling: "Cancelling" , "Отменяется"; + player_import_phase_fetching: "Reading playlists from Spotify" , "Чтение плейлистов из Spotify"; + player_import_phase_resolve_local: "Matching with the library" , "Поиск в библиотеке"; + player_import_phase_resolve_federation: "Searching the federation" , "Поиск в федерации"; + player_import_phase_publish: "Adding tracks to playlists" , "Добавление треков в плейлисты"; + player_import_phase_waiting: "Waiting to start" , "Ожидает запуска"; + player_import_found_of: "{found} of {total} found" , "Найдено {found} из {total}"; + player_import_number: "#{id}" , "№{id}"; + player_import_playlists_more: "and {count} more" , "и ещё {count}"; + player_import_retry_unmatched: "Retry unmatched" , "Искать ненайденные"; + player_import_retry_started: "Unmatched tracks will be searched again." , "Ненайденные треки будут найдены заново."; + player_import_cancel: "Cancel" , "Отменить"; + player_import_cancel_requested: "The import stops after the current step. Added tracks stay." , "Импорт остановится после текущего шага. Добавленные треки останутся."; + player_import_delete_history: "Delete history" , "Удалить историю"; + player_import_delete_confirm: "Delete this import history? Created playlists stay." , "Удалить историю этого импорта? Созданные плейлисты останутся."; + player_import_deleted: "Import history deleted. Playlists stay." , "История импорта удалена. Плейлисты остались."; + player_import_reauth_needed: "The Spotify sign-in has expired. Sign in again to continue this import." , "Вход в Spotify истёк. Войдите снова, чтобы продолжить этот импорт."; + player_import_stat_total: "Entries" , "Записей"; + player_import_stat_found: "Found" , "Найдено"; + player_import_stat_published: "Added to playlists" , "Добавлено в плейлисты"; + player_import_stat_ambiguous: "Needs a choice" , "Нужен выбор"; + player_import_stat_unmatched: "Not found" , "Не найдено"; + player_import_stat_unsupported: "Not supported" , "Не поддерживается"; + player_import_stat_failed: "Errors" , "Ошибки"; + player_import_stat_deferred: "Deferred by the sync limit" , "Отложено из-за лимита синхронизации"; + player_import_stat_duplicate: "Repeats" , "Повторы"; + player_import_stat_already_present: "Already in the playlist or removed" , "Уже в плейлисте или удалены"; + player_import_stat_paused: "Paused" , "Приостановлено"; + player_import_stat_no_content: "No content id" , "Без идентификатора содержимого"; + player_import_stat_publish_failed: "Not added" , "Не добавлено"; + player_import_playlists: "Playlists" , "Плейлисты"; + player_import_playlist_deleted: "The playlist was deleted" , "Плейлист удалён"; + player_import_playlist_pending: "Not created yet" , "Ещё не создан"; + player_import_recreate: "Create again" , "Создать заново"; + player_import_recreate_started: "The playlist will be created again." , "Плейлист будет создан заново."; + player_import_entries: "Entries" , "Записи"; + player_import_filter_all: "All" , "Все"; + player_import_all_playlists: "All playlists" , "Все плейлисты"; + player_import_search: "Search entries" , "Поиск по записям"; + player_import_no_entries: "No entries to show." , "Записей нет."; + player_import_load_more: "Load more" , "Загрузить ещё"; + player_import_loading: "Loading…" , "Загрузка…"; + player_import_candidates: "Possible matches" , "Возможные совпадения"; + player_import_choose: "Choose" , "Выбрать"; + player_import_chosen: "The track will be added to the playlist." , "Трек будет добавлен в плейлист."; + player_import_origin_local: "Library" , "Библиотека"; + player_import_origin_federation: "Federation" , "Федерация"; + player_import_res_pending: "Waiting" , "Ожидает"; + player_import_res_matched: "Found" , "Найден"; + player_import_res_ambiguous: "Needs a choice" , "Нужен выбор"; + player_import_res_unmatched: "Not found" , "Не найден"; + player_import_res_unsupported: "Not supported" , "Не поддерживается"; + player_import_res_failed: "Error" , "Ошибка"; + player_import_pub_pending: "Waiting to be added" , "Ожидает добавления"; + player_import_pub_published: "Added" , "Добавлен"; + player_import_pub_duplicate: "Repeat in the source" , "Повтор в источнике"; + player_import_pub_already_present: "Already in the playlist or removed" , "Уже в плейлисте или удалён"; + player_import_pub_no_content_id: "No content id" , "Нет идентификатора содержимого"; + player_import_pub_deferred: "Deferred by the sync limit" , "Отложен из-за лимита синхронизации"; + player_import_pub_paused: "Playlist deleted" , "Плейлист удалён"; + player_import_pub_failed: "Not added" , "Не добавлен"; + player_import_note_not_found: "No such track" , "Такого трека нет"; + player_import_note_version_mismatch: "Only other versions" , "Есть только другие версии"; + player_import_note_duration_mismatch: "Duration differs" , "Длительность отличается"; + player_import_note_federation_error: "Federation search failed" , "Поиск в федерации не удался"; + player_import_note_federation_budget: "Federation search limit reached" , "Исчерпан лимит поиска в федерации"; + player_import_note_federation_unavailable: "Federation unavailable" , "Федерация недоступна"; + player_import_note_episode: "Podcast episode" , "Выпуск подкаста"; + player_import_note_audiobook: "Audiobook" , "Аудиокнига"; + player_import_note_local_file: "Local file" , "Локальный файл"; + player_import_note_unknown_kind: "Unknown item" , "Неизвестная запись"; + player_import_note_missing_title: "No title" , "Нет названия"; + player_import_note_failed: "Processing error" , "Ошибка обработки"; + player_import_oauth_state: "The sign-in could not be verified. Try again." , "Не удалось проверить вход. Попробуйте ещё раз."; + player_import_oauth_expired: "The sign-in took too long. Try again." , "Вход занял слишком много времени. Попробуйте ещё раз."; + player_import_oauth_denied: "Access was not granted." , "Доступ не предоставлен."; + player_import_oauth_not_configured: "Spotify sign-in is not configured on this server." , "Вход через Spotify на этом сервере не настроен."; + player_import_oauth_exchange: "Spotify did not confirm the sign-in. Try again." , "Spotify не подтвердил вход. Попробуйте ещё раз."; + player_import_oauth_not_allowed: "This Spotify account is not on the application user list. Ask the administrator, or use the data export." , "Этого аккаунта Spotify нет в списке пользователей приложения. Обратитесь к администратору или используйте выгрузку данных."; + player_import_oauth_unavailable: "Spotify is unavailable. Try again later." , "Spotify недоступен. Попробуйте позже."; + player_import_oauth_not_waiting: "This import is not waiting for a sign-in." , "Этот импорт не ожидает входа."; + player_import_oauth_account_mismatch: "Sign in with the Spotify account used for this import." , "Войдите в тот аккаунт Spotify, из которого делался этот импорт."; } diff --git a/src/library_import/tests.rs b/src/library_import/tests.rs index 384c856..f7018c3 100644 --- a/src/library_import/tests.rs +++ b/src/library_import/tests.rs @@ -34,6 +34,7 @@ use crate::federation::client::{CatalogPeers, CatalogStream}; use crate::scheduler::JobLog; mod publisher; +mod web; /// Workers share a process-wide slot counter, so database tests run one at a time. static SERIAL: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(()); diff --git a/src/library_import/tests/publisher.rs b/src/library_import/tests/publisher.rs index 3453e8a..87b6cc8 100644 --- a/src/library_import/tests/publisher.rs +++ b/src/library_import/tests/publisher.rs @@ -650,6 +650,81 @@ async fn library_import_entry_failing_in_its_transaction_leaves_nothing_behind() fixture.drop().await; } +#[tokio::test] +#[ignore = "requires FURU_LIBRARY_IMPORT_TEST_DATABASE_URL pointing to a disposable PostgreSQL database"] +async fn library_import_federated_track_removed_in_the_web_stays_removed() { + use crate::player::{ContentRemoval, remove_content_from_playlist}; + + let (_serial, fixture) = setup().await; + let pool = &fixture.pool; + library(pool, 1).await; + let import_id = matched_import( + pool, + "web-removal", + &[("Web removal", vec![Entry::Local(1), Entry::Fed(2)])], + ) + .await; + publish(pool, 826).await; + let road = target(pool, import_id, 0).await.unwrap(); + assert!(register(pool, road, 2).await.unwrap().0); + + // Only the owner can remove, and only a valid content id. + assert_eq!( + remove_content_from_playlist(pool, 2, road, &cid(2)) + .await + .unwrap(), + ContentRemoval::NotOwned + ); + assert_eq!( + remove_content_from_playlist(pool, USER, road, "not-a-content-id") + .await + .unwrap(), + ContentRemoval::InvalidContentId + ); + assert!(register(pool, road, 2).await.unwrap().0); + + // The web removes the federated track with the existing operation. + assert_eq!( + remove_content_from_playlist(pool, USER, road, &cid(2)) + .await + .unwrap(), + ContentRemoval::Removed + ); + assert!(!register(pool, road, 2).await.unwrap().0); + assert_eq!( + own_ops(pool, "playlist_track_removed", Some(&cid(2))).await, + 1 + ); + assert_eq!(rows(pool, road).await, [(1001, 0)]); + + // Even without its receipt, a later pass does not add it back. + sqlx::query( + "DELETE FROM furumusic__library_import_publication WHERE target_playlist_id = $1 AND content_id = $2", + ) + .bind(road) + .bind(cid(2)) + .execute(pool) + .await + .unwrap(); + sqlx::query("UPDATE furumusic__library_import_item SET publication_status = 'pending' WHERE source_position = 1") + .execute(pool) + .await + .unwrap(); + resync(pool, import_id).await; + publish(pool, 827).await; + assert_eq!( + statuses(pool, import_id).await, + ["published", "already_present"] + ); + assert!(!register(pool, road, 2).await.unwrap().0); + assert_eq!( + own_ops(pool, "playlist_track_added", Some(&cid(2))).await, + 1 + ); + assert_consistent(pool, road).await; + fixture.drop().await; +} + #[tokio::test] #[ignore = "requires FURU_LIBRARY_IMPORT_TEST_DATABASE_URL pointing to a disposable PostgreSQL database"] async fn library_import_rolls_back_when_a_register_is_written_concurrently() { diff --git a/src/library_import/tests/web.rs b/src/library_import/tests/web.rs new file mode 100644 index 0000000..70a86e2 --- /dev/null +++ b/src/library_import/tests/web.rs @@ -0,0 +1,76 @@ +//! Rendering of the import page, menu entry and wizard in the player. Set +//! `FURU_LIBRARY_IMPORT_RENDER_FIXTURE=1` to write the rendered player for +//! `tests/browser-library-import.cjs`. + +use cot::Template; + +use crate::i18n::{Lang, Translations}; +use crate::player::PlayerPageTemplate; + +fn render(lang: Lang, guest: bool) -> String { + PlayerPageTemplate { + t: Translations::for_lang(lang), + guest, + account_id: if guest { 0 } else { 1 }, + share_token: if guest { "share".into() } else { String::new() }, + downloads_enabled: true, + torrent_downloads_enabled: true, + youtube_downloads_enabled: true, + } + .render() + .unwrap() +} + +#[test] +fn library_import_page_menu_and_wizard_render_in_the_player() { + let html = render(Lang::En, false); + // The menu entry sits between Followed and Settings in both account menus. + let menus: Vec<&str> = html + .split("
cot::Result> { 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> { + 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> { let identity = crate::auth::checked_session_identity(&session, &db).await?; let user = identity.filter(|user| user.is_active()); diff --git a/src/player/mod.rs b/src/player/mod.rs index 15fdb61..7acb8fc 100644 --- a/src/player/mod.rs +++ b/src/player/mod.rs @@ -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 { + 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, +) -> cot::Result { + 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| { + 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", ), diff --git a/src/player/vendor/fflate-0.8.2.min.js b/src/player/vendor/fflate-0.8.2.min.js new file mode 100644 index 0000000..6b81793 --- /dev/null +++ b/src/player/vendor/fflate-0.8.2.min.js @@ -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<>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>h]=f}else for(a=new r(i),o=0;o>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;rn&&(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>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<>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=rt>>4;if(rt||I(3),m+=15&rt,W=c[et],et>3){var it=o[et];W+=A(t,m)&(1<F){v&&I(0);break}p&&d(b+131072);var ot=b+nt;if(b>8},E=function(t,n,r){var e=n/8|0;t[e]|=r<<=7&n,t[e+1]|=r>>8,t[e+2]|=r>>16},Z=function(t,e){for(var i=[],o=0;ov&&(v=a[o].s);var d=new r(v+1),g=q(i[c-1],d,0);if(g>e){o=0;var y=0,m=g-e,b=1<e))break;y+=b-(1<>=m;y>0;){var x=a[o].s;d[x]=0&&y;--o){var z=a[o].s;d[z]==e&&(--d[z],++y)}g=e}return{t:new n(d),l:g}},q=function(t,n,r){return-1==t.s?Math.max(q(t.l,n,r+1),q(t.r,n,r+1)):n[t.s]=r},O=function(t){for(var n=t.length;n&&!t[--n];);for(var e=new r(++n),i=0,o=t[0],s=1,a=function(t){e[i++]=t},u=1;u<=n;++u)if(t[u]==o&&u!=n)++s;else{if(!o&&s>2){for(;s>138;s-=138)a(32754);s>2&&(a(s>10?s-11<<5|28690:s-3<<5|12305),s=0)}else if(s>3){for(a(o),--s;s>6;s-=6)a(8304);s>2&&(a(s-3<<5|8208),s=0)}for(;s--;)a(o);s=1,o=t[u]}return{c:e.subarray(0,i),n:n}},G=function(t,n){for(var r=0,e=0;e>8,t[i+2]=255^t[i],t[i+3]=255^t[i+1];for(var o=0;o4&&!N[s[B-1]];--B);var Y,J,K,Q,R=p+5<<3,V=G(u,m)+G(h,b)+f,W=G(u,g)+G(h,M)+f+14+3*B+G(q,N)+2*q[16]+3*q[17]+7*q[18];if(c>=0&&R<=V&&R<=W)return L(n,v,t.subarray(c,c+p));if(F(n,v,1+(W15&&(F(n,v,tt[H]>>5&127),v+=tt[H]>>12)}}else Y=w,J=m,K=z,Q=b;for(H=0;H255){var rt;E(n,v,Y[257+(rt=nt>>18&31)]),v+=J[rt+257],rt>7&&(F(n,v,nt>>23&31),v+=i[rt]);var et=31&nt;E(n,v,K[et]),v+=Q[et],et>3&&(E(n,v,nt>>5&8191),v+=o[et])}else E(n,v,Y[nt]),v+=J[nt]}return E(n,v,Y[256]),v+J[256]},j=new e([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),N=new n(0),P=function(t,s,a,u,h,l){var c=l.z||t.length,v=new n(u+c+5*(1+Math.ceil(c/7e3))+h),d=v.subarray(u,v.length-h),g=l.l,y=7&(l.r||0);if(s){y&&(d[0]=l.r>>3);for(var m=j[s-1],b=m>>13,w=8191&m,x=(1<7e3||q>24576)&&(Y>423||!g)){y=H(t,d,0,C,I,U,E,q,G,Z-G,y),q=F=E=0,G=Z;for(var J=0;J<286;++J)I[J]=0;for(J=0;J<30;++J)U[J]=0}var K=2,Q=0,R=w,V=P-B&32767;if(Y>2&&N==A(Z-V))for(var W=Math.min(b,Y)-1,X=Math.min(32767,Z),$=Math.min(258,Y);V<=X&&--R&&P!=B;){if(t[Z+K]==t[Z+K-V]){for(var _=0;_<$&&t[Z+_]==t[Z+_-V];++_);if(_>K){if(K=_,Q=V,_>W)break;var tt=Math.min(V,_-2),nt=0;for(J=0;Jnt&&(nt=et,B=rt)}}}V+=(P=B)-(B=z[P])&32767}if(Q){C[q++]=268435456|f[K]<<18|p[Q];var it=31&f[K],ot=31&p[Q];E+=i[it]+o[ot],++I[257+it],++U[ot],O=Z+K,++F}else C[q++]=t[Z],++I[t[Z]]}}for(Z=Math.max(Z,O);Z=c&&(d[y/8|0]=g,st=c),y=L(d,y+1,t.subarray(Z,st))}l.i=c}return D(v,0,u+T(y)+h)},B=function(){for(var t=new Int32Array(256),n=0;n<256;++n){for(var r=n,e=9;--e;)r=(1&r&&-306674912)^r>>>1;t[n]=r}return t}(),Y=function(){var t=-1;return{p:function(n){for(var r=t,e=0;e>>8;t=r},d:function(){return~t}}},J=function(){var t=1,n=0;return{p:function(r){for(var e=t,i=n,o=0|r.length,s=0;s!=o;){for(var a=Math.min(s+2655,o);s>16),i=(65535&i)+15*(i>>16)}t=e,n=i},d:function(){return(255&(t%=65521))<<24|(65280&t)<<8|(255&(n%=65521))<<8|n>>8}}},K=function(t,r,e,i,o){if(!o&&(o={l:1},r.dictionary)){var s=r.dictionary.subarray(-32768),a=new n(s.length+t.length);a.set(s),a.set(t,s.length),t=a,o.w=s.length}return P(t,null==r.level?6:r.level,null==r.mem?o.l?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(t.length)))):20:12+r.mem,e,i,o)},Q=function(t,n){var r={};for(var e in t)r[e]=t[e];for(var e in n)r[e]=n[e];return r},R=function(t,n,r){for(var e=t(),i=""+t,o=i.slice(i.indexOf("[")+1,i.lastIndexOf("]")).replace(/\s+/g,"").split(","),s=0;s>>0},lt=function(t,n){return ft(t,n)+4294967296*ft(t,n+4)},ct=function(t,n,r){for(;r;++n)t[n]=r,r>>>=8},pt=function(t,n){var r=n.filename;if(t[0]=31,t[1]=139,t[2]=8,t[8]=n.level<2?4:9==n.level?2:0,t[9]=3,0!=n.mtime&&ct(t,4,Math.floor(new Date(n.mtime||Date.now())/1e3)),r){t[3]=8;for(var e=0;e<=r.length;++e)t[e+10]=r.charCodeAt(e)}},vt=function(t){31==t[0]&&139==t[1]&&8==t[2]||I(6,"invalid gzip data");var n=t[3],r=10;4&n&&(r+=2+(t[10]|t[11]<<8));for(var e=(n>>3&1)+(n>>4&1);e>0;e-=!t[r++]);return r+(2&n)},dt=function(t){var n=t.length;return(t[n-4]|t[n-3]<<8|t[n-2]<<16|t[n-1]<<24)>>>0},gt=function(t){return 10+(t.filename?t.filename.length+1:0)},yt=function(t,n){var r=n.level,e=0==r?0:r<6?1:9==r?3:2;if(t[0]=120,t[1]=e<<6|(n.dictionary&&32),t[1]|=31-(t[0]<<8|t[1])%31,n.dictionary){var i=J();i.p(n.dictionary),ct(t,2,i.d())}},mt=function(t,n){return(8!=(15&t[0])||t[0]>>4>7||(t[0]<<8|t[1])%31)&&I(6,"invalid zlib data"),(t[1]>>5&1)==+!n&&I(6,"invalid zlib data: "+(32&t[1]?"need":"unexpected")+" dictionary"),2+(t[1]>>3&4)};function bt(t,n){return"function"==typeof t&&(n=t,t={}),this.ondata=n,t}var wt=function(){function t(t,r){if("function"==typeof t&&(r=t,t={}),this.ondata=r,this.o=t||{},this.s={l:0,i:32768,w:32768,z:32768},this.b=new n(98304),this.o.dictionary){var e=this.o.dictionary.subarray(-32768);this.b.set(e,32768-e.length),this.s.i=32768-e.length}}return t.prototype.p=function(t,n){this.ondata(K(t,this.o,0,0,this.s),n)},t.prototype.push=function(t,r){this.ondata||I(5),this.s.l&&I(4);var e=t.length+this.s.z;if(e>this.b.length){if(e>2*this.b.length-32768){var i=new n(-32768&e);i.set(this.b.subarray(0,this.s.z)),this.b=i}var o=this.b.length-this.s.z;this.b.set(t.subarray(0,o),this.s.z),this.s.z=this.b.length,this.p(this.b,!1),this.b.set(this.b.subarray(-32768)),this.b.set(t.subarray(o),32768),this.s.z=t.length-o+32768,this.s.i=32766,this.s.w=32768}else this.b.set(t,this.s.z),this.s.z+=t.length;this.s.l=1&r,(this.s.z>this.s.w+8191||r)&&(this.p(this.b,r||!1),this.s.w=this.s.i,this.s.i-=2)},t.prototype.flush=function(){this.ondata||I(5),this.s.l&&I(4),this.p(this.b,!1),this.s.w=this.s.i,this.s.i-=2},t}();_e.Deflate=wt;var xt=function(){return function(t,n){ut([_,function(){return[at,wt]}],this,bt.call(this,t,n),(function(t){var n=new wt(t.data);onmessage=at(n)}),6,1)}}();function zt(t,n,r){return r||(r=n,n={}),"function"!=typeof r&&I(7),st(t,n,[_],(function(t){return it(kt(t.data[0],t.data[1]))}),0,r)}function kt(t,n){return K(t,n||{},0,0)}_e.AsyncDeflate=xt,_e.deflate=zt,_e.deflateSync=kt;var Mt=function(){function t(t,r){"function"==typeof t&&(r=t,t={}),this.ondata=r;var e=t&&t.dictionary&&t.dictionary.subarray(-32768);this.s={i:0,b:e?e.length:0},this.o=new n(32768),this.p=new n(0),e&&this.o.set(e)}return t.prototype.e=function(t){if(this.ondata||I(5),this.d&&I(4),this.p.length){if(t.length){var r=new n(this.p.length+t.length);r.set(this.p),r.set(t,this.p.length),this.p=r}}else this.p=t},t.prototype.c=function(t){this.s.i=+(this.d=t||!1);var n=this.s.b,r=U(this.p,this.s,this.o);this.ondata(D(r,n,this.s.b),this.d),this.o=D(r,this.s.b-32768),this.s.b=this.o.length,this.p=D(this.p,this.s.p/8|0),this.s.p&=7},t.prototype.push=function(t,n){this.e(t),this.c(n)},t}();_e.Inflate=Mt;var St=function(){return function(t,n){ut([$,function(){return[at,Mt]}],this,bt.call(this,t,n),(function(t){var n=new Mt(t.data);onmessage=at(n)}),7,0)}}();function At(t,n,r){return r||(r=n,n={}),"function"!=typeof r&&I(7),st(t,n,[$],(function(t){return it(Tt(t.data[0],ot(t.data[1])))}),1,r)}function Tt(t,n){return U(t,{i:2},n&&n.out,n&&n.dictionary)}_e.AsyncInflate=St,_e.inflate=At,_e.inflateSync=Tt;var Dt=function(){function t(t,n){this.c=Y(),this.l=0,this.v=1,wt.call(this,t,n)}return t.prototype.push=function(t,n){this.c.p(t),this.l+=t.length,wt.prototype.push.call(this,t,n)},t.prototype.p=function(t,n){var r=K(t,this.o,this.v&>(this.o),n&&8,this.s);this.v&&(pt(r,this.o),this.v=0),n&&(ct(r,r.length-8,this.c.d()),ct(r,r.length-4,this.l)),this.ondata(r,n)},t.prototype.flush=function(){wt.prototype.flush.call(this)},t}();_e.Gzip=Dt,_e.Compress=Dt;var Ct=function(){return function(t,n){ut([_,tt,function(){return[at,wt,Dt]}],this,bt.call(this,t,n),(function(t){var n=new Dt(t.data);onmessage=at(n)}),8,1)}}();function It(t,n,r){return r||(r=n,n={}),"function"!=typeof r&&I(7),st(t,n,[_,tt,function(){return[Ut]}],(function(t){return it(Ut(t.data[0],t.data[1]))}),2,r)}function Ut(t,n){n||(n={});var r=Y(),e=t.length;r.p(t);var i=K(t,n,gt(n),8),o=i.length;return pt(i,n),ct(i,o-8,r.d()),ct(i,o-4,e),i}_e.AsyncGzip=Ct,_e.AsyncCompress=Ct,_e.gzip=It,_e.compress=It,_e.gzipSync=Ut,_e.compressSync=Ut;var Ft=function(){function t(t,n){this.v=1,this.r=0,Mt.call(this,t,n)}return t.prototype.push=function(t,r){if(Mt.prototype.e.call(this,t),this.r+=t.length,this.v){var e=this.p.subarray(this.v-1),i=e.length>3?vt(e):4;if(i>e.length){if(!r)return}else this.v>1&&this.onmember&&this.onmember(this.r-e.length);this.p=e.subarray(i),this.v=0}Mt.prototype.c.call(this,r),!this.s.f||this.s.l||r||(this.v=T(this.s.p)+9,this.s={i:0},this.o=new n(0),this.push(new n(0),r))},t}();_e.Gunzip=Ft;var Et=function(){return function(t,n){var r=this;ut([$,nt,function(){return[at,Mt,Ft]}],this,bt.call(this,t,n),(function(t){var n=new Ft(t.data);n.onmember=function(t){return postMessage(t)},onmessage=at(n)}),9,0,(function(t){return r.onmember&&r.onmember(t)}))}}();function Zt(t,n,r){return r||(r=n,n={}),"function"!=typeof r&&I(7),st(t,n,[$,nt,function(){return[qt]}],(function(t){return it(qt(t.data[0],t.data[1]))}),3,r)}function qt(t,r){var e=vt(t);return e+8>t.length&&I(6,"invalid gzip data"),U(t.subarray(e,-8),{i:2},r&&r.out||new n(dt(t)),r&&r.dictionary)}_e.AsyncGunzip=Et,_e.gunzip=Zt,_e.gunzipSync=qt;var Ot=function(){function t(t,n){this.c=J(),this.v=1,wt.call(this,t,n)}return t.prototype.push=function(t,n){this.c.p(t),wt.prototype.push.call(this,t,n)},t.prototype.p=function(t,n){var r=K(t,this.o,this.v&&(this.o.dictionary?6:2),n&&4,this.s);this.v&&(yt(r,this.o),this.v=0),n&&ct(r,r.length-4,this.c.d()),this.ondata(r,n)},t.prototype.flush=function(){wt.prototype.flush.call(this)},t}();_e.Zlib=Ot;var Gt=function(){return function(t,n){ut([_,rt,function(){return[at,wt,Ot]}],this,bt.call(this,t,n),(function(t){var n=new Ot(t.data);onmessage=at(n)}),10,1)}}();function Lt(t,n,r){return r||(r=n,n={}),"function"!=typeof r&&I(7),st(t,n,[_,rt,function(){return[Ht]}],(function(t){return it(Ht(t.data[0],t.data[1]))}),4,r)}function Ht(t,n){n||(n={});var r=J();r.p(t);var e=K(t,n,n.dictionary?6:2,4);return yt(e,n),ct(e,e.length-4,r.d()),e}_e.AsyncZlib=Gt,_e.zlib=Lt,_e.zlibSync=Ht;var jt=function(){function t(t,n){Mt.call(this,t,n),this.v=t&&t.dictionary?2:1}return t.prototype.push=function(t,n){if(Mt.prototype.e.call(this,t),this.v){if(this.p.length<6&&!n)return;this.p=this.p.subarray(mt(this.p,this.v-1)),this.v=0}n&&(this.p.length<4&&I(6,"invalid zlib data"),this.p=this.p.subarray(0,-4)),Mt.prototype.c.call(this,n)},t}();_e.Unzlib=jt;var Nt=function(){return function(t,n){ut([$,et,function(){return[at,Mt,jt]}],this,bt.call(this,t,n),(function(t){var n=new jt(t.data);onmessage=at(n)}),11,0)}}();function Pt(t,n,r){return r||(r=n,n={}),"function"!=typeof r&&I(7),st(t,n,[$,et,function(){return[Bt]}],(function(t){return it(Bt(t.data[0],ot(t.data[1])))}),5,r)}function Bt(t,n){return U(t.subarray(mt(t,n&&n.dictionary),-4),{i:2},n&&n.out,n&&n.dictionary)}_e.AsyncUnzlib=Nt,_e.unzlib=Pt,_e.unzlibSync=Bt;var Yt=function(){function t(t,n){this.o=bt.call(this,t,n)||{},this.G=Ft,this.I=Mt,this.Z=jt}return t.prototype.i=function(){var t=this;this.s.ondata=function(n,r){t.ondata(n,r)}},t.prototype.push=function(t,r){if(this.ondata||I(5),this.s)this.s.push(t,r);else{if(this.p&&this.p.length){var e=new n(this.p.length+t.length);e.set(this.p),e.set(t,this.p.length)}else this.p=t;this.p.length>2&&(this.s=31==this.p[0]&&139==this.p[1]&&8==this.p[2]?new this.G(this.o):8!=(15&this.p[0])||this.p[0]>>4>7||(this.p[0]<<8|this.p[1])%31?new this.I(this.o):new this.Z(this.o),this.i(),this.s.push(this.p,r),this.p=null)}},t}();_e.Decompress=Yt;var Jt=function(){function t(t,n){Yt.call(this,t,n),this.queuedSize=0,this.G=Et,this.I=St,this.Z=Nt}return t.prototype.i=function(){var t=this;this.s.ondata=function(n,r,e){t.ondata(n,r,e)},this.s.ondrain=function(n){t.queuedSize-=n,t.ondrain&&t.ondrain(n)}},t.prototype.push=function(t,n){this.queuedSize+=t.length,Yt.prototype.push.call(this,t,n)},t}();function Kt(t,n,r){return r||(r=n,n={}),"function"!=typeof r&&I(7),31==t[0]&&139==t[1]&&8==t[2]?Zt(t,n,r):8!=(15&t[0])||t[0]>>4>7||(t[0]<<8|t[1])%31?At(t,n,r):Pt(t,n,r)}function Qt(t,n){return 31==t[0]&&139==t[1]&&8==t[2]?qt(t,n):8!=(15&t[0])||t[0]>>4>7||(t[0]<<8|t[1])%31?Tt(t,n):Bt(t,n)}_e.AsyncDecompress=Jt,_e.decompress=Kt,_e.decompressSync=Qt;var Rt=function(t,r,e,i){for(var o in t){var s=t[o],a=r+o,u=i;Array.isArray(s)&&(u=Q(i,s[1]),s=s[0]),s instanceof n?e[a]=[s,u]:(e[a+="/"]=[new n(0),u],Rt(s,a,e,i))}},Vt="undefined"!=typeof TextEncoder&&new TextEncoder,Wt="undefined"!=typeof TextDecoder&&new TextDecoder,Xt=0;try{Wt.decode(N,{stream:!0}),Xt=1}catch(t){}var $t=function(t){for(var n="",r=0;;){var e=t[r++],i=(e>127)+(e>223)+(e>239);if(r+i>t.length)return{s:n,r:D(t,r-1)};i?3==i?(e=((15&e)<<18|(63&t[r++])<<12|(63&t[r++])<<6|63&t[r++])-65536,n+=String.fromCharCode(55296|e>>10,56320|1023&e)):n+=String.fromCharCode(1&i?(31&e)<<6|63&t[r++]:(15&e)<<12|(63&t[r++])<<6|63&t[r++]):n+=String.fromCharCode(e)}},_t=function(){function t(t){this.ondata=t,Xt?this.t=new TextDecoder:this.p=N}return t.prototype.push=function(t,r){if(this.ondata||I(5),r=!!r,this.t)return this.ondata(this.t.decode(t,{stream:!0}),r),void(r&&(this.t.decode().length&&I(8),this.t=null));this.p||I(4);var e=new n(this.p.length+t.length);e.set(this.p),e.set(t,this.p.length);var i=$t(e),o=i.s,s=i.r;r?(s.length&&I(8),this.p=null):this.p=s,this.ondata(o,r)},t}();_e.DecodeUTF8=_t;var tn=function(){function t(t){this.ondata=t}return t.prototype.push=function(t,n){this.ondata||I(5),this.d&&I(4),this.ondata(nn(t),this.d=n||!1)},t}();function nn(t,r){if(r){for(var e=new n(t.length),i=0;i>1)),a=0,u=function(t){s[a++]=t};for(i=0;is.length){var h=new n(a+8+(o-i<<1));h.set(s),s=h}var f=t.charCodeAt(i);f<128||r?u(f):f<2048?(u(192|f>>6),u(128|63&f)):f>55295&&f<57344?(u(240|(f=65536+(1047552&f)|1023&t.charCodeAt(++i))>>18),u(128|f>>12&63),u(128|f>>6&63),u(128|63&f)):(u(224|f>>12),u(128|f>>6&63),u(128|63&f))}return D(s,0,a)}function rn(t,n){if(n){for(var r="",e=0;e65535&&I(9),n+=e+4}return n},hn=function(t,n,r,e,i,o,s,a){var u=e.length,h=r.extra,f=a&&a.length,l=un(h);ct(t,n,null!=s?33639248:67324752),n+=4,null!=s&&(t[n++]=20,t[n++]=r.os),t[n]=20,n+=2,t[n++]=r.flag<<1|(o<0&&8),t[n++]=i&&8,t[n++]=255&r.compression,t[n++]=r.compression>>8;var c=new Date(null==r.mtime?Date.now():r.mtime),p=c.getFullYear()-1980;if((p<0||p>119)&&I(10),ct(t,n,p<<25|c.getMonth()+1<<21|c.getDate()<<16|c.getHours()<<11|c.getMinutes()<<5|c.getSeconds()>>1),n+=4,-1!=o&&(ct(t,n,r.crc),ct(t,n+4,o<0?-o-2:o),ct(t,n+8,r.size)),ct(t,n+12,u),ct(t,n+14,l),n+=16,null!=s&&(ct(t,n,f),ct(t,n+6,r.attrs),ct(t,n+10,s),n+=14),t.set(e,n),n+=u,l)for(var v in h){var d=h[v],g=d.length;ct(t,n,+v),ct(t,n+2,g),t.set(d,n+4),n+=4+g}return f&&(t.set(a,n),n+=f),n},fn=function(t,n,r,e,i){ct(t,n,101010256),ct(t,n+8,r),ct(t,n+10,r),ct(t,n+12,e),ct(t,n+16,i)},ln=function(){function t(t){this.filename=t,this.c=Y(),this.size=0,this.compression=0}return t.prototype.process=function(t,n){this.ondata(null,t,n)},t.prototype.push=function(t,n){this.ondata||I(5),this.c.p(t),this.size+=t.length,n&&(this.crc=this.c.d()),this.process(t,n||!1)},t}();_e.ZipPassThrough=ln;var cn=function(){function t(t,n){var r=this;n||(n={}),ln.call(this,t),this.d=new wt(n,(function(t,n){r.ondata(null,t,n)})),this.compression=8,this.flag=en(n.level)}return t.prototype.process=function(t,n){try{this.d.push(t,n)}catch(t){this.ondata(t,null,n)}},t.prototype.push=function(t,n){ln.prototype.push.call(this,t,n)},t}();_e.ZipDeflate=cn;var pn=function(){function t(t,n){var r=this;n||(n={}),ln.call(this,t),this.d=new xt(n,(function(t,n,e){r.ondata(t,n,e)})),this.compression=8,this.flag=en(n.level),this.terminate=this.d.terminate}return t.prototype.process=function(t,n){this.d.push(t,n)},t.prototype.push=function(t,n){ln.prototype.push.call(this,t,n)},t}();_e.AsyncZipDeflate=pn;var vn=function(){function t(t){this.ondata=t,this.u=[],this.d=1}return t.prototype.add=function(t){var r=this;if(this.ondata||I(5),2&this.d)this.ondata(I(4+8*(1&this.d),0,1),null,!1);else{var e=nn(t.filename),i=e.length,o=t.comment,s=o&&nn(o),a=i!=t.filename.length||s&&o.length!=s.length,u=i+un(t.extra)+30;i>65535&&this.ondata(I(11,0,1),null,!1);var h=new n(u);hn(h,0,t,e,a,-1);var f=[h],l=function(){for(var t=0,n=f;t65535&&M(I(11,0,1),null),k)if(g<16e4)try{M(null,kt(e,h))}catch(t){M(t,null)}else l.push(zt(e,h,M));else M(null,e)},g=0;g65535&&I(11);var y=l?kt(h,f):h,m=y.length,b=Y();b.p(h),i.push(Q(f,{size:h.length,crc:b.d(),c:y,f:M,m:v,u:c!=a.length||v&&p.length!=d,o:o,compression:l})),o+=30+c+g+m,s+=76+2*(c+g)+(d||0)+m}for(var w=new n(s+22),x=o,z=s-o,k=0;k0){var i=Math.min(this.c,t.length),o=t.subarray(0,i);if(this.c-=i,this.d?this.d.push(o,!this.c):this.k[0].push(o),(t=t.subarray(i)).length)return this.push(t,r)}else{var s=0,a=0,u=void 0,h=void 0;this.p.length?t.length?((h=new n(this.p.length+t.length)).set(this.p),h.set(t,this.p.length)):h=this.p:h=t;for(var f=h.length,l=this.c,c=l&&this.d,p=function(){var t,n=ft(h,a);if(67324752==n){s=1,u=a,v.d=null,v.c=0;var r=ht(h,a+6),i=ht(h,a+8),o=2048&r,c=8&r,p=ht(h,a+26),d=ht(h,a+28);if(f>a+30+p+d){var g=[];v.k.unshift(g),s=2;var y,m=ft(h,a+18),b=ft(h,a+22),w=rn(h.subarray(a+30,a+=30+p),!o);4294967295==m?(t=c?[-2]:an(h,a),m=t[0],b=t[1]):c&&(m=-1),a+=d,v.c=m;var x={name:w,compression:i,start:function(){if(x.ondata||I(5),m){var t=e.o[i];t||x.ondata(I(14,"unknown compression type "+i,1),null,!1),(y=m<0?new t(w):new t(w,m,b)).ondata=function(t,n,r){x.ondata(t,n,r)};for(var n=0,r=g;n=0&&(x.size=m,x.originalSize=b),v.onfile(x)}return"break"}if(l){if(134695760==n)return u=a+=12+(-2==l&&8),s=3,v.c=0,"break";if(33639248==n)return u=a-=4,s=3,v.c=0,"break"}},v=this;a65558)return a(I(13,0,1),null),o;var h=ht(t,u+8);if(h){var f=h,l=ft(t,u+16),c=4294967295==l||65535==f;if(c){var p=ft(t,u-12);(c=101075792==ft(t,p))&&(f=h=ft(t,p+32),l=ft(t,p+48))}for(var v=r&&r.filter,d=function(r){var e=sn(t,l,c),u=e[0],f=e[1],p=e[2],d=e[3],g=e[4],y=on(t,e[5]);l=g;var m=function(t,n){t?(o(),a(t,null)):(n&&(s[d]=n),--h||a(null,s))};if(!v||v({name:d,size:f,originalSize:p,compression:u}))if(u)if(8==u){var b=t.subarray(y,y+f);if(p<524288||f>.8*p)try{m(null,Tt(b,{out:new n(p)}))}catch(t){m(t,null)}else i.push(At(b,{size:p},m))}else m(I(14,"unknown compression type "+u,1),null);else m(null,D(t,y,y+f));else m(null,null)},g=0;g65558)&&I(13);var o=ht(t,i+8);if(!o)return{};var s=ft(t,i+16),a=4294967295==s||65535==o;if(a){var u=ft(t,i-12);(a=101075792==ft(t,u))&&(o=ft(t,u+32),s=ft(t,u+48))}for(var h=r&&r.filter,f=0;f{% include "player/dialog_styles.css" %} {% if !guest %} +{% include "player/imports_styles.html" %} {% endif %} {% if downloads_enabled %} diff --git a/templates/player/imports_wizard.html b/templates/player/imports_wizard.html new file mode 100644 index 0000000..be61078 --- /dev/null +++ b/templates/player/imports_wizard.html @@ -0,0 +1,134 @@ + diff --git a/templates/player/scripts.html b/templates/player/scripts.html index 4f77d57..cea146e 100644 --- a/templates/player/scripts.html +++ b/templates/player/scripts.html @@ -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) { diff --git a/templates/player/shell.html b/templates/player/shell.html index b9d5740..0a13530 100644 --- a/templates/player/shell.html +++ b/templates/player/shell.html @@ -168,6 +168,7 @@ {% include "player/podcasts.html" %} {% if !guest %} {% include "player/collection.html" %} + {% include "player/imports.html" %} {% endif %} {% include "player/listening.html" %}