about summary refs log tree commit diff
path: root/app/lib/proof_provider/keybase/badge.rb
blob: f587b1cc74480f152d8c0b75b6707a551036fc3b (plain) (blame)
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
# frozen_string_literal: true

class ProofProvider::Keybase::Badge
  include RoutingHelper

  def initialize(local_username, provider_username, token, domain)
    @local_username    = local_username
    @provider_username = provider_username
    @token             = token
    @domain            = domain
  end

  def proof_url
    "#{ProofProvider::Keybase::BASE_URL}/#{@provider_username}/sigchain\##{@token}"
  end

  def profile_url
    "#{ProofProvider::Keybase::BASE_URL}/#{@provider_username}"
  end

  def icon_url
    "#{ProofProvider::Keybase::BASE_URL}/#{@provider_username}/proof_badge/#{@token}?username=#{@local_username}&domain=#{@domain}"
  end

  def avatar_url
    Rails.cache.fetch("proof_providers/keybase/#{@provider_username}/avatar_url", expires_in: 5.minutes) { remote_avatar_url } || default_avatar_url
  end

  private

  def remote_avatar_url
    request = Request.new(:get, "#{ProofProvider::Keybase::BASE_URL}/_/api/1.0/user/pic_url.json", params: { username: @provider_username })

    request.perform do |res|
      json = Oj.load(res.body_with_limit, mode: :strict)
      json['pic_url'] if json.is_a?(Hash)
    end
  rescue Oj::ParseError, HTTP::Error, OpenSSL::SSL::SSLError
    nil
  end

  def default_avatar_url
    asset_pack_path('media/images/proof_providers/keybase.png')
  end
end