Class: MuaraiCaptcha::Client
- Inherits:
-
Object
- Object
- MuaraiCaptcha::Client
- Defined in:
- lib/muaraicaptcha.rb
Instance Method Summary collapse
-
#create_job(task) ⇒ Integer
(also: #create_task)
JobId.
-
#get_balance ⇒ Float
Account balance in USD.
-
#get_job_result(job_id) ⇒ Object
(also: #get_task_result)
Poll once.
-
#initialize(client_key, base_url: DEFAULT_BASE_URL, timeout: 30) ⇒ Client
constructor
A new instance of Client.
-
#report_incorrect(job_id) ⇒ Object
Report a bad solution — the charge is refunded automatically.
-
#solve(task, poll_interval: 5, timeout: 180) ⇒ Object
Create a job and poll until solved.
Constructor Details
#initialize(client_key, base_url: DEFAULT_BASE_URL, timeout: 30) ⇒ Client
Returns a new instance of Client.
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.
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_balance ⇒ Float
Returns 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.
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 |