1 import { useEffect, useRef, useState } from 'react';
3 import { c, msgid } from 'ttag';
5 import useApi from '@proton/components/hooks/useApi';
6 import { SECOND } from '@proton/shared/lib/constants';
8 import type { Gateway } from './Gateway';
9 import type { GatewayLocation } from './GatewayLocation';
10 import type { GatewayUser } from './GatewayUser';
11 import { queryVPNGateways } from './api';
13 interface TableConfig {
23 interface GatewayConfig {
25 ServerTable: TableConfig;
27 TranslatedDuration: string;
31 interface GatewayResult {
32 Config: GatewayConfig;
33 Countries: readonly string[];
34 Locations: readonly GatewayLocation[];
35 Gateways: readonly Gateway[];
36 Users: readonly GatewayUser[];
39 export const useGateways = (maxAge: number) => {
40 const [result, setResult] = useState<GatewayResult | null>(null);
41 const [loading, setLoading] = useState<boolean>(true);
45 const refreshStateRef = useRef({ lastUpdate: 0, lastSuccess: 0 });
47 const refresh = async () => {
49 refreshStateRef.current.lastUpdate = Date.now();
50 const result = await api<GatewayResult>(queryVPNGateways());
51 refreshStateRef.current.lastSuccess = Date.now();
63 const refreshHandle = setInterval(() => {
64 const { lastSuccess, lastUpdate } = refreshStateRef.current;
66 // Don't start to refresh until first success
71 const now = Date.now();
72 if (now > lastUpdate + maxAge / 5 && now > lastSuccess + maxAge) {
78 clearInterval(refreshHandle);
85 loading: !result || loading,
86 config: result?.Config || {
104 TranslatedDuration: c('Label').ngettext(msgid`${nbDay} day`, `${nbDay} days`, nbDay),
107 countries: result?.Countries,
108 locations: result?.Locations,
109 gateways: result?.Gateways,
110 users: result?.Users || [],
115 export default useGateways;