Class: Zold::Push

Inherits:
Object
  • Object
show all
Defined in:
lib/zold/commands/push.rb

Overview

Wallet pushing command

Instance Method Summary collapse

Constructor Details

#initialize(wallets:, remotes:, log: Log::Quiet.new) ⇒ Push

Returns a new instance of Push.



37
38
39
40
41
# File 'lib/zold/commands/push.rb', line 37

def initialize(wallets:, remotes:, log: Log::Quiet.new)
  @wallets = wallets
  @remotes = remotes
  @log = log
end

Instance Method Details

#push(wallet, _) ⇒ Object



56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
# File 'lib/zold/commands/push.rb', line 56

def push(wallet, _)
  raise 'The wallet is absent' unless wallet.exists?
  total = 0
  @remotes.all.each do |r|
    uri = URI("#{r[:home]}wallet/#{wallet.id}")
    response = Http.new(uri).put(File.read(wallet.path))
    if response.code == '304'
      @log.info("#{uri}: same version there")
      next
    end
    unless response.code == '200'
      @remotes.error(r[:host], r[:port])
      @log.error("#{uri} failed as #{response.code}/#{response.message}")
      next
    end
    json = JSON.parse(response.body)['score']
    score = Score.parse_json(json)
    unless score.valid?
      @remotes.error(r[:host], r[:port])
      @log.error("#{uri} invalid score: #{score}")
      next
    end
    if score.expired?
      @remotes.error(r[:host], r[:port])
      @log.error("#{uri} expired score: #{score}")
      next
    end
    if score.strength < Score::STRENGTH
      @remotes.error(r[:host], r[:port])
      @log.error("#{uri} score is too weak")
      next
    end
    @log.info("#{uri} accepted: #{Rainbow(score.value).green}")
    total += score.value
  end
  @log.info("Total score is #{total}")
end

#run(args = []) ⇒ Object



43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/zold/commands/push.rb', line 43

def run(args = [])
  opts = Slop.parse(args, help: true, suppress_errors: true) do |o|
    o.banner = "Usage: zold push [ID...] [options]
Available options:"
    o.bool '--help', 'Print instructions'
  end
  mine = Args.new(opts, @log).take || return
  mine = @wallets.all if mine.empty?
  mine.each do |id|
    push(@wallets.find(Id.new(id)), opts)
  end
end