Files
Psychotoxical-psysonic/src/hooks/useAlbumDetailData.ts
T
cucadmuh fc34a0ec59 feat(offline): local-bytes browse when server is unreachable (#1017)
* feat(offline): local-bytes browse for artists and albums

Make Artists, All Albums, and artist/album detail pages work offline
from the library index limited to on-disk library and favorite-auto
tracks. Add a DEV header toggle to simulate offline browse for testing.

* feat(offline): reactive DEV offline toggle with full disconnect simulation

Subscribe nav and browse/detail hooks to useOfflineBrowseActive so UI
refreshes on toggle. DEV force-offline now blocks server probes, reports
disconnected status, and gates Subsonic like real offline for player parity.

* feat(offline): bytes-first favorites when offline browse is active

Load Favorites from local playback bytes, filter starred tracks client-side,
and restrict album-level star queries to local album ids. Drop interim perf
attempts (lean SQL, progressive load, connection singleton, prefetch UX).

* feat(offline): tracks, help, player stats; suspend library picker offline

- Offline browse for Tracks hub from local bytes; sidebar nav for tracks/help/statistics
- Statistics redirects to player-stats offline; server/Last.fm tabs skip network fetches
- Hide music-library picker offline; save filter and restore on reconnect (all libraries while disconnected)
- Unified isOfflineSidebarNavAllowed for library + system entries

* feat(offline): fork disconnect navigation by offline browse capability

When the server drops: stay on the page if nothing is browsable offline;
reload in place on offline-capable routes; otherwise redirect to All Albums
instead of the old /offline or /favorites bounce.

* feat(offline): browse cached playlists when the server is down

List and open manually pinned regular playlists from local library-tier
bytes offline, with sidebar/nav routing and read-only playlist UI.

* feat(offline): read-only artist detail and local play-all paths

Hide favorites and discography offline actions when browse is offline;
load Play All, Shuffle, and top-track continuation from local album bytes.

* feat(offline): read-only album detail and enqueue from local bytes

Hide favorites, download, and cache-offline actions on album pages when
offline browse is active. Favorites album cards enqueue via the same
resolveAlbumForServer path as play, including local playback bytes.

* chore: remove unused import in AlbumCard after enqueue refactor

* feat(offline): unify browse integration contract across the app

Add useOfflineBrowseContext, offlineMediaResolve, and offlineActionPolicy;
wire shell nav to a single capability source; migrate play/enqueue and
context-menu paths off raw getAlbum; replace readOnly with action policy
on detail surfaces. Tests updated for the media-resolve facade.

* feat(offline): close browse contract gaps and fix offline Home feed

Split offline browse modules, align favorites capability across servers,
wire action policy on context menus, migrate hooks to useOfflineBrowseContext,
and preserve stale Home feed cache when offline so the UI does not empty.

* fix(offline): block playbar stars, close audit gaps, trim dead exports

Hide star rating and favorite in PlayerBar when offline browse is active via
offlineActionPolicy playerBar surface. Wire stay-reload token into browse
hooks, migrate hooks to context.active, guard rating prefetch network calls,
and route playlist load through resolvePlaylist.

* docs: add CHANGELOG and credits for offline browse PR #1017

* fix(offline): stop DEV connection probe regression in tests

React to devForceOffline transitions only in useConnectionStatus so mount
does not double-fire check() or ignore disableBackgroundPolling. Add
pingWithCredentials to PlayerBar test mock and DEV-toggle unit tests.
2026-06-07 15:59:41 +03:00

177 lines
5.9 KiB
TypeScript

import { useEffect, useState } from 'react';
import { useSearchParams } from 'react-router-dom';
import type { SubsonicAlbum } from '../api/subsonicTypes';
import { useAuthStore } from '../store/authStore';
import {
loadAlbumFromLibraryIndex,
loadArtistFromLibraryIndex,
} from '../utils/offline/offlineLibraryIndexLoad';
import {
resolveAlbum,
resolveArtist,
type ResolvedAlbum,
} from '../utils/offline/offlineMediaResolve';
import { useOfflineBrowseContext } from './useOfflineBrowseContext';
import {
loadArtistFromLocalPlayback,
offlineLocalBrowseEnabled,
} from '../utils/offline/offlineLocalBrowse';
import { readDetailServerId } from '../utils/navigation/detailServerScope';
import {
shouldAttemptSubsonicForActiveServer,
shouldAttemptSubsonicForServer,
} from '../utils/network/subsonicNetworkGuard';
type AlbumPayload = ResolvedAlbum;
interface UseAlbumDetailDataResult {
album: AlbumPayload | null;
setAlbum: React.Dispatch<React.SetStateAction<AlbumPayload | null>>;
relatedAlbums: SubsonicAlbum[];
loading: boolean;
isStarred: boolean;
setIsStarred: (v: boolean) => void;
starredSongs: Set<string>;
setStarredSongs: React.Dispatch<React.SetStateAction<Set<string>>>;
}
/**
* Load an album payload by id, then resolve the artist's other albums in
* a follow-up call so the related-albums grid can render without blocking
* the initial paint.
*/
export function useAlbumDetailData(id: string | undefined): UseAlbumDetailDataResult {
const [album, setAlbum] = useState<AlbumPayload | null>(null);
const [relatedAlbums, setRelatedAlbums] = useState<SubsonicAlbum[]>([]);
const [loading, setLoading] = useState(true);
const [isStarred, setIsStarred] = useState(false);
const [starredSongs, setStarredSongs] = useState<Set<string>>(new Set());
const favoritesOfflineEnabled = useAuthStore(s => s.favoritesOfflineEnabled);
const activeServerId = useAuthStore(s => s.activeServerId);
const [searchParams] = useSearchParams();
const detailServerId = readDetailServerId(searchParams, activeServerId);
const offlineBrowseActive = useOfflineBrowseContext().active && !!detailServerId;
useEffect(() => {
if (!id) return;
setLoading(true);
setRelatedAlbums([]);
const applyAlbumPayload = (data: AlbumPayload) => {
setAlbum(data);
setIsStarred(!!data.album.starred);
const initialStarred = new Set<string>();
data.songs.forEach(s => { if (s.starred) initialStarred.add(s.id); });
setStarredSongs(initialStarred);
setLoading(false);
};
const loadRelatedAlbums = async (
serverId: string | null,
artistId: string | undefined,
useLocalArtist: boolean,
localBytesOnly: boolean,
) => {
if (!artistId) return;
try {
if (useLocalArtist && serverId) {
const artistLocal = localBytesOnly
? await loadArtistFromLocalPlayback(serverId, artistId)
: await loadArtistFromLibraryIndex(serverId, artistId);
if (artistLocal) {
setRelatedAlbums(artistLocal.albums.filter(a => a.id !== id));
return;
}
}
const relatedServerId = serverId ?? detailServerId ?? activeServerId;
if (!relatedServerId) return;
const artistData = await resolveArtist(relatedServerId, artistId);
if (artistData) {
setRelatedAlbums(artistData.albums.filter(a => a.id !== id));
}
} catch (e) {
console.error('Failed to fetch related albums', e);
}
};
const libraryFirst = favoritesOfflineEnabled && !!detailServerId;
void (async () => {
if (offlineBrowseActive && detailServerId) {
const local = await resolveAlbum(detailServerId, id);
if (local) {
applyAlbumPayload(local);
await loadRelatedAlbums(
detailServerId,
local.album.artistId,
true,
offlineLocalBrowseEnabled(detailServerId),
);
return;
}
setLoading(false);
return;
}
if (libraryFirst && detailServerId) {
try {
const local = await resolveAlbum(detailServerId, id);
if (local) {
applyAlbumPayload(local);
await loadRelatedAlbums(detailServerId, local.album.artistId, true, false);
return;
}
} catch { /* fall through */ }
}
const detailNetworkAllowed = detailServerId
? shouldAttemptSubsonicForServer(detailServerId)
: shouldAttemptSubsonicForActiveServer();
if (!detailNetworkAllowed) {
if (favoritesOfflineEnabled && detailServerId) {
try {
const local = await resolveAlbum(detailServerId, id);
if (local) {
applyAlbumPayload(local);
await loadRelatedAlbums(detailServerId, local.album.artistId, true, false);
return;
}
} catch { /* ignore */ }
}
setLoading(false);
return;
}
try {
const sid = detailServerId ?? activeServerId;
if (!sid) {
setLoading(false);
return;
}
const data = await resolveAlbum(sid, id);
if (!data) {
setLoading(false);
return;
}
applyAlbumPayload(data);
await loadRelatedAlbums(detailServerId, data.album.artistId, false, false);
} catch {
if (favoritesOfflineEnabled && detailServerId) {
try {
const local = await loadAlbumFromLibraryIndex(detailServerId, id);
if (local) {
applyAlbumPayload(local);
await loadRelatedAlbums(detailServerId, local.album.artistId, true, false);
return;
}
} catch { /* ignore */ }
}
setLoading(false);
}
})();
}, [activeServerId, detailServerId, favoritesOfflineEnabled, id, offlineBrowseActive, searchParams]);
return { album, setAlbum, relatedAlbums, loading, isStarred, setIsStarred, starredSongs, setStarredSongs };
}