1 import { useEffect, useState } from 'react';
3 import { getSilentApi } from '@proton/shared/lib/api/helpers/customConfig';
4 import { getLocation } from '@proton/shared/lib/api/vpn';
5 import { singleCountryTimezoneDatabase } from '@proton/shared/lib/date/singleCountryTimezoneDatabase';
6 import { manualFindTimeZone } from '@proton/shared/lib/date/timezoneDatabase';
7 import { getNaiveCountryCode } from '@proton/shared/lib/i18n/helper';
8 import type { Api, MyLocationResponse } from '@proton/shared/lib/interfaces';
10 import useApi from './useApi';
12 const tryTimezone = (tz: string): string | undefined =>
13 singleCountryTimezoneDatabase[tz as keyof typeof singleCountryTimezoneDatabase];
15 const getCountryFromTimezone = () => {
17 const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
20 return tryTimezone(timezone) || tryTimezone(manualFindTimeZone(timezone));
27 export const getCountryFromLanguage = () => {
28 const language = navigator.languages.find((language) => /[_-]/.test(language));
30 return getNaiveCountryCode(language);
34 const getStaticState = () => {
35 return (getCountryFromTimezone() || getCountryFromLanguage())?.toUpperCase();
38 const getMyCountry = async (api: Api): Promise<string | undefined> => {
39 // TODO: Have a non-VPN dedicated API for that purpose
40 const value = await api<MyLocationResponse>(getLocation());
41 return value?.Country?.toUpperCase();
44 const state: { initialized: boolean; promise: null | Promise<string | undefined>; value: string | undefined } = {
50 const getInitialValue = () => {
51 if (!state.initialized) {
52 state.initialized = true;
53 state.value = getStaticState();
58 const getCountryPromise = (api: Api) => {
62 state.promise = getMyCountry(getSilentApi(api))
73 const useMyCountry = (): string | undefined => {
74 const [country, setMyCountry] = useState<string | undefined>(getInitialValue);
80 void getCountryPromise(api).then(setMyCountry);
85 export default useMyCountry;