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

+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.