2024-03-25 08:12:31 +00:00
|
|
|
import { useInvalidate } from "@refinedev/core";
|
2024-03-22 13:54:46 +00:00
|
|
|
import {
|
2024-03-22 17:53:39 +00:00
|
|
|
type QueryClient,
|
|
|
|
type UseQueryResult,
|
2024-03-22 13:54:46 +00:00
|
|
|
useQuery,
|
|
|
|
useQueryClient,
|
|
|
|
} from "@tanstack/react-query";
|
2024-03-25 08:12:31 +00:00
|
|
|
import { createContext, useContext, useEffect } from "react";
|
2024-03-22 17:53:39 +00:00
|
|
|
import { PinningProcess, type PinningStatus } from "~/data/pinning";
|
2024-03-21 05:16:27 +00:00
|
|
|
|
|
|
|
export interface IPinningData {
|
2024-03-22 13:54:46 +00:00
|
|
|
cid: string;
|
|
|
|
progress: number;
|
2024-03-21 05:16:27 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
export interface IPinningContextType {
|
2024-03-22 13:54:46 +00:00
|
|
|
query: UseQueryResult<
|
|
|
|
{
|
|
|
|
items: PinningStatus[];
|
|
|
|
lastUpdated: number;
|
|
|
|
},
|
|
|
|
Error
|
|
|
|
>;
|
|
|
|
queryClient: QueryClient;
|
2024-03-21 05:16:27 +00:00
|
|
|
}
|
|
|
|
|
2024-03-22 13:54:46 +00:00
|
|
|
export const PinningContext = createContext<IPinningContextType>(
|
|
|
|
{} as IPinningContextType,
|
|
|
|
);
|
2024-03-25 08:12:31 +00:00
|
|
|
export const PinningProvider = ({ children }: React.PropsWithChildren) => {
|
|
|
|
const invalidate = useInvalidate();
|
|
|
|
const queryClient = useQueryClient();
|
|
|
|
const queryResult = useQuery({
|
2024-03-22 13:54:46 +00:00
|
|
|
queryKey: ["pin-progress"],
|
|
|
|
refetchInterval: (query) => {
|
2024-03-28 22:59:11 +00:00
|
|
|
if (!query.state.data?.items || query.state.data.items.length === 0) {
|
2024-03-22 13:54:46 +00:00
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
|
|
|
return 1000;
|
|
|
|
},
|
|
|
|
refetchIntervalInBackground: true,
|
|
|
|
queryFn: () => {
|
|
|
|
const response = PinningProcess.pollAllProgress();
|
|
|
|
const result = response.next();
|
|
|
|
|
|
|
|
return {
|
|
|
|
items: result.value || [],
|
|
|
|
lastUpdated: Date.now(),
|
|
|
|
};
|
|
|
|
},
|
|
|
|
});
|
|
|
|
|
2024-03-25 08:12:31 +00:00
|
|
|
useEffect(() => {
|
|
|
|
if (
|
|
|
|
queryResult.isSuccess &&
|
|
|
|
queryResult.fetchStatus === "idle" &&
|
|
|
|
queryResult.isFetched
|
|
|
|
) {
|
|
|
|
const hasCompletedItems = queryResult.data.items.some(item => item.status === 'completed');
|
|
|
|
if (hasCompletedItems) {
|
2024-03-27 06:46:12 +00:00
|
|
|
invalidate({ resource: "file", invalidates: ["list"] });
|
2024-03-25 08:12:31 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}, [
|
|
|
|
queryResult.fetchStatus,
|
|
|
|
queryResult.isSuccess,
|
|
|
|
queryResult.isFetched,
|
|
|
|
invalidate,
|
|
|
|
queryResult.data,
|
|
|
|
]);
|
2024-03-22 13:54:46 +00:00
|
|
|
|
|
|
|
return (
|
|
|
|
<PinningContext.Provider value={{ query: queryResult, queryClient }}>
|
|
|
|
{children}
|
|
|
|
</PinningContext.Provider>
|
|
|
|
);
|
|
|
|
};
|