66 lines
1.9 KiB
TypeScript
66 lines
1.9 KiB
TypeScript
import { useState, useCallback, useEffect } from "react";
|
|
import { fetchCodexUsage } from "@/lib/api/codexApi";
|
|
import { loadCodexAuth, saveCodexAuth, clearCodexAuth } from "@/lib/storage";
|
|
import { pickAndReadCodexAuth } from "@/lib/fileReader";
|
|
import type { CodexUsageResponse, CodexAuth } from "@/types/codex";
|
|
|
|
type Status = "idle" | "loading" | "success" | "error";
|
|
|
|
export function useCodexUsage() {
|
|
const [auth, setAuth] = useState<CodexAuth | null>(null);
|
|
const [usage, setUsage] = useState<CodexUsageResponse | null>(null);
|
|
const [status, setStatus] = useState<Status>("idle");
|
|
const [error, setError] = useState<string | null>(null);
|
|
|
|
useEffect(() => {
|
|
loadCodexAuth().then((stored) => {
|
|
if (stored) setAuth(stored);
|
|
});
|
|
}, []);
|
|
|
|
const importAuthFile = useCallback(async () => {
|
|
try {
|
|
const parsed = await pickAndReadCodexAuth();
|
|
await saveCodexAuth(parsed);
|
|
setAuth(parsed);
|
|
setError(null);
|
|
} catch (e: unknown) {
|
|
const msg = e instanceof Error ? e.message : "UNKNOWN_ERROR";
|
|
if (msg !== "PICKER_CANCELLED") setError(msg);
|
|
}
|
|
}, []);
|
|
|
|
const refresh = useCallback(async () => {
|
|
if (!auth) return;
|
|
setStatus("loading");
|
|
setError(null);
|
|
try {
|
|
const data = await fetchCodexUsage(auth);
|
|
setUsage(data);
|
|
setStatus("success");
|
|
} catch (e: unknown) {
|
|
const msg = e instanceof Error ? e.message : "UNKNOWN_ERROR";
|
|
setError(msg);
|
|
setStatus("error");
|
|
if (msg === "TOKEN_EXPIRED") {
|
|
await clearCodexAuth();
|
|
setAuth(null);
|
|
}
|
|
}
|
|
}, [auth]);
|
|
|
|
useEffect(() => {
|
|
if (auth) void refresh();
|
|
}, [auth]);
|
|
|
|
const clearAuth = useCallback(async () => {
|
|
await clearCodexAuth();
|
|
setAuth(null);
|
|
setUsage(null);
|
|
setStatus("idle");
|
|
setError(null);
|
|
}, []);
|
|
|
|
return { auth, usage, status, error, importAuthFile, refresh, clearAuth };
|
|
}
|