useCameraStreamToken.ts 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. import { useEffect } from 'react';
  2. import { useQuery } from '@tanstack/react-query';
  3. import { api, setStreamToken, withStreamToken } from '../api/client';
  4. import { useAuth } from '../contexts/AuthContext';
  5. /**
  6. * Fetches and caches a stream token for <img>/<video> src URLs.
  7. * Stores the token globally via setStreamToken() so URL generators
  8. * in client.ts can use withStreamToken() automatically.
  9. *
  10. * Mount this hook once near the app root (e.g., in App.tsx or a layout component).
  11. * Components that need token-protected URLs can import withStreamToken directly.
  12. */
  13. export function useStreamTokenSync() {
  14. const { authEnabled } = useAuth();
  15. const { data } = useQuery({
  16. queryKey: ['camera-stream-token'],
  17. queryFn: () => api.getCameraStreamToken(),
  18. enabled: authEnabled,
  19. staleTime: 50 * 60 * 1000, // refresh at 50 min (tokens expire at 60)
  20. refetchInterval: 50 * 60 * 1000,
  21. });
  22. useEffect(() => {
  23. setStreamToken(data?.token ?? null);
  24. return () => setStreamToken(null);
  25. }, [data?.token]);
  26. }
  27. /**
  28. * Hook for components that need to wrap URLs with the stream token.
  29. * Returns a withToken function that appends ?token=xxx when auth is enabled.
  30. */
  31. export function useCameraStreamToken() {
  32. return { withToken: withStreamToken };
  33. }