Migrate to Postgresql for better network handling. Add more user functionality.
This commit is contained in:
43
app/services/ipapi.rb
Normal file
43
app/services/ipapi.rb
Normal file
@@ -0,0 +1,43 @@
|
||||
class Ipapi
|
||||
include BookoAgent
|
||||
BASE_URL = "https://api.ipapi.is/"
|
||||
API_KEY = Rails.application.credentials.ipapi_key
|
||||
|
||||
def lookup(ip) = json_at("#{BASE_URL}?q=#{ip}&key=#{API_KEY}")
|
||||
|
||||
def self.lookup(ip) = new.lookup(ip)
|
||||
|
||||
def multi_lookup(ips)
|
||||
ips = Array(ips)
|
||||
ips.each_slice(100).flat_map { |slice| post_data({ips: slice}) }
|
||||
end
|
||||
|
||||
def data(ip)
|
||||
uri = URI.parse(BASE_URL)
|
||||
|
||||
if ip.is_a?(Array)
|
||||
post_data(ip)
|
||||
else
|
||||
uri.query = "q=#{ip}"
|
||||
JSON.parse(http.request(uri).body)
|
||||
end
|
||||
rescue JSON::ParserError
|
||||
{}
|
||||
end
|
||||
|
||||
def post_data(ips)
|
||||
url = URI.parse(BASE_URL + "?key=#{API_KEY}")
|
||||
|
||||
results = post_json(url, body: ips)
|
||||
|
||||
results["response"].map do |ip, data|
|
||||
IPAddr.new(ip)
|
||||
cidr = data.dig("asn", "route")
|
||||
|
||||
NetworkRange.add_network(cidr).tap { |acl| acl&.update(ip_api_data: data) }
|
||||
rescue IPAddr::InvalidAddressError
|
||||
puts "Skipping #{ip}"
|
||||
next
|
||||
end
|
||||
end
|
||||
end
|
||||
Reference in New Issue
Block a user