6434 lines
276 KiB
HTML
6434 lines
276 KiB
HTML
<script>
|
||
const GUEST = {{ guest }};
|
||
const SHARE_TOKEN = "{{ share_token }}";
|
||
// Handle expired sessions centrally, including background player requests.
|
||
let loginRedirectStarted = false;
|
||
function redirectOnUnauthorized(status) {
|
||
if (GUEST || status !== 401 || loginRedirectStarted) return;
|
||
loginRedirectStarted = true;
|
||
window.location.replace('/login');
|
||
}
|
||
|
||
const playerFetch = window.fetch.bind(window);
|
||
function playerOffline() { return window.Alpine?.store('offline')?.active === true; }
|
||
window.fetch = async (input, init) => {
|
||
const url = new URL(input instanceof Request ? input.url : input, window.location.href);
|
||
const offline = window.Alpine?.store('offline');
|
||
// The browser can disable networking before it delivers the offline event.
|
||
const disconnected = offline?.enabled && offline.supported && navigator.onLine === false;
|
||
const recoveryProbe = offline?.automatic && url.origin === location.origin && url.pathname === '/offline-probe';
|
||
if (disconnected || (offline?.active && !recoveryProbe)) {
|
||
if (url.origin === location.origin && url.pathname.startsWith('/api/player/')) {
|
||
const request = new Request(input instanceof Request ? input : url.href, init);
|
||
const local = await offline.localResponse(request);
|
||
if (local) return local;
|
||
}
|
||
return new Response(null, {status:503});
|
||
}
|
||
const response = await playerFetch(input, init);
|
||
if (url.origin === window.location.origin && url.pathname.startsWith('/api/')) {
|
||
redirectOnUnauthorized(response.status);
|
||
if ((init?.method || input?.method || 'GET').toUpperCase() === 'GET') offline?.observe(url, response);
|
||
}
|
||
return response;
|
||
};
|
||
|
||
const T = {
|
||
info: "{{ t.player_info }}",
|
||
noDetails: "{{ t.player_no_details }}",
|
||
trackInfoTitle: "{{ t.player_track_info }}",
|
||
releaseInfoTitle: "{{ t.player_release_info }}",
|
||
unknown: "{{ t.player_unknown }}",
|
||
unknownSize: "{{ t.player_unknown_size }}",
|
||
title: "{{ t.player_title }}",
|
||
release: "{{ t.player_release }}",
|
||
unknownRelease: "{{ t.player_unknown_release }}",
|
||
unknownTrack: "{{ t.player_unknown_track }}",
|
||
unknownAudio: "{{ t.player_unknown_audio }}",
|
||
type: "{{ t.player_type }}",
|
||
year: "{{ t.player_year }}",
|
||
tracks: "{{ t.player_tracks }}",
|
||
uploaders: "{{ t.player_uploaders }}",
|
||
artists: "{{ t.player_artists }}",
|
||
releaseYear: "{{ t.player_release_year }}",
|
||
duration: "{{ t.player_duration }}",
|
||
audio: "{{ t.player_audio }}",
|
||
size: "{{ t.player_size }}",
|
||
uploader: "{{ t.player_uploader }}",
|
||
lastfmRating: "{{ t.player_lastfm_rating }}",
|
||
lastfmListeners: "{{ t.player_lastfm_listeners }}",
|
||
lastfmPlaycount: "{{ t.player_lastfm_playcount }}",
|
||
lastfmUpdated: "{{ t.player_lastfm_updated }}",
|
||
lastfmNotLoaded: "{{ t.player_lastfm_not_loaded }}",
|
||
lastfmProfile: "{{ t.player_lastfm_profile }}",
|
||
lastfmConnect: "{{ t.player_lastfm_connect }}",
|
||
lastfmConnected: "{{ t.player_lastfm_connected }}",
|
||
lastfmReconnect: "{{ t.player_lastfm_reconnect }}",
|
||
lastfmNotConfigured: "{{ t.player_lastfm_not_configured }}",
|
||
lastfmStatusConnect: "{{ t.player_lastfm_status_connect }}",
|
||
lastfmStatusConnected: "{{ t.player_lastfm_status_connected }}",
|
||
lastfmStatusReconnect: "{{ t.player_lastfm_status_reconnect }}",
|
||
lastfmStatusNotConfigured: "{{ t.player_lastfm_status_not_configured }}",
|
||
lastfmDisconnectConfirm: "{{ t.player_lastfm_disconnect_confirm }}",
|
||
lastfmConnectFailed: "{{ t.player_lastfm_connect_failed }}",
|
||
lastfmDisconnectFailed: "{{ t.player_lastfm_disconnect_failed }}",
|
||
shareUnavailable: "{{ t.share_unavailable }}",
|
||
searchSimilarTo: "{{ t.player_search_similar_to }}",
|
||
similarityFailed: "{{ t.player_similarity_failed }}",
|
||
share: "{{ t.player_share }}",
|
||
shareTrack: "{{ t.player_share_track }}",
|
||
shareQueue: "{{ t.player_share_queue }}",
|
||
sharedPlaylist: "{{ t.player_shared_playlist }}",
|
||
connectionLost: "{{ t.player_connection_lost }}",
|
||
connectionLostDetail: "{{ t.player_connection_lost_detail }}",
|
||
activeDevice: "{{ t.player_active_device }}",
|
||
trackWord: "{{ t.player_tracks_count }}",
|
||
releaseWord: "{{ t.player_releases_count }}",
|
||
ofWord: "{{ t.player_of }}",
|
||
needsApproval: "{{ t.player_needs_approval }}",
|
||
showing: "{{ t.player_showing }}",
|
||
statusLabelText: "{{ t.player_status }}",
|
||
fileLabel: "{{ t.player_file }}",
|
||
createdLabel: "{{ t.player_created }}",
|
||
updatedLabel: "{{ t.player_updated }}",
|
||
errorLabel: "{{ t.player_error }}",
|
||
pending: "{{ t.player_pending }}",
|
||
featuredShort: "{{ t.player_featured_short }}",
|
||
noYear: "{{ t.player_no_year }}",
|
||
loadUploadsFailed: "{{ t.player_failed_load_uploaded_tracks }}",
|
||
releaseMetadata: "{{ t.player_release_metadata }}",
|
||
trackMetadata: "{{ t.player_track_metadata }}",
|
||
metadata: "{{ t.player_metadata }}",
|
||
approveMetadata: "{{ t.player_approve_metadata }}",
|
||
editRelease: "{{ t.player_edit_release }}",
|
||
editTrack: "{{ t.player_edit_track }}",
|
||
editMetadata: "{{ t.player_edit_metadata }}",
|
||
failedSaveTrack: "{{ t.player_failed_save_track }}",
|
||
trackMetadataSaved: "{{ t.player_track_metadata_saved }}",
|
||
failedSaveRelease: "{{ t.player_failed_save_release }}",
|
||
releaseMetadataSaved: "{{ t.player_release_metadata_saved }}",
|
||
failedDeleteReview: "{{ t.player_failed_delete_review }}",
|
||
reviewDeleted: "{{ t.player_review_deleted }}",
|
||
failedApproveReview: "{{ t.player_failed_approve_review }}",
|
||
trackApprovedImported: "{{ t.player_track_approved_imported }}",
|
||
failedUpdateSelectedTracks: "{{ t.player_failed_update_selected_tracks }}",
|
||
selectedTracksUpdated: "{{ t.player_selected_tracks_updated }}",
|
||
clientIdle: "{{ t.player_client_idle }}",
|
||
active: "{{ t.player_active }}",
|
||
aiIdle: "{{ t.player_ai_idle }}",
|
||
aiPrefix: "{{ t.player_ai_prefix }}",
|
||
processing: "{{ t.player_processing }}",
|
||
queued: "{{ t.player_queued }}",
|
||
saved: "{{ t.player_saved }}",
|
||
chooseSavedOrAddTorrent: "{{ t.player_choose_saved_or_add_torrent }}",
|
||
uploadFailed: "{{ t.player_upload_failed }}",
|
||
uploadComplete: "{{ t.player_upload_complete }}",
|
||
uploadingFiles: "{{ t.player_uploading_files }}",
|
||
preview: "{{ t.player_preview }}",
|
||
resolving: "{{ t.player_resolving }}",
|
||
downloading: "{{ t.player_downloading }}",
|
||
moving: "{{ t.player_moving }}",
|
||
completed: "{{ t.player_completed }}",
|
||
failed: "{{ t.player_failed }}",
|
||
paused: "{{ t.player_paused }}",
|
||
noTorrentSelected: "{{ t.player_no_torrent_selected }}",
|
||
downloaded: "{{ t.player_downloaded }}",
|
||
speed: "{{ t.player_speed }}",
|
||
down: "{{ t.player_down }}",
|
||
up: "{{ t.player_up }}",
|
||
peers: "{{ t.player_peers }}",
|
||
live: "{{ t.player_live }}",
|
||
seen: "{{ t.player_seen }}",
|
||
eta: "{{ t.player_eta }}",
|
||
selected: "{{ t.player_selected }}",
|
||
downloadSelected: "{{ t.player_download_selected }}",
|
||
pauseDownload: "{{ t.player_pause_download }}",
|
||
chooseTorrent: "{{ t.player_choose_torrent }}",
|
||
readingTorrent: "{{ t.player_reading_torrent }}",
|
||
resolvingMagnet: "{{ t.player_resolving_magnet }}",
|
||
previewFailed: "{{ t.player_preview_failed }}",
|
||
allFilesSelected: "{{ t.player_all_files_selected }}",
|
||
openingSavedTorrent: "{{ t.player_opening_saved_torrent }}",
|
||
savedTorrentOpened: "{{ t.player_saved_torrent_opened }}",
|
||
removeTorrentConfirm: "{{ t.player_remove_torrent_confirm }}",
|
||
torrentRemoved: "{{ t.player_torrent_removed }}",
|
||
selectOneFile: "{{ t.player_select_one_file }}",
|
||
startingDownload: "{{ t.player_starting_download }}",
|
||
downloadStarted: "{{ t.player_download_started }}",
|
||
pausingDownload: "{{ t.player_pausing_download }}",
|
||
downloadPaused: "{{ t.player_download_paused }}",
|
||
statusFailed: "{{ t.player_status_failed }}",
|
||
startFailed: "{{ t.player_start_failed }}",
|
||
pauseFailed: "{{ t.player_pause_failed }}",
|
||
loadTorrentsFailed: "{{ t.player_load_torrents_failed }}",
|
||
openTorrentFailed: "{{ t.player_open_torrent_failed }}",
|
||
deleteTorrentFailed: "{{ t.player_delete_torrent_failed }}",
|
||
loadAiQueueFailed: "{{ t.player_load_ai_queue_failed }}",
|
||
fileUploadLoadFailed: "{{ t.player_file_upload_load_failed }}",
|
||
removeFileUploadConfirm: "{{ t.player_remove_file_upload_confirm }}",
|
||
fileUploadHistoryRemoved: "{{ t.player_file_upload_history_removed }}",
|
||
loadHistoryFailed: "{{ t.player_failed_load_history }}",
|
||
fileUploadHistoryRemoveFailed: "{{ t.player_file_upload_history_remove_failed }}",
|
||
noSupportedAudioFiles: "{{ t.player_no_supported_audio_files }}",
|
||
youtubeQueued: "{{ t.player_youtube_queued }}",
|
||
youtubeResolving: "{{ t.player_youtube_resolving }}",
|
||
youtubePostprocessing: "{{ t.player_youtube_postprocessing }}",
|
||
youtubeAwaitingAi: "{{ t.player_youtube_awaiting_ai }}",
|
||
youtubeAiProcessing: "{{ t.player_youtube_ai_processing }}",
|
||
youtubeNeedsReview: "{{ t.player_youtube_needs_review }}",
|
||
youtubeCompleteWithErrors: "{{ t.player_youtube_complete_with_errors }}",
|
||
youtubeSkipped: "{{ t.player_youtube_skipped }}",
|
||
youtubeStarting: "{{ t.player_youtube_starting }}",
|
||
youtubeStarted: "{{ t.player_youtube_started }}",
|
||
youtubeLoadFailed: "{{ t.player_youtube_load_failed }}",
|
||
youtubeStartFailed: "{{ t.player_youtube_start_failed }}",
|
||
youtubeRetryFailed: "{{ t.player_youtube_retry_failed }}",
|
||
youtubeDeleteFailed: "{{ t.player_youtube_delete_failed }}",
|
||
youtubeDeleteConfirm: "{{ t.player_youtube_delete_confirm }}",
|
||
youtubeParse: "{{ t.player_youtube_parse }}",
|
||
youtubeParsing: "{{ t.player_youtube_parsing }}",
|
||
youtubePreviewFailed: "{{ t.player_youtube_preview_failed }}",
|
||
youtubeSelectAll: "{{ t.player_youtube_select_all }}",
|
||
youtubeClearSelection: "{{ t.player_youtube_clear_selection }}",
|
||
youtubeSelectedCount: "{{ t.player_youtube_selected_count }}",
|
||
youtubePlaylistCreateFailed: "{{ t.player_youtube_playlist_create_failed }}",
|
||
youtubeAddedTo: "{{ t.player_youtube_added_to }}",
|
||
youtubeCancelled: "{{ t.player_youtube_cancelled }}",
|
||
youtubeStopConfirm: "{{ t.player_youtube_stop_confirm }}",
|
||
youtubeStopping: "{{ t.player_youtube_stopping }}",
|
||
youtubeStopped: "{{ t.player_youtube_stopped }}",
|
||
youtubeStopFailed: "{{ t.player_youtube_stop_failed }}",
|
||
youtubeVideo: "{{ t.player_youtube_video }}",
|
||
youtubePlaylist: "{{ t.player_youtube_playlist }}",
|
||
youtubeItems: "{{ t.player_youtube_items }}",
|
||
youtubeErrors: "{{ t.player_youtube_errors }}",
|
||
chapters: "{{ t.player_chapters }}",
|
||
deletePlaylistConfirm: "{{ t.player_delete_playlist_confirm }}",
|
||
albums: "{{ t.player_albums }}",
|
||
eps: "{{ t.player_eps }}",
|
||
singles: "{{ t.player_singles }}",
|
||
compilations: "{{ t.player_compilations }}",
|
||
mixtapes: "{{ t.player_mixtapes }}",
|
||
liveReleases: "{{ t.player_live_releases }}",
|
||
soundtracks: "{{ t.player_soundtracks }}",
|
||
likesPlaylist: "{{ t.player_likes_playlist }}",
|
||
expand: "{{ t.player_expand }}",
|
||
collapse: "{{ t.player_collapse }}",
|
||
};
|
||
|
||
const artistPluralRules = new Intl.PluralRules(document.documentElement.lang);
|
||
const artistCountLabels = {
|
||
tracks: { one: "{{ t.player_track_one }}", few: "{{ t.player_track_few }}", other: "{{ t.player_tracks_count }}" },
|
||
releases: { one: "{{ t.player_release_one }}", few: "{{ t.player_release_few }}", other: "{{ t.player_releases_count }}" },
|
||
plays: { one: "{{ t.player_play_one }}", few: "{{ t.player_play_few }}", other: "{{ t.player_plays_count }}" },
|
||
};
|
||
|
||
function formatArtistCount(count, kind) {
|
||
const labels = artistCountLabels[kind];
|
||
return count + ' ' + (labels[artistPluralRules.select(count)] || labels.other);
|
||
}
|
||
|
||
async function finishPlayerDialog(dialog, close) {
|
||
if (dialog?.dataset.closing) return;
|
||
if (dialog?.animate && matchMedia('(prefers-reduced-motion: no-preference)').matches) {
|
||
dialog.dataset.closing = 'true';
|
||
await dialog.animate([{opacity:1}, {opacity:0}], {duration:120, easing:'ease-in', fill:'forwards'}).finished.catch(() => {});
|
||
}
|
||
close();
|
||
}
|
||
|
||
function formatTime(seconds) {
|
||
if (!seconds || isNaN(seconds)) return '0:00';
|
||
const s = Math.floor(seconds);
|
||
const m = Math.floor(s / 60);
|
||
const sec = s % 60;
|
||
return m + ':' + (sec < 10 ? '0' : '') + sec;
|
||
}
|
||
|
||
function coverVariantUrl(url, variant) {
|
||
if (!url) return url;
|
||
return url.replace(/^(\/api\/player\/cover\/\d+\/)(?:small|medium|large)(?=[?#]|$)/, '$1' + variant);
|
||
}
|
||
|
||
function nudgeWordmark(button) {
|
||
if (window.matchMedia('(prefers-reduced-motion: reduce)').matches) return;
|
||
button.getAnimations().find(motion => motion.id === 'wordmark-nudge')?.cancel();
|
||
const direction = Math.random() < 0.5 ? -1 : 1;
|
||
const angle = direction * (1 + Math.random());
|
||
button.animate([
|
||
{transform:'none'},
|
||
{transform:`translateX(${direction * 1.5}px) rotate(${angle}deg) scaleX(1.02)`, offset:0.32},
|
||
{transform:`rotate(${-angle * 0.45}deg) scaleX(0.995)`, offset:0.68},
|
||
{transform:'none'},
|
||
], {id:'wordmark-nudge', duration:360, easing:'ease-in-out'});
|
||
}
|
||
|
||
// A row uses double-click for playback. Keep the first press native so dragging still selects text.
|
||
document.addEventListener('mousedown', event => {
|
||
if (event.button !== 0 || event.detail !== 2 || event.shiftKey || event.ctrlKey || event.metaKey || event.altKey) return;
|
||
if (event.target.closest('.track-row') && !event.target.closest('a, button, input, textarea, select, [contenteditable]')) {
|
||
event.preventDefault();
|
||
}
|
||
});
|
||
|
||
document.addEventListener('alpine:init', () => {
|
||
Alpine.data('playerCoverPreview', () => ({
|
||
visible: false,
|
||
pinned: false,
|
||
leaveTimer: null,
|
||
get artwork() { return Alpine.store('player').currentTrack?.cover_url; },
|
||
hover(event) {
|
||
if (!this.artwork || event.pointerType !== 'mouse') return;
|
||
clearTimeout(this.leaveTimer);
|
||
this.visible = true;
|
||
},
|
||
leave(event) {
|
||
if (this.pinned || !this.visible || event.pointerType !== 'mouse') return;
|
||
clearTimeout(this.leaveTimer);
|
||
this.leaveTimer = setTimeout(() => this.closePreview(), 160);
|
||
},
|
||
pin() {
|
||
clearTimeout(this.leaveTimer);
|
||
this.visible = this.pinned = Boolean(this.artwork);
|
||
},
|
||
activate(event) {
|
||
const mobile = Alpine.store('mobile');
|
||
const touch = event.pointerType === 'touch' ||
|
||
(!event.pointerType && !window.matchMedia('(hover: hover)').matches);
|
||
if (!mobile.playerExpanded && mobile.isMobilePlayer() && (touch || !this.artwork)) {
|
||
this.closePreview();
|
||
mobile.openPlayerFullscreen();
|
||
} else {
|
||
this.pin();
|
||
}
|
||
},
|
||
closePreview() {
|
||
clearTimeout(this.leaveTimer);
|
||
this.visible = this.pinned = false;
|
||
},
|
||
destroy() { clearTimeout(this.leaveTimer); },
|
||
}));
|
||
|
||
// -----------------------------------------------------------------------
|
||
// Connection monitor
|
||
// -----------------------------------------------------------------------
|
||
Alpine.store('connection', {
|
||
failureCount: 0,
|
||
disconnected: false,
|
||
threshold: 2,
|
||
|
||
init() {
|
||
if (navigator.onLine === false) {
|
||
this.failureCount = this.threshold;
|
||
this.disconnected = true;
|
||
}
|
||
window.addEventListener('online', () => this.recordSuccess());
|
||
window.addEventListener('offline', () => this.recordFailure());
|
||
},
|
||
|
||
message() {
|
||
return T.connectionLostDetail;
|
||
},
|
||
|
||
recordSuccess() {
|
||
this.failureCount = 0;
|
||
this.disconnected = false;
|
||
},
|
||
|
||
recordFailure() {
|
||
this.failureCount += 1;
|
||
if (this.failureCount >= this.threshold) {
|
||
this.disconnected = true;
|
||
}
|
||
},
|
||
});
|
||
|
||
installConnectionFetchMonitor();
|
||
|
||
// -----------------------------------------------------------------------
|
||
// Audio element
|
||
// -----------------------------------------------------------------------
|
||
const audio = new Audio();
|
||
audio.preload = 'auto';
|
||
|
||
Alpine.store('mobile', {
|
||
libraryOpen: false,
|
||
playerExpanded: false,
|
||
toggleLibrary() {
|
||
this.libraryOpen = !this.libraryOpen;
|
||
if (this.libraryOpen) Alpine.store('user').menuOpen = false;
|
||
},
|
||
closeLibrary() {
|
||
Alpine.store('pins')?.cancelDrag();
|
||
document.querySelector('dialog.mobile-library-backdrop[open]')?.close();
|
||
this.libraryOpen = false;
|
||
},
|
||
isMobilePlayer() {
|
||
if (!window.matchMedia) return false;
|
||
return window.matchMedia('(max-width: 900px)').matches
|
||
|| window.matchMedia('(pointer: coarse) and (max-width: 1024px)').matches;
|
||
},
|
||
openPlayerFullscreen() {
|
||
if (!this.isMobilePlayer() || !Alpine.store('player').currentTrack) return;
|
||
this.playerExpanded = true;
|
||
Alpine.store('queue').visible = false;
|
||
Alpine.store('devices').open = false;
|
||
this.resetPlayerFullscreenScroll();
|
||
},
|
||
closePlayerFullscreen() {
|
||
this.playerExpanded = false;
|
||
Alpine.store('queue').visible = false;
|
||
Alpine.store('devices').open = false;
|
||
},
|
||
resetPlayerFullscreenScroll() {
|
||
requestAnimationFrame(() => {
|
||
const full = document.querySelector('.player-bar .mobile-full-player');
|
||
if (full) {
|
||
full.scrollTop = 0;
|
||
full.scrollLeft = 0;
|
||
}
|
||
});
|
||
},
|
||
});
|
||
|
||
Alpine.store('info', {
|
||
modal: null,
|
||
open(title, body, actions = []) {
|
||
if (Array.isArray(body)) {
|
||
this.openRows(title, body, actions);
|
||
return;
|
||
}
|
||
this.modal = {
|
||
title: title || T.info,
|
||
body: body || T.noDetails,
|
||
rows: null,
|
||
actions: actions || [],
|
||
};
|
||
},
|
||
openRows(title, rows, actions = []) {
|
||
this.modal = {
|
||
title: title || T.info,
|
||
body: '',
|
||
rows: (rows || []).filter(row => row && ((row.value !== undefined && row.value !== null && row.value !== '') || (row.links && row.links.length))),
|
||
actions: actions || [],
|
||
};
|
||
},
|
||
close() {
|
||
this.modal = null;
|
||
},
|
||
async runAction(actionOrIndex) {
|
||
const index = Number.isInteger(actionOrIndex) ? actionOrIndex : this.modal?.actions?.indexOf(actionOrIndex);
|
||
const action = index >= 0 ? this.modal?.actions?.[index] : actionOrIndex;
|
||
if (!action || action.busy === true || typeof action.run !== 'function') return;
|
||
if (index >= 0 && this.modal?.actions) {
|
||
this.modal.actions[index] = { ...action, busy: true };
|
||
this.modal.actions = [...this.modal.actions];
|
||
}
|
||
try {
|
||
await action.run();
|
||
} finally {
|
||
if (index >= 0 && this.modal?.actions?.[index]) {
|
||
this.modal.actions[index] = { ...this.modal.actions[index], busy: false };
|
||
this.modal.actions = [...this.modal.actions];
|
||
}
|
||
}
|
||
},
|
||
});
|
||
|
||
Alpine.store('sharing', {
|
||
_handledInitialLink: false,
|
||
sharedTrackId: null,
|
||
|
||
absoluteUrl(path) {
|
||
return new URL(path, window.location.origin).href;
|
||
},
|
||
|
||
async copyText(text) {
|
||
try {
|
||
if (navigator.clipboard?.writeText && window.isSecureContext) {
|
||
await navigator.clipboard.writeText(text);
|
||
return true;
|
||
}
|
||
} catch {}
|
||
|
||
const textarea = document.createElement('textarea');
|
||
textarea.value = text;
|
||
textarea.setAttribute('readonly', '');
|
||
textarea.style.position = 'fixed';
|
||
textarea.style.left = '-9999px';
|
||
textarea.style.top = '0';
|
||
document.body.appendChild(textarea);
|
||
textarea.select();
|
||
let ok = false;
|
||
try {
|
||
ok = document.execCommand('copy');
|
||
} catch {}
|
||
textarea.remove();
|
||
return ok;
|
||
},
|
||
|
||
async copyUrl(path, trigger = null) {
|
||
const copied = await this.copyText(this.absoluteUrl(path));
|
||
this.flashTrigger(trigger, copied);
|
||
return copied;
|
||
},
|
||
|
||
async copyTrack(track, trigger = null) {
|
||
const id = Number(track?.id || track);
|
||
if (id) return this.copyTracks([{id}], track?.title || T.sharedPlaylist, trigger);
|
||
},
|
||
|
||
async copyQueue(trigger = null) {
|
||
return this.copyTracks(Alpine.store('queue')?.tracks || [], T.sharedPlaylist, trigger);
|
||
},
|
||
|
||
async copyRelease(release, trigger = null) {
|
||
try {
|
||
const id = Number(release?.id || release || 0);
|
||
if (!id) return;
|
||
const response = await fetch(`/api/player/releases/${id}`);
|
||
if (!response.ok) throw new Error('release load failed');
|
||
const data = await response.json();
|
||
return this.copyTracks(data.tracks || [], data.title || T.sharedPlaylist, trigger);
|
||
} catch { this.flashTrigger(trigger, false); }
|
||
},
|
||
|
||
async copyTracks(tracks, title = T.sharedPlaylist, trigger = null) {
|
||
if (GUEST) return this.copyUrl(`/share/${SHARE_TOKEN}`, trigger);
|
||
const trackIds = (tracks || []).map(track => Number(track.id)).filter(Boolean);
|
||
if (!trackIds.length) return;
|
||
try {
|
||
const res = await fetch('/api/player/shares', {
|
||
method: 'POST',
|
||
headers: { 'Content-Type': 'application/json' },
|
||
body: JSON.stringify({ track_ids: trackIds, title }),
|
||
});
|
||
if (!res.ok) throw new Error('share failed');
|
||
const data = await res.json();
|
||
await this.copyUrl(data.url || `/share/${data.token}`, trigger);
|
||
} catch (err) {
|
||
this.flashTrigger(trigger, false);
|
||
console.warn(err);
|
||
}
|
||
},
|
||
|
||
flashTrigger(trigger, copied) {
|
||
if (!trigger) return;
|
||
const className = copied ? 'share-copy-flash' : 'share-copy-failed';
|
||
trigger.classList.remove('share-copy-flash', 'share-copy-failed');
|
||
void trigger.offsetWidth;
|
||
trigger.classList.add(className);
|
||
window.setTimeout(() => trigger.classList.remove(className), 720);
|
||
},
|
||
|
||
markSharedTrack(trackId) {
|
||
const id = Number(trackId || 0);
|
||
this.sharedTrackId = id > 0 ? id : null;
|
||
},
|
||
|
||
isSharedTrack(track) {
|
||
const id = Number(track?.id || track || 0);
|
||
return id > 0 && id === Number(this.sharedTrackId || 0);
|
||
},
|
||
|
||
focusSharedTrack(trackId) {
|
||
const run = () => this.scrollSharedTrackIntoView(trackId);
|
||
requestAnimationFrame(run);
|
||
setTimeout(run, 120);
|
||
setTimeout(run, 360);
|
||
setTimeout(run, 720);
|
||
},
|
||
|
||
scrollSharedTrackIntoView(trackId) {
|
||
const id = Number(trackId || 0);
|
||
if (!id) return false;
|
||
const row = document.querySelector(`#center-scroll [data-shared-track-id="${id}"]`);
|
||
const container = document.getElementById('center-scroll');
|
||
if (!row || !container) return false;
|
||
|
||
const containerRect = container.getBoundingClientRect();
|
||
const rowRect = row.getBoundingClientRect();
|
||
const top = container.scrollTop
|
||
+ rowRect.top
|
||
- containerRect.top
|
||
- ((container.clientHeight - rowRect.height) / 2);
|
||
container.scrollTo({ top: Math.max(0, top), behavior: 'smooth' });
|
||
return true;
|
||
},
|
||
|
||
async handleInitialShareLinks() {
|
||
if (this._handledInitialLink || !SHARE_TOKEN) return;
|
||
this._handledInitialLink = true;
|
||
const library = Alpine.store('library');
|
||
library._beginNavigation(library._activeHash, {fromHash:true});
|
||
const route = library._navigationVersion;
|
||
library.currentPlaylist = null;
|
||
library.playlistUnavailable = false;
|
||
library.view = 'playlist_detail';
|
||
try {
|
||
const response = await fetch(`/api/player/shares/${SHARE_TOKEN}`);
|
||
if (!response.ok) throw new Error('share unavailable');
|
||
const data = await response.json();
|
||
if (route !== library._navigationVersion) return;
|
||
const tracks = data.tracks || [];
|
||
if (!tracks.length) throw new Error('share empty');
|
||
library.showSharedPlaylist(data);
|
||
const queue = Alpine.store('queue');
|
||
queue.tracks = tracks;
|
||
queue.currentIndex = 0;
|
||
Alpine.store('player')._playLocal(tracks[0], {paused:true});
|
||
} catch {
|
||
if (route === library._navigationVersion) library.showSharedPlaylist({title:T.shareUnavailable, tracks:[]});
|
||
}
|
||
},
|
||
|
||
});
|
||
|
||
// -----------------------------------------------------------------------
|
||
// User store
|
||
// -----------------------------------------------------------------------
|
||
Alpine.store('user', {
|
||
profile: null,
|
||
accessStatus: "anonymous",
|
||
menuOpen: false,
|
||
settingsOpen: false,
|
||
getAppOpen: false,
|
||
settingsFocus: 'user-settings-title',
|
||
lastfm: { configured: false, connected: false, username: null, reauth_required: false, last_error: null },
|
||
lastfmBusy: false,
|
||
|
||
init() {
|
||
if (GUEST) {
|
||
this.checkAccess();
|
||
setInterval(() => this.checkAccess(), 5000);
|
||
return;
|
||
}
|
||
this.cleanLastfmQuery();
|
||
document.addEventListener('click', event => {
|
||
if (this.menuOpen && !event.target.closest?.('[data-account-menu]')) this.menuOpen = false;
|
||
}, true);
|
||
this.load();
|
||
this.loadLastfm();
|
||
},
|
||
|
||
async checkAccess() {
|
||
try {
|
||
const response = await fetch('/auth/status', {cache:'no-store'});
|
||
if (!response.ok) return;
|
||
const data = await response.json();
|
||
this.accessStatus = data.status;
|
||
if (data.status === 'active') window.location.reload();
|
||
} catch {}
|
||
},
|
||
|
||
cleanLastfmQuery() {
|
||
const url = new URL(window.location.href);
|
||
if (!url.searchParams.has('lastfm')) return;
|
||
url.searchParams.delete('lastfm');
|
||
const clean = `${url.pathname}${url.search}${url.hash}`;
|
||
window.history.replaceState({}, document.title, clean || '/');
|
||
},
|
||
|
||
async load() {
|
||
try {
|
||
const res = await fetch('/api/player/me');
|
||
if (!res.ok) throw new Error('failed');
|
||
this.profile = await res.json();
|
||
} catch {
|
||
this.profile = null;
|
||
}
|
||
},
|
||
|
||
async loadLastfm() {
|
||
if (playerOffline()) return;
|
||
try {
|
||
const res = await fetch('/api/player/lastfm/status');
|
||
if (!res.ok) throw new Error('failed');
|
||
this.lastfm = await res.json();
|
||
const player = Alpine.store('player');
|
||
if (player?.isPlaying) player._sendNowPlaying();
|
||
} catch {
|
||
this.lastfm = { configured: false, connected: false, username: null, reauth_required: false, last_error: null };
|
||
}
|
||
},
|
||
|
||
lastfmLabel() {
|
||
if (!this.lastfm?.configured) return T.lastfmNotConfigured;
|
||
if (this.lastfm?.connected && this.lastfm?.reauth_required) return T.lastfmReconnect;
|
||
if (this.lastfm?.connected) {
|
||
const user = this.lastfm.username || T.unknown;
|
||
return T.lastfmConnected.replace('{user}', user);
|
||
}
|
||
return T.lastfmConnect;
|
||
},
|
||
|
||
lastfmStatusLabel() {
|
||
if (!this.lastfm?.configured) return T.lastfmStatusNotConfigured;
|
||
if (this.lastfm?.connected && this.lastfm?.reauth_required) return T.lastfmStatusReconnect;
|
||
if (this.lastfm?.connected) return this.lastfm.username || T.lastfmStatusConnected;
|
||
return T.lastfmStatusConnect;
|
||
},
|
||
|
||
lastfmClass() {
|
||
if (!this.lastfm?.configured) return 'not-configured';
|
||
if (this.lastfm?.connected && this.lastfm?.reauth_required) return 'needs-auth';
|
||
if (this.lastfm?.connected) return 'connected';
|
||
return 'available';
|
||
},
|
||
|
||
async handleLastfm() {
|
||
if (this.lastfmBusy) return;
|
||
if (!this.lastfm?.configured) return;
|
||
if (!this.lastfm?.connected || this.lastfm?.reauth_required) {
|
||
window.location.href = '/api/player/lastfm/connect';
|
||
return;
|
||
}
|
||
const user = this.lastfm.username || T.unknown;
|
||
if (!window.confirm(T.lastfmDisconnectConfirm.replace('{user}', user))) return;
|
||
this.lastfmBusy = true;
|
||
try {
|
||
const res = await fetch('/api/player/lastfm/disconnect', { method: 'POST' });
|
||
if (!res.ok) throw new Error(T.lastfmDisconnectFailed);
|
||
await this.loadLastfm();
|
||
} catch {
|
||
alert(T.lastfmDisconnectFailed);
|
||
} finally {
|
||
this.lastfmBusy = false;
|
||
}
|
||
},
|
||
|
||
openSettings(heading = 'user-settings-title') {
|
||
this.settingsFocus = heading;
|
||
this.menuOpen = false;
|
||
this.settingsOpen = true;
|
||
if (!playerOffline()) {
|
||
this.loadLastfm();
|
||
Alpine.store('devices')?.loadFedDevices();
|
||
}
|
||
},
|
||
|
||
async closeSettings() {
|
||
const dialog = document.querySelector('.user-settings-overlay[open]');
|
||
await finishPlayerDialog(dialog, () => {
|
||
this.settingsOpen = false;
|
||
Alpine.nextTick(() => this.focusAccountTrigger());
|
||
});
|
||
},
|
||
|
||
async closeGetApp(dialog) {
|
||
await finishPlayerDialog(dialog, () => {
|
||
this.getAppOpen = false;
|
||
Alpine.nextTick(() => this.focusAccountTrigger());
|
||
});
|
||
},
|
||
|
||
focusAccountTrigger() {
|
||
const triggers = document.querySelectorAll('.sidebar-account-trigger, .mobile-account-chip');
|
||
Array.from(triggers).find(button => button.getClientRects().length)?.focus({preventScroll:true});
|
||
},
|
||
|
||
initials() {
|
||
const name = this.profile?.name || '';
|
||
return name.trim().charAt(0) || '?';
|
||
},
|
||
|
||
format(value) {
|
||
return new Intl.NumberFormat().format(value || 0);
|
||
},
|
||
|
||
duration(minutes) {
|
||
let value = Number(minutes || 0);
|
||
const units = [
|
||
['y', 525600],
|
||
['mo', 43800],
|
||
['d', 1440],
|
||
['h', 60],
|
||
['m', 1],
|
||
];
|
||
const parts = [];
|
||
for (const [label, size] of units) {
|
||
if (value >= size) {
|
||
const count = Math.floor(value / size);
|
||
value -= count * size;
|
||
parts.push(count + label);
|
||
}
|
||
if (parts.length >= 2) break;
|
||
}
|
||
return parts.length ? parts.join(' ') : '0m';
|
||
},
|
||
|
||
logout() {
|
||
window.location.href = '/logout';
|
||
},
|
||
});
|
||
|
||
// -----------------------------------------------------------------------
|
||
// Player store
|
||
// -----------------------------------------------------------------------
|
||
let playbackConnection = new AbortController();
|
||
let releaseSessionArtwork, sessionMetadataKey;
|
||
let pendingMedia = null, audioObjectUrl = null, audibleTrackId = null;
|
||
|
||
// Firefox updates onLine before delivering the offline event that switches the catalog.
|
||
function deviceSyncUnavailable() { return playerOffline() || navigator.onLine === false; }
|
||
|
||
function detachAudio() {
|
||
if (audio.hasAttribute('src')) {
|
||
audio.removeAttribute('src');
|
||
audio.load();
|
||
}
|
||
if (audioObjectUrl) URL.revokeObjectURL(audioObjectUrl);
|
||
audioObjectUrl = null;
|
||
}
|
||
window.addEventListener('furumusic:offline-mode', () => {
|
||
playbackConnection.abort();
|
||
playbackConnection = new AbortController();
|
||
Alpine.store('player')._updateMediaSession();
|
||
});
|
||
|
||
Alpine.store('player', {
|
||
currentTrack: null,
|
||
isPlaying: false,
|
||
currentTime: 0,
|
||
duration: 0,
|
||
volume: 0.7,
|
||
_prevVolume: 0.7,
|
||
_volumeCurve: 2.4,
|
||
shuffle: false,
|
||
repeatMode: 'off', // off, all, one
|
||
progress: 0,
|
||
_saveTimer: null,
|
||
_historyRecorded: false,
|
||
_historyTrack: null,
|
||
_nowPlayingSent: false,
|
||
_playbackStartedAt: null,
|
||
_listenId: null,
|
||
_listenedSeconds: 0,
|
||
_lastAudioTime: 0,
|
||
_localSourceTrackId: null,
|
||
_offlinePlaybackHeld: false,
|
||
_remoteExecuting: false,
|
||
_remoteStateBaseTime: 0,
|
||
_remoteStateReceivedAt: 0,
|
||
_remoteStateTimer: null,
|
||
_prefetchedQueueKey: null,
|
||
_baseDocumentTitle: '',
|
||
|
||
_hasInitialShareLink() { return !!SHARE_TOKEN; },
|
||
|
||
init() {
|
||
audio.volume = this.volume;
|
||
this._baseDocumentTitle = document.title.replace(/^▶\s*/, '');
|
||
Alpine.effect(() => {
|
||
document.title = `${this.isPlaying ? '▶ ' : ''}${this._baseDocumentTitle}`;
|
||
});
|
||
|
||
audio.addEventListener('timeupdate', () => {
|
||
// Loading or losing an HTTP source can report a zero position before cache recovery.
|
||
if (pendingMedia || audio.error || !audio.readyState) return;
|
||
this.currentTime = audio.currentTime;
|
||
this.duration = audio.duration || 0;
|
||
this.progress = this.duration > 0 ? (this.currentTime / this.duration) * 100 : 0;
|
||
Alpine.store('podcasts')?.tick(this);
|
||
this._trackListenedDelta();
|
||
this._maybePrefetchNext();
|
||
});
|
||
|
||
audio.addEventListener('ended', () => {
|
||
if (pendingMedia || !audio.ended || (playerOffline() && this._offlinePlaybackHeld)) return;
|
||
audibleTrackId = null;
|
||
if (this.currentTrack?.podcast) {
|
||
this.isPlaying = false;
|
||
this.currentTrack.podcast_completed = true;
|
||
Alpine.store('podcasts')?.checkpoint(this, true);
|
||
return;
|
||
}
|
||
this._trackListenedDelta();
|
||
this._recordHistory('finished');
|
||
if (Alpine.store('devices')?.shouldPlayJamLocally()) {
|
||
this.isPlaying = false;
|
||
return;
|
||
}
|
||
this.next();
|
||
});
|
||
|
||
audio.addEventListener('playing', () => {
|
||
if (pendingMedia || audio.paused || (playerOffline() && this._offlinePlaybackHeld)) return;
|
||
audibleTrackId = this._localSourceTrackId;
|
||
if (!this._cachePlayCounted && Alpine.store('offline')?.enabled) {
|
||
this._cachePlayCounted = true;
|
||
Alpine.store('offline').played(this.currentTrack);
|
||
}
|
||
});
|
||
audio.addEventListener('play', () => {
|
||
if (pendingMedia || audio.paused || (playerOffline() && this._offlinePlaybackHeld)) return;
|
||
this.isPlaying = true;
|
||
if (!this._playbackStartedAt) this._playbackStartedAt = Math.floor(Date.now() / 1000);
|
||
this._lastAudioTime = audio.currentTime || 0;
|
||
this._sendNowPlaying();
|
||
});
|
||
audio.addEventListener('pause', () => {
|
||
if (pendingMedia || !audio.paused) return;
|
||
if (this.currentTrack?.podcast) Alpine.store('podcasts')?.checkpoint(this, !!this.currentTrack.podcast_completed);
|
||
this._trackListenedDelta();
|
||
this.isPlaying = false;
|
||
this._lastAudioTime = audio.currentTime || 0;
|
||
});
|
||
|
||
audio.addEventListener('loadedmetadata', () => {
|
||
this.duration = audio.duration || 0;
|
||
});
|
||
audio.addEventListener('error', () => {
|
||
const offline = Alpine.store('offline'), track = this.currentTrack;
|
||
if (!audio.error || pendingMedia || audioObjectUrl || !offline?.enabled || offline.active ||
|
||
!track || track.id !== this._localSourceTrackId) return;
|
||
// A native media load can fail before fetch or navigator notices the outage.
|
||
offline.networkResult(false);
|
||
if (!offline.active && this._isLocalPlaybackDevice() && audibleTrackId === track.id && offline.isSaved(track)) {
|
||
this._loadSource(track, this.currentTime, false, true);
|
||
}
|
||
});
|
||
|
||
// Periodic state save
|
||
this._saveTimer = setInterval(() => {
|
||
if (this._isLocalPlaybackDevice()) this._saveState();
|
||
}, 10000);
|
||
this._remoteStateTimer = setInterval(() => {
|
||
this._tickRemoteProgress();
|
||
}, 250);
|
||
|
||
// Restore state
|
||
if (!this._hasInitialShareLink()) {
|
||
this._restoreState();
|
||
}
|
||
|
||
// Save state on page unload
|
||
window.addEventListener('pagehide', (event) => {
|
||
if (this._isLocalPlaybackDevice()) {
|
||
this._saveStateSync();
|
||
this._recordHistory('stopped', true);
|
||
}
|
||
if (!event.persisted) {
|
||
releaseSessionArtwork?.();
|
||
releaseSessionArtwork = sessionMetadataKey = null;
|
||
pendingMedia = null;
|
||
if (audioObjectUrl) detachAudio();
|
||
}
|
||
});
|
||
window.addEventListener('pageshow', (event) => {
|
||
if (event.persisted && this._historyRecorded) {
|
||
this._historyRecorded = false;
|
||
this._resetPlaybackTracking();
|
||
this._lastAudioTime = audio.currentTime || 0;
|
||
if (this.isPlaying) this._playbackStartedAt = Math.floor(Date.now() / 1000);
|
||
}
|
||
});
|
||
},
|
||
|
||
play(track) {
|
||
if (!track) return;
|
||
if (this._shouldSendRemote()) {
|
||
this._mirrorRemoteTrack(track, true, 0);
|
||
if (this._shouldMirrorRemoteLocally()) {
|
||
this._playLocal(track, {
|
||
position_seconds: 0,
|
||
paused: false,
|
||
});
|
||
}
|
||
this._sendRemote('play_track', this._remotePlaybackPayload(track, {
|
||
position_seconds: 0,
|
||
paused: false,
|
||
}));
|
||
return;
|
||
}
|
||
this._playLocal(track);
|
||
},
|
||
|
||
playQueueIndex(idx) {
|
||
const queue = Alpine.store('queue');
|
||
if (!queue || idx < 0 || idx >= queue.tracks.length) return;
|
||
queue.currentIndex = idx;
|
||
const track = queue.tracks[idx];
|
||
if (track?.federation_pending && track?._federationTrack) {
|
||
Alpine.store('library')?.playFederatedTrack(track._federationTrack, {
|
||
queueIndex: idx,
|
||
});
|
||
return;
|
||
}
|
||
if (this._shouldSendRemote()) {
|
||
this._mirrorRemoteTrack(track, true, 0);
|
||
if (this._shouldMirrorRemoteLocally()) {
|
||
this._playLocal(track, {
|
||
position_seconds: 0,
|
||
paused: false,
|
||
});
|
||
}
|
||
this._sendRemote('play_from_index', this._remotePlaybackPayload(track, {
|
||
index: idx,
|
||
position_seconds: 0,
|
||
paused: false,
|
||
}));
|
||
return;
|
||
}
|
||
this._playLocal(track);
|
||
},
|
||
|
||
_maybePrefetchNext() {
|
||
if (playerOffline()) return;
|
||
if (this.currentTrack?.podcast) return;
|
||
if (this.progress < 90 || !this.isPlaying) return;
|
||
const queue = Alpine.store('queue');
|
||
const nextIndex = queue?.currentIndex + 1;
|
||
if (!queue || nextIndex < 0 || nextIndex >= queue.tracks.length) return;
|
||
const next = queue.tracks[nextIndex];
|
||
if (!next?.federation_pending || !next?._federationTrack) return;
|
||
const key = next.content_id || next.id;
|
||
if (!key || this._prefetchedQueueKey === key) return;
|
||
this._prefetchedQueueKey = key;
|
||
Alpine.store('library')?.playFederatedTrack(next._federationTrack, {
|
||
queueIndex: nextIndex,
|
||
playAfterPrepare: false,
|
||
});
|
||
},
|
||
|
||
_playLocal(track, options = {}) {
|
||
if (!options.paused) this._offlinePlaybackHeld = false;
|
||
if (this.currentTrack?.podcast) Alpine.store('podcasts')?.checkpoint(this, !!this.currentTrack.podcast_completed);
|
||
this._recordHistory('replaced');
|
||
this._cachePlayCounted = false;
|
||
this._offlineSession = playerOffline() || !!track.offline_remote;
|
||
this.currentTrack = track;
|
||
this._historyTrack = track;
|
||
this._prefetchedQueueKey = null;
|
||
Alpine.store('queue')?.syncCurrentIndexToTrack(track);
|
||
this._localSourceTrackId = track.id;
|
||
this._historyRecorded = false;
|
||
this._resetPlaybackTracking();
|
||
const seekSeconds = Number(options.position_seconds || 0);
|
||
this.currentTime = seekSeconds;
|
||
this.duration = Number(track.duration_seconds || 0);
|
||
this.progress = this.duration > 0 ? seekSeconds / this.duration * 100 : 0;
|
||
this._updateMediaSession();
|
||
return this._loadSource(track, seekSeconds, !!options.paused);
|
||
},
|
||
|
||
async _loadSource(track, position, paused, recoverStream = false) {
|
||
const offline = Alpine.store('offline');
|
||
const localOnly = () => recoverStream || !!track.offline_remote || offline?.active || (offline?.enabled && navigator.onLine === false);
|
||
this._seekOnLoad(0);
|
||
pendingMedia = null;
|
||
audibleTrackId = null;
|
||
if (localOnly() || (offline?.enabled && offline.isSaved(track))) {
|
||
// Media requests can fail in browser offline mode before reaching the service worker.
|
||
// Keep the actual File in the media pipeline, with native seeking and streaming.
|
||
const request = pendingMedia = {position, paused, recoverStream};
|
||
detachAudio();
|
||
this.isPlaying = false;
|
||
const file = await offline.openAudio(track).catch(() => null);
|
||
if (pendingMedia !== request) return;
|
||
pendingMedia = null;
|
||
if (file) audioObjectUrl = URL.createObjectURL(file);
|
||
else if (localOnly()) {
|
||
this._localSourceTrackId = null;
|
||
return;
|
||
}
|
||
({position, paused} = request);
|
||
} else if (audioObjectUrl) {
|
||
detachAudio();
|
||
}
|
||
audio.src = audioObjectUrl || track.stream_url;
|
||
this._seekOnLoad(position);
|
||
if (paused) {
|
||
audio.pause();
|
||
this.isPlaying = false;
|
||
} else {
|
||
audio.play().catch(() => {});
|
||
}
|
||
},
|
||
|
||
_seekOnLoad(seconds) {
|
||
if (this._pendingSeek) audio.removeEventListener('loadedmetadata', this._pendingSeek);
|
||
this._pendingSeek = null;
|
||
if (seconds <= 0) return;
|
||
this._pendingSeek = () => {
|
||
audio.currentTime = seconds;
|
||
this._lastAudioTime = audio.currentTime || 0;
|
||
this._pendingSeek = null;
|
||
};
|
||
audio.addEventListener('loadedmetadata', this._pendingSeek, {once:true});
|
||
},
|
||
|
||
_pauseLocal() {
|
||
audibleTrackId = null;
|
||
if (pendingMedia) pendingMedia.paused = true;
|
||
if (playerOffline()) this._offlinePlaybackHeld = true;
|
||
audio.pause();
|
||
this.isPlaying = false;
|
||
},
|
||
|
||
prepareForOffline() {
|
||
// Read the online owner before offline mode makes this tab the active device.
|
||
// Jam monitoring can play real local audio on a tab that only controls the owner.
|
||
const ownedPlayback = this._isLocalPlaybackDevice();
|
||
const lostStream = (audio.error && audibleTrackId === this._localSourceTrackId) ||
|
||
(pendingMedia?.recoverStream && !pendingMedia.paused);
|
||
this._offlinePlaybackHeld = !ownedPlayback || ((!this.isPlaying || audio.paused) && !lostStream) || audio.ended ||
|
||
!this.currentTrack || this.currentTrack.id !== this._localSourceTrackId;
|
||
if (this._offlinePlaybackHeld) this._pauseLocal();
|
||
if (!ownedPlayback) this._cachePlayCounted = false;
|
||
},
|
||
|
||
useOfflineCatalog(saved) {
|
||
const byId = new Map(saved.map(t => [Number(t.id), t]));
|
||
const byContent = new Map(saved.filter(t => t.content_id).map(t => [t.content_id, t]));
|
||
const lookup = track => {
|
||
if (!track) return null;
|
||
const local = byId.get(OfflineCatalog.trackId(track));
|
||
return local && (!track.content_id || !local.content_id || local.content_id === track.content_id)
|
||
? local : byContent.get(track.content_id);
|
||
};
|
||
const queue = Alpine.store('queue');
|
||
queue.tracks = queue.tracks.map(lookup).filter(Boolean);
|
||
const previous = this.currentTrack;
|
||
const cached = lookup(previous);
|
||
if (cached) {
|
||
queue.syncCurrentIndexToTrack(cached);
|
||
if ((audioObjectUrl || pendingMedia) && this._localSourceTrackId === previous.id) {
|
||
// Already reading this recording locally. Keep its decoder, playhead and play count.
|
||
this.currentTrack = this._historyTrack = cached;
|
||
this._localSourceTrackId = cached.id;
|
||
if (audibleTrackId === previous.id) audibleTrackId = cached.id;
|
||
this._offlineSession = true;
|
||
} else {
|
||
const counted = this._cachePlayCounted;
|
||
this._playLocal(cached, {paused:this._offlinePlaybackHeld, position_seconds:this.currentTime});
|
||
this._cachePlayCounted = counted;
|
||
}
|
||
} else if (previous) {
|
||
this._offlineSession = true;
|
||
this._seekOnLoad(0);
|
||
this._pauseLocal();
|
||
pendingMedia = null;
|
||
detachAudio();
|
||
this.currentTrack = this._historyTrack = this._localSourceTrackId = null;
|
||
this.currentTime = this.progress = this.duration = 0;
|
||
this._updateMediaSession();
|
||
}
|
||
if (!cached) queue.currentIndex = -1;
|
||
Alpine.store('offline').saveState(this._buildStatePayload(true));
|
||
},
|
||
|
||
pause() {
|
||
if (this._shouldSendRemote()) {
|
||
this.isPlaying = false;
|
||
this._remoteStateBaseTime = this.currentTime;
|
||
this._remoteStateReceivedAt = Date.now();
|
||
if (this._shouldMirrorRemoteLocally()) {
|
||
this._pauseLocal();
|
||
}
|
||
this._sendRemote('pause');
|
||
return;
|
||
}
|
||
this._pauseLocal();
|
||
},
|
||
|
||
resume() {
|
||
if (this._shouldSendRemote()) {
|
||
this.isPlaying = true;
|
||
this._remoteStateBaseTime = this.currentTime;
|
||
this._remoteStateReceivedAt = Date.now();
|
||
if (this._shouldMirrorRemoteLocally()) {
|
||
this._resumeLocal();
|
||
}
|
||
this._sendRemote('resume');
|
||
return;
|
||
}
|
||
this._offlinePlaybackHeld = false;
|
||
const offline = Alpine.store('offline');
|
||
const retrySaved = audio.error && !audioObjectUrl && offline?.enabled && offline.isSaved(this.currentTrack);
|
||
if (this.currentTrack && (retrySaved || (playerOffline() && (!this._offlineSession || this._localSourceTrackId !== this.currentTrack.id)))) {
|
||
this._playLocal(this.currentTrack, {position_seconds:this.currentTime});
|
||
return;
|
||
}
|
||
this._resumeLocal();
|
||
},
|
||
|
||
_resumeLocal() {
|
||
if (pendingMedia) pendingMedia.paused = false;
|
||
else audio.play().catch(() => {});
|
||
},
|
||
|
||
toggle() {
|
||
if (!this.currentTrack) return;
|
||
if (this.isPlaying || pendingMedia && !pendingMedia.paused) { this.pause(); }
|
||
else { this.resume(); }
|
||
},
|
||
|
||
seek(time) {
|
||
const nextTime = Math.max(0, Number(time || 0));
|
||
if (this._shouldSendRemote()) {
|
||
this.currentTime = nextTime;
|
||
this.progress = this.duration > 0 ? (this.currentTime / this.duration) * 100 : 0;
|
||
this._remoteStateBaseTime = nextTime;
|
||
this._remoteStateReceivedAt = Date.now();
|
||
if (this._shouldMirrorRemoteLocally() && this._localSourceTrackId === this.currentTrack?.id) {
|
||
audio.currentTime = nextTime;
|
||
this._lastAudioTime = audio.currentTime || 0;
|
||
}
|
||
this._sendRemote('seek', { time: nextTime });
|
||
return;
|
||
}
|
||
if (pendingMedia) {
|
||
pendingMedia.position = this.currentTime = nextTime;
|
||
return;
|
||
}
|
||
if (!audio.readyState) {
|
||
this.currentTime = nextTime;
|
||
this._seekOnLoad(nextTime);
|
||
return;
|
||
}
|
||
audio.currentTime = nextTime;
|
||
this._lastAudioTime = audio.currentTime || 0;
|
||
},
|
||
|
||
seekRelative(delta) {
|
||
if (!this.currentTrack) return;
|
||
const duration = this.duration || audio.duration || 0;
|
||
const current = pendingMedia || !audio.readyState || this._shouldSendRemote() ? this.currentTime : audio.currentTime;
|
||
const max = duration > 0 ? duration : Number.MAX_SAFE_INTEGER;
|
||
this.seek(Math.max(0, Math.min(max, current + delta)));
|
||
},
|
||
|
||
next() {
|
||
if (this._shouldSendRemote()) {
|
||
this._sendRemote('next', {
|
||
shuffle: this.shuffle,
|
||
repeat_mode: this.repeatMode,
|
||
});
|
||
return;
|
||
}
|
||
const queue = Alpine.store('queue');
|
||
if (queue.tracks.length === 0) return;
|
||
|
||
this._recordHistory('skipped');
|
||
|
||
let nextIdx;
|
||
if (this.repeatMode === 'one') {
|
||
this.seek(0);
|
||
this._historyRecorded = false;
|
||
this._resetPlaybackTracking();
|
||
this.resume();
|
||
return;
|
||
} else if (this.shuffle) {
|
||
nextIdx = Math.floor(Math.random() * queue.tracks.length);
|
||
} else {
|
||
nextIdx = queue.currentIndex + 1;
|
||
if (nextIdx >= queue.tracks.length) {
|
||
if (this.repeatMode === 'all') {
|
||
nextIdx = 0;
|
||
} else {
|
||
this.isPlaying = false;
|
||
return;
|
||
}
|
||
}
|
||
}
|
||
this.playQueueIndex(nextIdx);
|
||
},
|
||
|
||
prev() {
|
||
if (this._shouldSendRemote()) {
|
||
this._sendRemote('prev');
|
||
return;
|
||
}
|
||
if (this.currentTime > 3) {
|
||
this.seek(0);
|
||
return;
|
||
}
|
||
const queue = Alpine.store('queue');
|
||
if (queue.tracks.length === 0) return;
|
||
|
||
let prevIdx = queue.currentIndex - 1;
|
||
if (prevIdx < 0) {
|
||
if (this.repeatMode === 'all') {
|
||
prevIdx = queue.tracks.length - 1;
|
||
} else {
|
||
this.seek(0);
|
||
return;
|
||
}
|
||
}
|
||
this.playQueueIndex(prevIdx);
|
||
},
|
||
|
||
setVolume(v) {
|
||
this._setVolumeLocal(v);
|
||
if (this._shouldSendRemote() && !this._shouldMirrorRemoteLocally()) {
|
||
this._sendRemote('set_volume', { volume: this.volume });
|
||
}
|
||
},
|
||
|
||
_setVolumeLocal(v) {
|
||
this.volume = Math.max(0, Math.min(1, Number(v || 0)));
|
||
audio.volume = this.volume;
|
||
},
|
||
|
||
volumeSliderPercent() {
|
||
if (this.volume <= 0) return 0;
|
||
return Math.pow(this.volume, 1 / this._volumeCurve) * 100;
|
||
},
|
||
|
||
_volumeFromSliderPosition(position) {
|
||
const pct = Math.max(0, Math.min(1, Number(position || 0)));
|
||
if (pct <= 0.002) return 0;
|
||
return Math.pow(pct, this._volumeCurve);
|
||
},
|
||
|
||
toggleMute() {
|
||
if (this.volume > 0) {
|
||
this._prevVolume = this.volume;
|
||
this.setVolume(0);
|
||
} else {
|
||
this.setVolume(this._prevVolume || 0.7);
|
||
}
|
||
},
|
||
|
||
toggleShuffle() {
|
||
this.shuffle = !this.shuffle;
|
||
if (this._shouldSendRemote()) {
|
||
this._sendRemote('set_options', {
|
||
shuffle: this.shuffle,
|
||
repeat_mode: this.repeatMode,
|
||
});
|
||
}
|
||
},
|
||
|
||
cycleRepeat() {
|
||
if (this.repeatMode === 'off') this.repeatMode = 'all';
|
||
else if (this.repeatMode === 'all') this.repeatMode = 'one';
|
||
else this.repeatMode = 'off';
|
||
if (this._shouldSendRemote()) {
|
||
this._sendRemote('set_options', {
|
||
shuffle: this.shuffle,
|
||
repeat_mode: this.repeatMode,
|
||
});
|
||
}
|
||
},
|
||
|
||
_isLocalPlaybackDevice() {
|
||
const devices = Alpine.store('devices');
|
||
return !devices || devices.isActive();
|
||
},
|
||
|
||
_shouldSendRemote() {
|
||
const devices = Alpine.store('devices');
|
||
return !!devices && !this._remoteExecuting && !devices.isActive();
|
||
},
|
||
|
||
_shouldMirrorRemoteLocally() {
|
||
return !!Alpine.store('devices')?.shouldPlayJamLocally();
|
||
},
|
||
|
||
_sendRemote(command, payload = {}) {
|
||
const devices = Alpine.store('devices');
|
||
if (!devices) return false;
|
||
devices.sendCommand(command, payload);
|
||
return true;
|
||
},
|
||
|
||
_remotePlaybackPayload(track, overrides = {}) {
|
||
const queue = Alpine.store('queue');
|
||
const tracks = queue?.tracks?.length ? queue._tracksWithJamDefaults(queue.tracks) : (track ? queue?._tracksWithJamDefaults([track]) || [track] : []);
|
||
let index = Number.isInteger(overrides.index) ? overrides.index : (queue?.currentIndex ?? 0);
|
||
if (track && tracks[index]?.id !== track.id) {
|
||
const foundIndex = tracks.findIndex(item => item.id === track.id);
|
||
index = foundIndex >= 0 ? foundIndex : 0;
|
||
}
|
||
return {
|
||
track,
|
||
tracks,
|
||
index,
|
||
position_seconds: overrides.position_seconds ?? this.currentTime,
|
||
duration_seconds: overrides.duration_seconds ?? this._trackDuration(),
|
||
paused: overrides.paused ?? !this.isPlaying,
|
||
shuffle: this.shuffle,
|
||
repeat_mode: this.repeatMode,
|
||
volume: this.volume,
|
||
};
|
||
},
|
||
|
||
_devicePlaybackStatePayload() {
|
||
if (this.currentTrack?.podcast || this._offlineSession) return null;
|
||
const queue = Alpine.store('queue');
|
||
const track = this.currentTrack || queue?.tracks?.[queue.currentIndex] || null;
|
||
if (!track && (!queue || queue.tracks.length === 0)) return null;
|
||
return this._remotePlaybackPayload(track, {
|
||
position_seconds: audio.currentTime || this.currentTime || 0,
|
||
duration_seconds: this._trackDuration(),
|
||
paused: !this.isPlaying,
|
||
});
|
||
},
|
||
|
||
_mirrorRemoteTrack(track, playing, positionSeconds = null) {
|
||
if (!track) return;
|
||
this.currentTrack = track;
|
||
Alpine.store('queue')?.syncCurrentIndexToTrack(track);
|
||
this.isPlaying = !!playing;
|
||
if (positionSeconds !== null) this.currentTime = Math.max(0, Number(positionSeconds || 0));
|
||
this.duration = Number(track.duration_seconds || this.duration || 0);
|
||
this.progress = this.duration > 0 ? (this.currentTime / this.duration) * 100 : 0;
|
||
this._remoteStateBaseTime = this.currentTime;
|
||
this._remoteStateReceivedAt = Date.now();
|
||
this._updateMediaSession();
|
||
},
|
||
|
||
_applyRemotePlaybackState(state) {
|
||
if (!state || deviceSyncUnavailable()) return;
|
||
const queue = Alpine.store('queue');
|
||
const tracks = Array.isArray(state.tracks) ? state.tracks.filter(Boolean) : [];
|
||
if (queue && tracks.length > 0) {
|
||
queue.tracks = queue._tracksWithJamDefaults(tracks);
|
||
queue.currentIndex = Math.max(0, Math.min(Number(state.index || 0), tracks.length - 1));
|
||
}
|
||
const track = state.track || queue?.tracks?.[queue.currentIndex] || null;
|
||
if (track) {
|
||
this.currentTrack = track;
|
||
queue?.syncCurrentIndexToTrack(track);
|
||
}
|
||
this.shuffle = !!state.shuffle;
|
||
this.repeatMode = state.repeat_mode || 'off';
|
||
if (typeof state.volume === 'number') this._setVolumeLocal(state.volume);
|
||
this.duration = Number(state.duration_seconds || track?.duration_seconds || this.duration || 0);
|
||
this.isPlaying = !state.paused;
|
||
this._remoteStateBaseTime = Math.max(0, Number(state.position_seconds || 0));
|
||
this._remoteStateReceivedAt = Date.now();
|
||
this._tickRemoteProgress(true);
|
||
this._updateMediaSession();
|
||
},
|
||
|
||
_syncLocalPlaybackState(state) {
|
||
if (!state || deviceSyncUnavailable()) return;
|
||
const queue = Alpine.store('queue');
|
||
const tracks = Array.isArray(state.tracks) ? state.tracks.filter(Boolean) : [];
|
||
if (queue && tracks.length > 0) {
|
||
queue.tracks = queue._tracksWithJamDefaults(tracks);
|
||
queue.currentIndex = Math.max(0, Math.min(Number(state.index || 0), queue.tracks.length - 1));
|
||
}
|
||
|
||
const track = state.track || queue?.tracks?.[queue.currentIndex] || null;
|
||
if (!track) return;
|
||
|
||
const desiredTime = Math.max(0, Number(state.position_seconds || 0));
|
||
const duration = Number(state.duration_seconds || track.duration_seconds || this.duration || 0);
|
||
this.currentTrack = track;
|
||
this.shuffle = !!state.shuffle;
|
||
this.repeatMode = state.repeat_mode || 'off';
|
||
this.duration = duration;
|
||
this._remoteStateBaseTime = desiredTime;
|
||
this._remoteStateReceivedAt = Date.now();
|
||
|
||
if (this._localSourceTrackId !== track.id) {
|
||
this._playLocal(track, {
|
||
position_seconds: desiredTime,
|
||
paused: !!state.paused,
|
||
});
|
||
} else if (pendingMedia) {
|
||
pendingMedia.position = desiredTime;
|
||
pendingMedia.paused = !!state.paused;
|
||
} else {
|
||
const drift = Math.abs((audio.currentTime || 0) - desiredTime);
|
||
const driftLimit = state.paused ? 0.08 : 0.75;
|
||
if (drift > driftLimit) {
|
||
audio.currentTime = desiredTime;
|
||
this._lastAudioTime = audio.currentTime || 0;
|
||
}
|
||
if (state.paused) {
|
||
if (!audio.paused) audio.pause();
|
||
this.isPlaying = false;
|
||
} else if (audio.paused) {
|
||
audio.play().catch(() => {});
|
||
this.isPlaying = true;
|
||
} else {
|
||
this.isPlaying = true;
|
||
}
|
||
}
|
||
|
||
this.currentTime = audio.currentTime || desiredTime;
|
||
this.progress = duration > 0 ? (this.currentTime / duration) * 100 : 0;
|
||
this._updateMediaSession();
|
||
},
|
||
|
||
_tickRemoteProgress(force = false) {
|
||
if (this._isLocalPlaybackDevice() || this._shouldMirrorRemoteLocally() || !this.currentTrack) return;
|
||
if (!force && !this.isPlaying) return;
|
||
let nextTime = Number(this._remoteStateBaseTime || 0);
|
||
if (this.isPlaying && this._remoteStateReceivedAt > 0) {
|
||
nextTime += (Date.now() - this._remoteStateReceivedAt) / 1000;
|
||
}
|
||
const duration = Number(this.duration || this.currentTrack?.duration_seconds || 0);
|
||
if (duration > 0) nextTime = Math.min(nextTime, duration);
|
||
this.currentTime = Math.max(0, nextTime);
|
||
this.progress = duration > 0 ? (this.currentTime / duration) * 100 : 0;
|
||
},
|
||
|
||
_executeRemoteCommand(command) {
|
||
if (!command?.command || deviceSyncUnavailable()) return;
|
||
const payload = command.payload || {};
|
||
const queue = Alpine.store('queue');
|
||
this._remoteExecuting = true;
|
||
try {
|
||
if (typeof payload.shuffle === 'boolean') this.shuffle = payload.shuffle;
|
||
if (payload.repeat_mode) this.repeatMode = payload.repeat_mode;
|
||
if (typeof payload.volume === 'number') this._setVolumeLocal(payload.volume);
|
||
|
||
if (command.command === 'play_track' || command.command === 'play_from_index' || command.command === 'transfer_state') {
|
||
if (Array.isArray(payload.tracks) && payload.tracks.length > 0) {
|
||
queue.tracks = queue._tracksWithJamDefaults(payload.tracks);
|
||
queue.currentIndex = Math.max(0, Math.min(Number(payload.index || 0), queue.tracks.length - 1));
|
||
}
|
||
const track = payload.track || queue.tracks[queue.currentIndex];
|
||
if (track?.unavailable || (track && !track.stream_url)) {
|
||
this._applyRemotePlaybackState({ ...payload, track, paused: true });
|
||
this._pauseLocal();
|
||
} else if (track) {
|
||
this._playLocal(track, payload);
|
||
}
|
||
} else if (command.command === 'pause') {
|
||
this.pause();
|
||
} else if (command.command === 'resume') {
|
||
this.resume();
|
||
} else if (command.command === 'seek') {
|
||
this.seek(Number(payload.time || 0));
|
||
} else if (command.command === 'next') {
|
||
this.next();
|
||
} else if (command.command === 'prev') {
|
||
this.prev();
|
||
} else if (command.command === 'set_volume') {
|
||
this.setVolume(payload.volume);
|
||
} else if (command.command === 'set_options') {
|
||
// Options were already applied above.
|
||
} else if (command.command === 'queue_add_end') {
|
||
queue._addToEndLocal(payload.tracks || []);
|
||
} else if (command.command === 'queue_add_next') {
|
||
queue._addNextLocal(payload.tracks || []);
|
||
} else if (command.command === 'queue_remove') {
|
||
queue._removeLocal(Number(payload.index));
|
||
} else if (command.command === 'queue_move') {
|
||
queue._moveTrackLocal(Number(payload.from_index), Number(payload.to_index));
|
||
} else if (command.command === 'queue_clear') {
|
||
queue._clearLocal();
|
||
}
|
||
this._saveState();
|
||
Alpine.store('devices')?.heartbeat();
|
||
} finally {
|
||
this._remoteExecuting = false;
|
||
}
|
||
},
|
||
|
||
_updateMediaSession() {
|
||
if (!('mediaSession' in navigator)) return;
|
||
const t = this.currentTrack;
|
||
const artist = Array.isArray(t?.artists) ? t.artists.map(a => a?.name || a).join(', ') : '';
|
||
const cover = typeof t?.cover_url === 'string' ? coverVariantUrl(t.cover_url, 'large') : null;
|
||
const key = t && JSON.stringify([t.id, t.title, artist, cover, Alpine.store('offline').localArtworkOnly]);
|
||
if (key === sessionMetadataKey) return;
|
||
sessionMetadataKey = key;
|
||
releaseSessionArtwork?.();
|
||
releaseSessionArtwork = null;
|
||
// OS media controls are optional. An unsupported action or image must never interrupt audio.
|
||
try {
|
||
const metadata = t ? new MediaMetadata({title:t.title, artist}) : null;
|
||
navigator.mediaSession.metadata = metadata;
|
||
if (!metadata) return;
|
||
if (cover) releaseSessionArtwork = Alpine.store('offline').bindArtwork(cover, src => {
|
||
try {
|
||
// Firefox requires absolute URLs for MediaImage, including online covers.
|
||
metadata.artwork = src ? [{src:new URL(src, document.baseURI).href}] : [];
|
||
} catch { /* Keep the text if the platform rejects this artwork. */ }
|
||
});
|
||
navigator.mediaSession.setActionHandler('play', () => this.resume());
|
||
navigator.mediaSession.setActionHandler('pause', () => this.pause());
|
||
navigator.mediaSession.setActionHandler('previoustrack', () => this.prev());
|
||
navigator.mediaSession.setActionHandler('nexttrack', () => this.next());
|
||
navigator.mediaSession.setActionHandler('seekto', d => { if (d.seekTime != null) this.seek(d.seekTime); });
|
||
} catch { /* Playback does not depend on Media Session support. */ }
|
||
},
|
||
|
||
_buildStatePayload(forDeviceCache = false) {
|
||
const queue = Alpine.store('queue');
|
||
const idFor = track => {
|
||
if (!track) return null;
|
||
if (forDeviceCache && globalThis.OfflineCatalog) return OfflineCatalog.trackId(track);
|
||
return !track.offline_remote && Number.isInteger(Number(track.id)) ? Number(track.id) : null;
|
||
};
|
||
const ids = queue.tracks.map(idFor).filter(id => id !== null);
|
||
const currentLocalId = idFor(this.currentTrack);
|
||
if (forDeviceCache && currentLocalId !== null && !ids.includes(currentLocalId)) ids.unshift(currentLocalId);
|
||
return {
|
||
current_track_id: currentLocalId,
|
||
position_ms: Math.floor(this.currentTime * 1000),
|
||
queue: ids,
|
||
queue_position: currentLocalId == null
|
||
? 0
|
||
: Math.max(0, ids.indexOf(currentLocalId)),
|
||
shuffle: this.shuffle,
|
||
repeat_mode: this.repeatMode,
|
||
volume: this.volume,
|
||
};
|
||
},
|
||
|
||
_saveState() {
|
||
if (!GUEST && this.currentTrack && Alpine.store('offline')?.enabled) Alpine.store('offline').saveState(this._buildStatePayload(true));
|
||
if (playerOffline() || this._offlineSession) return;
|
||
if (this.currentTrack?.podcast) { Alpine.store('podcasts')?.checkpoint(this, !!this.currentTrack.podcast_completed); return; }
|
||
if (GUEST) return;
|
||
const queue = Alpine.store('queue');
|
||
if (!this.currentTrack && queue.tracks.length === 0) return;
|
||
const state = this._buildStatePayload();
|
||
fetch('/api/player/state', {
|
||
method: 'PUT',
|
||
headers: { 'Content-Type': 'application/json' },
|
||
body: JSON.stringify(state),
|
||
}).catch(() => {});
|
||
},
|
||
|
||
_saveStateSync() {
|
||
if (!GUEST && this.currentTrack && Alpine.store('offline')?.enabled) Alpine.store('offline').saveState(this._buildStatePayload(true));
|
||
if (playerOffline() || this._offlineSession) return;
|
||
if (this.currentTrack?.podcast) { Alpine.store('podcasts')?.checkpoint(this, !!this.currentTrack.podcast_completed, true); return; }
|
||
if (GUEST) return;
|
||
const queue = Alpine.store('queue');
|
||
if (!this.currentTrack && queue.tracks.length === 0) return;
|
||
const state = this._buildStatePayload();
|
||
const blob = new Blob([JSON.stringify(state)], { type: 'application/json' });
|
||
navigator.sendBeacon('/api/player/state', blob);
|
||
},
|
||
|
||
async _restoreState() {
|
||
if (GUEST) return;
|
||
const {signal} = playbackConnection;
|
||
try {
|
||
const offline = playerOffline();
|
||
const initialTrack = this.currentTrack;
|
||
let state;
|
||
if (offline) state = Alpine.store('offline').state();
|
||
else {
|
||
const res = await fetch('/api/player/state', { signal });
|
||
if (!res.ok || playerOffline()) return;
|
||
state = await res.json();
|
||
}
|
||
if (signal.aborted || playerOffline() !== offline || this.currentTrack !== initialTrack) return;
|
||
this.shuffle = state.shuffle || false;
|
||
this.repeatMode = state.repeat_mode || 'off';
|
||
this._setVolumeLocal(typeof state.volume === 'number' ? state.volume : 0.7);
|
||
|
||
// Restore queue if there are track IDs
|
||
if (state.queue && state.queue.length > 0) {
|
||
try {
|
||
const tracksRes = await fetch('/api/player/tracks-by-ids', {
|
||
method: 'POST',
|
||
headers: { 'Content-Type': 'application/json' },
|
||
body: JSON.stringify({ ids: state.queue }),
|
||
signal,
|
||
});
|
||
if (tracksRes.ok) {
|
||
const tracks = await tracksRes.json();
|
||
if (signal.aborted || playerOffline() !== offline || this.currentTrack !== initialTrack) return;
|
||
if (tracks.length > 0) {
|
||
const queue = Alpine.store('queue');
|
||
queue.tracks = tracks;
|
||
const idx = Math.max(0, Math.min(state.queue_position, tracks.length - 1));
|
||
queue.currentIndex = idx;
|
||
|
||
// Restore current track
|
||
const currentTrack = state.current_track_id
|
||
? tracks.find(t => t.id === state.current_track_id)
|
||
: tracks[idx];
|
||
if (currentTrack) {
|
||
this.currentTrack = currentTrack;
|
||
this._historyTrack = currentTrack;
|
||
this._offlineSession = offline;
|
||
this._cachePlayCounted = false;
|
||
queue.syncCurrentIndexToTrack(currentTrack);
|
||
this._localSourceTrackId = currentTrack.id;
|
||
this._historyRecorded = false;
|
||
this._resetPlaybackTracking();
|
||
this.currentTime = (state.position_ms || 0) / 1000;
|
||
this._loadSource(currentTrack, this.currentTime, true);
|
||
this._updateMediaSession();
|
||
}
|
||
}
|
||
}
|
||
} catch {}
|
||
}
|
||
} catch {}
|
||
},
|
||
|
||
_recordHistory(endedReason, unloading = false) {
|
||
if (GUEST || playerOffline() || this._offlineSession) return;
|
||
const track = this._historyTrack;
|
||
if (this._historyRecorded || !track || !this._playbackStartedAt) return;
|
||
if (!Number.isInteger(Number(track.id)) || track.federated_cache) return;
|
||
this._trackListenedDelta();
|
||
const completed = endedReason === 'finished';
|
||
const listenedSeconds = this._historyListenedSeconds(completed);
|
||
if (!completed && listenedSeconds < 5) return;
|
||
const listenId = this._listenId;
|
||
const body = JSON.stringify({
|
||
track_id: track.id,
|
||
listen_id: listenId,
|
||
started_at: this._playbackStartedAt,
|
||
duration_listened: listenedSeconds,
|
||
completed,
|
||
ended_reason: endedReason,
|
||
});
|
||
this._historyRecorded = true;
|
||
if (unloading && navigator.sendBeacon('/api/player/history', new Blob([body], {type:'application/json'}))) return;
|
||
// Retry the captured event, never the next track. The server deduplicates by listen_id.
|
||
const send = async () => {
|
||
for (let attempt = 0; attempt < 3; attempt++) {
|
||
if (playerOffline()) return;
|
||
try {
|
||
const response = await fetch('/api/player/history', {
|
||
method: 'POST', headers: {'Content-Type':'application/json'}, body, keepalive: true,
|
||
});
|
||
if (response.ok) return;
|
||
if (response.status >= 400 && response.status < 500) break;
|
||
} catch (_) {}
|
||
if (attempt < 2) await new Promise(resolve => setTimeout(resolve, 500 * (attempt + 1)));
|
||
}
|
||
if (this._listenId === listenId) this._historyRecorded = false;
|
||
};
|
||
send();
|
||
},
|
||
|
||
_resetPlaybackTracking() {
|
||
this._nowPlayingSent = false;
|
||
this._playbackStartedAt = null;
|
||
this._listenId = (globalThis.crypto?.randomUUID?.()
|
||
|| `${Date.now()}-${Math.random().toString(16).slice(2)}`);
|
||
this._listenedSeconds = 0;
|
||
this._lastAudioTime = 0;
|
||
},
|
||
|
||
_trackListenedDelta() {
|
||
if (!this.currentTrack) return;
|
||
const current = audio.currentTime || 0;
|
||
if (!this.isPlaying) {
|
||
this._lastAudioTime = current;
|
||
return;
|
||
}
|
||
const previous = Number.isFinite(this._lastAudioTime) ? this._lastAudioTime : current;
|
||
const delta = current - previous;
|
||
if (delta > 0 && delta < 5) {
|
||
this._listenedSeconds += delta;
|
||
}
|
||
this._lastAudioTime = current;
|
||
},
|
||
|
||
_trackDuration() {
|
||
const candidates = [
|
||
this.currentTrack?.duration_seconds,
|
||
this.duration,
|
||
audio.duration,
|
||
];
|
||
for (const value of candidates) {
|
||
const duration = Number(value || 0);
|
||
if (Number.isFinite(duration) && duration > 0) return duration;
|
||
}
|
||
return 0;
|
||
},
|
||
|
||
_scrobbleThreshold(duration) {
|
||
return Math.min(duration / 2, 240);
|
||
},
|
||
|
||
_historyListenedSeconds(completed) {
|
||
// Seeking is not listening time. Allow rounding grace only at a natural finish.
|
||
return Math.max(0, Math.floor(Number(this._listenedSeconds || 0) + (completed ? 1 : 0)));
|
||
},
|
||
|
||
_sendNowPlaying() {
|
||
if (playerOffline() || this._offlineSession) return;
|
||
if (GUEST) return;
|
||
if (this._nowPlayingSent || !this.currentTrack) return;
|
||
if (!Number.isInteger(Number(this.currentTrack.id)) || this.currentTrack.federated_cache) {
|
||
return;
|
||
}
|
||
const lastfm = Alpine.store('user')?.lastfm;
|
||
if (!lastfm?.configured || !lastfm?.connected || lastfm?.reauth_required) return;
|
||
this._nowPlayingSent = true;
|
||
fetch('/api/player/lastfm/now-playing', {
|
||
method: 'POST',
|
||
headers: { 'Content-Type': 'application/json' },
|
||
body: JSON.stringify({ track_id: this.currentTrack.id }),
|
||
}).catch(() => {});
|
||
},
|
||
});
|
||
|
||
// -----------------------------------------------------------------------
|
||
// Playback devices store
|
||
// -----------------------------------------------------------------------
|
||
Alpine.store('devices', {
|
||
id: null,
|
||
devices: [],
|
||
jams: [],
|
||
activeDeviceId: null,
|
||
currentJamId: null,
|
||
open: false,
|
||
jamPanelOpen: false,
|
||
jamPanelMode: 'create',
|
||
jamPanelJamId: null,
|
||
jamQuery: '',
|
||
jamUsers: [],
|
||
jamSelectedUsers: [],
|
||
jamSearching: false,
|
||
jamLocalPlayback: false,
|
||
fed: null,
|
||
fedInvite: '',
|
||
fedInviteInput: '',
|
||
fedBusy: false,
|
||
fedError: '',
|
||
remoteHintVisible: false,
|
||
remoteHintDeviceName: '',
|
||
_remoteHintShown: false,
|
||
_remoteHintTimer: null,
|
||
_pollTimer: null,
|
||
_jamSearchTimer: null,
|
||
_fedRefreshTick: 0,
|
||
_stateRefreshTick: 0,
|
||
_lastPlaybackState: null,
|
||
|
||
init() {
|
||
if (GUEST) return;
|
||
this.id = this._ensureId();
|
||
this.currentJamId = sessionStorage.getItem('furu_player_jam_id') || null;
|
||
window.addEventListener('furumusic:offline-mode', ({detail}) => {
|
||
if (detail.active) {
|
||
if (this.remoteHintVisible) this.dismissRemoteHint();
|
||
this._lastPlaybackState = null;
|
||
}
|
||
});
|
||
this.heartbeat();
|
||
this.loadFedDevices();
|
||
this._pollTimer = setInterval(() => this.poll(), 500);
|
||
document.addEventListener('visibilitychange', () => {
|
||
if (!document.hidden) {
|
||
this.poll();
|
||
this.loadFedDevices();
|
||
}
|
||
});
|
||
},
|
||
|
||
_ensureId() {
|
||
let id = sessionStorage.getItem('furu_player_device_id');
|
||
if (!id) {
|
||
id = (crypto.randomUUID ? crypto.randomUUID() : this._fallbackId()).replace(/[^a-zA-Z0-9_-]/g, '');
|
||
sessionStorage.setItem('furu_player_device_id', id);
|
||
}
|
||
return id;
|
||
},
|
||
|
||
_fallbackId() {
|
||
return 'device-' + Date.now().toString(36) + '-' + Math.random().toString(36).slice(2);
|
||
},
|
||
|
||
requestPayload() {
|
||
const player = Alpine.store('player');
|
||
return {
|
||
device_id: this.id,
|
||
user_agent: navigator.userAgent || '',
|
||
current_jam_id: this.currentJamId,
|
||
playback_state: player && this.isActive() ? player._devicePlaybackStatePayload() : null,
|
||
};
|
||
},
|
||
|
||
async _requestState(path, payload) {
|
||
if (deviceSyncUnavailable()) return null;
|
||
const {signal} = playbackConnection;
|
||
const res = await fetch(path, {
|
||
method: 'POST', headers: { 'Content-Type': 'application/json' },
|
||
body: JSON.stringify(payload), signal,
|
||
});
|
||
if (!res.ok) return null;
|
||
const data = await res.json();
|
||
return signal.aborted || deviceSyncUnavailable() ? null : data;
|
||
},
|
||
|
||
async heartbeat() {
|
||
if (deviceSyncUnavailable()) return;
|
||
try {
|
||
const data = await this._requestState('/api/player/devices/heartbeat', this.requestPayload());
|
||
if (data) this._apply(data);
|
||
} catch {}
|
||
},
|
||
|
||
async poll() {
|
||
if (deviceSyncUnavailable()) return;
|
||
try {
|
||
const data = await this._requestState('/api/player/devices/poll', this.requestPayload());
|
||
if (!data) return;
|
||
this._apply(data);
|
||
if (this.open || (++this._fedRefreshTick % 10 === 0)) {
|
||
this.loadFedDevices();
|
||
}
|
||
|
||
const player = Alpine.store('player');
|
||
if (player && (this.isActive() || this.shouldPlayJamLocally()) && Array.isArray(data.commands)) {
|
||
data.commands.forEach(command => player._executeRemoteCommand(command));
|
||
}
|
||
if (player && !this.isActive()) {
|
||
if (data.playback_state) {
|
||
if (this.shouldPlayJamLocally()) {
|
||
player._syncLocalPlaybackState(data.playback_state);
|
||
} else {
|
||
player._applyRemotePlaybackState(data.playback_state);
|
||
}
|
||
} else if (++this._stateRefreshTick % 8 === 0) {
|
||
player._restoreState();
|
||
}
|
||
}
|
||
} catch {}
|
||
},
|
||
|
||
_apply(data) {
|
||
if (deviceSyncUnavailable()) return;
|
||
const previousJamId = this.currentJamId;
|
||
this.activeDeviceId = data.active_device_id || null;
|
||
this.devices = Array.isArray(data.devices) ? data.devices : [];
|
||
this.jams = Array.isArray(data.jams) ? data.jams : [];
|
||
if (data.playback_state) this._lastPlaybackState = data.playback_state;
|
||
if (data.current_jam_id) {
|
||
this.currentJamId = data.current_jam_id;
|
||
sessionStorage.setItem('furu_player_jam_id', this.currentJamId);
|
||
} else if (this.currentJamId && !this.jams.some(jam => jam.id === this.currentJamId)) {
|
||
this.currentJamId = null;
|
||
sessionStorage.removeItem('furu_player_jam_id');
|
||
}
|
||
if (previousJamId !== this.currentJamId || !this.canPlayJamLocally()) {
|
||
this._setJamLocalPlayback(false, { pauseLocal: true });
|
||
}
|
||
if (!this.isActive() && !this.shouldPlayJamLocally()) {
|
||
Alpine.store('player')?._pauseLocal();
|
||
}
|
||
this._maybeShowRemoteHint();
|
||
},
|
||
|
||
remoteActiveDevice() {
|
||
if (!this.activeDeviceId || this.activeDeviceId === this.id) return null;
|
||
return this.devices.find(device => device.id === this.activeDeviceId) || null;
|
||
},
|
||
|
||
_maybeShowRemoteHint() {
|
||
if (this._remoteHintShown || this.remoteHintVisible || this.open) return;
|
||
const active = this.remoteActiveDevice();
|
||
if (!active) return;
|
||
this.remoteHintDeviceName = active.name || 'Devices';
|
||
this.remoteHintVisible = true;
|
||
this._remoteHintShown = true;
|
||
clearTimeout(this._remoteHintTimer);
|
||
this._remoteHintTimer = setTimeout(() => this.dismissRemoteHint(), 60000);
|
||
},
|
||
|
||
dismissRemoteHint() {
|
||
this.remoteHintVisible = false;
|
||
this._remoteHintShown = true;
|
||
clearTimeout(this._remoteHintTimer);
|
||
this._remoteHintTimer = null;
|
||
},
|
||
|
||
remoteHintText() {
|
||
return `${T.activeDevice}: ${this.remoteHintDeviceName || this.activeLabel()}`;
|
||
},
|
||
|
||
selectedJam() {
|
||
return !playerOffline() && this.currentJamId ? this.jams.find(jam => jam.id === this.currentJamId) : null;
|
||
},
|
||
|
||
currentJamUser(jam = this.selectedJam()) {
|
||
const profile = Alpine.store('user')?.profile;
|
||
if (profile?.id) {
|
||
return { id: profile.id, name: profile.name || 'User' };
|
||
}
|
||
const current = (jam?.members || []).find(member => member.is_current_user);
|
||
if (current?.user_id) {
|
||
return { id: current.user_id, name: current.name || 'User' };
|
||
}
|
||
if (jam?.is_owner && jam.host_user_id) {
|
||
return { id: jam.host_user_id, name: jam.host_name || 'User' };
|
||
}
|
||
return null;
|
||
},
|
||
|
||
hasJoinedJam() {
|
||
if (playerOffline()) return false;
|
||
return this.jams.some(jam => jam.is_member);
|
||
},
|
||
|
||
activeJamMembers() {
|
||
const jam = this.selectedJam();
|
||
return (jam?.members || []).filter(member => member.is_joined && Number(member.last_seen_ms || 0) <= 45000);
|
||
},
|
||
|
||
jamMemberIds(jamId = this.jamPanelJamId || this.currentJamId) {
|
||
const jam = this.jams.find(item => item.id === jamId);
|
||
return new Set((jam?.members || []).map(member => Number(member.user_id)));
|
||
},
|
||
|
||
userColorStyle(userId, name = '') {
|
||
const palette = ['#4cc9f0', '#f72585', '#f9c74f', '#90be6d', '#f8961e', '#b5179e', '#43aa8b', '#577590'];
|
||
const raw = String(userId || name || '');
|
||
let hash = 0;
|
||
for (let i = 0; i < raw.length; i++) hash = ((hash * 31) + raw.charCodeAt(i)) >>> 0;
|
||
const hex = palette[hash % palette.length];
|
||
const r = parseInt(hex.slice(1, 3), 16);
|
||
const g = parseInt(hex.slice(3, 5), 16);
|
||
const b = parseInt(hex.slice(5, 7), 16);
|
||
return `--jam-contributor-color:${hex};--jam-contributor-bg:rgba(${r},${g},${b},0.13);--jam-contributor-bg-active:rgba(${r},${g},${b},0.2)`;
|
||
},
|
||
|
||
isControllingRemoteJam() {
|
||
const jam = this.selectedJam();
|
||
return !!jam && !jam.is_owner;
|
||
},
|
||
|
||
canPlayJamLocally() {
|
||
const jam = this.selectedJam();
|
||
return !!jam && jam.is_member && !jam.is_owner && jam.host_device_online;
|
||
},
|
||
|
||
shouldPlayJamLocally() {
|
||
if (playerOffline()) return false;
|
||
return this.jamLocalPlayback && this.canPlayJamLocally();
|
||
},
|
||
|
||
setJamLocalPlayback(enabled) {
|
||
this._setJamLocalPlayback(enabled, { pauseLocal: true });
|
||
if (!this.jamLocalPlayback) return;
|
||
|
||
const player = Alpine.store('player');
|
||
if (player && this._lastPlaybackState) {
|
||
player._syncLocalPlaybackState(this._lastPlaybackState);
|
||
} else if (player?.currentTrack) {
|
||
player._syncLocalPlaybackState(player._remotePlaybackPayload(player.currentTrack, {
|
||
position_seconds: player.currentTime || 0,
|
||
duration_seconds: player.duration || 0,
|
||
paused: !player.isPlaying,
|
||
}));
|
||
}
|
||
this.poll();
|
||
},
|
||
|
||
_setJamLocalPlayback(enabled, options = {}) {
|
||
const next = !!enabled && this.canPlayJamLocally();
|
||
const wasEnabled = this.jamLocalPlayback;
|
||
this.jamLocalPlayback = next;
|
||
if (wasEnabled && !next && options.pauseLocal) {
|
||
Alpine.store('player')?._pauseLocal();
|
||
}
|
||
},
|
||
|
||
isActive() {
|
||
if (GUEST || playerOffline()) return true;
|
||
if (this.isControllingRemoteJam()) return false;
|
||
return !this.activeDeviceId || this.activeDeviceId === this.id;
|
||
},
|
||
|
||
activeLabel() {
|
||
const jam = this.selectedJam();
|
||
if (jam) return jam.name;
|
||
const active = this.devices.find(device => device.id === this.activeDeviceId);
|
||
return active ? active.name : 'Devices';
|
||
},
|
||
|
||
toggle() {
|
||
this.dismissRemoteHint();
|
||
this.open = !this.open;
|
||
if (this.open && !playerOffline()) {
|
||
this.poll();
|
||
this.loadFedDevices();
|
||
}
|
||
},
|
||
|
||
fedDevices() {
|
||
return (this.fed?.devices || []).filter(device => !device.revoked);
|
||
},
|
||
|
||
webDevices() {
|
||
return this.devices.filter(device => device.kind !== 'fed');
|
||
},
|
||
|
||
playbackFedDevices() {
|
||
return this.devices.filter(device => device.kind === 'fed');
|
||
},
|
||
|
||
fedPending() {
|
||
return this.fed?.pending || [];
|
||
},
|
||
|
||
async loadFedDevices() {
|
||
if (deviceSyncUnavailable()) return;
|
||
const {signal} = playbackConnection;
|
||
try {
|
||
const res = await fetch('/api/player/fed-devices', {signal});
|
||
if (!res.ok) {
|
||
const message = await this._errorText(res);
|
||
if (!signal.aborted) this.fedError = message;
|
||
return;
|
||
}
|
||
const devices = await res.json();
|
||
if (signal.aborted) return;
|
||
this.fed = devices;
|
||
this.fedError = '';
|
||
} catch (err) {
|
||
if (!signal.aborted) this.fedError = String(err?.message || err || 'Fed sync unavailable');
|
||
}
|
||
},
|
||
|
||
async generateFedInvite() {
|
||
if (this.fedBusy) return;
|
||
this.fedBusy = true;
|
||
try {
|
||
const res = await fetch('/api/player/fed-devices/invite', { method: 'POST' });
|
||
if (!res.ok) throw new Error(await this._errorText(res));
|
||
const data = await res.json();
|
||
this.fedInvite = data.invite || '';
|
||
if (this.fedInvite && navigator.clipboard?.writeText) {
|
||
navigator.clipboard.writeText(this.fedInvite).catch(() => {});
|
||
}
|
||
await this.loadFedDevices();
|
||
} catch (err) {
|
||
this.fedError = String(err?.message || err || 'Invite failed');
|
||
} finally {
|
||
this.fedBusy = false;
|
||
}
|
||
},
|
||
|
||
async connectFedInvite() {
|
||
const invite = this.fedInviteInput.trim();
|
||
if (!invite || this.fedBusy) return;
|
||
this.fedBusy = true;
|
||
try {
|
||
const res = await fetch('/api/player/fed-devices/connect', {
|
||
method: 'POST',
|
||
headers: { 'Content-Type': 'application/json' },
|
||
body: JSON.stringify({ invite }),
|
||
});
|
||
if (!res.ok) throw new Error(await this._errorText(res));
|
||
this.fedInviteInput = '';
|
||
await this.loadFedDevices();
|
||
} catch (err) {
|
||
this.fedError = String(err?.message || err || 'Connect failed');
|
||
} finally {
|
||
this.fedBusy = false;
|
||
}
|
||
},
|
||
|
||
async answerFedPairing(request, accept, useRequesterGroup = false) {
|
||
if (!request?.request_id || this.fedBusy) return;
|
||
this.fedBusy = true;
|
||
try {
|
||
const res = await fetch('/api/player/fed-devices/pairing', {
|
||
method: 'POST',
|
||
headers: { 'Content-Type': 'application/json' },
|
||
body: JSON.stringify({
|
||
request_id: request.request_id,
|
||
accept,
|
||
use_requester_group: useRequesterGroup,
|
||
}),
|
||
});
|
||
if (!res.ok) throw new Error(await this._errorText(res));
|
||
await this.loadFedDevices();
|
||
} catch (err) {
|
||
this.fedError = String(err?.message || err || 'Pairing failed');
|
||
} finally {
|
||
this.fedBusy = false;
|
||
}
|
||
},
|
||
|
||
async revokeFedDevice(device) {
|
||
if (!device?.device_id || device.is_self || this.fedBusy) return;
|
||
if (!window.confirm(`Revoke ${device.name || device.device_id}?`)) return;
|
||
this.fedBusy = true;
|
||
try {
|
||
const res = await fetch('/api/player/fed-devices/revoke', {
|
||
method: 'POST',
|
||
headers: { 'Content-Type': 'application/json' },
|
||
body: JSON.stringify({ device_id: device.device_id }),
|
||
});
|
||
if (!res.ok) throw new Error(await this._errorText(res));
|
||
await this.loadFedDevices();
|
||
} catch (err) {
|
||
this.fedError = String(err?.message || err || 'Revoke failed');
|
||
} finally {
|
||
this.fedBusy = false;
|
||
}
|
||
},
|
||
|
||
async syncFedDevices() {
|
||
if (this.fedBusy) return;
|
||
this.fedBusy = true;
|
||
try {
|
||
const res = await fetch('/api/player/fed-devices/sync', { method: 'POST' });
|
||
if (!res.ok) throw new Error(await this._errorText(res));
|
||
await this.loadFedDevices();
|
||
} catch (err) {
|
||
this.fedError = String(err?.message || err || 'Sync failed');
|
||
} finally {
|
||
this.fedBusy = false;
|
||
}
|
||
},
|
||
|
||
async _errorText(res) {
|
||
try {
|
||
const data = await res.json();
|
||
return data.error || res.statusText || 'Request failed';
|
||
} catch {
|
||
return res.statusText || 'Request failed';
|
||
}
|
||
},
|
||
|
||
async select(deviceId) {
|
||
if (!deviceId || deviceSyncUnavailable()) return;
|
||
const player = Alpine.store('player');
|
||
|
||
try {
|
||
this.clearJamSelection();
|
||
const data = await this._requestState('/api/player/devices/active', {
|
||
device_id: deviceId, current_device_id: this.id,
|
||
});
|
||
if (!data) return;
|
||
this._apply(data);
|
||
this.open = false;
|
||
|
||
if (deviceId === this.id && data.playback_state && player) {
|
||
player._executeRemoteCommand({
|
||
command: 'transfer_state',
|
||
payload: data.playback_state,
|
||
});
|
||
} else if (deviceId !== this.id && player && this.id !== this.activeDeviceId) {
|
||
player._applyRemotePlaybackState(data.playback_state);
|
||
}
|
||
} catch {}
|
||
},
|
||
|
||
async sendCommand(command, payload = {}, targetDeviceId = null) {
|
||
if (deviceSyncUnavailable()) return false;
|
||
const jamId = this.isControllingRemoteJam() ? this.currentJamId : null;
|
||
const target = jamId ? null : (targetDeviceId || this.activeDeviceId);
|
||
if (!jamId && (!target || target === this.id)) return false;
|
||
try {
|
||
const res = await fetch('/api/player/devices/command', {
|
||
method: 'POST',
|
||
headers: { 'Content-Type': 'application/json' },
|
||
body: JSON.stringify({
|
||
target_device_id: target,
|
||
jam_id: jamId,
|
||
command,
|
||
payload,
|
||
}),
|
||
});
|
||
return res.ok;
|
||
} catch {
|
||
return false;
|
||
}
|
||
},
|
||
|
||
openJamPanel() {
|
||
if (this.hasJoinedJam()) return;
|
||
this.jamPanelMode = 'create';
|
||
this.jamPanelJamId = null;
|
||
this.jamSelectedUsers = [];
|
||
this.jamUsers = [];
|
||
this.jamQuery = '';
|
||
this.jamPanelOpen = !this.jamPanelOpen;
|
||
if (this.jamPanelOpen && this.jamQuery.trim()) this.searchJamUsers();
|
||
},
|
||
|
||
openJamManagePanel(jam) {
|
||
if (!jam?.is_member) return;
|
||
if (this.jamPanelOpen && this.jamPanelMode === 'manage' && this.jamPanelJamId === jam.id) {
|
||
this.jamPanelOpen = false;
|
||
return;
|
||
}
|
||
this.jamPanelMode = 'manage';
|
||
this.jamPanelJamId = jam.id;
|
||
this.jamSelectedUsers = [];
|
||
this.jamUsers = [];
|
||
this.jamQuery = '';
|
||
this.jamPanelOpen = true;
|
||
},
|
||
|
||
handleJamRowClick(jam) {
|
||
if (!jam) return;
|
||
if (jam.is_active && jam.is_member) {
|
||
this.openJamManagePanel(jam);
|
||
return;
|
||
}
|
||
this.selectJam(jam);
|
||
},
|
||
|
||
queueJamSearch() {
|
||
clearTimeout(this._jamSearchTimer);
|
||
this._jamSearchTimer = setTimeout(() => this.searchJamUsers(), 180);
|
||
},
|
||
|
||
async searchJamUsers() {
|
||
const query = this.jamQuery.trim();
|
||
if (!query) {
|
||
this.jamUsers = [];
|
||
return;
|
||
}
|
||
this.jamSearching = true;
|
||
try {
|
||
const res = await fetch('/api/player/jams/users?q=' + encodeURIComponent(query));
|
||
if (!res.ok) return;
|
||
const selected = new Set(this.jamSelectedUsers.map(user => user.id));
|
||
const existing = this.jamMemberIds();
|
||
this.jamUsers = (await res.json()).filter(user => !selected.has(user.id) && !existing.has(Number(user.id)));
|
||
} catch {
|
||
} finally {
|
||
this.jamSearching = false;
|
||
}
|
||
},
|
||
|
||
addJamInvitee(user) {
|
||
if (!user || this.jamSelectedUsers.some(item => item.id === user.id)) return;
|
||
this.jamSelectedUsers.push(user);
|
||
this.jamUsers = this.jamUsers.filter(item => item.id !== user.id);
|
||
this.jamQuery = '';
|
||
},
|
||
|
||
removeJamInvitee(userId) {
|
||
this.jamSelectedUsers = this.jamSelectedUsers.filter(user => user.id !== userId);
|
||
},
|
||
|
||
submitJamPanel() {
|
||
if (this.jamPanelMode === 'manage') this.inviteToJam();
|
||
else this.createJam();
|
||
},
|
||
|
||
async createJam() {
|
||
if (this.hasJoinedJam()) return;
|
||
try {
|
||
const data = await this._requestState('/api/player/jams', {
|
||
device_id: this.id,
|
||
invitee_user_ids: this.jamSelectedUsers.map(user => user.id),
|
||
});
|
||
if (!data) return;
|
||
this._apply(data);
|
||
Alpine.store('queue')?._ensureCurrentJamAttribution();
|
||
this.jamPanelOpen = false;
|
||
this.jamQuery = '';
|
||
this.jamUsers = [];
|
||
this.jamSelectedUsers = [];
|
||
this.open = false;
|
||
} catch {}
|
||
},
|
||
|
||
async inviteToJam() {
|
||
if (!this.jamPanelJamId || this.jamSelectedUsers.length === 0) return;
|
||
try {
|
||
const data = await this._requestState('/api/player/jams/invite', {
|
||
jam_id: this.jamPanelJamId, device_id: this.id,
|
||
invitee_user_ids: this.jamSelectedUsers.map(user => user.id),
|
||
});
|
||
if (!data) return;
|
||
this._apply(data);
|
||
this.jamQuery = '';
|
||
this.jamUsers = [];
|
||
this.jamSelectedUsers = [];
|
||
} catch {}
|
||
},
|
||
|
||
async selectJam(jam) {
|
||
if (!jam) return;
|
||
try {
|
||
if (jam.is_pending) {
|
||
const ok = window.confirm('Join this Jam and control the shared queue?');
|
||
if (!ok) return;
|
||
}
|
||
const data = await this._requestState('/api/player/jams/join', {
|
||
jam_id: jam.id, device_id: this.id,
|
||
});
|
||
if (!data) return;
|
||
this.currentJamId = jam.id;
|
||
sessionStorage.setItem('furu_player_jam_id', jam.id);
|
||
if (data.playback_state) this._lastPlaybackState = data.playback_state;
|
||
this._apply(data);
|
||
Alpine.store('queue')?._ensureCurrentJamAttribution();
|
||
this.open = false;
|
||
const player = Alpine.store('player');
|
||
if (player && this.isControllingRemoteJam() && data.playback_state) {
|
||
player._applyRemotePlaybackState(data.playback_state);
|
||
}
|
||
} catch {}
|
||
},
|
||
|
||
async leaveJam(jamId = null) {
|
||
const id = jamId || this.currentJamId;
|
||
if (!id || playerOffline()) return;
|
||
const {signal} = playbackConnection;
|
||
try {
|
||
const data = await this._requestState('/api/player/jams/leave', {
|
||
jam_id: id, device_id: this.id,
|
||
});
|
||
if (data) this._apply(data);
|
||
} catch {
|
||
} finally {
|
||
if (!signal.aborted) this.clearJamSelection();
|
||
}
|
||
},
|
||
|
||
clearJamSelection() {
|
||
this.currentJamId = null;
|
||
this.jamPanelOpen = false;
|
||
this.jamPanelJamId = null;
|
||
this._setJamLocalPlayback(false, { pauseLocal: true });
|
||
sessionStorage.removeItem('furu_player_jam_id');
|
||
},
|
||
});
|
||
|
||
// -----------------------------------------------------------------------
|
||
// Queue store
|
||
// -----------------------------------------------------------------------
|
||
Alpine.store('queue', {
|
||
tracks: [],
|
||
currentIndex: 0,
|
||
visible: false,
|
||
_dragIdx: null,
|
||
_dragOverIdx: null,
|
||
_pointerDragMove: null,
|
||
_pointerDragEnd: null,
|
||
_playNextGroupId: null,
|
||
_playNextGroupSequence: 0,
|
||
|
||
add(track) {
|
||
this.addToEnd([track]);
|
||
},
|
||
|
||
upcoming(limit = 12) {
|
||
const start = Math.max(0, this.currentIndex + 1);
|
||
return this.tracks.slice(start, start + limit);
|
||
},
|
||
|
||
effectiveCurrentIndex() {
|
||
const currentTrack = Alpine.store('player')?.currentTrack || null;
|
||
const currentKey = this._trackIdentity(currentTrack);
|
||
if (currentKey) {
|
||
const index = this.tracks.findIndex(track => this._trackIdentity(track) === currentKey);
|
||
if (index >= 0) return index;
|
||
}
|
||
if (!this.tracks.length) return -1;
|
||
return Math.max(0, Math.min(Number(this.currentIndex || 0), this.tracks.length - 1));
|
||
},
|
||
|
||
_trackIdentity(track) {
|
||
if (track?.content_id) return `content:${track.content_id}`;
|
||
if (track?.id != null && track.id !== '') return `id:${String(track.id)}`;
|
||
return '';
|
||
},
|
||
|
||
queueItemState(index) {
|
||
const current = this.effectiveCurrentIndex();
|
||
if (current < 0) return 'upcoming';
|
||
if (index < current) return 'played';
|
||
if (index === current) return 'current';
|
||
return 'upcoming';
|
||
},
|
||
|
||
displayItems() {
|
||
const current = this.effectiveCurrentIndex();
|
||
const playerTrack = Alpine.store('player')?.currentTrack || null;
|
||
const items = this.tracks.map((track, index) => ({
|
||
track,
|
||
index,
|
||
key: `${index}-${track?.id || 'track'}`,
|
||
state: current >= 0
|
||
? (index < current ? 'played' : (index === current ? 'current' : 'upcoming'))
|
||
: 'upcoming',
|
||
synthetic: false,
|
||
}));
|
||
|
||
if (playerTrack?.id && current < 0) {
|
||
items.unshift({
|
||
track: playerTrack,
|
||
index: -1,
|
||
key: `current-${playerTrack.id}`,
|
||
state: 'current',
|
||
synthetic: true,
|
||
});
|
||
}
|
||
|
||
return items;
|
||
},
|
||
|
||
syncCurrentIndexToTrack(track) {
|
||
const key = this._trackIdentity(track);
|
||
if (!key || !this.tracks.length) return -1;
|
||
const index = this.tracks.findIndex(item => this._trackIdentity(item) === key);
|
||
if (index >= 0) this.currentIndex = index;
|
||
return index;
|
||
},
|
||
|
||
addToEnd(tracks) {
|
||
const items = this._tracksForQueueAdd(tracks);
|
||
if (!items.length) return;
|
||
if (this._sendRemoteQueueCommand('queue_add_end', { tracks: items })) {
|
||
this._addToEndLocal(items);
|
||
return;
|
||
}
|
||
this._addToEndLocal(items);
|
||
},
|
||
|
||
addNextInQueue(tracks) {
|
||
const items = this._tracksForQueueAdd(tracks);
|
||
if (!items.length) return;
|
||
if (this._sendRemoteQueueCommand('queue_add_next', { tracks: items })) {
|
||
this._addNextLocal(items);
|
||
return;
|
||
}
|
||
this._addNextLocal(items);
|
||
},
|
||
|
||
playRelease(tracks, startIndex) {
|
||
this.tracks = this._tracksForQueueAdd(tracks);
|
||
this._playNextGroupId = null;
|
||
this.playFromIndex(startIndex || 0);
|
||
},
|
||
|
||
playFromIndex(idx) {
|
||
if (idx < 0 || idx >= this.tracks.length) return;
|
||
Alpine.store('player').playQueueIndex(idx);
|
||
},
|
||
|
||
remove(idx) {
|
||
if (this._sendRemoteQueueCommand('queue_remove', { index: idx })) {
|
||
this._removeLocal(idx);
|
||
return;
|
||
}
|
||
this._removeLocal(idx);
|
||
},
|
||
|
||
moveTrack(fromIdx, toIdx) {
|
||
if (this._sendRemoteQueueCommand('queue_move', { from_index: fromIdx, to_index: toIdx })) {
|
||
this._moveTrackLocal(fromIdx, toIdx);
|
||
return;
|
||
}
|
||
this._moveTrackLocal(fromIdx, toIdx);
|
||
},
|
||
|
||
startPointerReorder(event, idx) {
|
||
if (event.pointerType === 'mouse') return;
|
||
if (event.button && event.button !== 0) return;
|
||
if (idx < 0 || idx >= this.tracks.length) return;
|
||
event.preventDefault();
|
||
this._endPointerReorder(false);
|
||
this._dragIdx = idx;
|
||
this._dragOverIdx = idx;
|
||
const handle = event.currentTarget;
|
||
try {
|
||
handle?.setPointerCapture?.(event.pointerId);
|
||
} catch (_) {}
|
||
|
||
this._pointerDragMove = (moveEvent) => {
|
||
moveEvent.preventDefault();
|
||
this._autoScrollDuringReorder(moveEvent.clientY);
|
||
const target = document
|
||
.elementFromPoint(moveEvent.clientX, moveEvent.clientY)
|
||
?.closest?.('.queue-track[data-queue-index]');
|
||
const targetIdx = Number(target?.dataset?.queueIndex);
|
||
if (!Number.isInteger(targetIdx) || targetIdx < 0 || targetIdx >= this.tracks.length) return;
|
||
this._dragOverIdx = targetIdx;
|
||
document.querySelectorAll('.queue-track.drag-over').forEach(el => el.classList.remove('drag-over'));
|
||
if (targetIdx !== this._dragIdx) target.classList.add('drag-over');
|
||
};
|
||
|
||
this._pointerDragEnd = (endEvent) => {
|
||
try {
|
||
if (handle?.hasPointerCapture?.(endEvent.pointerId)) handle.releasePointerCapture(endEvent.pointerId);
|
||
} catch (_) {}
|
||
this._endPointerReorder(true);
|
||
};
|
||
|
||
window.addEventListener('pointermove', this._pointerDragMove, { passive: false });
|
||
window.addEventListener('pointerup', this._pointerDragEnd, { passive: false });
|
||
window.addEventListener('pointercancel', this._pointerDragEnd, { passive: false });
|
||
},
|
||
|
||
_autoScrollDuringReorder(clientY) {
|
||
const scroller = document.querySelector('.queue-tracks');
|
||
if (!scroller) return;
|
||
const rect = scroller.getBoundingClientRect();
|
||
const edge = 52;
|
||
if (clientY < rect.top + edge) {
|
||
scroller.scrollTop -= Math.ceil((rect.top + edge - clientY) / 4);
|
||
} else if (clientY > rect.bottom - edge) {
|
||
scroller.scrollTop += Math.ceil((clientY - (rect.bottom - edge)) / 4);
|
||
}
|
||
},
|
||
|
||
_endPointerReorder(commit) {
|
||
if (this._pointerDragMove) window.removeEventListener('pointermove', this._pointerDragMove);
|
||
if (this._pointerDragEnd) {
|
||
window.removeEventListener('pointerup', this._pointerDragEnd);
|
||
window.removeEventListener('pointercancel', this._pointerDragEnd);
|
||
}
|
||
document.querySelectorAll('.queue-track.drag-over').forEach(el => el.classList.remove('drag-over'));
|
||
const fromIdx = this._dragIdx;
|
||
const toIdx = this._dragOverIdx;
|
||
this._pointerDragMove = null;
|
||
this._pointerDragEnd = null;
|
||
this._dragIdx = null;
|
||
this._dragOverIdx = null;
|
||
if (commit && Number.isInteger(fromIdx) && Number.isInteger(toIdx) && fromIdx !== toIdx) {
|
||
this.moveTrack(fromIdx, toIdx);
|
||
}
|
||
},
|
||
|
||
clear() {
|
||
if (this._sendRemoteQueueCommand('queue_clear')) {
|
||
this._clearLocal();
|
||
return;
|
||
}
|
||
this._clearLocal();
|
||
},
|
||
|
||
_trackList(tracks) {
|
||
return (Array.isArray(tracks) ? tracks : [tracks]).filter(Boolean);
|
||
},
|
||
|
||
_tracksForQueueAdd(tracks) {
|
||
const items = this._trackList(tracks).map(track => ({ ...track }));
|
||
const devices = Alpine.store('devices');
|
||
const jam = devices?.selectedJam?.();
|
||
const user = devices?.currentJamUser?.(jam);
|
||
if (!jam || !jam.is_member || !user?.id) return items;
|
||
return items.map(track => ({
|
||
...track,
|
||
added_by_user_id: user.id,
|
||
added_by_user_name: user.name || 'User',
|
||
}));
|
||
},
|
||
|
||
_tracksWithJamDefaults(tracks) {
|
||
const items = this._trackList(tracks);
|
||
const jam = Alpine.store('devices')?.selectedJam?.();
|
||
if (!jam?.is_member || !jam.host_user_id) return items;
|
||
return items.map(track => {
|
||
if (track?.added_by_user_id) return track;
|
||
return {
|
||
...track,
|
||
added_by_user_id: jam.host_user_id,
|
||
added_by_user_name: jam.host_name || 'Host',
|
||
};
|
||
});
|
||
},
|
||
|
||
_ensureCurrentJamAttribution() {
|
||
this.tracks = this._tracksWithJamDefaults(this.tracks);
|
||
},
|
||
|
||
isForeignJamTrack(track) {
|
||
const devices = Alpine.store('devices');
|
||
const jam = devices?.selectedJam?.();
|
||
const userId = Alpine.store('user')?.profile?.id;
|
||
if (!jam || !jam.is_member || !track?.added_by_user_id || !userId) return false;
|
||
return String(track.added_by_user_id) !== String(userId);
|
||
},
|
||
|
||
contributorTitle(track) {
|
||
return track?.added_by_user_name ? `Added by ${track.added_by_user_name}` : 'Added by another listener';
|
||
},
|
||
|
||
contributorStyle(track) {
|
||
return Alpine.store('devices')?.userColorStyle(track?.added_by_user_id, track?.added_by_user_name) || '';
|
||
},
|
||
|
||
_sendRemoteQueueCommand(command, payload = {}) {
|
||
const player = Alpine.store('player');
|
||
if (!player?._shouldSendRemote()) return false;
|
||
Alpine.store('devices')?.sendCommand(command, payload);
|
||
return true;
|
||
},
|
||
|
||
_addToEndLocal(tracks) {
|
||
const items = this._tracksWithJamDefaults(tracks);
|
||
if (!items.length) return;
|
||
this.tracks = [...this.tracks, ...items];
|
||
},
|
||
|
||
_addNextLocal(tracks) {
|
||
const items = this._tracksWithJamDefaults(tracks);
|
||
if (!items.length) return;
|
||
const current = this.effectiveCurrentIndex();
|
||
let insertAt = Math.min(Math.max(0, current + 1), this.tracks.length);
|
||
let groupId = this._playNextGroupId
|
||
|| this.tracks[insertAt]?._playNextGroupId
|
||
|| null;
|
||
if (groupId) this._playNextGroupId = groupId;
|
||
if (groupId) {
|
||
let lastGroupIndex = -1;
|
||
for (let index = current; index < this.tracks.length; index++) {
|
||
if (this.tracks[index]?._playNextGroupId === groupId) {
|
||
lastGroupIndex = index;
|
||
}
|
||
}
|
||
if (lastGroupIndex >= current) {
|
||
insertAt = lastGroupIndex + 1;
|
||
} else {
|
||
groupId = null;
|
||
}
|
||
}
|
||
if (!groupId) {
|
||
this._playNextGroupSequence += 1;
|
||
groupId = `next-${Date.now()}-${this._playNextGroupSequence}`;
|
||
this._playNextGroupId = groupId;
|
||
}
|
||
const groupedItems = items.map(item => ({
|
||
...item,
|
||
_playNextGroupId: groupId,
|
||
}));
|
||
this.tracks.splice(insertAt, 0, ...groupedItems);
|
||
},
|
||
|
||
_removeLocal(idx) {
|
||
if (idx < 0 || idx >= this.tracks.length) return;
|
||
this.tracks.splice(idx, 1);
|
||
if (this.tracks.length === 0) {
|
||
this.currentIndex = 0;
|
||
} else if (idx < this.currentIndex) {
|
||
this.currentIndex--;
|
||
} else if (idx === this.currentIndex) {
|
||
if (this.currentIndex >= this.tracks.length) {
|
||
this.currentIndex = this.tracks.length - 1;
|
||
}
|
||
}
|
||
},
|
||
|
||
_moveTrackLocal(fromIdx, toIdx) {
|
||
if (fromIdx === toIdx) return;
|
||
if (fromIdx < 0 || fromIdx >= this.tracks.length) return;
|
||
if (toIdx < 0 || toIdx >= this.tracks.length) return;
|
||
const [track] = this.tracks.splice(fromIdx, 1);
|
||
this.tracks.splice(toIdx, 0, track);
|
||
this._playNextGroupId = null;
|
||
// Adjust currentIndex to follow the currently playing track
|
||
if (this.currentIndex === fromIdx) {
|
||
this.currentIndex = toIdx;
|
||
} else if (fromIdx < this.currentIndex && toIdx >= this.currentIndex) {
|
||
this.currentIndex--;
|
||
} else if (fromIdx > this.currentIndex && toIdx <= this.currentIndex) {
|
||
this.currentIndex++;
|
||
}
|
||
},
|
||
|
||
_clearLocal() {
|
||
this.tracks = [];
|
||
this.currentIndex = 0;
|
||
this._playNextGroupId = null;
|
||
},
|
||
});
|
||
|
||
// -----------------------------------------------------------------------
|
||
// Library store
|
||
// -----------------------------------------------------------------------
|
||
Alpine.store('library', {
|
||
view: 'artists',
|
||
artistFilter: 'all',
|
||
artists: [],
|
||
artistsPage: 0,
|
||
artistsTotal: 0,
|
||
loading: false,
|
||
_allLoaded: false,
|
||
_artistsLoadToken: 0,
|
||
get pendingDetail() {
|
||
if (this.view === 'artist_detail' && !this.currentArtist && !this.artistUnavailable) return 'artist';
|
||
if (this.view === 'playlist_detail' && !this.currentPlaylist && !this.playlistUnavailable) return 'playlist';
|
||
if (this.view === 'release_detail' && !this.currentRelease && !this.releaseUnavailable) return 'release';
|
||
return '';
|
||
},
|
||
currentArtist: null,
|
||
artistUnavailable: false,
|
||
currentRelease: null,
|
||
currentPlaylist: null,
|
||
playlistUnavailable: false,
|
||
_playlistReadVersion: 0,
|
||
_observer: null,
|
||
searchQuery: '',
|
||
searchResults: null,
|
||
searchMode: 'normal',
|
||
_searchTimer: null,
|
||
_searchController: null,
|
||
_searchGeneration: 0,
|
||
cancelPendingSearch() {
|
||
clearTimeout(this._searchTimer); this._searchTimer=null;
|
||
this._searchController?.abort(); this._searchController=null;
|
||
this._searchGeneration++;
|
||
},
|
||
queueSearch() {
|
||
this.cancelPendingSearch();
|
||
if (!this.searchQuery.trim()) {this.clearSearch();return;}
|
||
this._searchTimer=setTimeout(()=>this.search(this.searchQuery),this.searchMode==='lyrics'?1800:300);
|
||
},
|
||
toggleSearchMode() {
|
||
this.cancelPendingSearch(); this.stopFederationSearch();
|
||
this.searchMode=this.searchMode==='lyrics'?'normal':'lyrics';
|
||
this.searchResults=null;this.searchLoading=false;this.similaritySearchLabel='';this.similaritySearchError='';
|
||
if (this.searchQuery.trim()) this.queueSearch();
|
||
},
|
||
searchLoading: false,
|
||
similaritySearchLabel: '',
|
||
similaritySearchError: '',
|
||
similaritySearchStats: { loading: false, tracks: 0, artists: 0, peers: 0, elapsed_ms: 0 },
|
||
federationSearch: { loading: false, error: '', artists: [], releases: [], tracks: [] },
|
||
unifiedSearch: { artists: [], releases: [], tracks: [], podcasts: [] },
|
||
get ordinarySearch() {
|
||
return this.searchMode === 'normal' && !this.similaritySearchLabel
|
||
&& !this._activeHash?.startsWith('#similar/');
|
||
},
|
||
get displaySearchResults() {
|
||
if (this.searchMode !== 'lyrics') return this.unifiedSearch;
|
||
return this.searchResults || { artists: [], releases: [], tracks: [], podcasts: [] };
|
||
},
|
||
get hasDisplaySearchResults() {
|
||
const data = this.displaySearchResults;
|
||
return !!(data.artists?.length || data.releases?.length || data.tracks?.length || data.podcasts?.length);
|
||
},
|
||
artistFederation: { loading: false, error: '', releases: [], tracks: [] },
|
||
federationPreparing: {},
|
||
federationFailures: {},
|
||
trackAvailability: {},
|
||
_navigationVersion: 0,
|
||
releaseUnavailable: false,
|
||
federationLiked: [],
|
||
_cancelFederationSearch: null,
|
||
failedFederationArtwork: new Set(),
|
||
_artistFederationSource: null,
|
||
_releaseFederationSource: null,
|
||
releaseFederationLoading: false,
|
||
_previousView: 'artists',
|
||
_activeHash: location.hash || '#artists',
|
||
_scrollPositions: {},
|
||
|
||
_hashNav: false, // guard against circular hash updates
|
||
|
||
init() {
|
||
if (GUEST) {
|
||
this.$nextTick(() => Alpine.store('sharing').handleInitialShareLinks());
|
||
return;
|
||
}
|
||
this._setupScroll();
|
||
this.loadFederationLikes();
|
||
window.addEventListener('furumi:track-availability', event => {
|
||
if (event.detail?.source !== 'library') {
|
||
this.applyTrackAvailability(event.detail || {});
|
||
}
|
||
});
|
||
|
||
// Listen for browser back/forward
|
||
window.addEventListener('hashchange', () => {
|
||
if (this._hashNav) return;
|
||
const nextHash = location.hash || '#artists';
|
||
this._saveScrollPosition(this._activeHash);
|
||
this._activeHash = nextHash;
|
||
this._navigateFromHash({ fromHash: true, restoreScroll: true });
|
||
});
|
||
|
||
// Navigate to initial hash (if any)
|
||
this._navigateFromHash({ fromHash: true, restoreScroll: true });
|
||
this.$nextTick(() => {
|
||
Alpine.store('sharing')?.handleInitialShareLinks();
|
||
});
|
||
},
|
||
|
||
_setHash(hash) {
|
||
this._hashNav = true;
|
||
this._activeHash = hash;
|
||
location.hash = hash;
|
||
// Reset guard after a tick
|
||
setTimeout(() => { this._hashNav = false; }, 0);
|
||
},
|
||
|
||
_navigateFromHash(options = {}) {
|
||
if (GUEST) return;
|
||
if (this._hashNav) return;
|
||
const hash = location.hash || '#artists';
|
||
if (playerOffline() && (/^#(?:listening|podcasts?|artistfed|releasefed|similar|share)(?:[/?]|$)/.test(hash) ||
|
||
(hash.startsWith('#search?') && new URLSearchParams(hash.slice(8)).get('mode') === 'lyrics'))) {
|
||
return this.openCollectionView('offline_unavailable', hash, options);
|
||
}
|
||
const listening = hash.match(/^#listening(?:\/(history))?(?:\?(.*))?$/);
|
||
if (listening) {
|
||
return this.openListening(listening[1] || 'overview', {
|
||
...options, day: new URLSearchParams(listening[2]).get('day') || '',
|
||
});
|
||
}
|
||
const match = hash.match(/^#(\w+)(?:\/([-]?\d+))?(?:\?(.*))?$/);
|
||
if (!match) {
|
||
this.goArtists(options);
|
||
return;
|
||
}
|
||
const view = match[1];
|
||
const id = match[2] ? parseInt(match[2], 10) : null;
|
||
const params = match[3] || '';
|
||
|
||
if (view === 'collection') {
|
||
const target = new URLSearchParams(params).get('tab') === 'artists' ? '#followed' : '#artists?tab=playlists';
|
||
history.replaceState(history.state, '', target);
|
||
return this._navigateFromHash({...options, fromHash:true});
|
||
} else if (view === 'followed') {
|
||
this.openCollectionView('followed', '#followed', options);
|
||
} else if (view === 'artists' && new URLSearchParams(params).get('tab') === 'playlists') {
|
||
this.openCollectionView('playlists', '#artists?tab=playlists', options);
|
||
} else if (view === 'artists' && !id) {
|
||
if (this.view !== 'artists' || this.artistsPage === 0) this.goArtists(options);
|
||
else if (options.restoreScroll) this._restoreScrollPosition(hash);
|
||
} else if (view === 'podcasts') {
|
||
Alpine.store('podcasts').enter(options);
|
||
} else if (view === 'podcast') {
|
||
const podcastId = new URLSearchParams(params).get('id');
|
||
if(podcastId)Alpine.store('podcasts').open(podcastId,options);
|
||
else Alpine.store('podcasts').enter(options);
|
||
} else if (view === 'uploads' && !id) {
|
||
if (this.view !== 'my_uploads' || this.artistsPage === 0) this.goMyUploads(options);
|
||
else if (options.restoreScroll) this._restoreScrollPosition(hash);
|
||
} else if (view === 'artist' && id) {
|
||
this.openArtist(id, options);
|
||
} else if (view === 'artistfed') {
|
||
const name = new URLSearchParams(params).get('name');
|
||
if (name) this.openFederatedArtist(name, options);
|
||
else this.goArtists(options);
|
||
} else if (view === 'release' && id) {
|
||
this.openRelease(id, options);
|
||
} else if (view === 'releasefed') {
|
||
let key;
|
||
try { key = JSON.parse(new URLSearchParams(params).get('key')); } catch {}
|
||
this.openFederatedRelease({ key }, options);
|
||
} else if (view === 'playlist' && id) {
|
||
this.openPlaylist(id, options);
|
||
} else if (view === 'search') {
|
||
const qMatch = params.match(/q=([^&]*)/);
|
||
if (qMatch) {
|
||
const q = decodeURIComponent(qMatch[1]);
|
||
this.searchQuery = q;
|
||
this.searchMode=/(?:^|&)mode=lyrics(?:&|$)/.test(params)?'lyrics':'normal';
|
||
this.search(q, options);
|
||
}
|
||
} else if (view === 'similar' && id) {
|
||
this.searchSimilar(id, options);
|
||
} else {
|
||
this.goArtists(options);
|
||
}
|
||
},
|
||
|
||
_scrollElement() {
|
||
return document.getElementById('center-scroll');
|
||
},
|
||
|
||
_saveScrollPosition(hash = this._activeHash) {
|
||
const el = this._scrollElement();
|
||
if (!el || !hash) return;
|
||
this._scrollPositions[hash] = el.scrollTop;
|
||
},
|
||
|
||
_scrollToTop() {
|
||
const el = this._scrollElement();
|
||
if (el) el.scrollTop = 0;
|
||
},
|
||
|
||
_restoreScrollPosition(hash = this._activeHash) {
|
||
const top = this._scrollPositions[hash];
|
||
if (top == null) return;
|
||
const version = this._navigationVersion;
|
||
const restore = () => {
|
||
if (version !== this._navigationVersion) return;
|
||
const el = this._scrollElement();
|
||
if (el) el.scrollTop = top;
|
||
};
|
||
this.$nextTick(() => {
|
||
restore();
|
||
requestAnimationFrame(restore);
|
||
setTimeout(restore, 150);
|
||
});
|
||
},
|
||
|
||
_afterNavigation(options = {}) {
|
||
if (options.focusSharedTrackId) {
|
||
this.$nextTick(() => {
|
||
Alpine.store('sharing')?.focusSharedTrack(options.focusSharedTrackId);
|
||
});
|
||
} else if (options.restoreScroll) {
|
||
this._restoreScrollPosition(this._activeHash);
|
||
} else {
|
||
this.$nextTick(() => { this._scrollToTop(); });
|
||
}
|
||
},
|
||
|
||
_beginNavigation(hash, options = {}) {
|
||
this._navigationVersion++;
|
||
if (this.view === 'playlist_detail') Alpine.store('playlists')?.stopEdit?.();
|
||
this.cancelPendingSearch();
|
||
if (this._cancelFederationSearch && !hash.startsWith('#search?')) this.stopFederationSearch();
|
||
if (!hash.startsWith('#artistfed')) this.stopArtistFederation();
|
||
if (!hash.startsWith('#release/')) this.stopReleaseFederation();
|
||
if (!options.fromHash) {
|
||
this._saveScrollPosition(this._activeHash);
|
||
this._setHash(hash);
|
||
} else {
|
||
this._activeHash = hash;
|
||
}
|
||
if (/^#(?:artist|release|playlist|artistfed|releasefed|share)[/?]/.test(hash)) this._scrollToTop();
|
||
},
|
||
|
||
_resetArtistList(filter) {
|
||
this.artistFilter = filter;
|
||
this.artists = [];
|
||
this.artistsPage = 0;
|
||
this.artistsTotal = 0;
|
||
this._allLoaded = false;
|
||
this.loading = false;
|
||
this._artistsLoadToken += 1;
|
||
},
|
||
|
||
goArtists(options = {}) {
|
||
if (GUEST) return;
|
||
this._beginNavigation('#artists', options);
|
||
if (this.artistFilter !== 'all' || this.artistsPage === 0) {
|
||
this._resetArtistList('all');
|
||
this.loadArtists(1);
|
||
}
|
||
this.view = 'artists';
|
||
this.currentArtist = null;
|
||
this.currentRelease = null;
|
||
this.currentPlaylist = null;
|
||
this.searchQuery = '';
|
||
this.searchResults = null;
|
||
this._previousView = 'artists';
|
||
this.$nextTick(() => { this._setupScroll(); });
|
||
this._afterNavigation(options);
|
||
},
|
||
|
||
openCollectionView(view, hash, options) {
|
||
this._beginNavigation(hash, options);
|
||
this.searchQuery = '';
|
||
this.searchResults = null;
|
||
this.currentArtist = null;
|
||
this.currentRelease = null;
|
||
this.currentPlaylist = null;
|
||
this.view = view;
|
||
this._previousView = view;
|
||
this._afterNavigation(options);
|
||
},
|
||
|
||
openListening(tab = 'overview', options = {}) {
|
||
if (GUEST) return;
|
||
const history = tab === 'history';
|
||
const day = history && /^\d{4}-\d{2}-\d{2}$/.test(options.day || '') ? options.day : '';
|
||
const hash = history ? '#listening/history' + (day ? '?day=' + day : '') : '#listening';
|
||
this.openCollectionView('listening', hash, options);
|
||
Alpine.store('listening').enter(history ? 'history' : 'overview', day);
|
||
},
|
||
|
||
goMyUploads(options = {}) {
|
||
if (GUEST) return;
|
||
this._beginNavigation('#uploads', options);
|
||
if (this.artistFilter !== 'uploads' || this.artistsPage === 0) {
|
||
this._resetArtistList('uploads');
|
||
this.loadArtists(1);
|
||
}
|
||
this.view = 'my_uploads';
|
||
this.currentArtist = null;
|
||
this.currentRelease = null;
|
||
this.currentPlaylist = null;
|
||
this.searchQuery = '';
|
||
this.searchResults = null;
|
||
this._previousView = 'my_uploads';
|
||
this.$nextTick(() => { this._setupScroll(); });
|
||
this._afterNavigation(options);
|
||
},
|
||
|
||
async loadArtists(page) {
|
||
if (this.loading || this._allLoaded) return;
|
||
this.loading = true;
|
||
const filter = this.artistFilter;
|
||
const token = this._artistsLoadToken + 1;
|
||
this._artistsLoadToken = token;
|
||
try {
|
||
const mine = filter === 'uploads' ? '&mine=true' : '';
|
||
const res = await fetch(`/api/player/artists?page=${page}&limit=80${mine}`);
|
||
if (!res.ok) throw new Error('failed');
|
||
const data = await res.json();
|
||
if (token !== this._artistsLoadToken || filter !== this.artistFilter) return;
|
||
const incoming = Array.isArray(data.items) ? data.items : [];
|
||
if (page === 1) {
|
||
this.artists = incoming;
|
||
} else {
|
||
const existing = new Set(this.artists.map(artist => artist.id));
|
||
this.artists = [...this.artists, ...incoming.filter(artist => !existing.has(artist.id))];
|
||
}
|
||
this.artistsPage = data.page;
|
||
this.artistsTotal = data.total;
|
||
if (data.has_more === false || this.artists.length >= data.total) {
|
||
this._allLoaded = true;
|
||
}
|
||
} catch {}
|
||
if (token === this._artistsLoadToken) {
|
||
this.loading = false;
|
||
this.$nextTick(() => { this._fillArtistViewport(); });
|
||
}
|
||
},
|
||
|
||
isFeaturedOnlyArtist(artist) {
|
||
return Number(artist?.release_count || 0) <= 0 && Number(artist?.track_count || 0) > 0;
|
||
},
|
||
|
||
shouldShowFeaturedSeparator(index) {
|
||
if (!(this.view === 'artists' || this.view === 'my_uploads') || index <= 0) return false;
|
||
const current = this.artists[index];
|
||
const previous = this.artists[index - 1];
|
||
return this.isFeaturedOnlyArtist(current) && !this.isFeaturedOnlyArtist(previous);
|
||
},
|
||
|
||
async openArtist(id, options = {}) {
|
||
if (GUEST) return;
|
||
this.stopArtistFederation();
|
||
this._beginNavigation('#artist/' + id, options);
|
||
const version = this._navigationVersion;
|
||
this.artistUnavailable = false;
|
||
this.searchQuery = '';
|
||
this.searchResults = null;
|
||
this.view = 'artist_detail';
|
||
this.currentArtist = null;
|
||
try {
|
||
const res = await fetch(`/api/player/artists/${id}`);
|
||
if (!res.ok) throw new Error('failed');
|
||
const artist = await res.json();
|
||
if (version !== this._navigationVersion) return;
|
||
this.currentArtist = artist;
|
||
this.startArtistFederation(this.currentArtist.name);
|
||
} catch {
|
||
if (version === this._navigationVersion) {
|
||
this.artistUnavailable = true;
|
||
if (playerOffline()) this.view = 'offline_unavailable';
|
||
}
|
||
}
|
||
if (version === this._navigationVersion) this._afterNavigation(options);
|
||
},
|
||
|
||
stopArtistFederation() {
|
||
if (this._artistFederationSource) {
|
||
this._artistFederationSource.close();
|
||
this._artistFederationSource = null;
|
||
}
|
||
this.artistFederation = { loading: false, error: '', releases: [], tracks: [] };
|
||
},
|
||
|
||
stopFederation() {
|
||
this.stopFederationSearch();
|
||
this.stopArtistFederation();
|
||
this.stopReleaseFederation();
|
||
},
|
||
|
||
get federationPaused() {
|
||
const offline = Alpine.store('offline');
|
||
return offline?.active || (offline?.manual && offline.busy);
|
||
},
|
||
|
||
async openFederatedArtist(artist, options = {}) {
|
||
const name = typeof artist === 'string' ? artist : artist?.name;
|
||
if (!name || GUEST) return;
|
||
if (artist.local_id) return this.openArtist(artist.local_id, options);
|
||
this.stopFederationSearch();
|
||
this.stopArtistFederation();
|
||
this._beginNavigation('#artistfed?name=' + encodeURIComponent(name), options);
|
||
const version = this._navigationVersion;
|
||
this.artistUnavailable = false;
|
||
this.searchQuery = '';
|
||
this.searchResults = null;
|
||
this.view = 'artist_detail';
|
||
this.currentArtist = null;
|
||
const id = await this.resolveFederatedId('artist', { name });
|
||
if (version !== this._navigationVersion) return;
|
||
if (id) {
|
||
history.replaceState(history.state, '', '#artist/' + id);
|
||
return this.openArtist(id, { ...options, fromHash: true });
|
||
}
|
||
this.currentArtist = {
|
||
id: null,
|
||
name,
|
||
image_url: null,
|
||
releases: [],
|
||
top_tracks: [],
|
||
featured_tracks: [],
|
||
total_track_count: 0,
|
||
total_play_count: 0,
|
||
federated: true,
|
||
};
|
||
this.startArtistFederation(name);
|
||
this._afterNavigation(options);
|
||
},
|
||
|
||
async resolveFederatedId(kind, params) {
|
||
try {
|
||
const res = await fetch(`/api/player/federation/${kind}/resolve?${new URLSearchParams(params)}`);
|
||
if (res.ok) return (await res.json()).local_id;
|
||
} catch {}
|
||
return null;
|
||
},
|
||
|
||
normalizeFederationName(value) {
|
||
return typeof value === 'string'
|
||
? Array.from(value.normalize('NFKC'), letter =>
|
||
/[\p{Alphabetic}\p{N}]/u.test(letter) ? letter.toLowerCase() : ' '
|
||
).join('').trim().replace(/ +/g, ' ')
|
||
: '';
|
||
},
|
||
|
||
federationReleaseKey(title, names, year, releaseType = null) {
|
||
const normalizedTitle = this.normalizeFederationName(title);
|
||
if (!normalizedTitle || !Array.isArray(names)) return null;
|
||
return {
|
||
normalized_title: normalizedTitle,
|
||
primary_artists: [...new Set(names.map(name => this.normalizeFederationName(name)).filter(Boolean))].sort(),
|
||
release_type: this.normalizeFederationName(releaseType) || null,
|
||
year: year ?? null,
|
||
};
|
||
},
|
||
|
||
artistTrackCount() {
|
||
const artist = this.currentArtist;
|
||
if (!artist) return 0;
|
||
if (!this.artistFederation.tracks.length) return artist.total_track_count;
|
||
const local = new Set(artist.track_content_ids ??
|
||
[...(artist.top_tracks || []), ...(artist.featured_tracks || [])].map(track => track.content_id));
|
||
return artist.total_track_count + this.artistFederation.tracks.filter(track => !local.has(track.key.content_id)).length;
|
||
},
|
||
|
||
startArtistFederation(name) {
|
||
this.stopArtistFederation();
|
||
if (this.federationPaused) return;
|
||
this.artistFederation = { loading: true, error: '', releases: [], tracks: [] };
|
||
const source = new EventSource(
|
||
`/api/player/federation/artists/events?name=${encodeURIComponent(name)}`
|
||
);
|
||
this._artistFederationSource = source;
|
||
source.addEventListener('federation.artist.catalog', event => {
|
||
if (this._artistFederationSource !== source) return;
|
||
const payload = JSON.parse(event.data);
|
||
const owner = payload.peer;
|
||
const artist = payload.entity || {};
|
||
const artistName = artist.name || name;
|
||
const artworkBase = this.federationDiscoveredArtwork(artistName);
|
||
if (!this.currentArtist?.image_url) {
|
||
this.currentArtist = { ...this.currentArtist, image_url: artworkBase };
|
||
}
|
||
const releases = new Map(this.artistFederation.releases.map(item => [item.identity, item]));
|
||
const tracks = new Map(this.artistFederation.tracks.map(item => [item.key.content_id, item]));
|
||
const localEditions = new Set((this.currentArtist?.releases || []).map(release =>
|
||
JSON.stringify(this.federationReleaseKey(release.title, [artistName], release.year, release.release_type))));
|
||
const localPreview = new Set([...(this.currentArtist?.top_tracks || []), ...(this.currentArtist?.featured_tracks || [])]
|
||
.map(track => track.content_id).filter(Boolean));
|
||
const catalogReleases = [
|
||
...(artist.releases || []),
|
||
...(artist.appears_on || []).map(appearance => ({
|
||
title: appearance.release_title,
|
||
release_type: appearance.release_type,
|
||
year: appearance.year,
|
||
tracks: [appearance.track],
|
||
artists: appearance.track?.artists,
|
||
appearance: true,
|
||
})),
|
||
];
|
||
for (const release of catalogReleases) {
|
||
const artists = release.artists?.length ? release.artists : [artistName];
|
||
const key = this.federationReleaseKey(release.title, artists, release.year, release.release_type);
|
||
if (!key) continue;
|
||
const identity = JSON.stringify(key);
|
||
const wireTracks = this.catalogReleaseTracks(release, owner, key);
|
||
for (const track of wireTracks) {
|
||
const id = track.key.content_id;
|
||
if (localPreview.has(id)) continue;
|
||
const existing = tracks.get(id);
|
||
if (!existing) {
|
||
tracks.set(id, track);
|
||
continue;
|
||
}
|
||
const sourceInfo = track.availability.federation[0];
|
||
if (!existing.availability.federation.some(item =>
|
||
item.owner === sourceInfo.owner && item.item_id === sourceInfo.item_id
|
||
)) existing.availability.federation.push(sourceInfo);
|
||
}
|
||
if (release.appearance || localEditions.has(identity)) continue;
|
||
const existingRelease = releases.get(identity);
|
||
if (existingRelease) {
|
||
const known = new Set(existingRelease.tracks.map(item => item.key.content_id));
|
||
existingRelease.tracks = [
|
||
...existingRelease.tracks,
|
||
...wireTracks.filter(item => !known.has(item.key.content_id)),
|
||
];
|
||
if (!existingRelease.owners.includes(owner)) existingRelease.owners.push(owner);
|
||
} else {
|
||
releases.set(identity, {
|
||
key, identity, artists,
|
||
title: release.title,
|
||
release_type: release.release_type || null,
|
||
year: release.year,
|
||
owners: [owner],
|
||
cover_url: this.federationDiscoveredArtwork(artistName, release.title),
|
||
tracks: wireTracks,
|
||
});
|
||
}
|
||
}
|
||
this.artistFederation = {
|
||
...this.artistFederation,
|
||
releases: [...releases.values()],
|
||
tracks: [...tracks.values()],
|
||
};
|
||
if (this.currentArtist?.releases?.length) {
|
||
this.currentArtist = {
|
||
...this.currentArtist,
|
||
releases: this.currentArtist.releases.map(localRelease => ({
|
||
...localRelease,
|
||
cover_url: localRelease.cover_url || this.federationDiscoveredArtwork(
|
||
artistName,
|
||
localRelease.title,
|
||
),
|
||
})),
|
||
};
|
||
}
|
||
});
|
||
source.addEventListener('artist.completed', () => {
|
||
if (this._artistFederationSource === source) {
|
||
this.artistFederation = { ...this.artistFederation, loading: false };
|
||
this._artistFederationSource = null;
|
||
}
|
||
source.close();
|
||
});
|
||
source.onerror = () => {
|
||
if (this._artistFederationSource !== source) return;
|
||
this.artistFederation = {
|
||
...this.artistFederation,
|
||
loading: false,
|
||
error: 'Federation connection interrupted',
|
||
};
|
||
this._artistFederationSource = null;
|
||
source.close();
|
||
};
|
||
},
|
||
|
||
artistReleaseGroups() {
|
||
const releases = this.currentArtist?.releases || [];
|
||
const order = ['album', 'ep', 'single', 'compilation', 'mixtape', 'live', 'soundtrack'];
|
||
const labels = {
|
||
album: T.albums,
|
||
ep: T.eps,
|
||
single: T.singles,
|
||
compilation: T.compilations,
|
||
mixtape: T.mixtapes,
|
||
live: T.liveReleases,
|
||
soundtrack: T.soundtracks,
|
||
};
|
||
const groups = new Map();
|
||
for (const release of releases) {
|
||
const type = (release.release_type || 'other').toLowerCase();
|
||
if (!groups.has(type)) {
|
||
groups.set(type, []);
|
||
}
|
||
groups.get(type).push(release);
|
||
}
|
||
return Array.from(groups.entries())
|
||
.sort(([a], [b]) => {
|
||
const ai = order.includes(a) ? order.indexOf(a) : order.length;
|
||
const bi = order.includes(b) ? order.indexOf(b) : order.length;
|
||
return ai === bi ? a.localeCompare(b) : ai - bi;
|
||
})
|
||
.map(([type, groupReleases]) => ({
|
||
type,
|
||
label: labels[type] || type,
|
||
releases: groupReleases,
|
||
}));
|
||
},
|
||
|
||
followsHere(event) {
|
||
return event.currentTarget.hasAttribute('href') && !event.ctrlKey && !event.metaKey
|
||
&& !event.shiftKey && !event.altKey && event.button === 0;
|
||
},
|
||
|
||
artistHref(artist) {
|
||
if (!artist || GUEST) return null;
|
||
const id = artist.local_id ?? artist.id;
|
||
if (id) return '#artist/' + id;
|
||
const name = typeof artist === 'string' ? artist : artist.name;
|
||
return name ? '#artistfed?name=' + encodeURIComponent(name) : null;
|
||
},
|
||
|
||
releaseHref(release) {
|
||
if (!release || GUEST) return null;
|
||
const id = release.local_id ?? release.id;
|
||
if (id) return '#release/' + id;
|
||
if (!release.key) return null;
|
||
const key = typeof release.key === 'string' ? release.key : JSON.stringify(release.key);
|
||
return '#releasefed?key=' + encodeURIComponent(key);
|
||
},
|
||
|
||
trackRelease(track) {
|
||
const data = track?.metadata || track;
|
||
if (!data || data.podcast) return null;
|
||
const release = data.release || track._federationTrack?.metadata?.release;
|
||
const id = data.release_id ?? release?.local_id;
|
||
const title = data.release_title || release?.title;
|
||
if (!title && !id) return null;
|
||
const key = data.release_key || release?.key || (!id && this.federationReleaseKey(
|
||
title, (data.artists || []).map(artist => artist.name || artist), data.release_year ?? data.year,
|
||
));
|
||
return { id, title: title || T.unknownRelease, key: key || null };
|
||
},
|
||
|
||
trackArtistLinks(track) {
|
||
const data = track?.metadata || track;
|
||
const links = [];
|
||
const add = (artists, prefix) => {
|
||
for (const artist of artists || []) {
|
||
const name = typeof artist === 'string' ? artist : artist?.name;
|
||
if (!name) continue;
|
||
links.push({ label: prefix + name, href: data.podcast ? null : this.artistHref(artist) });
|
||
}
|
||
};
|
||
add(data?.artists, '');
|
||
add(data?.featured_artists, 'ft. ');
|
||
return links;
|
||
},
|
||
|
||
bytes(value) {
|
||
if (!value) return T.unknownSize;
|
||
const units = ['B', 'KB', 'MB', 'GB', 'TB'];
|
||
let size = Number(value);
|
||
let idx = 0;
|
||
while (size >= 1024 && idx < units.length - 1) {
|
||
size /= 1024;
|
||
idx++;
|
||
}
|
||
return (idx === 0 ? size.toFixed(0) : size.toFixed(1)) + ' ' + units[idx];
|
||
},
|
||
|
||
trackPopularityValue(track) {
|
||
const value = Number(track?.lastfm_rating);
|
||
return Number.isFinite(value) && value > 0 ? value : null;
|
||
},
|
||
|
||
hasPopularity(track) {
|
||
return this.trackPopularityValue(track) != null;
|
||
},
|
||
|
||
popularityLabel(track) {
|
||
const value = this.trackPopularityValue(track);
|
||
if (value == null) return '';
|
||
if (value >= 10000) return Math.round(value / 1000) + 'k';
|
||
if (value >= 1000) return (value / 1000).toFixed(1).replace(/\.0$/, '') + 'k';
|
||
return Math.round(value).toString();
|
||
},
|
||
|
||
popularityStyle(track) {
|
||
const value = this.trackPopularityValue(track);
|
||
if (value == null) return '';
|
||
const t = Math.max(0, Math.min(1, Math.log1p(value) / Math.log1p(180)));
|
||
const hue = 210 - (190 * t);
|
||
const saturation = 42 + (46 * t);
|
||
const lightness = 30 + (16 * t);
|
||
const bg = `hsla(${hue.toFixed(0)}, ${saturation.toFixed(0)}%, ${lightness.toFixed(0)}%, 0.28)`;
|
||
const hoverBg = `hsla(${hue.toFixed(0)}, ${saturation.toFixed(0)}%, ${Math.min(54, lightness + 6).toFixed(0)}%, 0.36)`;
|
||
const border = `hsla(${hue.toFixed(0)}, ${saturation.toFixed(0)}%, ${Math.min(66, lightness + 16).toFixed(0)}%, 0.52)`;
|
||
const fg = `hsl(${hue.toFixed(0)}, ${Math.min(96, saturation + 8).toFixed(0)}%, ${Math.min(86, lightness + 34).toFixed(0)}%)`;
|
||
return `--popularity-bg:${bg};--popularity-hover-bg:${hoverBg};--popularity-border:${border};--popularity-fg:${fg}`;
|
||
},
|
||
|
||
downloadTrack(track) {
|
||
if (!track?.id) return;
|
||
const link = document.createElement('a');
|
||
link.href = GUEST ? `/api/player/shares/${SHARE_TOKEN}/download/${track.id}` : `/api/player/download/${track.id}`;
|
||
link.download = '';
|
||
document.body.appendChild(link);
|
||
link.click();
|
||
link.remove();
|
||
},
|
||
|
||
openTrackInfo(track) {
|
||
const rows = this.trackInfoRows(track).map(row => GUEST && row.links
|
||
? {...row, value: row.links.map(link => link.label).join(', '), links: null} : row);
|
||
const peers = new Set((track._federationTrack?.availability?.federation || []).map(source => source.owner));
|
||
if (peers.size) rows.push({ label: T.peers, value: peers.size });
|
||
rows.push({label:Alpine.store('lyrics').text('lyrics'), value:track.has_lyrics ? Alpine.store('lyrics').text('available') : Alpine.store('lyrics').text('unavailable'), run:()=>{Alpine.store('info').close();Alpine.store('lyrics').open(track,false);}});
|
||
Alpine.store('info').openRows(T.trackInfoTitle, rows);
|
||
},
|
||
|
||
uploadersInfo(uploaders) {
|
||
const rows = uploaders || [];
|
||
if (!rows.length) return 'UFO';
|
||
return rows
|
||
.map(row => `${row.name || 'UFO'} (${row.track_count} ${T.trackWord})`)
|
||
.join(', ');
|
||
},
|
||
|
||
releaseInfo(release) {
|
||
if (!release) return '';
|
||
const lines = [
|
||
release.title || T.unknownRelease,
|
||
`${T.type}: ${release.release_type || T.unknown}`,
|
||
`${T.year}: ${release.year || T.unknown}`,
|
||
`${T.tracks}: ${release.track_count ?? release.tracks?.length ?? T.unknown}`,
|
||
];
|
||
if (release.uploaders) lines.push(`${T.uploaders}: ${this.uploadersInfo(release.uploaders)}`);
|
||
return lines.join('\n');
|
||
},
|
||
|
||
openReleaseInfo(release) {
|
||
Alpine.store('info').openRows(T.releaseInfoTitle, this.releaseInfoRows(release));
|
||
},
|
||
|
||
releaseInfoRows(release) {
|
||
if (!release) return [];
|
||
const title = release.title || T.unknownRelease;
|
||
const href = this.releaseHref(release);
|
||
const rows = [
|
||
{ label: T.release, value: title, links: href ? [{ href, label: title }] : [] },
|
||
{ label: T.type, value: release.release_type || T.unknown },
|
||
{ label: T.year, value: release.year || T.unknown },
|
||
{ label: T.tracks, value: release.track_count ?? release.tracks?.length ?? T.unknown },
|
||
];
|
||
if (release.uploaders) rows.push({ label: T.uploaders, value: this.uploadersInfo(release.uploaders) });
|
||
const peers = new Set([
|
||
...(release.federationPeers || []),
|
||
...(release._federationRelease?.sources || []).map(source => source.owner),
|
||
].filter(Boolean));
|
||
if (peers.size) rows.push({ label: T.peers, value: peers.size });
|
||
const artistLinks = this.trackArtistLinks(release.artists ? release : (release._federationRelease || release));
|
||
if (artistLinks.length) rows.splice(1, 0, { label: T.artists, links: artistLinks });
|
||
return rows;
|
||
},
|
||
|
||
trackInfoRows(track) {
|
||
if (!track) return [];
|
||
const artistLinks = this.trackArtistLinks(track);
|
||
const release = this.trackRelease(track);
|
||
const releaseLinks = release ? [{ href: this.releaseHref(release), label: release.title }] : [];
|
||
const audio = [
|
||
track.audio_format || null,
|
||
track.audio_bitrate ? `${track.audio_bitrate} kbps` : null,
|
||
track.audio_sample_rate ? `${track.audio_sample_rate} Hz` : null,
|
||
track.audio_bit_depth ? `${track.audio_bit_depth}-bit` : null,
|
||
].filter(Boolean).join(' · ') || T.unknownAudio;
|
||
const rows = [
|
||
{ label: T.title, value: track.title || T.unknownTrack },
|
||
{ label: T.release, links: releaseLinks },
|
||
{ label: T.artists, links: artistLinks },
|
||
{ label: T.releaseYear, value: track.release_year || T.unknown },
|
||
{ label: T.duration, value: formatTime(track.duration_seconds) },
|
||
{ label: T.audio, value: audio },
|
||
{ label: T.size, value: this.bytes(track.file_size_bytes) },
|
||
];
|
||
if (!SHARE_TOKEN) rows.push({ label: T.uploader, value: track.uploader_name || 'UFO' });
|
||
if (track.lastfm_rating != null || track.lastfm_listeners != null || track.lastfm_playcount != null) {
|
||
const rating = Number(track.lastfm_rating || 0);
|
||
rows.push({ label: T.lastfmRating, value: Number.isFinite(rating) ? Math.round(rating) : T.unknown });
|
||
rows.push({ label: T.lastfmListeners, value: new Intl.NumberFormat().format(track.lastfm_listeners || 0) });
|
||
rows.push({ label: T.lastfmPlaycount, value: new Intl.NumberFormat().format(track.lastfm_playcount || 0) });
|
||
if (track.lastfm_updated_at) rows.push({ label: T.lastfmUpdated, value: track.lastfm_updated_at });
|
||
} else {
|
||
rows.push({ label: T.lastfmRating, value: T.lastfmNotLoaded });
|
||
}
|
||
return rows;
|
||
},
|
||
|
||
listenToArtist() {
|
||
const tracks = [];
|
||
const ids = new Set();
|
||
const contentIds = new Set();
|
||
const add = track => {
|
||
if (ids.has(track.id) || (track.content_id && contentIds.has(track.content_id))) return;
|
||
ids.add(track.id);
|
||
if (track.content_id) contentIds.add(track.content_id);
|
||
tracks.push(track);
|
||
};
|
||
for (const track of this.currentArtist?.top_tracks || []) add(track);
|
||
for (const track of this.currentArtist?.featured_tracks || []) add(track);
|
||
for (const track of this.artistFederation.tracks) add(this.federationQueueTrack(track));
|
||
if (tracks.length) Alpine.store('queue').playRelease(tracks, 0);
|
||
},
|
||
|
||
async openRelease(id, options = {}) {
|
||
if (GUEST) return;
|
||
this.stopReleaseFederation();
|
||
this._beginNavigation('#release/' + id, options);
|
||
const version = this._navigationVersion;
|
||
this.releaseUnavailable = false;
|
||
this.searchQuery = '';
|
||
this.searchResults = null;
|
||
this.view = 'release_detail';
|
||
this.currentRelease = null;
|
||
try {
|
||
const res = await fetch(`/api/player/releases/${id}`);
|
||
if (!res.ok) throw new Error('failed');
|
||
const release = await res.json();
|
||
if (version !== this._navigationVersion) return;
|
||
this.currentRelease = release;
|
||
if (!this.currentRelease.cover_url && this.currentRelease.artists?.[0]?.name) {
|
||
this.currentRelease = {
|
||
...this.currentRelease,
|
||
cover_url: this.federationDiscoveredArtwork(
|
||
this.currentRelease.artists[0].name,
|
||
this.currentRelease.title,
|
||
),
|
||
};
|
||
}
|
||
this.startReleaseFederation(this.currentRelease);
|
||
} catch {
|
||
if (version === this._navigationVersion) {
|
||
this.releaseUnavailable = true;
|
||
if (playerOffline()) this.view = 'offline_unavailable';
|
||
}
|
||
}
|
||
if (version === this._navigationVersion) this._afterNavigation(options);
|
||
},
|
||
|
||
stopReleaseFederation() {
|
||
if (this._releaseFederationSource) {
|
||
this._releaseFederationSource.close();
|
||
this._releaseFederationSource = null;
|
||
}
|
||
this.releaseFederationLoading = false;
|
||
},
|
||
|
||
catalogReleaseTracks(release, owner, key, localReleaseId = null, known = new Set()) {
|
||
const tracks = [];
|
||
for (const item of release.tracks || []) {
|
||
if (!item?.content_id || !item.item_id || known.has(item.content_id)) continue;
|
||
const track = this.federationTrackFromWire({
|
||
...item, owner, artist_names: item.artists, featured_artist_names: item.featured_artists,
|
||
release_title: release.title, year: release.year,
|
||
});
|
||
track.metadata.release = { key, title: release.title, local_id: localReleaseId };
|
||
tracks.push(track);
|
||
known.add(item.content_id);
|
||
}
|
||
return tracks;
|
||
},
|
||
|
||
releaseArtworkFailed(image) {
|
||
const release = this.currentRelease;
|
||
if (!release || release.cover_url !== image.getAttribute('src')) return;
|
||
this.federationArtworkFailed(image);
|
||
const fallback = this.federationDiscoveredArtwork(release.artists?.[0]?.name, release.title);
|
||
this.currentRelease = { ...release, cover_url: this.availableFederationArtwork(fallback) || null };
|
||
},
|
||
|
||
startReleaseFederation(release) {
|
||
this.stopReleaseFederation();
|
||
if (this.federationPaused) return;
|
||
const artistName = release?.artists?.[0]?.name;
|
||
const artists = (release?.artists || []).map(artist => artist.name);
|
||
const key = release?.federationRelease?.key ||
|
||
this.federationReleaseKey(release?.title, artists, release?.year, release?.release_type);
|
||
if (!artistName || !key) {
|
||
this.releaseUnavailable = !this.currentRelease;
|
||
return;
|
||
}
|
||
this.releaseFederationLoading = true;
|
||
const source = new EventSource(
|
||
`/api/player/federation/artists/events?name=${encodeURIComponent(artistName)}`
|
||
);
|
||
this._releaseFederationSource = source;
|
||
const requestedArtist = this.normalizeFederationName(artistName);
|
||
source.addEventListener('federation.artist.catalog', event => {
|
||
if (this._releaseFederationSource !== source) return;
|
||
const payload = JSON.parse(event.data);
|
||
const owner = payload.peer;
|
||
const catalog = payload.entity || {};
|
||
if (!owner || this.normalizeFederationName(catalog.name) !== requestedArtist) return;
|
||
const matches = (catalog.releases || []).filter(candidate =>
|
||
this.normalizeFederationName(candidate.title) === key.normalized_title
|
||
&& (key.year == null || key.year === candidate.year)
|
||
&& (!key.release_type || key.release_type === this.normalizeFederationName(candidate.release_type))
|
||
);
|
||
if (matches.length !== 1) return;
|
||
const candidate = matches[0];
|
||
const current = this.currentRelease || release;
|
||
// A legacy URL can omit the year or type. Never mix different
|
||
// editions received for that URL from different peers.
|
||
if (current.year && candidate.year && current.year !== candidate.year) return;
|
||
if (current.release_type && candidate.release_type &&
|
||
this.normalizeFederationName(current.release_type) !== this.normalizeFederationName(candidate.release_type)) return;
|
||
const names = artists.map((name, index) => index === 0 ? (catalog.name || name) : name);
|
||
const releaseKey = this.federationReleaseKey(candidate.title, names, candidate.year, candidate.release_type);
|
||
const existing = new Set(
|
||
current.tracks.map(track => track.content_id).filter(Boolean)
|
||
);
|
||
const additions = this.catalogReleaseTracks(candidate, owner, releaseKey, current.id, existing)
|
||
.map(track => this.federationQueueTrack(track));
|
||
const peers = current.federationPeers || [];
|
||
if (!additions.length && peers.includes(owner) && this.currentRelease) return;
|
||
const tracks = additions.length
|
||
? [...current.tracks, ...additions].sort((left, right) =>
|
||
Number(left.disc_number || 1) - Number(right.disc_number || 1)
|
||
|| Number(left.track_number || 9999) - Number(right.track_number || 9999)
|
||
|| String(left.title).localeCompare(String(right.title))
|
||
) : current.tracks;
|
||
const detail = { ...current, tracks, federationPeers: [...new Set([...peers, owner])] };
|
||
if (current.federated) {
|
||
detail.title = candidate.title;
|
||
detail.year = candidate.year;
|
||
detail.release_type = candidate.release_type || current.release_type;
|
||
detail.artists = names.map(name => ({ id: null, name }));
|
||
detail.cover_url = this.federationReleaseCover({
|
||
cover_url: current.federationRelease.cover_url, artists: names, title: candidate.title,
|
||
});
|
||
if (!peers.includes(owner)) detail.uploaders = [...current.uploaders, {
|
||
name: `Federation ${owner.slice(0, 10)}`, track_count: candidate.tracks?.length || 0,
|
||
}];
|
||
}
|
||
this.currentRelease = detail;
|
||
});
|
||
const finish = () => {
|
||
if (this._releaseFederationSource === source) {
|
||
this._releaseFederationSource = null;
|
||
this.releaseFederationLoading = false;
|
||
this.releaseUnavailable = !this.currentRelease;
|
||
}
|
||
source.close();
|
||
};
|
||
source.addEventListener('artist.completed', finish);
|
||
source.onerror = finish;
|
||
},
|
||
|
||
async openPlaylist(id, options = {}) {
|
||
if (GUEST) return;
|
||
this._beginNavigation('#playlist/' + id, options);
|
||
this.view = 'playlist_detail';
|
||
this.currentPlaylist = null;
|
||
return this._loadPlaylist(id, options);
|
||
},
|
||
|
||
refreshLikedPlaylist() {
|
||
if (this.view === 'playlist_detail' && this._activeHash === '#playlist/-1') {
|
||
return this._loadPlaylist(-1);
|
||
}
|
||
},
|
||
|
||
reloadLikes() {
|
||
return Promise.all([
|
||
Alpine.store('likes').reload(), this.loadFederationLikes(),
|
||
Alpine.store('playlists').reload(), this.refreshLikedPlaylist(),
|
||
]);
|
||
},
|
||
|
||
async _loadPlaylist(id, navigation) {
|
||
const version = ++this._playlistReadVersion;
|
||
const route = this._navigationVersion;
|
||
const current = () => version === this._playlistReadVersion && route === this._navigationVersion;
|
||
const likes = Number(id) === -1;
|
||
if (!this.currentPlaylist) this.playlistUnavailable = false;
|
||
try {
|
||
const pending = Alpine.store('playlists')?.trackChange;
|
||
if (pending?.id === Number(id)) {
|
||
await pending.done;
|
||
if (!current()) return;
|
||
}
|
||
const res = await fetch(`/api/player/playlists/${id}`);
|
||
if (!res.ok) throw new Error('failed');
|
||
const playlist = await res.json();
|
||
if (!current()) return;
|
||
const locals = playlist.tracks || [];
|
||
if (likes) {
|
||
// Keep already-visible remote likes until their endpoint finishes refreshing.
|
||
const previous = navigation ? [] : this.currentPlaylist?.tracks.filter(t => t.federation_pending) || [];
|
||
playlist.tracks = this.sortLikeTracks([...locals, ...previous]);
|
||
}
|
||
this.currentPlaylist = playlist;
|
||
if (navigation) this._afterNavigation(navigation);
|
||
if (playerOffline()) return;
|
||
const federationResponse = await fetch(`/api/player/playlists/${id}/federation-tracks`);
|
||
if (federationResponse.ok) {
|
||
const references = await federationResponse.json();
|
||
if (!current()) return;
|
||
const federated = (references || [])
|
||
.map(reference => {
|
||
const track = this.federationTrackFromWire(reference.federation);
|
||
if (!track) return null;
|
||
return {
|
||
...this.federationQueueTrack(track),
|
||
sort_key: Number(reference.position || 0),
|
||
};
|
||
})
|
||
.filter(Boolean);
|
||
if (likes) {
|
||
this.currentPlaylist.tracks = this.sortLikeTracks([...locals, ...federated]);
|
||
} else if (federated.length) {
|
||
this.currentPlaylist.tracks = [...this.currentPlaylist.tracks, ...federated];
|
||
}
|
||
}
|
||
} catch {
|
||
if (current() && !this.currentPlaylist) {
|
||
if (playerOffline()) this.view = 'offline_unavailable';
|
||
else this.playlistUnavailable = true;
|
||
if (navigation) this._afterNavigation(navigation);
|
||
}
|
||
}
|
||
},
|
||
|
||
showSharedPlaylist(share, options = {}) {
|
||
Alpine.store('playlists')?.stopEdit?.();
|
||
this._saveScrollPosition(this._activeHash);
|
||
this.searchQuery = '';
|
||
this.searchResults = null;
|
||
this.currentArtist = null;
|
||
this.currentRelease = null;
|
||
this.currentPlaylist = {
|
||
id: 0,
|
||
title: share?.title || T.sharedPlaylist,
|
||
description: null,
|
||
is_own: false,
|
||
owner_name: null,
|
||
is_public: false,
|
||
is_saved: false,
|
||
kind: 'shared',
|
||
tracks: Array.isArray(share?.tracks) ? share.tracks : [],
|
||
};
|
||
this.view = 'playlist_detail';
|
||
this._previousView = 'artists';
|
||
this._afterNavigation(options);
|
||
},
|
||
|
||
async playRelease(releaseId) {
|
||
try {
|
||
const res = await fetch(`/api/player/releases/${releaseId}`);
|
||
if (!res.ok) return;
|
||
const release = await res.json();
|
||
if (release.tracks.length > 0) {
|
||
Alpine.store('queue').playRelease(release.tracks, 0);
|
||
}
|
||
} catch {}
|
||
},
|
||
|
||
async enqueueRelease(releaseId) {
|
||
try {
|
||
const res = await fetch(`/api/player/releases/${releaseId}`);
|
||
if (!res.ok) return;
|
||
const release = await res.json();
|
||
if (release.tracks.length > 0) {
|
||
Alpine.store('queue').addToEnd(release.tracks);
|
||
}
|
||
} catch {}
|
||
},
|
||
|
||
async enqueueReleaseNext(releaseId) {
|
||
try {
|
||
const res = await fetch(`/api/player/releases/${releaseId}`);
|
||
if (!res.ok) return;
|
||
const release = await res.json();
|
||
if (release.tracks.length > 0) {
|
||
Alpine.store('queue').addNextInQueue(release.tracks);
|
||
}
|
||
} catch {}
|
||
},
|
||
|
||
async search(query, options = {}) {
|
||
this.cancelPendingSearch();
|
||
Alpine.store('searchGroups')?.reset();
|
||
if (GUEST) return;
|
||
const q=(query || '').trim();
|
||
if (!q) {this.clearSearch();return;}
|
||
const mode=this.searchMode;
|
||
this._beginNavigation('#search?q='+encodeURIComponent(q)+(mode==='lyrics'?'&mode=lyrics':''),options);
|
||
const generation=++this._searchGeneration;
|
||
const controller=new AbortController();this._searchController=controller;
|
||
if (this.view!=='search') this._previousView=this.view;
|
||
this.view='search';this.searchLoading=true;this.searchResults=null;
|
||
this.similaritySearchLabel='';this.similaritySearchError='';
|
||
this.similaritySearchStats = { loading: false, tracks: 0, artists: 0, peers: 0, elapsed_ms: 0 };
|
||
if (mode==='lyrics') this.stopFederationSearch();else this.startFederationSearch(q);
|
||
try {
|
||
const res=await fetch(`/api/player/search?q=${encodeURIComponent(q)}&limit=${mode==='lyrics'?30:10}&mode=${mode}`,{signal:controller.signal});
|
||
if (!res.ok) throw new Error('search failed');
|
||
const data=await res.json();
|
||
if(generation!==this._searchGeneration || controller.signal.aborted)return;
|
||
this.searchResults=data;
|
||
if (mode === 'normal') {
|
||
this.unifiedSearch.podcasts = data.podcasts || [];
|
||
for (const kind of ['artists', 'releases', 'tracks']) {
|
||
this.updateUnifiedSearch(kind);
|
||
}
|
||
}
|
||
} catch(error) {
|
||
if(generation!==this._searchGeneration || controller.signal.aborted)return;
|
||
this.searchResults={artists:[],releases:[],tracks:[]};
|
||
this.similaritySearchError=Alpine.store('lyricsSearch').text('error');
|
||
} finally {
|
||
if(generation===this._searchGeneration){this.searchLoading=false;this._searchController=null;this._afterNavigation(options);}
|
||
}
|
||
},
|
||
|
||
similarityTrackId(trackOrId) {
|
||
if (GUEST || trackOrId?.podcast) return null;
|
||
const id = Number(typeof trackOrId === 'object' ? trackOrId?.id : trackOrId);
|
||
return Number.isSafeInteger(id) && id > 0 ? id : null;
|
||
},
|
||
|
||
async searchSimilar(trackOrId, options = {}) {
|
||
const id = this.similarityTrackId(trackOrId);
|
||
if (!id) return;
|
||
this.cancelPendingSearch();
|
||
this.searchMode='normal';
|
||
if (Alpine.store('mobile').playerExpanded) Alpine.store('mobile').closePlayerFullscreen();
|
||
const track = typeof trackOrId === 'object' ? trackOrId : null;
|
||
const artist = (track?.artists || []).map(item => item.name).filter(Boolean).join(', ');
|
||
const initialLabel = track
|
||
? [track.title, artist].filter(Boolean).join(' — ')
|
||
: '';
|
||
this._beginNavigation(`#similar/${id}`, options);
|
||
const generation = this._searchGeneration;
|
||
if (this.view !== 'search') this._previousView = this.view;
|
||
this.stopFederationSearch();
|
||
this.view = 'search';
|
||
this.searchQuery = initialLabel;
|
||
this.similaritySearchLabel = initialLabel;
|
||
this.similaritySearchError = '';
|
||
this.searchLoading = true;
|
||
this.searchResults = null;
|
||
this.federationSearch = { loading: true, error: '', artists: [], releases: [], tracks: [] };
|
||
this.similaritySearchStats = { loading: true, tracks: 0, artists: 0, peers: 0, elapsed_ms: 0 };
|
||
Alpine.store('info').close();
|
||
try {
|
||
const completeRequest = fetch(`/api/player/similarity/${id}`).then(response => ({ response }), error => ({ error }));
|
||
const localResponse = await fetch(`/api/player/similarity/${id}?local_only=true`);
|
||
const localData = await localResponse.json().catch(() => ({}));
|
||
if (generation !== this._searchGeneration) return;
|
||
if (!localResponse.ok) throw new Error(localData.error || T.similarityFailed);
|
||
this.similaritySearchLabel = localData.label || initialLabel;
|
||
this.searchQuery = this.similaritySearchLabel;
|
||
this.searchResults = {
|
||
artists: [],
|
||
releases: [],
|
||
tracks: Array.isArray(localData.tracks) ? localData.tracks : [],
|
||
};
|
||
this.updateUnifiedSearch('tracks', true);
|
||
this.searchLoading = false;
|
||
this.similaritySearchStats = {
|
||
loading: true,
|
||
...this.similarityResultCounts(),
|
||
peers: 0,
|
||
elapsed_ms: localData.elapsed_ms || 0,
|
||
};
|
||
const { response, error } = await completeRequest;
|
||
if (error) throw error;
|
||
const data = await response.json().catch(() => ({}));
|
||
if (generation !== this._searchGeneration) return;
|
||
if (!response.ok) throw new Error(data.error || T.similarityFailed);
|
||
this.federationSearch = {
|
||
loading: false,
|
||
error: data.federation_error || '',
|
||
artists: [],
|
||
releases: [],
|
||
tracks: Array.isArray(data.federation_tracks) ? data.federation_tracks : [],
|
||
};
|
||
this.updateUnifiedSearch('tracks', true);
|
||
this.similaritySearchStats = {
|
||
loading: false,
|
||
...this.similarityResultCounts(),
|
||
peers: Number(data.queried_peers || 0),
|
||
elapsed_ms: Number(data.elapsed_ms || 0),
|
||
};
|
||
} catch (error) {
|
||
if (generation !== this._searchGeneration) return;
|
||
if (!this.searchResults) {
|
||
this.searchResults = { artists: [], releases: [], tracks: [] };
|
||
this.similaritySearchError = error?.message || T.similarityFailed;
|
||
} else {
|
||
this.federationSearch = {
|
||
...this.federationSearch,
|
||
loading: false,
|
||
error: error?.message || T.similarityFailed,
|
||
};
|
||
}
|
||
this.similaritySearchStats = {
|
||
...this.similaritySearchStats,
|
||
loading: false,
|
||
};
|
||
}
|
||
this.searchLoading = false;
|
||
this._afterNavigation(options);
|
||
},
|
||
|
||
similarityResultCounts() {
|
||
const artists = new Set();
|
||
for (const track of this.unifiedSearch.tracks) {
|
||
for (const artist of [...(track?.artists || []), ...(track?.featured_artists || [])]) {
|
||
const name = this.normalizeFederationSearchText(artist?.name);
|
||
if (name) artists.add(name);
|
||
}
|
||
}
|
||
return { tracks: this.unifiedSearch.tracks.length, artists: artists.size };
|
||
},
|
||
|
||
playSimilarityResult(track) {
|
||
const queue = Alpine.store('queue');
|
||
const tracks = this.displaySearchResults.tracks;
|
||
const key = queue._trackIdentity(track);
|
||
const index = tracks.findIndex(item => queue._trackIdentity(item) === key);
|
||
if (index >= 0) queue.playRelease(tracks, index);
|
||
},
|
||
|
||
formatSearchDuration(milliseconds) {
|
||
const ms = Math.max(0, Number(milliseconds) || 0);
|
||
if (ms < 10000) return `${(ms / 1000).toFixed(1)} s`;
|
||
if (ms < 60000) return `${Math.round(ms / 1000)} s`;
|
||
const totalSeconds = Math.round(ms / 1000);
|
||
const minutes = Math.floor(totalSeconds / 60);
|
||
const seconds = totalSeconds % 60;
|
||
return `${minutes}m ${String(seconds).padStart(2, '0')}s`;
|
||
},
|
||
|
||
clearSearch() {
|
||
this.cancelPendingSearch();
|
||
Alpine.store('searchGroups')?.reset();
|
||
this.stopFederationSearch();
|
||
this.searchQuery = '';
|
||
this.searchResults = null;
|
||
this.searchLoading = false;
|
||
this.similaritySearchLabel = '';
|
||
this.similaritySearchError = '';
|
||
this.similaritySearchStats = { loading: false, tracks: 0, artists: 0, peers: 0, elapsed_ms: 0 };
|
||
if (this.view === 'search') {
|
||
this.view = this._previousView || 'artists';
|
||
const catalogRoutes = {my_uploads:'#uploads', playlists:'#artists?tab=playlists', followed:'#followed'};
|
||
this._setHash(catalogRoutes[this.view] || '#artists');
|
||
if (this.view === 'artists' || this.view === 'my_uploads') {
|
||
this.$nextTick(() => { this._setupScroll(); });
|
||
}
|
||
}
|
||
},
|
||
|
||
stopFederationSearch() {
|
||
this._cancelFederationSearch?.();
|
||
this.federationSearch = { loading: false, error: '', artists: [], releases: [], tracks: [] };
|
||
this.unifiedSearch = { artists: [], releases: [], tracks: [], podcasts: [] };
|
||
},
|
||
|
||
updateUnifiedSearch(kind, audioSimilarity = false) {
|
||
const localScores = this.searchResults?.scores?.[kind] || {};
|
||
const rows = (this.searchResults?.[kind] || []).map(item => ({
|
||
...item, searchKey: 'local:' + item.id, search_score: localScores[item.id] ?? 0,
|
||
}));
|
||
const byId = new Map(rows.map(row => [row.id, row]));
|
||
const byContent = new Map(rows.filter(row => row.content_id).map(row => [row.content_id, row]));
|
||
for (const entity of this.federationSearch[kind]) {
|
||
const isTrack = kind === 'tracks';
|
||
const localId = isTrack ? entity.availability?.local?.track_id : entity.local_id;
|
||
let row = byId.get(localId) || byContent.get(entity.key.content_id);
|
||
if (!row) {
|
||
row = isTrack ? { ...(entity.local_track || this.federationQueueTrack(entity)) }
|
||
: { ...entity, id: localId ?? null };
|
||
const remoteKey = entity.key.content_id || entity.key.normalized_name || JSON.stringify(entity.key);
|
||
row.searchKey = localId ? 'local:' + localId : 'fed:' + remoteKey;
|
||
row.federation_only = !localId;
|
||
rows.push(row);
|
||
if (localId) byId.set(localId, row);
|
||
if (row.content_id) byContent.set(row.content_id, row);
|
||
}
|
||
if (audioSimilarity) {
|
||
row.similarity_score = Math.max(row.similarity_score ?? -1, entity.similarity_score ?? -1);
|
||
} else {
|
||
row.search_score = Math.max(row.search_score || 0, entity.search_score || 0);
|
||
}
|
||
if (isTrack) row._federationTrack = entity;
|
||
else if (kind === 'artists') row._federationArtist = entity;
|
||
else row._federationRelease = entity;
|
||
}
|
||
// Stable sort preserves the local catalogue order for equally ranked hits.
|
||
this.unifiedSearch[kind] = rows.sort(audioSimilarity
|
||
? (a, b) => (b.similarity_score ?? -1) - (a.similarity_score ?? -1) || a.title.localeCompare(b.title)
|
||
: (a, b) => b.search_score - a.search_score);
|
||
},
|
||
|
||
localSearchArtwork(kind, item) {
|
||
const local = this.availableFederationArtwork(item.image_url || item.cover_url);
|
||
if (local) return local;
|
||
const remote = item._federationArtist || item._federationRelease;
|
||
if (!remote) return '';
|
||
return kind === 'artists' ? this.federationArtistImage(remote) : this.federationReleaseCover(remote);
|
||
},
|
||
|
||
startFederationSearch(query) {
|
||
if (this.federationPaused) { this.stopFederationSearch(); return; }
|
||
this._cancelFederationSearch?.();
|
||
this.unifiedSearch = { artists: [], releases: [], tracks: [], podcasts: [] };
|
||
this.failedFederationArtwork = new Set();
|
||
this.federationSearch = { loading: true, error: '', artists: [], releases: [], tracks: [] };
|
||
const source = new EventSource(`/api/player/federation/search/events?q=${encodeURIComponent(query)}`);
|
||
const results = { tracks: new Map(), artists: new Map(), releases: new Map() };
|
||
const changed = new Set();
|
||
const collator = new Intl.Collator(undefined, { sensitivity: 'base' });
|
||
let batchTimer = null;
|
||
let active = true;
|
||
|
||
const publish = () => {
|
||
batchTimer = null;
|
||
for (const kind of changed) {
|
||
const ranked = Array.from(results[kind].values());
|
||
ranked.sort((a, b) => b.score - a.score || collator.compare(a.label, b.label));
|
||
this.federationSearch[kind] = ranked.map(({ entity, score }) => ({
|
||
...(kind === 'tracks' ? this.withTrackAvailability(entity) : entity),
|
||
search_score: score,
|
||
}));
|
||
this.updateUnifiedSearch(kind);
|
||
}
|
||
changed.clear();
|
||
};
|
||
const add = (kind, key, entity, label, score) => {
|
||
if (!active || !key) return;
|
||
results[kind].set(key, { entity, label, score: score ?? 0 });
|
||
changed.add(kind);
|
||
if (batchTimer === null) batchTimer = window.setTimeout(publish, 50);
|
||
};
|
||
const finish = (error = '') => {
|
||
if (!active) return;
|
||
this._cancelFederationSearch();
|
||
publish();
|
||
this.federationSearch.error = error;
|
||
this.federationSearch.loading = false;
|
||
};
|
||
const watchdog = window.setTimeout(() => finish('Federation search timed out'), 25000);
|
||
this._cancelFederationSearch = () => {
|
||
active = false;
|
||
window.clearTimeout(watchdog);
|
||
window.clearTimeout(batchTimer);
|
||
source.close();
|
||
this._cancelFederationSearch = null;
|
||
};
|
||
|
||
source.addEventListener('federation.track', event => {
|
||
const { entity: track, score } = JSON.parse(event.data);
|
||
add('tracks', track?.key?.content_id, track, track?.metadata?.title, score);
|
||
});
|
||
source.addEventListener('federation.artist', event => {
|
||
const { entity: artist, score } = JSON.parse(event.data);
|
||
add('artists', artist?.key?.normalized_name, artist, artist?.name, score);
|
||
});
|
||
source.addEventListener('federation.release', event => {
|
||
const { entity: release, score } = JSON.parse(event.data);
|
||
if (release?.key) add('releases', JSON.stringify(release.key), release, release.title, score);
|
||
});
|
||
source.addEventListener('search.completed', () => finish());
|
||
source.addEventListener('search.failed', event => {
|
||
let error = 'Federation search failed';
|
||
try {
|
||
error = JSON.parse(event.data)?.entity?.message || error;
|
||
} catch {}
|
||
finish(error);
|
||
});
|
||
source.onerror = () => finish('Federation connection interrupted');
|
||
},
|
||
|
||
normalizeFederationSearchText(value) {
|
||
return String(value || '')
|
||
.normalize('NFKD')
|
||
.toLocaleLowerCase()
|
||
.replace(/ё/g, 'е')
|
||
.replace(/[^\p{L}\p{N}]+/gu, ' ')
|
||
.trim()
|
||
.replace(/\s+/g, ' ');
|
||
},
|
||
|
||
availableFederationArtwork(url) {
|
||
return url && !this.failedFederationArtwork.has(url) ? url : '';
|
||
},
|
||
|
||
federationArtworkFailed(image) {
|
||
const url = image.getAttribute('src');
|
||
if (url) this.failedFederationArtwork.add(url);
|
||
},
|
||
|
||
federationArtistImage(artist) {
|
||
if (!artist?.name) return '';
|
||
return this.availableFederationArtwork(artist.image_url)
|
||
|| this.availableFederationArtwork(this.federationDiscoveredArtwork(artist.name));
|
||
},
|
||
|
||
hydrateFederationSearchRelease(release) {
|
||
if (!release?.key || release.local_id) return release;
|
||
const key = release.key;
|
||
const artistSet = names => JSON.stringify([...new Set(names || [])].sort());
|
||
const artists = artistSet(key.primary_artists);
|
||
const tracks = this.federationSearch.tracks.filter(track => {
|
||
const candidate = track.metadata?.release?.key;
|
||
return key.primary_artists?.length && candidate?.normalized_title === key.normalized_title
|
||
&& (candidate.year ?? null) === (key.year ?? null)
|
||
&& (candidate.release_type || null) === (key.release_type || null)
|
||
&& artistSet(candidate.primary_artists) === artists;
|
||
});
|
||
const owners = [...new Set([
|
||
...(release.sources || []).map(source => source.owner),
|
||
...tracks.flatMap(track =>
|
||
(track.availability?.federation || []).map(source => source.owner)
|
||
),
|
||
].filter(Boolean))];
|
||
return { ...release, tracks, owners };
|
||
},
|
||
|
||
federationReleaseCover(release) {
|
||
if (!release) return '';
|
||
return this.availableFederationArtwork(release.cover_url)
|
||
|| this.availableFederationArtwork(this.federationDiscoveredArtwork(release.artists?.[0], release.title));
|
||
},
|
||
|
||
federationDiscoveredArtwork(artist, release = '') {
|
||
if (!artist) return '';
|
||
const params = new URLSearchParams({ artist });
|
||
if (release) params.set('release', release);
|
||
return `/api/player/federation/catalog/artwork/discover?${params.toString()}`;
|
||
},
|
||
|
||
async loadFederationLikes() {
|
||
try {
|
||
const response = await fetch('/api/player/tracks/content/like');
|
||
if (!response.ok) return;
|
||
const ids = await response.json();
|
||
if (Array.isArray(ids)) this.federationLiked = ids;
|
||
} catch {}
|
||
},
|
||
|
||
federationIsLiked(track) {
|
||
return this.federationLiked.includes(track?.key?.content_id);
|
||
},
|
||
|
||
federationWireTrack(track) {
|
||
const metadata = track?.metadata || {};
|
||
const source = track?.availability?.federation?.[0] || {};
|
||
return {
|
||
item_id: source.item_id || '',
|
||
owner: source.owner || '',
|
||
title: metadata.title || '',
|
||
artist_names: (metadata.artists || []).map(artist => artist.name),
|
||
featured_artist_names: (metadata.featured_artists || []).map(artist => artist.name),
|
||
year: metadata.year || null,
|
||
duration_seconds: metadata.duration_seconds == null ? null : Math.round(metadata.duration_seconds),
|
||
content_id: track?.key?.content_id || '',
|
||
release_title: metadata.release?.title || null,
|
||
track_number: metadata.track_number || null,
|
||
disc_number: metadata.disc_number || null,
|
||
};
|
||
},
|
||
|
||
federationTrackFromWire(wire) {
|
||
if (!wire?.content_id || !wire?.owner || !wire?.item_id) return null;
|
||
return this.withTrackAvailability({
|
||
key: { content_id: wire.content_id },
|
||
metadata: {
|
||
title: wire.title || 'Unknown track',
|
||
artists: (wire.artist_names || []).map(name => ({
|
||
key: { normalized_name: name.trim().toLocaleLowerCase() },
|
||
name,
|
||
local_id: null,
|
||
})),
|
||
featured_artists: (wire.featured_artist_names || []).map(name => ({
|
||
key: { normalized_name: name.trim().toLocaleLowerCase() },
|
||
name,
|
||
local_id: null,
|
||
})),
|
||
release: wire.release_title ? { title: wire.release_title } : null,
|
||
year: wire.year,
|
||
duration_seconds: wire.duration_seconds,
|
||
track_number: wire.track_number,
|
||
disc_number: wire.disc_number,
|
||
cover_url: `/api/player/federation/tracks/artwork?owner=${encodeURIComponent(wire.owner)}&item_id=${encodeURIComponent(wire.item_id)}`,
|
||
},
|
||
availability: {
|
||
state: 'federated',
|
||
local: null,
|
||
federation: [{ owner: wire.owner, item_id: wire.item_id }],
|
||
},
|
||
});
|
||
},
|
||
|
||
federationQueueTrack(track) {
|
||
const metadata = track?.metadata || {};
|
||
const release = this.trackRelease(track);
|
||
const local = track.availability?.local;
|
||
return {
|
||
id: local?.track_id ?? `fed:${track.key.content_id}`,
|
||
content_id: track.key.content_id,
|
||
title: metadata.title || 'Unknown track',
|
||
track_number: metadata.track_number,
|
||
disc_number: metadata.disc_number,
|
||
duration_seconds: metadata.duration_seconds || 0,
|
||
artists: (metadata.artists || []).map(artist => ({
|
||
id: artist.local_id || null,
|
||
name: artist.name,
|
||
})),
|
||
featured_artists: (metadata.featured_artists || []).map(artist => ({
|
||
id: artist.local_id || null,
|
||
name: artist.name,
|
||
})),
|
||
release_id: release?.id ?? null,
|
||
release_key: release?.key || null,
|
||
release_title: release?.title || '',
|
||
release_year: release?.key?.year ?? metadata.year ?? null,
|
||
cover_url: metadata.cover_url || null,
|
||
stream_url: local?.stream_url || '',
|
||
uploader_name: 'Federation',
|
||
federation_pending: true,
|
||
_federationTrack: track,
|
||
similarity_score: track.similarity_score,
|
||
};
|
||
},
|
||
|
||
async openFederatedRelease(release, options = {}) {
|
||
if (GUEST || !release) return;
|
||
if (release.local_id) return this.openRelease(release.local_id, options);
|
||
const input = release.key;
|
||
const key = Array.isArray(input?.primary_artists) && input.primary_artists.every(name => typeof name === 'string')
|
||
&& (input.year == null || Number.isInteger(input.year))
|
||
&& (input.release_type == null || typeof input.release_type === 'string')
|
||
? this.federationReleaseKey(input.normalized_title, input.primary_artists, input.year, input.release_type)
|
||
: null;
|
||
this._beginNavigation(key ? this.releaseHref({ key }) : location.hash, options);
|
||
const version = this._navigationVersion;
|
||
this.view = 'release_detail';
|
||
this.searchQuery = '';
|
||
this.searchResults = null;
|
||
this.currentRelease = null;
|
||
this.releaseUnavailable = !key;
|
||
if (!key) return;
|
||
const id = await this.resolveFederatedId('release', { key: JSON.stringify(key) });
|
||
if (version !== this._navigationVersion) return;
|
||
if (id) {
|
||
history.replaceState(history.state, '', '#release/' + id);
|
||
return this.openRelease(id, { ...options, fromHash: true });
|
||
}
|
||
const queuedTracks = (release.tracks || []).map(track => this.federationQueueTrack(track));
|
||
const detail = {
|
||
id: null,
|
||
title: release.title || key.normalized_title,
|
||
release_type: release.release_type || key.release_type,
|
||
year: release.year ?? key.year,
|
||
cover_url: this.federationReleaseCover(release),
|
||
artists: (release.artists || key.primary_artists).map(name => ({ id: null, name })),
|
||
tracks: queuedTracks,
|
||
federationPeers: release.owners || [],
|
||
uploaders: (release.owners || []).map(owner => ({
|
||
name: `Federation ${owner.slice(0, 10)}`,
|
||
track_count: queuedTracks.length,
|
||
})),
|
||
federated: true,
|
||
federationRelease: { ...release, key },
|
||
};
|
||
if (release.title) this.currentRelease = detail;
|
||
this.startReleaseFederation(detail);
|
||
this._afterNavigation(options);
|
||
},
|
||
|
||
openSearchRelease(release) {
|
||
if (release.federation_only) {
|
||
return this.openFederatedRelease(this.hydrateFederationSearchRelease(release._federationRelease));
|
||
}
|
||
return this.openRelease(release.id);
|
||
},
|
||
|
||
playFederatedRelease(release) {
|
||
const tracks = (release?.tracks || []).map(track => this.federationQueueTrack(track));
|
||
if (tracks.length) Alpine.store('queue').playRelease(tracks, 0);
|
||
},
|
||
|
||
enqueueFederatedTrack(track, next = false) {
|
||
const queued = this.federationQueueTrack(track);
|
||
if (next) Alpine.store('queue').addNextInQueue([queued]);
|
||
else Alpine.store('queue').addToEnd([queued]);
|
||
},
|
||
|
||
openFederationTrackInfo(track) {
|
||
const metadata = track?.metadata || {};
|
||
const sources = track?.availability?.federation || [];
|
||
const release = this.trackRelease(track);
|
||
const rows = [
|
||
{ label: T.title, value: metadata.title || T.unknown },
|
||
{ label: T.artists, links: this.trackArtistLinks(track), value: T.unknown },
|
||
{ label: T.release, links: release ? [{ href: this.releaseHref(release), label: release.title }] : [], value: T.unknown },
|
||
{ label: T.year, value: metadata.year || T.unknown },
|
||
{ label: T.duration, value: formatTime(metadata.duration_seconds) },
|
||
{ label: 'Content ID', value: track?.key?.content_id || T.unknown },
|
||
{ label: 'Availability', value: this.isTrackLocal(track) ? 'Local' : `${sources.length} peer${sources.length === 1 ? '' : 's'}` },
|
||
{ label: 'Source', value: 'Federation' },
|
||
];
|
||
Alpine.store('info').openRows(T.trackInfoTitle, rows);
|
||
},
|
||
|
||
withTrackAvailability(track) {
|
||
const contentId = track?.key?.content_id;
|
||
const known = contentId ? this.trackAvailability[contentId] : null;
|
||
if (!known) return track;
|
||
return {
|
||
...track,
|
||
availability: {
|
||
...(track.availability || {}),
|
||
state: known.state,
|
||
local: known.local ?? track.availability?.local ?? null,
|
||
},
|
||
};
|
||
},
|
||
|
||
isTrackLocal(track) {
|
||
const contentId = track?.key?.content_id;
|
||
return (contentId && this.trackAvailability[contentId]?.state === 'local')
|
||
|| track?.availability?.state === 'local'
|
||
|| !!track?.availability?.local;
|
||
},
|
||
|
||
applyTrackAvailability(change) {
|
||
const contentId = change?.content_id;
|
||
if (!contentId || !change.state) return;
|
||
const previous = this.trackAvailability[contentId] || {};
|
||
const availability = {
|
||
...previous,
|
||
...change,
|
||
content_id: contentId,
|
||
};
|
||
this.trackAvailability[contentId] = availability;
|
||
const updateTrack = track => track?.key?.content_id === contentId
|
||
? this.withTrackAvailability(track)
|
||
: track;
|
||
const searchTracks = this.federationSearch.tracks;
|
||
const index = searchTracks.findIndex(track => track.key?.content_id === contentId);
|
||
if (index >= 0) {
|
||
searchTracks[index] = this.withTrackAvailability(searchTracks[index]);
|
||
if (this.view === 'search' && this.searchMode !== 'lyrics') {
|
||
this.updateUnifiedSearch('tracks', !this.ordinarySearch);
|
||
}
|
||
}
|
||
this.artistFederation = {
|
||
...this.artistFederation,
|
||
tracks: this.artistFederation.tracks.map(updateTrack),
|
||
releases: this.artistFederation.releases.map(release => ({
|
||
...release,
|
||
tracks: (release.tracks || []).map(updateTrack),
|
||
})),
|
||
};
|
||
},
|
||
|
||
publishTrackAvailability(change) {
|
||
this.applyTrackAvailability(change);
|
||
window.dispatchEvent(new CustomEvent('furumi:track-availability', {
|
||
detail: { ...change, source: 'library' },
|
||
}));
|
||
},
|
||
|
||
refreshMaterializedArtwork(track) {
|
||
const metadata = track?.metadata || {};
|
||
const names = (metadata.artists || []).map(artist =>
|
||
this.normalizeFederationSearchText(artist.name)
|
||
);
|
||
if (names.length) {
|
||
this.artists = this.artists.map(artist => {
|
||
if (artist.image_url
|
||
|| !names.includes(this.normalizeFederationSearchText(artist.name))) {
|
||
return artist;
|
||
}
|
||
return {
|
||
...artist,
|
||
image_url: this.federationDiscoveredArtwork(artist.name),
|
||
};
|
||
});
|
||
}
|
||
},
|
||
|
||
async toggleFederationLike(track) {
|
||
const contentId = track?.key?.content_id;
|
||
if (!contentId) return;
|
||
const liked = !this.federationLiked.includes(contentId);
|
||
return this.setFederationLike(track, liked);
|
||
},
|
||
|
||
async setFederationLike(track, liked, refresh = true) {
|
||
const contentId = track?.key?.content_id;
|
||
if (!contentId) return;
|
||
const response = await fetch('/api/player/tracks/content/like', {
|
||
method: 'POST',
|
||
headers: { 'Content-Type': 'application/json' },
|
||
body: JSON.stringify({
|
||
content_id: contentId,
|
||
liked,
|
||
federation: this.federationWireTrack(track),
|
||
}),
|
||
});
|
||
if (!response.ok) return;
|
||
this.updateLikeStatus(contentId, liked, []);
|
||
if (refresh) await this.reloadLikes();
|
||
},
|
||
|
||
updateLikeStatus(contentId, liked, trackIds) {
|
||
if (contentId) {
|
||
if (!liked) this.federationLiked = this.federationLiked.filter(id => id !== contentId);
|
||
else if (!this.federationLiked.includes(contentId)) this.federationLiked.push(contentId);
|
||
}
|
||
if (!liked && this.currentPlaylist?.id === -1) {
|
||
this.currentPlaylist.tracks = this.currentPlaylist.tracks.filter(track =>
|
||
!(contentId && track.content_id === contentId) && !trackIds.includes(track.id));
|
||
}
|
||
},
|
||
|
||
uniqueLikeTracks(tracks) {
|
||
const contentById = new Map();
|
||
for (const track of tracks) {
|
||
if (track.content_id) contentById.set(track.id, track.content_id);
|
||
}
|
||
const unique = new Map();
|
||
for (const track of tracks) {
|
||
const key = track.content_id || contentById.get(track.id) || track.id;
|
||
const previous = unique.get(key);
|
||
if (!previous || (previous.federation_pending && !track.federation_pending)) unique.set(key, track);
|
||
}
|
||
return [...unique.values()];
|
||
},
|
||
|
||
sortLikeTracks(tracks) {
|
||
return this.uniqueLikeTracks(tracks).sort((left, right) => {
|
||
const order = Number(right.sort_key || 0) - Number(left.sort_key || 0);
|
||
if (order) return order;
|
||
const stable = String(left.content_id || left.id || '')
|
||
.localeCompare(String(right.content_id || right.id || ''));
|
||
if (stable) return stable;
|
||
const title = String(left.title || '').localeCompare(
|
||
String(right.title || ''),
|
||
undefined,
|
||
{ sensitivity: 'base' },
|
||
);
|
||
return title;
|
||
});
|
||
},
|
||
|
||
isMixedReleaseLiked(release) {
|
||
const tracks = release?.tracks || [];
|
||
if (!tracks.length) return false;
|
||
return tracks.every(track => track.federation_pending
|
||
? this.federationIsLiked(track._federationTrack)
|
||
: Alpine.store('likes').has(track.id)
|
||
);
|
||
},
|
||
|
||
async toggleMixedReleaseLike(release) {
|
||
const tracks = release?.tracks || [];
|
||
if (!tracks.length) return;
|
||
if (release.id && tracks.every(track => !track.federation_pending)) {
|
||
return Alpine.store('likes').toggleRelease(release.id);
|
||
}
|
||
const liked = !this.isMixedReleaseLiked(release);
|
||
const operations = [];
|
||
for (const track of this.uniqueLikeTracks(tracks)) {
|
||
if (track.federation_pending) {
|
||
if (this.federationIsLiked(track._federationTrack) !== liked) {
|
||
operations.push(this.setFederationLike(track._federationTrack, liked, false));
|
||
}
|
||
} else if (Alpine.store('likes').has(track.id) !== liked) {
|
||
operations.push(Alpine.store('likes').toggle(track.id, false));
|
||
}
|
||
}
|
||
await Promise.allSettled(operations);
|
||
await this.reloadLikes();
|
||
},
|
||
|
||
async playFederatedTrack(track, options = {}) {
|
||
const contentId = track?.key?.content_id;
|
||
const sources = track?.availability?.federation || [];
|
||
const knownPlayable = contentId && this.trackAvailability[contentId]?.playable;
|
||
if (knownPlayable) {
|
||
if (Number.isInteger(options.queueIndex)) {
|
||
const queue = Alpine.store('queue');
|
||
queue.tracks = queue.tracks.map((item, index) =>
|
||
index === options.queueIndex ? knownPlayable : item
|
||
);
|
||
if (options.playAfterPrepare !== false) {
|
||
Alpine.store('player').playQueueIndex(options.queueIndex);
|
||
}
|
||
} else {
|
||
Alpine.store('queue').playRelease([knownPlayable], 0);
|
||
}
|
||
return;
|
||
}
|
||
if (!contentId || sources.length === 0) return;
|
||
if (this.federationFailures[contentId]) {
|
||
const failures = { ...this.federationFailures };
|
||
delete failures[contentId];
|
||
this.federationFailures = failures;
|
||
}
|
||
if (this.federationPreparing[contentId]) {
|
||
if (options.playAfterPrepare !== false) {
|
||
this.federationPreparing = {
|
||
...this.federationPreparing,
|
||
[contentId]: {
|
||
...this.federationPreparing[contentId],
|
||
playWhenReady: true,
|
||
queueIndex: options.queueIndex,
|
||
},
|
||
};
|
||
}
|
||
return;
|
||
}
|
||
this.federationPreparing = {
|
||
...this.federationPreparing,
|
||
[contentId]: {
|
||
phase: 'connecting',
|
||
received: 0,
|
||
total: 0,
|
||
percent: 0,
|
||
bytesPerSecond: 0,
|
||
sampledAt: performance.now(),
|
||
playWhenReady: options.playAfterPrepare !== false,
|
||
queueIndex: options.queueIndex,
|
||
},
|
||
};
|
||
try {
|
||
let prepared = null;
|
||
let lastError = 'Federated track download failed';
|
||
for (const source of sources) {
|
||
const preparedResponse = await fetch('/api/player/federation/tracks/prepare', {
|
||
method: 'POST',
|
||
headers: { 'Content-Type': 'application/json' },
|
||
body: JSON.stringify({
|
||
content_id: contentId,
|
||
owner: source.owner,
|
||
item_id: source.item_id,
|
||
}),
|
||
});
|
||
if (!preparedResponse.ok || !preparedResponse.body) {
|
||
const failure = await preparedResponse.json().catch(() => ({}));
|
||
lastError = failure.error || lastError;
|
||
continue;
|
||
}
|
||
const reader = preparedResponse.body.getReader();
|
||
const decoder = new TextDecoder();
|
||
let buffered = '';
|
||
let sourceFailed = false;
|
||
const consume = line => {
|
||
if (!line.trim()) return;
|
||
const event = JSON.parse(line);
|
||
if (event.kind === 'progress') {
|
||
const previous = this.federationPreparing[contentId];
|
||
if (!previous) return;
|
||
const now = performance.now();
|
||
const seconds = Math.max((now - previous.sampledAt) / 1000, 0.001);
|
||
const instantSpeed = event.received > previous.received
|
||
? (event.received - previous.received) / seconds
|
||
: previous.bytesPerSecond;
|
||
const speed = previous.bytesPerSecond > 0 && instantSpeed > 0
|
||
? previous.bytesPerSecond * 0.65 + instantSpeed * 0.35
|
||
: instantSpeed;
|
||
this.federationPreparing = {
|
||
...this.federationPreparing,
|
||
[contentId]: {
|
||
...previous,
|
||
phase: event.phase,
|
||
received: Number(event.received || 0),
|
||
total: Number(event.total || 0),
|
||
percent: event.total > 0
|
||
? Math.min(100, event.received / event.total * 100)
|
||
: 0,
|
||
bytesPerSecond: speed,
|
||
sampledAt: now,
|
||
},
|
||
};
|
||
} else if (event.kind === 'completed') {
|
||
prepared = event;
|
||
} else if (event.kind === 'failed') {
|
||
sourceFailed = true;
|
||
lastError = event.error || lastError;
|
||
}
|
||
};
|
||
while (true) {
|
||
const { value, done } = await reader.read();
|
||
buffered += decoder.decode(value || new Uint8Array(), { stream: !done });
|
||
const lines = buffered.split('\n');
|
||
buffered = lines.pop() || '';
|
||
for (const line of lines) consume(line);
|
||
if (done) {
|
||
consume(buffered);
|
||
break;
|
||
}
|
||
}
|
||
if (prepared) break;
|
||
if (!sourceFailed) lastError = 'Federated download ended unexpectedly';
|
||
}
|
||
if (!prepared) throw new Error(lastError);
|
||
let playable;
|
||
if (prepared.local_track_id != null) {
|
||
const tracksResponse = await fetch('/api/player/tracks-by-ids', {
|
||
method: 'POST',
|
||
headers: { 'Content-Type': 'application/json' },
|
||
body: JSON.stringify({ ids: [prepared.local_track_id] }),
|
||
});
|
||
const tracks = await tracksResponse.json();
|
||
playable = tracks?.[0];
|
||
} else {
|
||
playable = {
|
||
...this.federationQueueTrack(track),
|
||
id: `fed:${contentId}`,
|
||
stream_url: prepared.stream_url,
|
||
federation_pending: false,
|
||
federated_cache: true,
|
||
federation: { content_id: contentId, sources: track.availability.federation },
|
||
};
|
||
}
|
||
if (!playable) throw new Error('Prepared track is unavailable');
|
||
const queueCover = Number.isInteger(options.queueIndex)
|
||
? Alpine.store('queue')?.tracks?.[options.queueIndex]?.cover_url
|
||
: null;
|
||
if (!playable.cover_url) {
|
||
playable.cover_url = queueCover || track?.metadata?.cover_url || null;
|
||
}
|
||
if (prepared.local_track_id != null) {
|
||
this.publishTrackAvailability({
|
||
content_id: contentId,
|
||
state: 'local',
|
||
local: {
|
||
track_id: prepared.local_track_id,
|
||
stream_url: prepared.stream_url,
|
||
},
|
||
playable,
|
||
});
|
||
this.refreshMaterializedArtwork(track);
|
||
Alpine.store('likes')?.reload();
|
||
if (this.view === 'listening') Alpine.store('listening').load();
|
||
}
|
||
const finalProgress = this.federationPreparing[contentId] || {};
|
||
const queueIndex = Number.isInteger(finalProgress.queueIndex)
|
||
? finalProgress.queueIndex
|
||
: options.queueIndex;
|
||
const playWhenReady = finalProgress.playWhenReady !== false;
|
||
if (Number.isInteger(queueIndex)) {
|
||
const queue = Alpine.store('queue');
|
||
queue.tracks = queue.tracks.map((item, index) =>
|
||
index === queueIndex ? playable : item
|
||
);
|
||
if (playWhenReady) Alpine.store('player').playQueueIndex(queueIndex);
|
||
} else {
|
||
Alpine.store('queue').playRelease([playable], 0);
|
||
}
|
||
} catch (error) {
|
||
this.federationFailures = {
|
||
...this.federationFailures,
|
||
[contentId]: {
|
||
message: error?.message || 'Federated track is temporarily unavailable',
|
||
failedAt: Date.now(),
|
||
},
|
||
};
|
||
} finally {
|
||
const next = { ...this.federationPreparing };
|
||
delete next[contentId];
|
||
this.federationPreparing = next;
|
||
}
|
||
},
|
||
|
||
federationDownload(contentId) {
|
||
return this.federationPreparing[contentId] || null;
|
||
},
|
||
|
||
federationFailure(contentId) {
|
||
return this.federationFailures[contentId] || null;
|
||
},
|
||
|
||
federationDownloadTooltip(contentId) {
|
||
const progress = this.federationDownload(contentId);
|
||
if (!progress) return '';
|
||
const phases = {
|
||
checking: 'Checking local library',
|
||
connecting: 'Connecting to peer',
|
||
discovering: 'Looking for another peer',
|
||
downloading: 'Downloading',
|
||
verifying: 'Verifying content ID',
|
||
saving: 'Adding to library',
|
||
ready: 'Ready',
|
||
};
|
||
let text = phases[progress.phase] || 'Preparing';
|
||
if (progress.total > 0) {
|
||
text += ` · ${progress.percent.toFixed(0)}%`;
|
||
text += ` · ${this.formatFederationBytes(progress.received)} / ${this.formatFederationBytes(progress.total)}`;
|
||
}
|
||
if (progress.bytesPerSecond > 0 && progress.phase === 'downloading') {
|
||
text += ` · ${this.formatFederationBytes(progress.bytesPerSecond)}/s`;
|
||
}
|
||
return text;
|
||
},
|
||
|
||
formatFederationBytes(value) {
|
||
const bytes = Math.max(0, Number(value || 0));
|
||
if (bytes < 1024) return `${Math.round(bytes)} B`;
|
||
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
|
||
if (bytes < 1024 * 1024 * 1024) return `${(bytes / 1024 / 1024).toFixed(1)} MB`;
|
||
return `${(bytes / 1024 / 1024 / 1024).toFixed(1)} GB`;
|
||
},
|
||
|
||
searchTrackLiked(track) {
|
||
return track.federation_only ? this.federationIsLiked(track._federationTrack) : Alpine.store('likes').has(track.id);
|
||
},
|
||
|
||
searchTrackNumber(track) {
|
||
if (track.federation_only) {
|
||
const progress = this.federationDownload(track.content_id);
|
||
if (progress) return progress.total ? Math.round(progress.percent) + '%' : '…';
|
||
if (this.federationFailure(track.content_id)) return '!';
|
||
}
|
||
return track._searchGroupChild ? '↳' : track._searchGroupNumber;
|
||
},
|
||
|
||
playSearchTrack(idx) {
|
||
const tracks = this.displaySearchResults.tracks;
|
||
const groups = Alpine.store('searchGroups');
|
||
groups.playRows(groups.rows(tracks, 'search'), tracks, idx);
|
||
},
|
||
|
||
_setupScroll() {
|
||
if (this._observer) this._observer.disconnect();
|
||
this.$nextTick(() => {
|
||
const sentinel = document.getElementById('artist-sentinel');
|
||
if (!sentinel) return;
|
||
this._observer = new IntersectionObserver((entries) => {
|
||
if (entries[0].isIntersecting && !this.loading && !this._allLoaded) {
|
||
this.loadArtists(this.artistsPage + 1);
|
||
}
|
||
}, { root: document.getElementById('center-scroll'), rootMargin: '900px 0px', threshold: 0.01 });
|
||
this._observer.observe(sentinel);
|
||
this._fillArtistViewport();
|
||
});
|
||
},
|
||
|
||
_fillArtistViewport() {
|
||
if (!(this.view === 'artists' || this.view === 'my_uploads') || this.loading || this._allLoaded) return;
|
||
const el = this._scrollElement();
|
||
if (!el) return;
|
||
if (el.scrollHeight <= el.clientHeight + 900) {
|
||
this.loadArtists(this.artistsPage + 1);
|
||
}
|
||
},
|
||
|
||
$nextTick(fn) {
|
||
setTimeout(fn, 50);
|
||
},
|
||
});
|
||
|
||
// -----------------------------------------------------------------------
|
||
// Likes store
|
||
// -----------------------------------------------------------------------
|
||
Alpine.store('likes', {
|
||
_set: new Set(),
|
||
|
||
init() {
|
||
if (GUEST) return;
|
||
this.reload();
|
||
},
|
||
|
||
async reload() {
|
||
try {
|
||
const response = await fetch('/api/player/likes');
|
||
if (!response.ok) return;
|
||
const data = await response.json();
|
||
this._set = new Set(data.track_ids || []);
|
||
} catch {}
|
||
},
|
||
|
||
has(trackId) {
|
||
return this._set.has(trackId);
|
||
},
|
||
|
||
async toggle(trackId, refresh = true) {
|
||
const wasLiked = this._set.has(trackId);
|
||
if (wasLiked) {
|
||
this._set.delete(trackId);
|
||
} else {
|
||
this._set.add(trackId);
|
||
}
|
||
// Force Alpine reactivity
|
||
this._set = new Set(this._set);
|
||
try {
|
||
const res = await fetch(`/api/player/likes/toggle/${trackId}`, { method: 'POST' });
|
||
if (!res.ok) throw new Error('like update failed');
|
||
const data = await res.json();
|
||
const ids = data.affected_track_ids?.length ? data.affected_track_ids : [trackId];
|
||
for (const id of ids) {
|
||
if (data.liked) this._set.add(id);
|
||
else this._set.delete(id);
|
||
}
|
||
this._set = new Set(this._set);
|
||
const library = Alpine.store('library');
|
||
library.updateLikeStatus(data.content_id, data.liked, ids);
|
||
Alpine.store('offline')?.rememberLikes(this._set, library.federationLiked);
|
||
if (refresh) await Promise.all([Alpine.store('playlists').reload(), library.refreshLikedPlaylist()]);
|
||
} catch {
|
||
if (wasLiked) this._set.add(trackId);
|
||
else this._set.delete(trackId);
|
||
this._set = new Set(this._set);
|
||
await this.reload();
|
||
}
|
||
},
|
||
|
||
async toggleRelease(releaseId) {
|
||
try {
|
||
const res = await fetch(`/api/player/likes/release/${releaseId}`, { method: 'POST' });
|
||
if (res.ok) {
|
||
await Alpine.store('library').reloadLikes();
|
||
}
|
||
} catch {}
|
||
},
|
||
|
||
isReleaseLiked(release) {
|
||
if (!release || !release.tracks || release.tracks.length === 0) return false;
|
||
return release.tracks.every(t => this._set.has(t.id));
|
||
},
|
||
});
|
||
|
||
// -----------------------------------------------------------------------
|
||
// Artist follows store
|
||
// -----------------------------------------------------------------------
|
||
Alpine.store('follows', {
|
||
_set: new Set(),
|
||
artists: [],
|
||
|
||
init() {
|
||
if (GUEST) return;
|
||
this.reload();
|
||
},
|
||
|
||
has(artistId) {
|
||
return this._set.has(Number(artistId));
|
||
},
|
||
|
||
async reload() {
|
||
try {
|
||
const res = await fetch('/api/player/follows');
|
||
if (!res.ok) return;
|
||
const data = await res.json();
|
||
this._set = new Set((data.artist_ids || []).map(Number));
|
||
this.artists = data.artists || [];
|
||
} catch {}
|
||
},
|
||
|
||
_artistSnapshot(artistId) {
|
||
const id = Number(artistId);
|
||
const library = Alpine.store('library');
|
||
const fromLists = [
|
||
...(library.artists || []),
|
||
...((library.searchResults && library.searchResults.artists) || []),
|
||
].find(artist => Number(artist.id) === id);
|
||
if (fromLists) return fromLists;
|
||
if (library.currentArtist && Number(library.currentArtist.id) === id) {
|
||
return {
|
||
id,
|
||
name: library.currentArtist.name,
|
||
image_url: library.currentArtist.image_url,
|
||
release_count: (library.currentArtist.releases || []).length,
|
||
track_count: library.currentArtist.total_track_count || 0,
|
||
};
|
||
}
|
||
return null;
|
||
},
|
||
|
||
async toggle(artistId) {
|
||
const id = Number(artistId);
|
||
if (!id) return;
|
||
|
||
if (this._set.has(id)) {
|
||
this._set.delete(id);
|
||
this.artists = this.artists.filter(artist => Number(artist.id) !== id);
|
||
} else {
|
||
this._set.add(id);
|
||
const snapshot = this._artistSnapshot(id);
|
||
if (snapshot && !this.artists.some(artist => Number(artist.id) === id)) {
|
||
this.artists = [snapshot, ...this.artists];
|
||
}
|
||
}
|
||
this._set = new Set(this._set);
|
||
|
||
try {
|
||
const res = await fetch(`/api/player/follows/toggle/${id}`, { method: 'POST' });
|
||
if (res.ok) {
|
||
const data = await res.json();
|
||
if (data.followed) this._set.add(id);
|
||
else this._set.delete(id);
|
||
this._set = new Set(this._set);
|
||
}
|
||
} catch {}
|
||
|
||
await this.reload();
|
||
},
|
||
});
|
||
|
||
// -----------------------------------------------------------------------
|
||
// Torrent import store
|
||
// -----------------------------------------------------------------------
|
||
Alpine.store('torrents', {
|
||
modal: false,
|
||
downloadsEnabled: {{ downloads_enabled }},
|
||
torrentDownloadsEnabled: {{ torrent_downloads_enabled }},
|
||
youtubeDownloadsEnabled: {{ youtube_downloads_enabled }},
|
||
sourceTab: 'files',
|
||
downloadHistory: [],
|
||
latestDownload: null,
|
||
downloadStats: null,
|
||
historyPage: 0,
|
||
historyPageSize: 20,
|
||
historyHasMore: false,
|
||
historyLoading: false,
|
||
historyLoaded: false,
|
||
historyError: '',
|
||
historyRequest: 0,
|
||
youtubeUrl: '',
|
||
youtubePreview: null,
|
||
youtubePreviewSelected: new Set(),
|
||
torrentPlaylistChoice: '',
|
||
torrentNewPlaylistTitle: '',
|
||
localPlaylistChoice: '',
|
||
localNewPlaylistTitle: '',
|
||
localPlaylistLocked: false,
|
||
localTargetPlaylistId: null,
|
||
youtubePlaylistChoice: '',
|
||
youtubeNewPlaylistTitle: '',
|
||
youtubePreviewLoading: false,
|
||
youtubeDetail: null,
|
||
youtubeActionBusy: false,
|
||
youtubeSubmitting: false,
|
||
file: null,
|
||
localFiles: [],
|
||
localFilesBatchId: null,
|
||
localFileUploadIds: new WeakMap(),
|
||
localFilesDragging: false,
|
||
localFilesUploading: false,
|
||
localPendingFinish: false,
|
||
magnet: '',
|
||
currentJob: null,
|
||
previewData: null,
|
||
workspaceMode: 'new',
|
||
treeRoot: null,
|
||
selected: new Set(),
|
||
expanded: new Set(),
|
||
loading: false,
|
||
message: '',
|
||
error: false,
|
||
_pollTimer: null,
|
||
_pollRequest: 0,
|
||
_refreshTimer: null,
|
||
uploadProgress: 0,
|
||
uploadProgressText: '',
|
||
open() {
|
||
if (!this.downloadsEnabled || this.modal) return;
|
||
this.youtubeDetail = null;
|
||
if (this.workspaceMode === 'session' && !['preview','resolving'].includes(this.normalizedStatus(this.currentJob))) this.addNew();
|
||
this.sourceTab = 'files';
|
||
this.historyPage = 0;
|
||
this.modal = true;
|
||
Alpine.store('playlists')?.reload?.();
|
||
this.message = '';
|
||
this.error = false;
|
||
this.refreshDownloads();
|
||
this._startRefresh();
|
||
},
|
||
|
||
close() {
|
||
this.modal = false;
|
||
this.historyRequest++;
|
||
this.historyLoading = false;
|
||
this._stopRefresh();
|
||
this._stopPoll();
|
||
},
|
||
|
||
_stopPoll() {
|
||
if (this._pollTimer) clearTimeout(this._pollTimer);
|
||
this._pollTimer = null;
|
||
this._pollRequest++;
|
||
},
|
||
|
||
isImporting() {
|
||
return this.workspaceMode === 'new';
|
||
},
|
||
|
||
showSourceTab(tab) {
|
||
if (tab === 'torrents' && !this.torrentDownloadsEnabled || tab === 'youtube' && !this.youtubeDownloadsEnabled) return;
|
||
if (this.sourceTab === tab) return;
|
||
this._stopPoll();
|
||
this.sourceTab = tab;
|
||
if (tab === 'torrents') this.resumeTorrentPoll();
|
||
this._setMessage('');
|
||
this.historyPage = 0;
|
||
this.historyLoaded = false;
|
||
this.refreshDownloads();
|
||
},
|
||
|
||
async refreshDownloads() {
|
||
if (!this.modal) return;
|
||
const request = ++this.historyRequest;
|
||
const history = this.sourceTab === 'history';
|
||
const limit = history ? this.historyPageSize : 1;
|
||
const page = this.historyPage;
|
||
const detailId = this.sourceTab === 'youtube' && this.youtubeDetail?.id;
|
||
const params = detailId ? new URLSearchParams({source:'youtube', id:detailId})
|
||
: new URLSearchParams({limit, offset:history ? page * limit : 0});
|
||
this.historyLoading = true;
|
||
try {
|
||
const res = await fetch('/api/player/downloads/history?' + params);
|
||
if (!res.ok) throw new Error(T.loadHistoryFailed);
|
||
const data = await res.json();
|
||
if (request !== this.historyRequest) return;
|
||
if (history && page && !data.items.length) {
|
||
this.historyPage--;
|
||
return this.refreshDownloads();
|
||
}
|
||
if (!detailId && page === 0) this.latestDownload = data.items[0] || null;
|
||
if (history) {
|
||
this.downloadHistory = data.items;
|
||
this.historyHasMore = data.has_more;
|
||
this.historyLoaded = true;
|
||
}
|
||
if (this.downloadStats && data.stats.tracks !== this.downloadStats.tracks) Alpine.store('playlists')?.reload?.();
|
||
this.downloadStats = data.stats;
|
||
if (detailId && this.youtubeDetail?.id === detailId && !data.items.length) this.youtubeDetail = null;
|
||
else this.syncYoutubeJob(data.items);
|
||
this.historyError = '';
|
||
} catch {
|
||
if (request === this.historyRequest) this.historyError = T.loadHistoryFailed;
|
||
} finally {
|
||
if (request === this.historyRequest) this.historyLoading = false;
|
||
}
|
||
},
|
||
|
||
changeHistoryPage(delta) {
|
||
if (this.historyLoading || (delta < 0 ? !this.historyPage : !this.historyHasMore)) return;
|
||
this.historyPage += delta;
|
||
this.historyLoaded = false;
|
||
this.refreshDownloads();
|
||
},
|
||
|
||
clearYoutubePreview() {
|
||
this.youtubePreview = null;
|
||
this.youtubePreviewSelected = new Set();
|
||
this.youtubePlaylistChoice = '';
|
||
this.youtubeNewPlaylistTitle = '';
|
||
},
|
||
|
||
async previewYoutubeUrl() {
|
||
const url = String(this.youtubeUrl || '').trim();
|
||
if (!url || this.youtubePreviewLoading || this.youtubeSubmitting) return;
|
||
this.youtubePreviewLoading = true;
|
||
this.clearYoutubePreview();
|
||
this._setMessage(T.youtubeParsing);
|
||
try {
|
||
const res = await fetch('/api/player/youtube/preview', {
|
||
method: 'POST',
|
||
headers: { 'Content-Type': 'application/json' },
|
||
body: JSON.stringify({ url }),
|
||
});
|
||
const data = await res.json().catch(() => null);
|
||
if (!res.ok) throw new Error(data?.error || T.youtubePreviewFailed);
|
||
const items = Array.isArray(data?.items) ? data.items : [];
|
||
if (!items.length) throw new Error(T.youtubePreviewFailed);
|
||
if (String(this.youtubeUrl || '').trim() !== url) return;
|
||
this.youtubePreview = { ...data, items };
|
||
this.youtubePreviewSelected = new Set(
|
||
items.filter(item => item.selected_by_default).map(item => item.source_id)
|
||
);
|
||
this._setMessage('');
|
||
} catch (err) {
|
||
this._setMessage(err.message || T.youtubePreviewFailed, true);
|
||
} finally {
|
||
this.youtubePreviewLoading = false;
|
||
}
|
||
},
|
||
|
||
youtubePreviewIsSelected(sourceId) {
|
||
return this.youtubePreviewSelected.has(sourceId);
|
||
},
|
||
|
||
toggleYoutubePreviewItem(sourceId) {
|
||
const selected = new Set(this.youtubePreviewSelected);
|
||
if (selected.has(sourceId)) selected.delete(sourceId);
|
||
else selected.add(sourceId);
|
||
this.youtubePreviewSelected = selected;
|
||
},
|
||
|
||
selectAllYoutubePreview() {
|
||
const items = Array.isArray(this.youtubePreview?.items) ? this.youtubePreview.items : [];
|
||
this.youtubePreviewSelected = new Set(items.map(item => item.source_id));
|
||
},
|
||
|
||
clearYoutubePreviewSelection() {
|
||
this.youtubePreviewSelected = new Set();
|
||
},
|
||
|
||
youtubePreviewSelectedCount() {
|
||
return this.youtubePreviewSelected.size;
|
||
},
|
||
|
||
youtubeOwnedPlaylists() {
|
||
return (Alpine.store('playlists')?.list || []).filter(playlist => (
|
||
playlist.kind === 'user' && playlist.is_own && Number(playlist.id) > 0
|
||
));
|
||
},
|
||
|
||
youtubePlaylistChoiceChanged() {
|
||
if (
|
||
this.youtubePlaylistChoice === '__new__'
|
||
&& !String(this.youtubeNewPlaylistTitle || '').trim()
|
||
) {
|
||
this.youtubeNewPlaylistTitle = String(this.youtubePreview?.title || '').slice(0, 255);
|
||
}
|
||
},
|
||
|
||
youtubeDestinationValid() {
|
||
return this.youtubePlaylistChoice !== '__new__'
|
||
|| String(this.youtubeNewPlaylistTitle || '').trim().length > 0;
|
||
},
|
||
|
||
importPlaylistChoiceChanged(kind) {
|
||
const choice = kind + 'PlaylistChoice';
|
||
const title = kind + 'NewPlaylistTitle';
|
||
if (this[choice] !== '__new__' || String(this[title] || '').trim()) return;
|
||
const file = this.localFiles[0];
|
||
const suggestion = kind === 'torrent' ? this.previewData?.name
|
||
: (file?.webkitRelativePath?.split('/').slice(0, -1).join('/') || (this.localFiles.length === 1 ? file?.name?.replace(/\.[^.]+$/, '') : ''));
|
||
this[title] = String(suggestion || '').slice(0,255);
|
||
},
|
||
importDestinationValid(kind) {
|
||
return this[kind + 'PlaylistChoice'] !== '__new__' || String(this[kind + 'NewPlaylistTitle'] || '').trim().length > 0;
|
||
},
|
||
torrentDestinationLocked() {
|
||
return this.loading || (this.currentJob && !['preview', 'resolving'].includes(this.currentJob.status));
|
||
},
|
||
async resolveYoutubeTargetPlaylist() { return this.resolveImportTargetPlaylist('youtube'); },
|
||
async resolveImportTargetPlaylist(kind) {
|
||
const choice = kind + 'PlaylistChoice';
|
||
const titleKey = kind + 'NewPlaylistTitle';
|
||
if (this[choice] !== '__new__') {
|
||
const playlistId = Number(this[choice] || 0);
|
||
return playlistId > 0 ? playlistId : null;
|
||
}
|
||
const title = String(this[titleKey] || '').trim();
|
||
if (!title) throw new Error(T.youtubePlaylistCreateFailed);
|
||
const res = await fetch('/api/player/playlists', {
|
||
method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({title}),
|
||
});
|
||
const playlist = await res.json().catch(() => null);
|
||
if (!res.ok || Number(playlist?.id || 0) <= 0) throw new Error(playlist?.error || T.youtubePlaylistCreateFailed);
|
||
// Retrying an upload reuses this playlist, including after a failed start request.
|
||
this[choice] = String(playlist.id);
|
||
const playlists = Alpine.store('playlists');
|
||
if (playlists) {
|
||
playlists.list = [...(playlists.list || []).filter(item => Number(item.id) !== Number(playlist.id)), playlist];
|
||
await playlists.reload();
|
||
}
|
||
return Number(playlist.id);
|
||
},
|
||
|
||
async startYoutubeDownload() {
|
||
const preview = this.youtubePreview;
|
||
const selectedSourceIds = Array.from(this.youtubePreviewSelected);
|
||
if (
|
||
!preview
|
||
|| !selectedSourceIds.length
|
||
|| !this.youtubeDestinationValid()
|
||
|| this.youtubeSubmitting
|
||
) return;
|
||
this.youtubeSubmitting = true;
|
||
this._setMessage(T.youtubeStarting);
|
||
try {
|
||
const targetPlaylistId = await this.resolveYoutubeTargetPlaylist();
|
||
const res = await fetch('/api/player/youtube/start', {
|
||
method: 'POST',
|
||
headers: { 'Content-Type': 'application/json' },
|
||
body: JSON.stringify({
|
||
url: preview.source_url,
|
||
selected_source_ids: selectedSourceIds,
|
||
target_playlist_id: targetPlaylistId,
|
||
}),
|
||
});
|
||
const data = await res.json().catch(() => null);
|
||
if (!res.ok) throw new Error(data?.error || T.youtubeStartFailed);
|
||
this.youtubeUrl = '';
|
||
this.clearYoutubePreview();
|
||
this._setMessage(T.youtubeStarted);
|
||
await this.refreshDownloads();
|
||
} catch (err) {
|
||
this._setMessage(err.message || T.youtubeStartFailed, true);
|
||
} finally {
|
||
this.youtubeSubmitting = false;
|
||
}
|
||
},
|
||
|
||
openYoutubeJob(row) {
|
||
this.youtubeDetail = row;
|
||
this.showSourceTab('youtube');
|
||
},
|
||
|
||
syncYoutubeJob(rows) {
|
||
if (!this.youtubeDetail) return;
|
||
const updated = rows.find(row => row.source === 'youtube' && row.id === this.youtubeDetail.id);
|
||
if (updated) this.youtubeDetail = updated;
|
||
},
|
||
|
||
async cancelYoutubeJob(id) {
|
||
if (this.youtubeActionBusy || !confirm(T.youtubeStopConfirm)) return;
|
||
return this.updateYoutubeJob(id, 'cancel');
|
||
},
|
||
|
||
async retryYoutubeJob(id) {
|
||
if (!this.youtubeActionBusy) return this.updateYoutubeJob(id, 'retry');
|
||
},
|
||
|
||
async updateYoutubeJob(id, action) {
|
||
this.youtubeActionBusy = true;
|
||
try {
|
||
const res = await fetch('/api/player/youtube/' + encodeURIComponent(id) + '/' + action, {method:'POST'});
|
||
const job = await res.json().catch(() => null);
|
||
if (!res.ok) throw new Error(job?.error || (action === 'cancel' ? T.youtubeStopFailed : T.youtubeRetryFailed));
|
||
if (this.youtubeDetail?.id === id) {
|
||
this.youtubeDetail = {...this.youtubeDetail, status:job.status, error:job.error};
|
||
}
|
||
this._setMessage(action === 'cancel' ? T.youtubeStopped : T.youtubeStarted);
|
||
await this.refreshDownloads();
|
||
} catch (err) {
|
||
this._setMessage(err.message || String(err), true);
|
||
} finally {
|
||
this.youtubeActionBusy = false;
|
||
}
|
||
},
|
||
|
||
youtubeStatusLabel(status) {
|
||
const labels = {
|
||
queued: T.youtubeQueued,
|
||
resolving: T.youtubeResolving,
|
||
downloading: T.downloading,
|
||
postprocessing: T.youtubePostprocessing,
|
||
awaiting_ai: T.youtubeAwaitingAi,
|
||
ai_processing: T.youtubeAiProcessing,
|
||
needs_review: T.youtubeNeedsReview,
|
||
complete: T.completed,
|
||
complete_with_errors: T.youtubeCompleteWithErrors,
|
||
failed: T.failed,
|
||
ai_failed: T.failed,
|
||
skipped: T.youtubeSkipped,
|
||
cancelled: T.youtubeCancelled,
|
||
uploading: T.uploadingFiles,
|
||
};
|
||
return labels[String(status || '').toLowerCase()] || status || T.unknown;
|
||
},
|
||
|
||
youtubeStatusClass(status) {
|
||
const classes = {
|
||
queued: 'status-preview',
|
||
resolving: 'status-resolving',
|
||
downloading: 'status-downloading',
|
||
postprocessing: 'status-moving',
|
||
awaiting_ai: 'status-preview',
|
||
ai_processing: 'status-moving',
|
||
needs_review: 'status-paused',
|
||
complete: 'status-completed',
|
||
complete_with_errors: 'status-failed',
|
||
failed: 'status-failed',
|
||
ai_failed: 'status-failed',
|
||
skipped: 'status-completed',
|
||
cancelled: 'status-paused',
|
||
uploading: 'status-downloading',
|
||
};
|
||
return classes[String(status || '').toLowerCase()] || 'status-preview';
|
||
},
|
||
|
||
youtubeJobCancellable(status) {
|
||
return ['queued', 'resolving', 'downloading', 'postprocessing'].includes(String(status || '').toLowerCase());
|
||
},
|
||
|
||
addNew() {
|
||
if (this.loading) return;
|
||
this._stopPoll();
|
||
this.workspaceMode = 'new';
|
||
this.file = null;
|
||
this.magnet = '';
|
||
this.currentJob = null;
|
||
this.previewData = null;
|
||
this.treeRoot = null;
|
||
this.selected = new Set();
|
||
this.expanded = new Set();
|
||
this._setMessage('');
|
||
},
|
||
|
||
_setMessage(message, error = false) {
|
||
this.message = message || '';
|
||
this.error = error;
|
||
},
|
||
|
||
bytes(value) {
|
||
if (!value) return '0 B';
|
||
const units = ['B', 'KB', 'MB', 'GB', 'TB'];
|
||
let size = Number(value);
|
||
let idx = 0;
|
||
while (size >= 1024 && idx < units.length - 1) {
|
||
size /= 1024;
|
||
idx++;
|
||
}
|
||
return (idx === 0 ? size.toFixed(0) : size.toFixed(1)) + ' ' + units[idx];
|
||
},
|
||
|
||
isDownloading(job) {
|
||
return !!job && (job.active || job.status === 'downloading' || job.status === 'moving');
|
||
},
|
||
|
||
isCurrentDownloading() {
|
||
return this.isDownloading(this.currentJob);
|
||
},
|
||
|
||
isCompleted(job) {
|
||
return this.normalizedStatus(job) === 'completed';
|
||
},
|
||
|
||
isCurrentCompleted() {
|
||
return this.isCompleted(this.currentJob);
|
||
},
|
||
|
||
selectedArray() {
|
||
return [...this.selected].sort((a, b) => Number(a) - Number(b));
|
||
},
|
||
|
||
selectionMatchesJob(job) {
|
||
if (!job) return false;
|
||
const saved = Array.isArray(job.selected_files) ? job.selected_files : [];
|
||
const selected = this.selectedArray();
|
||
if (saved.length !== selected.length) return false;
|
||
const savedSet = new Set(saved.map(index => Number(index)));
|
||
return selected.every(index => savedSet.has(Number(index)));
|
||
},
|
||
|
||
hasCurrentSelectionChanges() {
|
||
return !!this.currentJob && !this.selectionMatchesJob(this.currentJob);
|
||
},
|
||
|
||
isCurrentCompletedLocked() {
|
||
return this.isCurrentCompleted() && !this.hasCurrentSelectionChanges();
|
||
},
|
||
|
||
normalizedStatus(job) {
|
||
const status = String(job?.status || 'preview').toLowerCase();
|
||
if (status === 'complete') return 'completed';
|
||
return status;
|
||
},
|
||
|
||
statusLabel(job) {
|
||
const labels = {
|
||
preview: T.preview,
|
||
resolving: T.resolving,
|
||
downloading: T.downloading,
|
||
moving: T.moving,
|
||
completed: T.completed,
|
||
failed: T.failed,
|
||
paused: T.paused,
|
||
};
|
||
const status = this.normalizedStatus(job);
|
||
return labels[status] || status;
|
||
},
|
||
|
||
statusBadgeClass(job) {
|
||
return 'status-' + this.normalizedStatus(job);
|
||
},
|
||
|
||
progressValue(job) {
|
||
if (!job) return 0;
|
||
if (this.normalizedStatus(job) === 'completed') return 100;
|
||
return Math.max(0, Math.min(100, Number(job.progress_percent || 0)));
|
||
},
|
||
|
||
statusText(job) {
|
||
if (!job) return T.noTorrentSelected;
|
||
const state = job.client_state ? ' / ' + job.client_state : '';
|
||
return this.statusLabel(job) + state;
|
||
},
|
||
|
||
speedText(job) {
|
||
if (!job) return '0 B/s';
|
||
const down = Number(job.download_speed_mbps || 0);
|
||
return down.toFixed(2) + ' MiB/s';
|
||
},
|
||
|
||
peerText(job) {
|
||
if (!job) return 'n/a';
|
||
const live = job.peers_live == null ? '?' : job.peers_live;
|
||
const seen = job.peers_seen == null ? '?' : job.peers_seen;
|
||
return live + ' ' + T.live + ' / ' + seen + ' ' + T.seen;
|
||
},
|
||
|
||
etaText(job) {
|
||
return job && job.eta ? job.eta : '';
|
||
},
|
||
|
||
progressDetailText(job) {
|
||
if (!job) return '';
|
||
const bytes = job.selected_size || job.total_size || this.previewData?.total_size;
|
||
if (!bytes) return '';
|
||
const size = this.bytes(bytes);
|
||
if (this.isCompleted(job) || !job.downloaded_bytes) return size;
|
||
return this.bytes(job.downloaded_bytes) + ' / ' + size;
|
||
},
|
||
|
||
actionButtonText() {
|
||
if (this.normalizedStatus(this.currentJob) === 'resolving') return T.resolving;
|
||
if (this.isCurrentCompletedLocked()) return T.completed;
|
||
return this.isCurrentDownloading() ? T.pauseDownload : T.downloadSelected;
|
||
},
|
||
|
||
actionButtonDisabled() {
|
||
return this.loading
|
||
|| (!this.isCurrentDownloading() && (!this.selected.size || !this.importDestinationValid('torrent')))
|
||
|| this.isCurrentCompletedLocked()
|
||
|| this.normalizedStatus(this.currentJob) === 'resolving'
|
||
|| !this.previewData
|
||
|| !Array.isArray(this.previewData.files)
|
||
|| this.previewData.files.length === 0;
|
||
},
|
||
|
||
toggleDownloadAction() {
|
||
if (this.isCurrentCompletedLocked()) return;
|
||
return this.isCurrentDownloading() ? this.pause() : this.start();
|
||
},
|
||
|
||
_startRefresh() {
|
||
this._stopRefresh();
|
||
let lastRefresh = Date.now();
|
||
this._refreshTimer = setInterval(() => {
|
||
if (!this.modal || document.hidden || this.historyLoading) return;
|
||
const rows = this.sourceTab === 'history' ? this.downloadHistory : [this.latestDownload, this.youtubeDetail];
|
||
const inProgress = rows.some(row => row && ['uploading','queued','resolving','downloading','moving','postprocessing','awaiting_ai','ai_processing'].includes(row.status));
|
||
if (inProgress || Date.now() - lastRefresh >= 30000) {
|
||
lastRefresh = Date.now();
|
||
this.refreshDownloads();
|
||
}
|
||
}, 5000);
|
||
},
|
||
|
||
_stopRefresh() {
|
||
if (this._refreshTimer) clearInterval(this._refreshTimer);
|
||
this._refreshTimer = null;
|
||
},
|
||
|
||
_isSelectedJob(id) {
|
||
return this.workspaceMode === 'session'
|
||
&& this.currentJob
|
||
&& this.currentJob.id === id
|
||
&& this.previewData
|
||
&& this.previewData.id === id;
|
||
},
|
||
|
||
_applySession(data) {
|
||
const preview = data.preview || data;
|
||
const job = data.job || null;
|
||
this.workspaceMode = 'session';
|
||
this.file = null;
|
||
this.magnet = '';
|
||
this.previewData = preview;
|
||
this.currentJob = job;
|
||
this.torrentPlaylistChoice = job?.target_playlist_id ? String(job.target_playlist_id) : '';
|
||
this.torrentNewPlaylistTitle = '';
|
||
const selected = Array.isArray(data.selected_files) && data.selected_files.length
|
||
? data.selected_files
|
||
: (preview.files || []).filter(f => f.selected).map(f => f.index);
|
||
this.selected = new Set(selected);
|
||
this.treeRoot = null;
|
||
},
|
||
|
||
resumeTorrentPoll() {
|
||
if (this.sourceTab !== 'torrents' || this.workspaceMode !== 'session' || !this.currentJob) return;
|
||
if (this.isCurrentDownloading() || this.normalizedStatus(this.currentJob) === 'resolving') this._poll(this.currentJob.id);
|
||
},
|
||
|
||
async openSession(id) {
|
||
if (!id || this.loading) return;
|
||
this._stopPoll();
|
||
this.loading = true;
|
||
this.workspaceMode = 'opening';
|
||
this._setMessage('');
|
||
try {
|
||
const res = await fetch(`/api/player/torrents/session/${id}`);
|
||
const data = await res.json();
|
||
if (this.workspaceMode !== 'opening' || !this.modal || this.sourceTab !== 'torrents') return;
|
||
if (!res.ok) throw new Error(data.error || T.openTorrentFailed);
|
||
this._applySession(data);
|
||
this.resumeTorrentPoll();
|
||
} catch (err) {
|
||
if (this.workspaceMode === 'opening') {
|
||
this.workspaceMode = 'new';
|
||
this._setMessage(err.message || String(err), true);
|
||
}
|
||
} finally {
|
||
this.loading = false;
|
||
}
|
||
},
|
||
|
||
async _fileBase64(file) {
|
||
return new Promise((resolve, reject) => {
|
||
const reader = new FileReader();
|
||
reader.onerror = () => reject(reader.error);
|
||
reader.onload = () => {
|
||
const result = String(reader.result || '');
|
||
resolve(result.includes(',') ? result.split(',')[1] : result);
|
||
};
|
||
reader.readAsDataURL(file);
|
||
});
|
||
},
|
||
|
||
setLocalFiles(files) {
|
||
if (this.localFilesUploading) return;
|
||
const supported = new Set(['mp3', 'flac', 'wav', 'm4a', 'ogg', 'opus', 'aac']);
|
||
const selected = Array.from(files || []).filter(file => {
|
||
const extension = String(file.name || '').split('.').pop().toLowerCase();
|
||
return String(file.type || '').startsWith('audio/') || supported.has(extension);
|
||
});
|
||
this.localFiles = selected;
|
||
this.localFilesBatchId = selected.length ? crypto.randomUUID() : null;
|
||
this.localFileUploadIds = new WeakMap();
|
||
this.localPendingFinish = false;
|
||
this.localPlaylistLocked = false;
|
||
this.localTargetPlaylistId = null;
|
||
this.localPlaylistChoice = '';
|
||
this.localNewPlaylistTitle = '';
|
||
this.localFilesDragging = false;
|
||
this.uploadProgress = 0;
|
||
this.uploadProgressText = '';
|
||
if (!selected.length && Array.from(files || []).length) {
|
||
this._setMessage(T.noSupportedAudioFiles, true);
|
||
} else {
|
||
this._setMessage('');
|
||
}
|
||
},
|
||
|
||
clearLocalFiles() {
|
||
if (this.localFilesUploading) return;
|
||
this.localFiles = [];
|
||
this.localFilesBatchId = null;
|
||
this.localFileUploadIds = new WeakMap();
|
||
this.localPendingFinish = false;
|
||
this.localPlaylistLocked = false;
|
||
this.localTargetPlaylistId = null;
|
||
this.localPlaylistChoice = '';
|
||
this.localNewPlaylistTitle = '';
|
||
this.uploadProgress = 0;
|
||
this.uploadProgressText = '';
|
||
},
|
||
|
||
leaveLocalFileDrop(event) {
|
||
if (!event.currentTarget.contains(event.relatedTarget)) this.localFilesDragging = false;
|
||
},
|
||
|
||
dropLocalFiles(event) {
|
||
this.localFilesDragging = false;
|
||
this.setLocalFiles(event?.dataTransfer?.files || []);
|
||
},
|
||
|
||
localUploadBytes() {
|
||
return this.localFiles.reduce((sum, file) => sum + Number(file.size || 0), 0);
|
||
},
|
||
|
||
localUploadSummary() {
|
||
const count = this.localFiles.length;
|
||
if (count === 0) return '';
|
||
return count + ' ' + T.selected + ' - ' + this.bytes(this.localUploadBytes());
|
||
},
|
||
|
||
uploadLocalFile(file, loadedBefore, totalBytes) {
|
||
return new Promise((resolve, reject) => {
|
||
const xhr = new XMLHttpRequest();
|
||
xhr.open('POST', '/api/player/uploads/local');
|
||
xhr.setRequestHeader('Content-Type', file.type || 'application/octet-stream');
|
||
xhr.setRequestHeader('X-Furumusic-Filename', encodeURIComponent(file.name || 'upload.mp3'));
|
||
let uploadId = this.localFileUploadIds.get(file);
|
||
if (!uploadId) {
|
||
uploadId = crypto.randomUUID();
|
||
this.localFileUploadIds.set(file, uploadId);
|
||
}
|
||
xhr.setRequestHeader('X-Furumusic-Upload-Id', uploadId);
|
||
xhr.setRequestHeader('X-Furumusic-Upload-Batch-Id', this.localFilesBatchId);
|
||
if (this.localTargetPlaylistId) xhr.setRequestHeader('X-Furumusic-Target-Playlist-Id', String(this.localTargetPlaylistId));
|
||
if (file.webkitRelativePath) {
|
||
xhr.setRequestHeader('X-Furumusic-Relative-Path', encodeURIComponent(file.webkitRelativePath));
|
||
}
|
||
xhr.upload.onprogress = event => {
|
||
if (!event.lengthComputable || totalBytes <= 0) return;
|
||
const loaded = loadedBefore + event.loaded;
|
||
this.uploadProgress = Math.max(0, Math.min(100, loaded / totalBytes * 100));
|
||
this.uploadProgressText = this.uploadProgress.toFixed(1) + '%';
|
||
};
|
||
xhr.onload = () => {
|
||
redirectOnUnauthorized(xhr.status);
|
||
let data = {};
|
||
try { data = JSON.parse(xhr.responseText || '{}'); } catch {}
|
||
if (xhr.status >= 200 && xhr.status < 300) resolve(data);
|
||
else reject(new Error(data.error || T.uploadFailed));
|
||
};
|
||
xhr.onerror = () => reject(new Error(T.uploadFailed));
|
||
xhr.send(file);
|
||
});
|
||
},
|
||
|
||
async uploadLocalFiles() {
|
||
if (this.localFilesUploading || (!this.localFiles.length && !this.localPendingFinish) || !this.importDestinationValid('local')) return;
|
||
const batchId = this.localFilesBatchId;
|
||
const totalBytes = this.localUploadBytes();
|
||
this.localFilesUploading = true;
|
||
this.uploadProgress = this.localPendingFinish ? 100 : 0;
|
||
this.uploadProgressText = this.uploadProgress + '%';
|
||
this._setMessage('');
|
||
let loaded = 0;
|
||
try {
|
||
if (!this.localPlaylistLocked) {
|
||
this.localTargetPlaylistId = await this.resolveImportTargetPlaylist('local');
|
||
this.localPlaylistLocked = true;
|
||
}
|
||
for (const file of [...this.localFiles]) {
|
||
await this.uploadLocalFile(file, loaded, totalBytes);
|
||
loaded += Number(file.size || 0);
|
||
this.localFileUploadIds.delete(file);
|
||
this.localFiles = this.localFiles.filter(item => item !== file);
|
||
this.uploadProgress = totalBytes > 0 ? Math.min(100, loaded / totalBytes * 100) : 100;
|
||
this.uploadProgressText = this.uploadProgress.toFixed(1) + '%';
|
||
}
|
||
this.localPendingFinish = true;
|
||
const res = await fetch('/api/player/uploads/local', {
|
||
method: 'POST',
|
||
headers: {
|
||
'X-Furumusic-Upload-Batch-Id': batchId,
|
||
'X-Furumusic-Upload-Complete': 'true',
|
||
},
|
||
});
|
||
redirectOnUnauthorized(res.status);
|
||
if (!res.ok) throw new Error(T.uploadFailed);
|
||
this.localPendingFinish = false;
|
||
this.localFilesBatchId = null;
|
||
this._setMessage(T.uploadComplete);
|
||
} catch (err) {
|
||
this._setMessage(err.message || String(err), true);
|
||
} finally {
|
||
this.localFilesUploading = false;
|
||
await this.refreshDownloads();
|
||
}
|
||
},
|
||
|
||
formatUploadDate(value) {
|
||
const date = new Date(value);
|
||
return Number.isNaN(date.getTime()) ? String(value || '') : date.toLocaleString();
|
||
},
|
||
|
||
async preview() {
|
||
if (this.loading) return;
|
||
const magnet = this.magnet.trim();
|
||
if (!this.file && !magnet) {
|
||
this._setMessage(T.chooseTorrent, true);
|
||
return;
|
||
}
|
||
|
||
this.loading = true;
|
||
this.previewData = null;
|
||
this.treeRoot = null;
|
||
this.currentJob = null;
|
||
this.workspaceMode = 'new';
|
||
this.selected = new Set();
|
||
this.expanded = new Set();
|
||
this._setMessage('');
|
||
|
||
try {
|
||
const payload = this.file
|
||
? { kind: 'torrent_file', torrent_base64: await this._fileBase64(this.file), source_label: this.file.name }
|
||
: { kind: 'magnet', magnet, source_label: magnet.slice(0, 120) };
|
||
const res = await fetch('/api/player/torrents/preview', {
|
||
method: 'POST',
|
||
headers: { 'Content-Type': 'application/json' },
|
||
body: JSON.stringify(payload),
|
||
});
|
||
const data = await res.json();
|
||
if (!res.ok) throw new Error(data.error || T.previewFailed);
|
||
if (this.isImporting() && this.modal) {
|
||
this._applySession(data);
|
||
this.resumeTorrentPoll();
|
||
}
|
||
await this.refreshDownloads();
|
||
} catch (err) {
|
||
this._setMessage(err.message || String(err), true);
|
||
} finally {
|
||
this.loading = false;
|
||
}
|
||
},
|
||
|
||
toggle(index, checked) {
|
||
const next = new Set(this.selected);
|
||
if (checked) next.add(index);
|
||
else next.delete(index);
|
||
this.selected = next;
|
||
},
|
||
|
||
selectAll(value) {
|
||
if (!this.previewData) return;
|
||
this.selected = value
|
||
? new Set(this.previewData.files.map(f => f.index))
|
||
: new Set();
|
||
},
|
||
|
||
clearSelection() {
|
||
this.selectAll(false);
|
||
},
|
||
|
||
selectedBytes() {
|
||
if (!this.previewData) return 0;
|
||
return this.previewData.files
|
||
.filter(file => this.selected.has(file.index))
|
||
.reduce((sum, file) => sum + Number(file.length || 0), 0);
|
||
},
|
||
|
||
_buildTree(files) {
|
||
const root = {
|
||
type: 'folder',
|
||
key: 'root',
|
||
name: 'root',
|
||
depth: -1,
|
||
size: 0,
|
||
fileIndexes: [],
|
||
children: [],
|
||
childMap: new Map(),
|
||
};
|
||
|
||
const ensureFolder = (parent, name, key, depth) => {
|
||
let node = parent.childMap.get(key);
|
||
if (!node) {
|
||
node = {
|
||
type: 'folder',
|
||
key,
|
||
name,
|
||
depth,
|
||
size: 0,
|
||
fileIndexes: [],
|
||
children: [],
|
||
childMap: new Map(),
|
||
};
|
||
parent.childMap.set(key, node);
|
||
parent.children.push(node);
|
||
}
|
||
return node;
|
||
};
|
||
|
||
files.forEach(file => {
|
||
const components = file.components && file.components.length
|
||
? file.components
|
||
: String(file.name || '').split('/').filter(Boolean);
|
||
const pathParts = components.length ? components : [file.name || ('file-' + file.index)];
|
||
let parent = root;
|
||
const folderChain = [root];
|
||
|
||
pathParts.slice(0, -1).forEach((part, depth) => {
|
||
const key = parent.key + '/' + part;
|
||
parent = ensureFolder(parent, part, key, depth);
|
||
folderChain.push(parent);
|
||
});
|
||
|
||
const fileNode = {
|
||
type: 'file',
|
||
key: 'file:' + file.index,
|
||
name: pathParts[pathParts.length - 1],
|
||
depth: Math.max(pathParts.length - 1, 0),
|
||
size: Number(file.length || 0),
|
||
fileIndex: file.index,
|
||
fileIndexes: [file.index],
|
||
children: [],
|
||
};
|
||
parent.children.push(fileNode);
|
||
|
||
folderChain.forEach(folder => {
|
||
folder.size += fileNode.size;
|
||
folder.fileIndexes.push(file.index);
|
||
});
|
||
});
|
||
|
||
const sortAndSeal = node => {
|
||
node.children.sort((a, b) => {
|
||
if (a.type !== b.type) return a.type === 'folder' ? -1 : 1;
|
||
return a.name.localeCompare(b.name, undefined, { numeric: true, sensitivity: 'base' });
|
||
});
|
||
node.children.forEach(sortAndSeal);
|
||
delete node.childMap;
|
||
};
|
||
sortAndSeal(root);
|
||
|
||
const initiallyExpanded = new Set();
|
||
const collectExpanded = node => {
|
||
if (node.type === 'folder' && node.depth < 1) initiallyExpanded.add(node.key);
|
||
node.children.forEach(collectExpanded);
|
||
};
|
||
collectExpanded(root);
|
||
this.expanded = initiallyExpanded;
|
||
|
||
return root;
|
||
},
|
||
|
||
visibleNodes() {
|
||
if (!this.treeRoot) return [];
|
||
const rows = [];
|
||
const visit = node => {
|
||
node.children.forEach(child => {
|
||
rows.push(child);
|
||
if (child.type === 'folder' && this.expanded.has(child.key)) {
|
||
visit(child);
|
||
}
|
||
});
|
||
};
|
||
visit(this.treeRoot);
|
||
return rows;
|
||
},
|
||
|
||
toggleExpand(node) {
|
||
if (node.type !== 'folder') return;
|
||
const next = new Set(this.expanded);
|
||
if (next.has(node.key)) next.delete(node.key);
|
||
else next.add(node.key);
|
||
this.expanded = next;
|
||
},
|
||
|
||
expandAll(value) {
|
||
if (!this.treeRoot) return;
|
||
const next = new Set();
|
||
const visit = node => {
|
||
if (node.type === 'folder' && value) next.add(node.key);
|
||
node.children.forEach(visit);
|
||
};
|
||
visit(this.treeRoot);
|
||
this.expanded = next;
|
||
},
|
||
|
||
nodeState(node) {
|
||
if (node.type === 'file') {
|
||
return this.selected.has(node.fileIndex) ? 'checked' : 'empty';
|
||
}
|
||
const total = node.fileIndexes.length;
|
||
const selected = node.fileIndexes.filter(index => this.selected.has(index)).length;
|
||
if (selected === 0) return 'empty';
|
||
if (selected === total) return 'checked';
|
||
return 'partial';
|
||
},
|
||
|
||
toggleNode(node) {
|
||
const next = new Set(this.selected);
|
||
if (node.type === 'file') {
|
||
if (next.has(node.fileIndex)) next.delete(node.fileIndex);
|
||
else next.add(node.fileIndex);
|
||
this.selected = next;
|
||
return;
|
||
}
|
||
|
||
if (this.nodeState(node) === 'checked') {
|
||
node.fileIndexes.forEach(index => next.delete(index));
|
||
} else {
|
||
node.fileIndexes.forEach(index => next.add(index));
|
||
}
|
||
this.selected = next;
|
||
},
|
||
|
||
async start() {
|
||
if (!this.importDestinationValid('torrent')) return;
|
||
if (!this.previewData || this.loading) return;
|
||
const selected = this.selectedArray();
|
||
if (selected.length === 0) {
|
||
this._setMessage(T.selectOneFile, true);
|
||
return;
|
||
}
|
||
|
||
this.loading = true;
|
||
this._setMessage(T.startingDownload);
|
||
try {
|
||
const targetPlaylistId = await this.resolveImportTargetPlaylist('torrent');
|
||
const res = await fetch(`/api/player/torrents/${this.previewData.id}/start`, {
|
||
method: 'POST',
|
||
headers: { 'Content-Type': 'application/json' },
|
||
body: JSON.stringify({ selected_files: selected, target_playlist_id: targetPlaylistId }),
|
||
});
|
||
const data = await res.json();
|
||
if (!res.ok) throw new Error(data.error || T.startFailed);
|
||
this.currentJob = data;
|
||
this._setMessage(T.downloadStarted);
|
||
if (this._isSelectedJob(data.id) && this.modal && this.sourceTab === 'torrents') this._poll(data.id);
|
||
await this.refreshDownloads();
|
||
} catch (err) {
|
||
this._setMessage(err.message || String(err), true);
|
||
} finally {
|
||
this.loading = false;
|
||
}
|
||
},
|
||
|
||
async pause() {
|
||
if (!this.currentJob || this.loading || !this.isCurrentDownloading()) return;
|
||
|
||
this.loading = true;
|
||
this._setMessage(T.pausingDownload);
|
||
try {
|
||
const res = await fetch(`/api/player/torrents/${this.currentJob.id}/pause`, {
|
||
method: 'POST',
|
||
});
|
||
const data = await res.json();
|
||
if (!res.ok) throw new Error(data.error || T.pauseFailed);
|
||
this.currentJob = data;
|
||
this._setMessage(T.downloadPaused);
|
||
this._stopPoll();
|
||
await this.refreshDownloads();
|
||
} catch (err) {
|
||
this._setMessage(err.message || String(err), true);
|
||
} finally {
|
||
this.loading = false;
|
||
}
|
||
},
|
||
|
||
_poll(id) {
|
||
this._stopPoll();
|
||
const request = this._pollRequest;
|
||
const poll = async () => {
|
||
try {
|
||
const res = await fetch('/api/player/torrents/' + encodeURIComponent(id) + '/status');
|
||
const job = await res.json();
|
||
if (this._pollRequest !== request || !this._isSelectedJob(id)) return;
|
||
if (!res.ok) throw new Error(job.error || T.statusFailed);
|
||
const wasResolving = this.normalizedStatus(this.currentJob) === 'resolving';
|
||
this.currentJob = job;
|
||
if (wasResolving && job.status !== 'resolving' && job.status !== 'failed') {
|
||
const resolved = await fetch('/api/player/torrents/session/' + encodeURIComponent(id));
|
||
if (!resolved.ok) throw new Error(T.openTorrentFailed);
|
||
const data = await resolved.json();
|
||
if (this._pollRequest !== request || !this._isSelectedJob(id)) return;
|
||
this._applySession(data);
|
||
}
|
||
if (!this.isCurrentDownloading() && this.normalizedStatus(this.currentJob) !== 'resolving') {
|
||
this._stopPoll();
|
||
if (job.status === 'failed') this._setMessage(job.error || this.statusText(job), true);
|
||
await this.refreshDownloads();
|
||
return;
|
||
}
|
||
} catch (err) {
|
||
if (this._pollRequest !== request) return;
|
||
this._setMessage(err.message || String(err), true);
|
||
this._stopPoll();
|
||
return;
|
||
}
|
||
if (this._pollRequest === request) this._pollTimer = setTimeout(poll, 2000);
|
||
};
|
||
this._pollTimer = setTimeout(poll, 2000);
|
||
},
|
||
});
|
||
|
||
// -----------------------------------------------------------------------
|
||
// Playlists store
|
||
// -----------------------------------------------------------------------
|
||
Alpine.store('playlists', {
|
||
list: [],
|
||
modal: null, // { mode: 'create'|'rename', title: '', id?: number }
|
||
picker: null, // { trackIds: [1,2,3] }
|
||
editingPlaylistId: null,
|
||
trackChange: null,
|
||
get changingTracks() { return !!this.trackChange; },
|
||
_dragIdx: null,
|
||
_dragOverIdx: null,
|
||
_pointerDragMove: null,
|
||
_pointerDragEnd: null,
|
||
|
||
init() {
|
||
if (GUEST) return;
|
||
this.reload();
|
||
},
|
||
|
||
async reload() {
|
||
try {
|
||
const res = await fetch('/api/player/playlists');
|
||
if (res.ok) this.list = await res.json();
|
||
} catch {}
|
||
},
|
||
|
||
regularList() {
|
||
return this.list.filter(pl => (
|
||
pl.kind === 'likes' ||
|
||
pl.is_own ||
|
||
!pl.is_public
|
||
));
|
||
},
|
||
|
||
catalogList() {
|
||
const mine = pl => pl.is_own || pl.kind === 'likes';
|
||
return [...this.list.filter(mine), ...this.list.filter(pl => !mine(pl) && (pl.is_public || pl.is_saved))];
|
||
},
|
||
|
||
displayTitle(pl) {
|
||
return pl?.kind === 'likes' ? T.likesPlaylist : (pl?.title || '');
|
||
},
|
||
|
||
currentPlaylist() {
|
||
return Alpine.store('library')?.currentPlaylist || null;
|
||
},
|
||
|
||
canEditCurrent() {
|
||
const playlist = this.currentPlaylist();
|
||
return !!playlist && playlist.kind === 'user' && playlist.is_own && Number(playlist.id) > 0;
|
||
},
|
||
|
||
isEditingCurrent() {
|
||
const playlist = this.currentPlaylist();
|
||
return this.canEditCurrent() && Number(this.editingPlaylistId) === Number(playlist.id);
|
||
},
|
||
|
||
toggleEditCurrent() {
|
||
if (this.isEditingCurrent()) {
|
||
return Alpine.store('playlistHeader').save();
|
||
}
|
||
if (!this.canEditCurrent()) return;
|
||
Alpine.store('playlistHeader').begin(this.currentPlaylist());
|
||
this.editingPlaylistId = Number(this.currentPlaylist().id);
|
||
},
|
||
|
||
stopEdit() {
|
||
Alpine.store('playlistHeader').reset();
|
||
this._endPointerReorder(false);
|
||
this.endDrag();
|
||
this.editingPlaylistId = null;
|
||
},
|
||
|
||
_updateListTrackCount(playlistId, count) {
|
||
const id = Number(playlistId);
|
||
this.list = this.list.map(pl => (
|
||
Number(pl.id) === id ? { ...pl, track_count: count } : pl
|
||
));
|
||
},
|
||
|
||
_playlistTrackIds(tracks) {
|
||
return (tracks || []).map(track => Number(track?.playlist_track_id || 0)).filter(Boolean);
|
||
},
|
||
|
||
_startTrackChange(id) {
|
||
let finish;
|
||
this.trackChange = {id, done:new Promise(resolve => { finish = resolve; })};
|
||
return () => { this.trackChange = null; finish(); };
|
||
},
|
||
|
||
async removeCurrentTrack(track, idx) {
|
||
if (!this.isEditingCurrent() || this.changingTracks || Alpine.store('playlistHeader').busy || !track) return;
|
||
const playlist = this.currentPlaylist();
|
||
const playlistId = Number(playlist.id);
|
||
const playlistTrackId = Number(track.playlist_track_id || 0);
|
||
const previous = (playlist.tracks || []).slice();
|
||
if (!playlistTrackId) return;
|
||
|
||
const finish = this._startTrackChange(playlistId);
|
||
playlist.tracks = previous.filter(item => Number(item.playlist_track_id || 0) !== playlistTrackId);
|
||
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 }),
|
||
});
|
||
if (!res.ok) throw new Error('remove failed');
|
||
await this._refreshAfterTrackChange(playlist, res);
|
||
} catch (err) {
|
||
if (this.currentPlaylist() === playlist) {
|
||
this.currentPlaylist().tracks = previous;
|
||
this._updateListTrackCount(playlistId, previous.length);
|
||
}
|
||
console.warn(err);
|
||
} finally {
|
||
finish();
|
||
}
|
||
},
|
||
|
||
async _refreshAfterTrackChange(playlist, response) {
|
||
const result = await response.json().catch(() => ({}));
|
||
if (this.currentPlaylist() === playlist && result.artwork) {
|
||
Alpine.store('playlistHeader').applyArtwork(playlist, result.artwork);
|
||
}
|
||
await Promise.all([this.reload(), Alpine.store('pins').reload()]);
|
||
},
|
||
|
||
startDrag(event, idx) {
|
||
const tracks = this.currentPlaylist()?.tracks || [];
|
||
if (!this.isEditingCurrent() || idx < 0 || idx >= tracks.length || !tracks[idx]?.playlist_track_id) {
|
||
return false;
|
||
}
|
||
this._dragIdx = idx;
|
||
this._dragOverIdx = idx;
|
||
if (event?.dataTransfer) {
|
||
event.dataTransfer.effectAllowed = 'move';
|
||
event.dataTransfer.setData('text/plain', String(tracks[idx].playlist_track_id));
|
||
}
|
||
return true;
|
||
},
|
||
|
||
dragOver(event, idx) {
|
||
if (!this.isEditingCurrent() || this._dragIdx === null) return;
|
||
const tracks = this.currentPlaylist()?.tracks || [];
|
||
if (idx < 0 || idx >= tracks.length) return;
|
||
this._dragOverIdx = idx;
|
||
if (event?.dataTransfer) event.dataTransfer.dropEffect = 'move';
|
||
document.querySelectorAll('.playlist-track-row.drag-over').forEach(el => el.classList.remove('drag-over'));
|
||
if (idx !== this._dragIdx) event.currentTarget.classList.add('drag-over');
|
||
},
|
||
|
||
dropOn(idx) {
|
||
const fromIdx = this._dragIdx;
|
||
this.endDrag();
|
||
if (!Number.isInteger(fromIdx) || fromIdx === idx) return;
|
||
this.moveCurrentTrack(fromIdx, idx);
|
||
},
|
||
|
||
endDrag() {
|
||
document.querySelectorAll('.playlist-track-row.drag-over').forEach(el => el.classList.remove('drag-over'));
|
||
this._dragIdx = null;
|
||
this._dragOverIdx = null;
|
||
},
|
||
|
||
async moveCurrentTrack(fromIdx, toIdx) {
|
||
if (!this.isEditingCurrent() || this.changingTracks || Alpine.store('playlistHeader').busy) return;
|
||
const playlist = this.currentPlaylist();
|
||
const playlistId = Number(playlist.id);
|
||
const previous = (playlist.tracks || []).slice();
|
||
if (fromIdx < 0 || fromIdx >= previous.length || toIdx < 0 || toIdx >= previous.length) return;
|
||
const next = previous.slice();
|
||
const [track] = next.splice(fromIdx, 1);
|
||
next.splice(toIdx, 0, track);
|
||
playlist.tracks = next;
|
||
|
||
const playlistTrackIds = this._playlistTrackIds(next);
|
||
if (playlistTrackIds.length !== next.length) {
|
||
playlist.tracks = previous;
|
||
return;
|
||
}
|
||
|
||
const finish = this._startTrackChange(playlistId);
|
||
try {
|
||
const res = await fetch(`/api/player/playlists/${playlistId}/tracks`, {
|
||
method: 'PUT',
|
||
headers: { 'Content-Type': 'application/json' },
|
||
body: JSON.stringify({ playlist_track_ids: playlistTrackIds }),
|
||
});
|
||
if (!res.ok) throw new Error('reorder failed');
|
||
await this._refreshAfterTrackChange(playlist, res);
|
||
} catch (err) {
|
||
if (this.currentPlaylist() === playlist) {
|
||
this.currentPlaylist().tracks = previous;
|
||
}
|
||
console.warn(err);
|
||
} finally {
|
||
finish();
|
||
}
|
||
},
|
||
|
||
startPointerReorder(event, idx) {
|
||
if (event.pointerType === 'mouse') return;
|
||
if (event.button && event.button !== 0) return;
|
||
const tracks = this.currentPlaylist()?.tracks || [];
|
||
if (!this.isEditingCurrent() || idx < 0 || idx >= tracks.length || !tracks[idx]?.playlist_track_id) return;
|
||
event.preventDefault();
|
||
this._endPointerReorder(false);
|
||
this._dragIdx = idx;
|
||
this._dragOverIdx = idx;
|
||
const handle = event.currentTarget;
|
||
try {
|
||
handle?.setPointerCapture?.(event.pointerId);
|
||
} catch (_) {}
|
||
|
||
this._pointerDragMove = (moveEvent) => {
|
||
moveEvent.preventDefault();
|
||
this._autoScrollDuringReorder(moveEvent.clientY);
|
||
const target = document
|
||
.elementFromPoint(moveEvent.clientX, moveEvent.clientY)
|
||
?.closest?.('.playlist-track-row[data-playlist-index]');
|
||
const targetIdx = Number(target?.dataset?.playlistIndex);
|
||
const currentTracks = this.currentPlaylist()?.tracks || [];
|
||
if (!Number.isInteger(targetIdx) || targetIdx < 0 || targetIdx >= currentTracks.length) return;
|
||
this._dragOverIdx = targetIdx;
|
||
document.querySelectorAll('.playlist-track-row.drag-over').forEach(el => el.classList.remove('drag-over'));
|
||
if (targetIdx !== this._dragIdx) target.classList.add('drag-over');
|
||
};
|
||
|
||
this._pointerDragEnd = (endEvent) => {
|
||
try {
|
||
if (handle?.hasPointerCapture?.(endEvent.pointerId)) handle.releasePointerCapture(endEvent.pointerId);
|
||
} catch (_) {}
|
||
this._endPointerReorder(true);
|
||
};
|
||
|
||
window.addEventListener('pointermove', this._pointerDragMove, { passive: false });
|
||
window.addEventListener('pointerup', this._pointerDragEnd, { passive: false });
|
||
window.addEventListener('pointercancel', this._pointerDragEnd, { passive: false });
|
||
},
|
||
|
||
_autoScrollDuringReorder(clientY) {
|
||
const scroller = document.getElementById('center-scroll');
|
||
if (!scroller) return;
|
||
const rect = scroller.getBoundingClientRect();
|
||
const edge = 52;
|
||
if (clientY < rect.top + edge) {
|
||
scroller.scrollTop -= Math.ceil((rect.top + edge - clientY) / 4);
|
||
} else if (clientY > rect.bottom - edge) {
|
||
scroller.scrollTop += Math.ceil((clientY - (rect.bottom - edge)) / 4);
|
||
}
|
||
},
|
||
|
||
_endPointerReorder(commit) {
|
||
if (this._pointerDragMove) window.removeEventListener('pointermove', this._pointerDragMove);
|
||
if (this._pointerDragEnd) {
|
||
window.removeEventListener('pointerup', this._pointerDragEnd);
|
||
window.removeEventListener('pointercancel', this._pointerDragEnd);
|
||
}
|
||
document.querySelectorAll('.playlist-track-row.drag-over').forEach(el => el.classList.remove('drag-over'));
|
||
const fromIdx = this._dragIdx;
|
||
const toIdx = this._dragOverIdx;
|
||
this._pointerDragMove = null;
|
||
this._pointerDragEnd = null;
|
||
this._dragIdx = null;
|
||
this._dragOverIdx = null;
|
||
if (commit && Number.isInteger(fromIdx) && Number.isInteger(toIdx) && fromIdx !== toIdx) {
|
||
this.moveCurrentTrack(fromIdx, toIdx);
|
||
}
|
||
},
|
||
|
||
showCreate() {
|
||
this.modal = { mode: 'create', title: '' };
|
||
},
|
||
|
||
startRename(pl) {
|
||
this.modal = { mode: 'rename', title: pl.title, id: pl.id };
|
||
},
|
||
|
||
async submitModal() {
|
||
if (!this.modal) return;
|
||
const title = this.modal.title.trim();
|
||
if (!title) return;
|
||
|
||
if (this.modal.mode === 'create') {
|
||
try {
|
||
await fetch('/api/player/playlists', {
|
||
method: 'POST',
|
||
headers: { 'Content-Type': 'application/json' },
|
||
body: JSON.stringify({ title }),
|
||
});
|
||
await this.reload();
|
||
} catch {}
|
||
} else if (this.modal.mode === 'rename') {
|
||
try {
|
||
const response = await fetch(`/api/player/playlists/${this.modal.id}`, {
|
||
method: 'PUT',
|
||
headers: { 'Content-Type': 'application/json' },
|
||
body: JSON.stringify({ title }),
|
||
});
|
||
if (response.ok) await Promise.all([this.reload(), Alpine.store('pins').reload()]);
|
||
} catch {}
|
||
}
|
||
this.modal = null;
|
||
},
|
||
|
||
async deletePlaylist(id) {
|
||
if (!confirm(T.deletePlaylistConfirm)) return;
|
||
try {
|
||
const response = await fetch(`/api/player/playlists/${id}`, { method: 'DELETE' });
|
||
if (response.ok) await Promise.all([this.reload(), Alpine.store('pins').reload()]);
|
||
} catch {}
|
||
},
|
||
|
||
showPicker(trackIds) {
|
||
this.picker = { trackIds };
|
||
},
|
||
|
||
showFederationPicker(track) {
|
||
this.picker = { trackIds: [], federationTrack: track };
|
||
},
|
||
|
||
async addToPicked(playlistId) {
|
||
if (!this.picker) return;
|
||
try {
|
||
if (this.picker.federationTrack) {
|
||
const track = this.picker.federationTrack;
|
||
await fetch('/api/player/tracks/content/playlist', {
|
||
method: 'POST',
|
||
headers: { 'Content-Type': 'application/json' },
|
||
body: JSON.stringify({
|
||
playlist_id: Number(playlistId),
|
||
content_id: track.key.content_id,
|
||
federation: Alpine.store('library').federationWireTrack(track),
|
||
}),
|
||
});
|
||
} else {
|
||
await fetch(`/api/player/playlists/${playlistId}/tracks`, {
|
||
method: 'POST',
|
||
headers: { 'Content-Type': 'application/json' },
|
||
body: JSON.stringify({ track_ids: this.picker.trackIds }),
|
||
});
|
||
}
|
||
await this.reload();
|
||
} catch {}
|
||
this.picker = null;
|
||
},
|
||
});
|
||
|
||
let catalogRevision = 0;
|
||
async function refreshCatalog() {
|
||
const version = ++catalogRevision;
|
||
const library = Alpine.store('library'), offline = Alpine.store('offline');
|
||
library.cancelPendingSearch();
|
||
library.stopFederation();
|
||
library._resetArtistList('all');
|
||
library._hashNav = false;
|
||
if (offline.active) {
|
||
library.searchMode = 'normal';
|
||
Alpine.store('playlists').stopEdit();
|
||
}
|
||
library._navigateFromHash({fromHash:true});
|
||
for (const name of ['playlists','likes','follows','pins']) Alpine.store(name)?.reload();
|
||
library.loadFederationLikes();
|
||
if (offline.active) {
|
||
await offline.refresh();
|
||
if (offline.active && catalogRevision === version) Alpine.store('player').useOfflineCatalog(offline.items);
|
||
} else {
|
||
Alpine.store('devices').heartbeat();
|
||
Alpine.store('devices').poll();
|
||
Alpine.store('user').loadLastfm();
|
||
}
|
||
}
|
||
window.addEventListener('furumusic:offline-mode', refreshCatalog);
|
||
window.addEventListener('furumusic:offline-catalog', refreshCatalog);
|
||
});
|
||
|
||
function installConnectionFetchMonitor() {
|
||
if (window.__furumusicConnectionMonitorInstalled || !window.fetch) return;
|
||
window.__furumusicConnectionMonitorInstalled = true;
|
||
const nativeFetch = window.fetch.bind(window);
|
||
|
||
window.fetch = async (...args) => {
|
||
const tracked = isTrackedPlayerRequest(args[0]);
|
||
try {
|
||
const response = await nativeFetch(...args);
|
||
if (tracked && !playerOffline()) {
|
||
Alpine.store('offline')?.networkResult(response.status < 500);
|
||
if (response.status >= 500) {
|
||
Alpine.store('connection')?.recordFailure();
|
||
} else {
|
||
Alpine.store('connection')?.recordSuccess();
|
||
}
|
||
}
|
||
return response;
|
||
} catch (error) {
|
||
if (tracked && !playerOffline() && error?.name !== 'AbortError') {
|
||
Alpine.store('connection')?.recordFailure();
|
||
Alpine.store('offline')?.networkResult(false);
|
||
}
|
||
throw error;
|
||
}
|
||
};
|
||
}
|
||
|
||
function isTrackedPlayerRequest(input) {
|
||
const rawUrl = typeof input === 'string' ? input : input?.url;
|
||
if (!rawUrl) return false;
|
||
try {
|
||
const url = new URL(rawUrl, window.location.href);
|
||
return url.origin === window.location.origin && url.pathname.startsWith('/api/player/');
|
||
} catch {
|
||
return false;
|
||
}
|
||
}
|
||
</script>
|