Public Access
The token is no longer stored; a tbp_session flag remembers the login. apiFetch renews the session once on a 401 and sends the request again. Parallel requests and other tabs share one refresh, because Auth revokes the session when a refresh token is used twice. Only a 401 from the refresh ends the session; a 502 or no network shows the normal error.
56 lines
1.8 KiB
JavaScript
56 lines
1.8 KiB
JavaScript
import {useState} from 'react';
|
|
import {useNavigate} from 'react-router-dom';
|
|
import {useTranslation} from 'react-i18next';
|
|
import {toast} from 'sonner';
|
|
import useSessionExpired from './useSessionExpired.js';
|
|
import {apiFetch} from '../utils/api.js';
|
|
import {hasSession} from '../utils/auth.js';
|
|
|
|
const RELOAD_DELAY_MS = 4000;
|
|
|
|
/**
|
|
* Starts a library sync (POST /api/library/sync), reports the result as a toast and calls
|
|
* onStarted after a short delay, so the caller can reload once Steam data has arrived.
|
|
*/
|
|
export default function useForceSync(onStarted) {
|
|
const {t} = useTranslation();
|
|
const navigate = useNavigate();
|
|
const expireSession = useSessionExpired();
|
|
const [busy, setBusy] = useState(false);
|
|
|
|
const trigger = async () => {
|
|
if (!hasSession()) {
|
|
navigate('/login');
|
|
return;
|
|
}
|
|
setBusy(true);
|
|
try {
|
|
const response = await apiFetch(`${import.meta.env.VITE_CORE_API_URL}/api/library/sync`, {
|
|
method: 'POST',
|
|
});
|
|
if (response.status === 401) {
|
|
expireSession();
|
|
return;
|
|
}
|
|
if (response.status === 429) {
|
|
const json = await response.json().catch(() => ({}));
|
|
toast.warning(t('LIBRARY.SYNC_COOLDOWN', {seconds: json.retryAfterSeconds ?? 60}));
|
|
return;
|
|
}
|
|
if (!response.ok) {
|
|
toast.error(t('LIBRARY.SYNC_FAILED'));
|
|
return;
|
|
}
|
|
toast.success(t('LIBRARY.SYNC_STARTED'));
|
|
setTimeout(onStarted, RELOAD_DELAY_MS);
|
|
} catch (err) {
|
|
console.error('sync trigger error:', err);
|
|
toast.error(t('INFO.ERROR.NETWORK_FAILURE'));
|
|
} finally {
|
|
setBusy(false);
|
|
}
|
|
};
|
|
|
|
return {trigger, busy};
|
|
}
|