@@ -450,43 +450,56 @@ defmodule PlausibleWeb.Api.ExternalController do
450450
451451 @ decorate trace ( "ingest.geolocation" )
452452 defp visitor_location_details ( conn ) do
453- result =
454- PlausibleWeb.RemoteIp . get ( conn )
455- |> Geolix . lookup ( )
453+ ip = PlausibleWeb.RemoteIp . get ( conn )
456454
457- country_code =
458- get_in ( result , [ :geolocation , :country , :iso_code ] )
459- |> ignore_unknown_country
455+ case :locus . lookup ( :geolocation , ip ) do
456+ { :ok , result } -> get_location_details ( result )
457+ _ -> get_location_details ( % { } )
458+ end
459+ end
460460
461- city_geoname_id = get_in ( result , [ :geolocation , :city , :geoname_id ] )
461+ defp get_location_details ( geo_data ) do
462+ % {
463+ country_code: get_country_code ( geo_data ) ,
464+ subdivision1_code: get_subdivision_code ( geo_data , 0 ) ,
465+ subdivision2_code: get_subdivision_code ( geo_data , 1 ) ,
466+ city_geoname_id: get_city_geoname_id ( geo_data )
467+ }
468+ end
462469
463- subdivision1_code =
464- case result do
465- % { geolocation: % { subdivisions: [ % { iso_code: iso_code } | _rest ] } } ->
466- country_code <> "-" <> iso_code
470+ defp get_country_code ( % { } ) , do: ""
467471
468- _ ->
469- ""
470- end
472+ defp get_country_code ( geo_data ) do
473+ geo_data
474+ |> Map . get ( "country" , % { } )
475+ |> Map . get ( "iso_code" )
476+ |> ignore_unknown_country ( )
477+ end
471478
472- subdivision2_code =
473- case result do
474- % { geolocation: % { subdivisions: [ _first , % { iso_code: iso_code } | _rest ] } } ->
475- country_code <> "-" <> iso_code
479+ defp get_city_geoname_id ( % { } ) , do: ""
476480
477- _ ->
478- ""
479- end
481+ defp get_city_geoname_id ( geo_data ) do
482+ city =
483+ geo_data
484+ |> Map . get ( "city" , % { } )
485+ |> Map . get ( "geoname_id" , "" )
480486
481- % {
482- country_code: country_code ,
483- subdivision1_code: subdivision1_code ,
484- subdivision2_code: subdivision2_code ,
485- city_geoname_id: Map . get ( @ city_overrides , city_geoname_id , city_geoname_id )
486- }
487+ Map . get ( @ city_overrides , city , city )
488+ end
489+
490+ defp get_subdivision_code ( % { } , _ ) , do: ""
491+
492+ defp get_subdivision_code ( geo_data , n ) do
493+ subdivisions = Map . get ( geo_data , "subdivision" , [ ] )
494+ country_code = get_country_code ( geo_data )
495+
496+ case Enum . at ( subdivisions , n ) do
497+ % { "iso_code" => iso_code } -> country_code <> "-" <> iso_code
498+ _ -> ""
499+ end
487500 end
488501
489- defp ignore_unknown_country ( "ZZ" ) , do: nil
502+ defp ignore_unknown_country ( "ZZ" ) , do: ""
490503 defp ignore_unknown_country ( country ) , do: country
491504
492505 @ decorate trace ( "ingest.parse_referrer" )
0 commit comments