Sha256: 31829416921597434acd43c1d04bba0b31b488d1f7e91c1ef04b6dd4a2b003e2

Contents?: true

Size: 1.03 KB

Versions: 3

Compression:

Stored size: 1.03 KB

Contents

require 'ipaddr'
require 'irrc'
require 'interval_tree'

module Legitbot
  # https://developers.facebook.com/docs/sharing/webmasters/crawler

  class Facebook < BotMatch
    AS = 'AS32934'

    def valid?
      ip = IPAddr.new(@ip)
      Facebook.valid_ips[ip.ipv4? ? :ipv4 : :ipv6].search(ip.to_i).size > 0
    end

    @mutex = Mutex.new

    def self.valid_ips
      @mutex.synchronize { @ips ||= load_ips }
    end

    def self.reload!
      @mutex.synchronize { @ips = load_ips }
    end

    def self.load_ips
      whois.map do |(family, records)|
        ranges = records.map do |cidr|
          range = IPAddr.new(cidr).to_range
          (range.begin.to_i..range.end.to_i)
        end
        [family, IntervalTree::Tree.new(ranges)]
      end.to_h
    end

    def self.whois
      client = Irrc::Client.new
      client.query :radb, AS
      results = client.perform

      %i(ipv4 ipv6).map do |family|
        [family, results[AS][family][AS]]
      end.to_h
    end
  end

  rule Legitbot::Facebook, %w(Facebot facebookexternalhit/1.1)
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
legitbot-0.3.2 lib/legitbot/facebook.rb
legitbot-0.3.1 lib/legitbot/facebook.rb
legitbot-0.3.0 lib/legitbot/facebook.rb