Class: MuaraiCaptcha::Client

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

Instance Method Summary collapse

Constructor Details

#initialize(client_key, base_url: DEFAULT_BASE_URL, timeout: 30) ⇒ Client

Returns a new instance of Client.

Parameters:

  • client_key (String)

    API key from console.muaraicaptcha.com

  • base_url (String) (defaults to: DEFAULT_BASE_URL)

    override the API base URL

  • timeout (Numeric) (defaults to: 30)

    per-request timeout in seconds

Raises:



44
45
46
47
48
49
50
# File 'lib/muaraicaptcha.rb', line 44

def initialize(client_key, base_url: DEFAULT_BASE_URL, timeout: 30)
  raise Error, "client_key is required" if client_key.nil? || client_key.empty?

  @client_key = client_key
  @base_url = base_url.sub(%r{/+\z}, "")
  @timeout = timeout
end

Instance Method Details

#create_job(task) ⇒ Integer Also known as: create_task

Returns jobId.

Parameters:

  • task (Hash)

    task object with "type" + fields

Returns:

  • (Integer)

    jobId



60
61
62
63
# File 'lib/muaraicaptcha.rb', line 60

def create_job(task)
  res = post("/v1/job/create", "clientKey" => @client_key, "task" => task)
  res.fetch("jobId").to_i
end

#get_balanceFloat

Returns account balance in USD.

Returns:

  • (Float)

    account balance in USD



53
54
55
56
# File 'lib/muaraicaptcha.rb', line 53

def get_balance
  res = post("/v1/account/balance", "clientKey" => @client_key)
  res.fetch("balance", 0).to_f
end

#get_job_result(job_id) ⇒ Object Also known as: get_task_result

Poll once. Returns the solution Hash when ready, or nil while processing. Raises ApiError if the job failed.



67
68
69
70
71
72
73
74
75
76
77
78
# File 'lib/muaraicaptcha.rb', line 67

def get_job_result(job_id)
  res = post("/v1/job/result", "clientKey" => @client_key, "jobId" => job_id)
  case res["status"]
  when "ready"
    res.fetch("solution", {})
  when "failed"
    raise ApiError.new(
      res.fetch("errorCode", "ERROR_CAPTCHA_UNSOLVABLE"),
      res.fetch("errorDescription", "Job failed")
    )
  end
end

#report_incorrect(job_id) ⇒ Object

Report a bad solution — the charge is refunded automatically.



81
82
83
84
# File 'lib/muaraicaptcha.rb', line 81

def report_incorrect(job_id)
  post("/v1/job/report", "clientKey" => @client_key, "jobId" => job_id, "correct" => false)
  nil
end

#solve(task, poll_interval: 5, timeout: 180) ⇒ Object

Create a job and poll until solved. Returns the solution Hash.

Raises:



87
88
89
90
91
92
93
94
95
96
97
# File 'lib/muaraicaptcha.rb', line 87

def solve(task, poll_interval: 5, timeout: 180)
  job_id = create_job(task)
  deadline = monotonic + timeout
  sleep([poll_interval, 3].min)
  while monotonic < deadline
    solution = get_job_result(job_id)
    return solution if solution
    sleep(poll_interval)
  end
  raise TimeoutError, "job #{job_id} did not resolve within #{timeout}s"
end