Files
psysonic/src/hooks/useConnectionStatus.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

182 lines
6.3 KiB
TypeScript

import { useState, useEffect, useCallback, useRef, useMemo } from 'react';
import { useAuthStore } from '../store/authStore';
import { scheduleInstantMixProbeForServer } from '../api/subsonic';
import { serverListDisplayLabel } from '../utils/server/serverDisplayName';
import {
ensureConnectUrlResolved,
invalidateReachableEndpointCache,
isLanUrl,
type ServerEndpointKind,
} from '../utils/server/serverEndpoint';
import { setActiveServerReachable } from '../utils/network/activeServerReachability';
import { usePerfProbeFlags } from '../utils/perf/perfFlags';
import {
isDevOfflineBrowseForced,
useDevOfflineBrowseStore,
} from '../store/devOfflineBrowseStore';
// Backward-compatible re-export for call sites that still import from the hook.
export { isLanUrl };
export type ConnectionStatus = 'connected' | 'disconnected' | 'checking';
export function useConnectionStatus() {
const perfFlags = usePerfProbeFlags();
const devForceOffline = useDevOfflineBrowseStore(s => s.forceOffline);
const [status, setStatus] = useState<ConnectionStatus>('checking');
const [isRetrying, setIsRetrying] = useState(false);
// Tracks the kind of endpoint the last successful probe answered on so the
// badge reflects the *active* connection, not just whatever the user typed
// as the primary URL. A LAN-tagged primary that has fallen over to its
// public alternate must read as 'public', not 'local'.
const [activeEndpointKind, setActiveEndpointKind] = useState<ServerEndpointKind | null>(null);
const intervalRef = useRef<ReturnType<typeof setInterval> | null>(null);
const prevDevForceOfflineRef = useRef<boolean | null>(null);
const check = useCallback(async () => {
if (isDevOfflineBrowseForced()) {
setActiveServerReachable(false);
setStatus('disconnected');
return;
}
const server = useAuthStore.getState().getActiveServer();
if (!server) {
setActiveServerReachable(false);
setStatus('disconnected');
return;
}
if (!navigator.onLine) {
setActiveServerReachable(false);
setStatus('disconnected');
return;
}
// Dual-address: probe LAN-first via the shared cache. On every poll the
// sticky entry is tried first; on failure the full sequence runs and the
// cache flips to whichever endpoint actually answers — so a laptop moving
// off WiFi smoothly transitions from LAN to public without a manual retry.
const probe = await ensureConnectUrlResolved(server);
if (probe.ok) {
const sid = useAuthStore.getState().activeServerId;
if (sid) {
const identity = {
type: probe.ping.type,
serverVersion: probe.ping.serverVersion,
openSubsonic: probe.ping.openSubsonic,
};
useAuthStore.getState().setSubsonicServerIdentity(sid, identity);
scheduleInstantMixProbeForServer(sid, probe.baseUrl, server.username, server.password, identity);
}
setActiveEndpointKind(probe.endpoint.kind);
} else {
setActiveEndpointKind(null);
}
setActiveServerReachable(probe.ok);
setStatus(probe.ok ? 'connected' : 'disconnected');
}, []);
const retry = useCallback(async () => {
setIsRetrying(true);
// Manual retry: drop the sticky cache so the next probe starts in the
// natural LAN-first order instead of revalidating whatever last worked.
const sid = useAuthStore.getState().activeServerId;
if (sid) invalidateReachableEndpointCache(sid);
await check();
setIsRetrying(false);
}, [check]);
// DEV offline toggle: react to transitions only — the polling effect already
// probes on mount; an unconditional check() here doubled probes and ignored
// disableBackgroundPolling (PlayerBar tests, perf-flagged runs).
useEffect(() => {
if (!import.meta.env.DEV) return;
if (prevDevForceOfflineRef.current === null) {
prevDevForceOfflineRef.current = devForceOffline;
if (devForceOffline) {
setActiveServerReachable(false);
setStatus('disconnected');
}
return;
}
if (prevDevForceOfflineRef.current === devForceOffline) return;
prevDevForceOfflineRef.current = devForceOffline;
if (devForceOffline) {
setActiveServerReachable(false);
setStatus('disconnected');
return;
}
if (!perfFlags.disableBackgroundPolling) {
void check();
}
}, [devForceOffline, check, perfFlags.disableBackgroundPolling]);
useEffect(() => {
if (perfFlags.disableBackgroundPolling) {
if (intervalRef.current) {
clearInterval(intervalRef.current);
intervalRef.current = null;
}
if (isDevOfflineBrowseForced()) {
setActiveServerReachable(false);
setStatus('disconnected');
} else {
setActiveServerReachable(true);
setStatus('connected');
}
return;
}
check();
intervalRef.current = setInterval(check, 120_000);
const handleOnline = () => {
// Network just came back — the sticky entry is from a different network
// moment and may be wrong. Flush, then re-probe LAN-first.
const sid = useAuthStore.getState().activeServerId;
if (sid) invalidateReachableEndpointCache(sid);
check();
};
const handleOffline = () => {
setActiveServerReachable(false);
setStatus('disconnected');
};
window.addEventListener('online', handleOnline);
window.addEventListener('offline', handleOffline);
return () => {
if (intervalRef.current) clearInterval(intervalRef.current);
window.removeEventListener('online', handleOnline);
window.removeEventListener('offline', handleOffline);
};
}, [check, devForceOffline, perfFlags.disableBackgroundPolling]);
const server = useAuthStore(s => s.getActiveServer());
const servers = useAuthStore(s => s.servers);
const serverName = useMemo(
() => (server ? serverListDisplayLabel(server, servers) : ''),
[server, servers],
);
return {
status,
isRetrying,
retry,
// Active endpoint kind preferred; until the first probe completes we
// fall back to the primary url's classification so the badge has
// *something* to render at mount time. Once a probe has resolved,
// `activeEndpointKind` is the source of truth.
isLan:
activeEndpointKind !== null
? activeEndpointKind === 'local'
: server
? isLanUrl(server.url)
: false,
serverName,
};
}