Class: Trackdown::DatabaseUpdater

Inherits:
Object
  • Object
show all
Defined in:
lib/trackdown/database_updater.rb

Constant Summary collapse

DOWNLOAD_URL =
"https://download.maxmind.com/app/geoip_download?edition_id=GeoLite2-City&license_key=%{license_key}&suffix=tar.gz"

Class Method Summary collapse

Class Method Details

.updateObject



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
# File 'lib/trackdown/database_updater.rb', line 10

def update
  download_url = DOWNLOAD_URL % { license_key: Trackdown.configuration.maxmind_license_key }

  options = {
    http_basic_authentication: [
      Trackdown.configuration..to_s,
      Trackdown.configuration.maxmind_license_key.to_s
    ],
    ssl_verify_mode: OpenSSL::SSL::VERIFY_PEER
  }

  URI.open(download_url, **options) do |remote_file|
    Zlib::GzipReader.wrap(remote_file) do |gz|
      Gem::Package::TarReader.new(gz) do |tar|
        tar.each do |entry|
          if entry.full_name.end_with?('.mmdb')
            FileUtils.mkdir_p(File.dirname(Trackdown.configuration.database_path))

            File.open(Trackdown.configuration.database_path, 'wb') do |file|
              file.write(entry.read)
            end
            break
          end
        end
      end
    end
  end

  Rails.logger.info("MaxMind database updated successfully") if defined?(Rails)
  true
rescue OpenURI::HTTPError => e
  message = case e.message
  when /401/
    "Authentication failed. Please check your MaxMind account ID and license key."
  when /403/
    "Access forbidden. Your MaxMind license may not have access to this database."
  else
    "HTTP Error: #{e.message}"
  end
  Rails.logger.error("Error updating MaxMind database: #{message}") if defined?(Rails)
  raise Error, message
rescue => e
  Rails.logger.error("Error updating MaxMind database: #{e.message}") if defined?(Rails)
  raise Error, "Failed to update database: #{e.message}"
end