84 lines
2.1 KiB
TypeScript
84 lines
2.1 KiB
TypeScript
import { useEffect, useRef, useState } from "react";
|
|
import { useQueryClient } from "@tanstack/react-query";
|
|
import { API_ENDPOINTS } from "@/config/api";
|
|
|
|
export interface MissingFiles {
|
|
fileName: string;
|
|
folderPath: string;
|
|
}
|
|
|
|
export interface ExtraFiles {
|
|
fileName: string;
|
|
folderPath: string;
|
|
}
|
|
|
|
export interface ClientFolderStatus {
|
|
id: number;
|
|
deviceId: string;
|
|
missingFiles: MissingFiles[];
|
|
extraFiles: ExtraFiles[];
|
|
createdAt: string;
|
|
updatedAt: string;
|
|
}
|
|
|
|
export function useClientFolderStatus(roomName?: string) {
|
|
const queryClient = useQueryClient();
|
|
const reconnectTimeout = useRef<ReturnType<typeof setTimeout> | null>(null);
|
|
const [folderStatuses, setFolderStatuses] = useState<
|
|
Map<string, ClientFolderStatus>
|
|
>(new Map());
|
|
|
|
useEffect(() => {
|
|
let eventSource: EventSource | null = null;
|
|
|
|
const connect = () => {
|
|
eventSource = new EventSource(
|
|
API_ENDPOINTS.SSE_EVENTS.GET_CLIENT_FOLDER_STATUS
|
|
);
|
|
|
|
eventSource.addEventListener("clientFolderStatus", (event) => {
|
|
try {
|
|
const data: ClientFolderStatus = JSON.parse(event.data);
|
|
|
|
if (roomName && data.deviceId) {
|
|
setFolderStatuses((prev) => {
|
|
const newMap = new Map(prev);
|
|
newMap.set(data.deviceId, data);
|
|
return newMap;
|
|
});
|
|
|
|
// Also cache in React Query for persistence
|
|
queryClient.setQueryData(
|
|
["folderStatus", data.deviceId],
|
|
data
|
|
);
|
|
}
|
|
} catch (err) {
|
|
console.error("Error parsing clientFolderStatus event:", err);
|
|
}
|
|
});
|
|
|
|
const onError = (err: any) => {
|
|
console.error("SSE connection error:", err);
|
|
cleanup();
|
|
reconnectTimeout.current = setTimeout(connect, 5000);
|
|
};
|
|
|
|
eventSource.onerror = onError;
|
|
};
|
|
|
|
const cleanup = () => {
|
|
if (eventSource) eventSource.close();
|
|
if (reconnectTimeout.current) {
|
|
clearTimeout(reconnectTimeout.current);
|
|
reconnectTimeout.current = null;
|
|
}
|
|
};
|
|
|
|
connect();
|
|
return cleanup;
|
|
}, [roomName, queryClient]);
|
|
|
|
return folderStatuses;
|
|
}
|