forked from Furumi/furumi-web
The wizard dialog leaves the DOM without close(), so focus fell to the page body. Closing it now returns focus to the button that opened it, or to New import, unless it closes to navigate, and each new step focuses the dialog title. Leaving the details clears a pending entry search, and entries are not loaded without an import, so /api/imports/null/items is never requested. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
826 lines
41 KiB
HTML
826 lines
41 KiB
HTML
<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 inflates a deflated entry into a buffer of its declared size and
|
||
// copies a stored entry by its compressed size, so each extracted file is
|
||
// charged the larger of both, and a stored entry must declare equal sizes.
|
||
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, _opener: 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;
|
||
clearTimeout(this._search);
|
||
this._search = null;
|
||
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) {
|
||
clearTimeout(this._search);
|
||
this._search = null;
|
||
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;
|
||
if (!id) return;
|
||
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._opener = document.activeElement;
|
||
this.wizard = {...emptyWizard(), open: true, provider};
|
||
if (!this.providersLoaded) this.loadProviders().catch(error => { this.wizard.error = error.message; });
|
||
},
|
||
// The dialog leaves the DOM without close(), so focus goes back to the
|
||
// button that opened it, unless the wizard closes to navigate.
|
||
async closeWizard(dialog, restoreFocus = true) {
|
||
const opener = this._opener;
|
||
this._opener = null;
|
||
const close = () => {
|
||
this.wizard = emptyWizard();
|
||
if (restoreFocus) Alpine.nextTick(() => {
|
||
const target = opener?.isConnected ? opener
|
||
: document.querySelector('.library-imports .release-action-btn.primary') || document.querySelector('.library-imports h1');
|
||
target?.focus({preventScroll: true});
|
||
});
|
||
};
|
||
if (dialog) await finishPlayerDialog(dialog, close);
|
||
else close();
|
||
},
|
||
// A new step replaces the focused control, so the title takes focus.
|
||
focusWizardTitle() {
|
||
Alpine.nextTick(() => document.getElementById('import-wizard-title')?.focus());
|
||
},
|
||
chooseMethod(provider, method) {
|
||
this.wizard = {...emptyWizard(), open: true, provider, method, step: method === 'api' ? 'connect' : 'upload'};
|
||
this.focusWizardTitle();
|
||
// 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};
|
||
this.focusWizardTitle();
|
||
},
|
||
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
|
||
// the sizes fflate allocates for them are limited before anything is
|
||
// decompressed; unknown methods, duplicates and stored entries whose
|
||
// sizes disagree are refused.
|
||
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 names = new Set();
|
||
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 packed = Number(entry.size);
|
||
const size = Number(entry.originalSize);
|
||
const valid = [packed, size].every(n => Number.isFinite(n) && n >= 0)
|
||
&& (entry.compression === 8 || (entry.compression === 0 && packed === size));
|
||
if (!valid || names.has(entry.name)) {
|
||
problem = 'zipInvalid';
|
||
return false;
|
||
}
|
||
names.add(entry.name);
|
||
budget.files += 1;
|
||
budget.bytes += Math.max(packed, size);
|
||
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;
|
||
this.focusWizardTitle();
|
||
},
|
||
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]'), false);
|
||
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>
|