import { DataStore } from '../common/data-store'; import { Utils } from '../common/utils'; import type { GeoApiResponse, GeoResponse } from '../models/geo-api-response'; import { Logger } from '../common/logger'; import { MP_VISIT_ID_COOKIE } from '../common/constants'; export class GeoLocationProcessor { /** * Always going to make the call if it's enabled in the sdk, because visit info cookie is passed on to the * collector, and it's easier to make changes on the collector end when to make the * ip info call or return with an updated cookie expiry */ public static shouldMakeGeoLocationCall(): boolean { return DataStore.isGeoLocationEnabledInSdk(); } public static async makeGeoLocationApiCall(): Promise { try { if (!this.shouldMakeGeoLocationCall()) { return null; } let geoResponse: GeoApiResponse; const urlInfo = DataStore.getUrlInfo(); // In React Native, we'll get the visit ID from AsyncStorage instead of cookies const visitId = await Utils.getValueFromAsyncStorage( MP_VISIT_ID_COOKIE, '' ); const urlSuffix = `?vid=${visitId}`; // For React Native, we'll try IPv6 first, then fallback to IPv4 if ( urlInfo.baseUrlV6 && (await Utils.getValueFromAsyncStorage('_mp_ipv6', 'false')) !== 'n' ) { try { geoResponse = await Utils.getHttp( `${urlInfo.baseUrlV6}${ urlInfo.geoUrl }/n/${Utils.getUniqueID()}${urlSuffix}` ); await Utils.setValueToAsyncStorage('_mp_ipv6', 'y'); } catch (err) { Logger.logDbg('Error posting to ipv6. Posting to ipv4'); await Utils.setValueToAsyncStorage('_mp_ipv6', 'n'); geoResponse = await Utils.getHttp( `${urlInfo.baseUrlV4}${ urlInfo.geoUrl }/n/${Utils.getUniqueID()}${urlSuffix}` ); } } else { // since the async storage said ipv6 failed, we will not try it again. post to ipv4 directly for this session geoResponse = await Utils.getHttp( `${urlInfo.baseUrlV4}${ urlInfo.geoUrl }/n/${Utils.getUniqueID()}${urlSuffix}` ); } if (!geoResponse) { Logger.logError('Geo API returned empty response'); return null; } if (geoResponse.status === 'KO') { Logger.logError('Geo API returned error status'); return null; } if (geoResponse.status === 'OK' && geoResponse.info) { // Success scenario DataStore.setGeoInfo(geoResponse.info); Logger.logDbg( 'Geo location info retrieved successfully:', geoResponse.info ); return geoResponse.info; } else { Logger.logError('Geo API returned invalid response format'); return null; } } catch (err) { Logger.logError('Error fetching geo info:', err); } return null; } }