372 lines
20 KiB
TypeScript
372 lines
20 KiB
TypeScript
// App data shared by every screen: app folders, studios, store accounts and the apps they see, the pairing / ignore
|
|
// overrides, settings, the sidecar, the portfolio (offline check + the last live read from the cache), app icons, and
|
|
// background jobs shown as toasts with progress and cancel.
|
|
import { createContext, type ReactNode, useCallback, useContext, useEffect, useMemo, useRef, useState } from 'react';
|
|
import {
|
|
type Account, type AccountCheck, api, type AppInfo, type AppsListResult, type AppStatus, type CacheEntry, DEFAULT_SETTINGS, errorText, newJob, onDownload,
|
|
onProgress, type PortfolioResult, type Project, reads, type Settings, type SidecarStatus, type Studio, type ToolResult,
|
|
} from './api';
|
|
import { t } from './i18n';
|
|
import { buildApps, NO_OVERRIDES, type Overrides, type UnifiedApp } from './lib/identity';
|
|
import { isError, type HealthSnapshot, type Review } from './lib/model';
|
|
import { crashCrossed, newLowReviews, releaseChanges } from './lib/notify';
|
|
|
|
export type ToastKind = 'job' | 'ok' | 'bad' | 'info';
|
|
export interface Toast {
|
|
id: string;
|
|
kind: ToastKind;
|
|
title: string;
|
|
detail?: string;
|
|
/** null: running without a known total. */
|
|
progress?: { done: number; total: number } | null;
|
|
/** Cancellable job id. */
|
|
job?: string;
|
|
}
|
|
|
|
export interface AccountHealth { check?: AccountCheck; error?: string; at: string }
|
|
|
|
export interface Data {
|
|
ready: boolean;
|
|
info: AppInfo | null;
|
|
projects: Project[];
|
|
accounts: Account[];
|
|
studios: Studio[];
|
|
overrides: Overrides;
|
|
settings: Settings;
|
|
/** Last app list read of each account (null: never read). */
|
|
storeApps: Record<string, CacheEntry<AppsListResult> | null>;
|
|
/** Last account check of this session. */
|
|
accountHealth: Record<string, AccountHealth>;
|
|
/** Every app across studios and accounts, ignored ones included (`ignored: true`). */
|
|
apps: UnifiedApp[];
|
|
sidecar: SidecarStatus | null;
|
|
sidecarError: string | null;
|
|
/** Latest portfolio read (offline check, or live when just read). */
|
|
portfolio: PortfolioResult | null;
|
|
/** Last live read of the stores (cached across runs). */
|
|
live: CacheEntry<PortfolioResult> | null;
|
|
portfolioBusy: 'offline' | 'live' | null;
|
|
portfolioError: string | null;
|
|
importBusy: boolean;
|
|
icons: Record<string, string | null>;
|
|
refreshPortfolio: (live?: boolean) => Promise<void>;
|
|
/** Reads the apps of one account (or all) from the stores. */
|
|
importApps: (account?: string) => Promise<void>;
|
|
checkAccount: (id: string) => Promise<void>;
|
|
reload: () => Promise<void>;
|
|
updateOverrides: (fn: (o: Overrides) => Overrides) => Promise<void>;
|
|
updateSettings: (s: Settings) => Promise<void>;
|
|
statusOf: (p: Project) => AppStatus | undefined;
|
|
liveOf: (p: Project) => AppStatus | undefined;
|
|
statusFor: (a: UnifiedApp) => AppStatus | undefined;
|
|
liveFor: (a: UnifiedApp) => AppStatus | undefined;
|
|
iconFor: (a: UnifiedApp) => string | null;
|
|
appByKey: (key: string) => UnifiedApp | undefined;
|
|
toasts: Toast[];
|
|
toast: (t: Omit<Toast, 'id'> & { id?: string }) => string;
|
|
updateToast: (id: string, patch: Partial<Toast>) => void;
|
|
dismiss: (id: string) => void;
|
|
cancelJob: (job: string) => void;
|
|
}
|
|
|
|
const Ctx = createContext<Data | null>(null);
|
|
export const useData = (): Data => {
|
|
const d = useContext(Ctx);
|
|
if (!d) throw new Error('useData outside DataProvider');
|
|
return d;
|
|
};
|
|
|
|
const lastLine = (s: string): string => s.trim().split('\n').filter(Boolean).at(-1)?.replace(/^\S+ \[[^\]]+\] /, '') ?? '';
|
|
|
|
export function DataProvider({ children }: { children: ReactNode }) {
|
|
const [ready, setReady] = useState(false);
|
|
const [info, setInfo] = useState<AppInfo | null>(null);
|
|
const [projects, setProjects] = useState<Project[]>([]);
|
|
const [accounts, setAccounts] = useState<Account[]>([]);
|
|
const [studios, setStudios] = useState<Studio[]>([]);
|
|
const [overrides, setOverrides] = useState<Overrides>(NO_OVERRIDES);
|
|
const [settings, setSettings] = useState<Settings>(DEFAULT_SETTINGS);
|
|
const [storeApps, setStoreApps] = useState<Record<string, CacheEntry<AppsListResult> | null>>({});
|
|
const [accountHealth, setAccountHealth] = useState<Record<string, AccountHealth>>({});
|
|
const [sidecar, setSidecar] = useState<SidecarStatus | null>(null);
|
|
const [sidecarError, setSidecarError] = useState<string | null>(null);
|
|
const [portfolio, setPortfolio] = useState<PortfolioResult | null>(null);
|
|
const [live, setLive] = useState<CacheEntry<PortfolioResult> | null>(null);
|
|
const [portfolioBusy, setBusy] = useState<Data['portfolioBusy']>(null);
|
|
const [portfolioError, setPortfolioError] = useState<string | null>(null);
|
|
const [importBusy, setImportBusy] = useState(false);
|
|
const [icons, setIcons] = useState<Record<string, string | null>>({});
|
|
const [toasts, setToasts] = useState<Toast[]>([]);
|
|
const timers = useRef(new Map<string, ReturnType<typeof setTimeout>>());
|
|
const liveRef = useRef(live);
|
|
liveRef.current = live;
|
|
const settingsRef = useRef(settings);
|
|
settingsRef.current = settings;
|
|
|
|
const dismiss = useCallback((id: string) => {
|
|
setToasts(ts => ts.filter(x => x.id !== id));
|
|
const tm = timers.current.get(id);
|
|
if (tm) { clearTimeout(tm); timers.current.delete(id); }
|
|
}, []);
|
|
const autoClose = useCallback((id: string, kind: ToastKind) => {
|
|
if (kind === 'job') return;
|
|
const old = timers.current.get(id);
|
|
if (old) clearTimeout(old);
|
|
timers.current.set(id, setTimeout(() => dismiss(id), kind === 'bad' ? 9000 : 4500));
|
|
}, [dismiss]);
|
|
const toast = useCallback((x: Omit<Toast, 'id'> & { id?: string }) => {
|
|
const id = x.id ?? newJob('toast');
|
|
setToasts(ts => [...ts.filter(o => o.id !== id), { ...x, id }].slice(-4));
|
|
autoClose(id, x.kind);
|
|
return id;
|
|
}, [autoClose]);
|
|
const updateToast = useCallback((id: string, patch: Partial<Toast>) => {
|
|
setToasts(ts => ts.map(x => (x.id === id ? { ...x, ...patch } : x)));
|
|
if (patch.kind) autoClose(id, patch.kind);
|
|
}, [autoClose]);
|
|
const cancelJob = useCallback((job: string) => { api.cancel(job).catch(() => {}); }, []);
|
|
|
|
const reload = useCallback(async () => {
|
|
const [p, a, w, s] = await Promise.all([api.projects(), api.accounts(), api.workspace(), api.storeAppsCached()]);
|
|
setProjects(p);
|
|
setAccounts(a);
|
|
setStudios(w.studios);
|
|
setOverrides(w.overrides);
|
|
setSettings(w.settings);
|
|
setStoreApps(Object.fromEntries(s.map(x => [x.account, x.entry])));
|
|
}, []);
|
|
|
|
const apps = useMemo(() => buildApps({
|
|
projects, accounts, overrides,
|
|
summaryOf: p => portfolio?.apps.find(a => a.project === p.path)?.summary ?? liveRef.current?.value.apps.find(a => a.project === p.path)?.summary,
|
|
storeApps: Object.entries(storeApps).filter(([, e]) => !!e).map(([account, e]) => ({ account, apps: e!.value.apps })),
|
|
}), [projects, accounts, overrides, portfolio, storeApps]);
|
|
const appsRef = useRef(apps);
|
|
appsRef.current = apps;
|
|
|
|
const refreshPortfolio = useCallback(async (liveRead = false) => {
|
|
const job = newJob(liveRead ? 'portfolio-live' : 'portfolio');
|
|
setBusy(liveRead ? 'live' : 'offline'); setPortfolioError(null);
|
|
const tid = liveRead ? toast({ id: job, kind: 'job', title: t('toast.readingStores'), detail: t('toast.readingStoresDetail'), progress: null, job }) : null;
|
|
try {
|
|
const stores = liveRead ? appsRef.current.filter(a => !a.project && !a.ignored).map(a => a.target) : [];
|
|
const r = await api.portfolio(liveRead, job, stores);
|
|
setPortfolio(r);
|
|
if (liveRead) {
|
|
const changes = releaseChanges(liveRef.current?.value, r);
|
|
setLive({ value: r, at: r.at });
|
|
if (settingsRef.current.notify.reviewState) for (const c of changes.slice(0, 5))
|
|
api.notify(t('notify.releaseTitle', { name: c.name }), t('notify.releaseBody', { store: c.store === 'ios' ? 'App Store' : 'Google Play', version: c.version, phase: t(`phase.${c.to}` as 'phase.live') })).catch(() => {});
|
|
const failed = r.apps.filter(a => a.storeErrors.ios || a.storeErrors.android).length;
|
|
if (tid) updateToast(tid, failed ? { kind: 'info', title: t('toast.readDonePartial'), detail: t('toast.readDonePartialDetail', { count: failed }), progress: undefined, job: undefined }
|
|
: { kind: 'ok', title: t('toast.readDone'), detail: t('toast.readDoneDetail', { count: r.apps.length }), progress: undefined, job: undefined });
|
|
}
|
|
} catch (e) {
|
|
const msg = errorText(e);
|
|
setPortfolioError(msg);
|
|
if (tid) updateToast(tid, { kind: /cancel/i.test(msg) ? 'info' : 'bad', title: /cancel/i.test(msg) ? t('toast.cancelled') : t('toast.readFailed'), detail: msg, progress: undefined, job: undefined });
|
|
} finally { setBusy(null); }
|
|
}, [toast, updateToast]);
|
|
|
|
const importApps = useCallback(async (account?: string) => {
|
|
const ids = (account ? [account] : accounts.map(a => a.id)).filter(id => account || !overrides.ignored.includes(`account:${id}`));
|
|
if (!ids.length) return;
|
|
const job = newJob('import');
|
|
setImportBusy(true);
|
|
const tid = toast({ id: job, kind: 'job', title: t('toast.importing'), detail: t('toast.importingDetail'), progress: { done: 0, total: ids.length }, job });
|
|
let ok = 0, apps = 0;
|
|
const errors: string[] = [];
|
|
for (const [n, id] of ids.entries()) {
|
|
try {
|
|
const e = await api.refreshStoreApps(id, job);
|
|
setStoreApps(m => ({ ...m, [id]: e }));
|
|
ok++; apps += e.value.apps.length;
|
|
} catch (e) {
|
|
const msg = errorText(e);
|
|
if (/cancel/i.test(msg)) { updateToast(tid, { kind: 'info', title: t('toast.cancelled'), detail: undefined, progress: undefined, job: undefined }); setImportBusy(false); return; }
|
|
errors.push(`${accounts.find(a => a.id === id)?.label ?? id}: ${msg}`);
|
|
}
|
|
updateToast(tid, { progress: { done: n + 1, total: ids.length } });
|
|
}
|
|
setImportBusy(false);
|
|
updateToast(tid, errors.length ? { kind: ok ? 'info' : 'bad', title: t('toast.importPartial', { count: errors.length }), detail: errors[0], progress: undefined, job: undefined }
|
|
: { kind: 'ok', title: t('toast.importDone', { count: apps }), detail: t('toast.importDoneDetail', { count: ok }), progress: undefined, job: undefined });
|
|
}, [accounts, overrides.ignored, toast, updateToast]);
|
|
|
|
const checkAccount = useCallback(async (id: string) => {
|
|
try {
|
|
const check = await api.checkAccount(id, newJob('check'));
|
|
setAccountHealth(m => ({ ...m, [id]: { check, at: new Date().toISOString() } }));
|
|
} catch (e) { setAccountHealth(m => ({ ...m, [id]: { error: errorText(e), at: new Date().toISOString() } })); }
|
|
}, []);
|
|
|
|
const updateOverrides = useCallback(async (fn: (o: Overrides) => Overrides) => {
|
|
const next = fn(overrides);
|
|
setOverrides(next);
|
|
try { setOverrides(await api.setOverrides(next)); } catch (e) {
|
|
setOverrides(overrides);
|
|
toast({ kind: 'bad', title: t('toast.saveFailed'), detail: errorText(e) });
|
|
}
|
|
}, [overrides, toast]);
|
|
|
|
const updateSettings = useCallback(async (s: Settings) => {
|
|
const old = settings;
|
|
setSettings(s);
|
|
try { setSettings(await api.setSettings(s)); } catch (e) { setSettings(old); toast({ kind: 'bad', title: t('toast.saveFailed'), detail: errorText(e) }); }
|
|
}, [settings, toast]);
|
|
|
|
// start: app info, folders, accounts, workspace, sidecar, cached live portfolio
|
|
useEffect(() => {
|
|
api.appInfo().then(setInfo, () => {});
|
|
reload().catch(() => {}).finally(() => setReady(true));
|
|
api.sidecarStatus().then(s => { setSidecar(s); setSidecarError(null); }, e => setSidecarError(errorText(e)));
|
|
api.cached<PortfolioResult>('portfolio.status', '*', { live: true }).then(e => { if (e) setLive(e); }, () => {});
|
|
}, [reload]);
|
|
|
|
useEffect(() => { if (projects.length) refreshPortfolio(false); }, [projects.length, refreshPortfolio]);
|
|
|
|
// Settings > Refresh: on launch, then every N minutes (store reads use the accounts' API quota: off by default)
|
|
const launched = useRef(false);
|
|
useEffect(() => {
|
|
if (!ready || launched.current) return;
|
|
launched.current = true;
|
|
if (settings.refresh.onLaunch && (projects.length || accounts.length)) importApps().finally(() => refreshPortfolio(true));
|
|
}, [ready, settings.refresh.onLaunch, projects.length, accounts.length, importApps, refreshPortfolio]);
|
|
const busyRef = useRef(portfolioBusy);
|
|
busyRef.current = portfolioBusy;
|
|
useEffect(() => {
|
|
const m = settings.refresh.autoMinutes;
|
|
if (!m) return;
|
|
const tm = setInterval(() => { if (!busyRef.current) refreshPortfolio(true); }, m * 60_000);
|
|
return () => clearInterval(tm);
|
|
}, [settings.refresh.autoMinutes, refreshPortfolio]);
|
|
|
|
// icons: cached first, then read (offline, cheap)
|
|
useEffect(() => {
|
|
for (const p of projects) {
|
|
if (p.id in icons) continue;
|
|
setIcons(m => ({ ...m, [p.id]: null }));
|
|
api.cached<ToolResult & { data?: { dataUrl: string | null } }>('project.icon', p.id).then(c => {
|
|
if (c?.value.data?.dataUrl) setIcons(m => ({ ...m, [p.id]: c.value.data!.dataUrl }));
|
|
}, () => {}).finally(() => {
|
|
reads.icon(p.id).then(r => setIcons(m => ({ ...m, [p.id]: r.data?.dataUrl ?? m[p.id] ?? null })), () => {});
|
|
});
|
|
}
|
|
}, [projects]); // eslint-disable-line react-hooks/exhaustive-deps
|
|
|
|
// progress of jobs -> their toasts
|
|
useEffect(() => {
|
|
const un = onProgress(p => {
|
|
if (!p.job) return;
|
|
setToasts(ts => ts.map(x => {
|
|
if (x.job !== p.job) return x;
|
|
if (p.total) return { ...x, progress: { done: p.n ?? 0, total: p.total } };
|
|
if (p.line) return { ...x, detail: lastLine(p.line) || x.detail };
|
|
return x;
|
|
}));
|
|
});
|
|
const unD = onDownload(e => {
|
|
setToasts(ts => ts.map(x => (x.job === e.job && e.stage !== 'done' && e.stage !== 'error' && e.stage !== 'cancelled'
|
|
? { ...x, detail: t(`dl.${e.stage}`), progress: e.total ? { done: e.received, total: e.total } : null } : x)));
|
|
});
|
|
return () => { un.then(f => f()); unD.then(f => f()); };
|
|
}, []);
|
|
|
|
const statusOf = useCallback((p: Project) => portfolio?.apps.find(a => a.project === p.path || a.app?.id === p.path), [portfolio]);
|
|
const liveOf = useCallback((p: Project) => {
|
|
const cur = portfolio?.apps.find(a => (a.project === p.path || a.app?.id === p.path) && a.release.source === 'live');
|
|
return cur ?? live?.value.apps.find(a => a.project === p.path || a.app?.id === p.path);
|
|
}, [portfolio, live]);
|
|
const statusFor = useCallback((a: UnifiedApp) => (a.project ? statusOf(a.project) : portfolio?.apps.find(x => x.project === a.target) ?? live?.value.apps.find(x => x.project === a.target)), [statusOf, portfolio, live]);
|
|
const liveFor = useCallback((a: UnifiedApp) => (a.project ? liveOf(a.project) : portfolio?.apps.find(x => x.project === a.target && x.release.source === 'live') ?? live?.value.apps.find(x => x.project === a.target)), [liveOf, portfolio, live]);
|
|
const iconFor = useCallback((a: UnifiedApp) => (a.project ? icons[a.project.id] ?? a.storeIcon : a.storeIcon), [icons]);
|
|
const appByKey = useCallback((key: string) => apps.find(a => a.key === key), [apps]);
|
|
|
|
const value = useMemo<Data>(() => ({
|
|
ready, info, projects, accounts, studios, overrides, settings, storeApps, accountHealth, apps, sidecar, sidecarError, portfolio, live, portfolioBusy, portfolioError,
|
|
importBusy, icons, refreshPortfolio, importApps, checkAccount, reload, updateOverrides, updateSettings, statusOf, liveOf, statusFor, liveFor, iconFor, appByKey,
|
|
toasts, toast, updateToast, dismiss, cancelJob,
|
|
}), [ready, info, projects, accounts, studios, overrides, settings, storeApps, accountHealth, apps, sidecar, sidecarError, portfolio, live, portfolioBusy, portfolioError,
|
|
importBusy, icons, refreshPortfolio, importApps, checkAccount, reload, updateOverrides, updateSettings, statusOf, liveOf, statusFor, liveFor, iconFor, appByKey,
|
|
toasts, toast, updateToast, dismiss, cancelJob]);
|
|
return <Ctx.Provider value={value}>{children}</Ctx.Provider>;
|
|
}
|
|
|
|
export interface ReadState<T> {
|
|
data: T | null;
|
|
/** When `data` was read (from the store or the cache). */
|
|
at: string | null;
|
|
fromCache: boolean;
|
|
loading: boolean;
|
|
error: string | null;
|
|
/** The command line it ran (shown with errors). */
|
|
command: string | null;
|
|
refresh: () => Promise<void>;
|
|
}
|
|
|
|
/** Notifications a fresh read may trigger (Settings > Notifications), compared with the read it replaces. */
|
|
function notifyAfterRead(method: string, prev: unknown, next: unknown, settings: Settings, appName: string | undefined): void {
|
|
const name = appName ?? '';
|
|
if (method === 'reviews.list' && settings.notify.lowReviews && Array.isArray(next)) {
|
|
const fresh = newLowReviews(prev as Review[] | null, next as Review[]);
|
|
if (fresh.length) api.notify(t('notify.lowTitle', { name, count: fresh.length }), `${'★'.repeat(fresh[0]!.rating)} ${fresh[0]!.title ?? ''} ${fresh[0]!.body}`.trim()).catch(() => {});
|
|
}
|
|
if (method === 'health' && settings.notify.crash && next && typeof next === 'object') {
|
|
const crossed = crashCrossed(prev as HealthSnapshot | null, next as HealthSnapshot);
|
|
if (crossed.length && !isError((next as HealthSnapshot).play)) api.notify(t('notify.crashTitle', { name }), crossed.map(k => (k === 'crash' ? t('health.crash') : t('health.anr'))).join(', ')).catch(() => {});
|
|
}
|
|
}
|
|
|
|
/**
|
|
* One read method of one app (a project id, or a store-only app's store target). The cached value shows at once with
|
|
* its time; offline reads (`network: false`) then refresh by themselves, store reads only on demand (they use the
|
|
* account's API quota). A failed read keeps the last good value and says so: never an empty "all fine".
|
|
*/
|
|
export function useRead<T>(target: string, method: string, o: { network: boolean; args?: Record<string, unknown>; title?: string; appName?: string; skip?: boolean }): ReadState<T> {
|
|
const d = useData();
|
|
const argsKey = JSON.stringify(o.args ?? {});
|
|
const [s, set] = useState<Omit<ReadState<T>, 'refresh'>>({ data: null, at: null, fromCache: false, loading: true, error: null, command: null });
|
|
const seq = useRef(0);
|
|
const dataRef = useRef<T | null>(null);
|
|
dataRef.current = s.data;
|
|
|
|
const refresh = useCallback(async () => {
|
|
const my = ++seq.current;
|
|
const job = newJob(method);
|
|
set(x => ({ ...x, loading: true, error: null }));
|
|
const tid = o.network ? d.toast({ id: job, kind: 'job', title: o.title ?? t('toast.reading'), detail: t('toast.readingDetail'), progress: null, job }) : null;
|
|
try {
|
|
const r = await api.call<ToolResult>(method, target, { args: JSON.parse(argsKey) as Record<string, unknown> }, job);
|
|
if (my !== seq.current) return;
|
|
if (r.ok && r.data !== undefined) {
|
|
notifyAfterRead(method, dataRef.current, r.data, d.settings, o.appName);
|
|
set({ data: r.data as T, at: new Date().toISOString(), fromCache: false, loading: false, error: null, command: r.command });
|
|
if (tid) d.updateToast(tid, { kind: 'ok', title: t('toast.readOk', { what: o.title ?? method }), detail: undefined, progress: undefined, job: undefined });
|
|
} else {
|
|
const msg = lastLine(r.output) || t('common.exit', { code: r.exitCode });
|
|
set(x => ({ ...x, loading: false, error: msg, command: r.command }));
|
|
if (tid) d.updateToast(tid, { kind: 'bad', title: t('toast.readFailedWhat', { what: o.title ?? method }), detail: msg, progress: undefined, job: undefined });
|
|
}
|
|
} catch (e) {
|
|
if (my !== seq.current) return;
|
|
const msg = errorText(e);
|
|
set(x => ({ ...x, loading: false, error: msg }));
|
|
if (tid) d.updateToast(tid, { kind: /cancel/i.test(msg) ? 'info' : 'bad', title: /cancel/i.test(msg) ? t('toast.cancelled') : t('toast.readFailedWhat', { what: o.title ?? method }), detail: msg, progress: undefined, job: undefined });
|
|
}
|
|
}, [target, method, argsKey, o.network, o.title, o.appName, d.settings]); // eslint-disable-line react-hooks/exhaustive-deps
|
|
|
|
useEffect(() => {
|
|
let alive = true;
|
|
if (o.skip) { set({ data: null, at: null, fromCache: false, loading: false, error: null, command: null }); return; }
|
|
set({ data: null, at: null, fromCache: false, loading: true, error: null, command: null });
|
|
api.cached<ToolResult>(method, target, JSON.parse(argsKey) as Record<string, unknown>).then(c => {
|
|
if (!alive) return;
|
|
if (c && c.value.data !== undefined) set({ data: c.value.data as T, at: c.at, fromCache: true, loading: !o.network, error: null, command: c.value.command });
|
|
else set(x => ({ ...x, loading: !o.network }));
|
|
if (!o.network) refresh();
|
|
}, () => { if (alive) { set(x => ({ ...x, loading: !o.network })); if (!o.network) refresh(); } });
|
|
return () => { alive = false; };
|
|
}, [target, method, argsKey, o.skip]); // eslint-disable-line react-hooks/exhaustive-deps
|
|
|
|
return { ...s, refresh };
|
|
}
|