File: ip2location.rb

package info (click to toggle)
ruby-geocoder 1.5.1-3
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bullseye, forky, sid, trixie
  • size: 732 kB
  • sloc: ruby: 6,173; makefile: 3
file content (75 lines) | stat: -rw-r--r-- 2,383 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
require 'geocoder/lookups/base'
require 'geocoder/results/ip2location'

module Geocoder::Lookup
  class Ip2location < Base

    def name
      "IP2LocationApi"
    end

    def supported_protocols
      [:http, :https]
    end

    private # ----------------------------------------------------------------

    def base_query_url(query)
      "#{protocol}://api.ip2location.com/?"
    end

    def query_url_params(query)
      {
        key: configuration.api_key ? configuration.api_key : "demo",
        format: "json",
        ip: query.sanitized_text
      }.merge(super)
    end

    def results(query)
      # don't look up a loopback or private address, just return the stored result
      return [reserved_result(query.text)] if query.internal_ip_address?
      return [] unless doc = fetch_data(query)
      if doc["response"] == "INVALID ACCOUNT"
        raise_error(Geocoder::InvalidApiKey) || Geocoder.log(:warn, "INVALID ACCOUNT")
        return []
      else
        return [doc]
      end
    end

    def reserved_result(query)
      {
        "country_code"         => "INVALID IP ADDRESS",
        "country_name"         => "INVALID IP ADDRESS",
        "region_name"          => "INVALID IP ADDRESS",
        "city_name"            => "INVALID IP ADDRESS",
        "latitude"             => "INVALID IP ADDRESS",
        "longitude"            => "INVALID IP ADDRESS",
        "zip_code"             => "INVALID IP ADDRESS",
        "time_zone"            => "INVALID IP ADDRESS",
        "isp"                  => "INVALID IP ADDRESS",
        "domain"               => "INVALID IP ADDRESS",
        "net_speed"            => "INVALID IP ADDRESS",
        "idd_code"             => "INVALID IP ADDRESS",
        "area_code"            => "INVALID IP ADDRESS",
        "weather_station_code" => "INVALID IP ADDRESS",
        "weather_station_name" => "INVALID IP ADDRESS",
        "mcc"                  => "INVALID IP ADDRESS",
        "mnc"                  => "INVALID IP ADDRESS",
        "mobile_brand"         => "INVALID IP ADDRESS",
        "elevation"            => "INVALID IP ADDRESS",
        "usage_type"           => "INVALID IP ADDRESS"
      }
    end

    def query_url_params(query)
      params = super
      if configuration.has_key?(:package)
        params.merge!(package: configuration[:package])
      end
      params
    end

  end
end