two_captcha 1.0.0

Sign up to get free protection for your applications and to get access to all the features.
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA1:
3
+ metadata.gz: ada135dad0428e66a55f12546ec887230eee89f4
4
+ data.tar.gz: 1cad1ca0f8021b9a9bc4d68e5e6e82e3c19f24b9
5
+ SHA512:
6
+ metadata.gz: 11d19a82c8beb97d7f0f4f774c274eec6f823efbabf759f2a7ef7b1bc121d833b8a15e7d085336da32b30709d4070f751e08d4213342dccf90d0c9f3c4aee7f8
7
+ data.tar.gz: f846b785745c2d7eda62128f05da068df0832adf974dedb660745354c0643ca1f9cb2d2786024e27662d6e5e8b7a6f84534a08d16774c2b00eeab7b1e96e3436
@@ -0,0 +1,12 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /Gemfile.lock
4
+ /_yardoc/
5
+ /coverage/
6
+ /doc/
7
+ /pkg/
8
+ /spec/reports/
9
+ /spec/credentials.yml
10
+ /tmp/
11
+ .ruby-version
12
+ .ruby-gemset
data/.rspec ADDED
@@ -0,0 +1,2 @@
1
+ --format documentation
2
+ --color
@@ -0,0 +1,3 @@
1
+ language: ruby
2
+ rvm:
3
+ - 2.2.0
@@ -0,0 +1,13 @@
1
+ # Contributor Code of Conduct
2
+
3
+ As contributors and maintainers of this project, we pledge to respect all people who contribute through reporting issues, posting feature requests, updating documentation, submitting pull requests or patches, and other activities.
4
+
5
+ We are committed to making participation in this project a harassment-free experience for everyone, regardless of level of experience, gender, gender identity and expression, sexual orientation, disability, personal appearance, body size, race, age, or religion.
6
+
7
+ Examples of unacceptable behavior by participants include the use of sexual language or imagery, derogatory comments or personal attacks, trolling, public or private harassment, insults, or other unprofessional conduct.
8
+
9
+ Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct. Project maintainers who do not follow the Code of Conduct may be removed from the project team.
10
+
11
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by opening an issue or contacting one or more of the project maintainers.
12
+
13
+ This Code of Conduct is adapted from the [Contributor Covenant](http:contributor-covenant.org), version 1.0.0, available at [http://contributor-covenant.org/version/1/0/0/](http://contributor-covenant.org/version/1/0/0/)
data/Gemfile ADDED
@@ -0,0 +1,4 @@
1
+ source 'https://rubygems.org'
2
+
3
+ # Specify your gem's dependencies in two_captcha.gemspec
4
+ gemspec
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2015 Infosimples
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
@@ -0,0 +1,183 @@
1
+ Developed by [Infosimples](https://infosimples.com), a brazilian company that
2
+ offers [data extraction solutions](https://infosimples.com/en/data-engineering)
3
+ and [Ruby on Rails development](https://infosimples.com/en/software-development).
4
+
5
+ # TwoCaptcha
6
+
7
+ TwoCaptcha is a Ruby API for 2Captcha - https://2captcha.com.
8
+
9
+ ## Installation
10
+
11
+ Add this line to your application's Gemfile:
12
+
13
+ ```ruby
14
+ gem 'two_captcha'
15
+ ```
16
+
17
+ And then execute:
18
+
19
+ $ bundle
20
+
21
+ Or install it yourself as:
22
+
23
+ $ gem install two_captcha
24
+
25
+ ## Usage
26
+
27
+ 1. **Create a client**
28
+
29
+ ```ruby
30
+ # Create a client
31
+ client = TwoCaptcha.new('my_captcha_key')
32
+ ```
33
+
34
+ 2. **Solve a captcha**
35
+
36
+ There are two methods available: **decode** and **decode!**
37
+ * **decode** doesn't raise exceptions.
38
+ * **decode!** may raise a *TwoCaptcha::Error* if something goes wrong.
39
+
40
+ If the solution is not available, an empty captcha object will be returned.
41
+
42
+ ```ruby
43
+ captcha = client.decode!(url: 'http://bit.ly/1xXZcKo')
44
+ captcha.text # Solution of the captcha
45
+ captcha.id # Numeric ID of the captcha solved by TwoCaptcha
46
+ ```
47
+
48
+ You can also specify *path*, *file*, *raw* and *raw64* when decoding an image.
49
+
50
+ ```ruby
51
+ client.decode(path: 'path/to/my/captcha/file')
52
+
53
+ client.decode(file: File.open('path/to/my/captcha/file', 'rb'))
54
+
55
+ client.decode(raw: File.open('path/to/my/captcha/file', 'rb').read)
56
+
57
+ client.decode(raw64: Base64.encode64(File.open('path/to/my/captcha/file', 'rb').read))
58
+ ```
59
+
60
+ > Internally, the gem will always convert the image to raw64 (binary base64 encoded).
61
+
62
+ You may also specify any POST parameters specified at
63
+ https://2captcha.com/setting.
64
+
65
+ 3. **Retrieve a previously solved captcha**
66
+
67
+ ```ruby
68
+ captcha = client.captcha('130920620') # with 130920620 as the captcha id
69
+ ```
70
+
71
+ 4. **Report incorrectly solved captcha for refund**
72
+
73
+ ```ruby
74
+ client.report!('130920620') # with 130920620 as the captcha id
75
+ # return true if successfully reported
76
+ ```
77
+
78
+ > ***Warning:*** *do not abuse on this method, otherwise you may get banned*
79
+
80
+ 5. **Get your balance on 2Captcha**
81
+
82
+ ```ruby
83
+ client.balance
84
+ # return a Float balance in USD.
85
+ ```
86
+
87
+ 6. **Get usage statistics for a specific date**
88
+
89
+ ```ruby
90
+ client.stats('2015-08-05')
91
+ # return an XML string with your usage statistics.
92
+ ```
93
+
94
+ 7. **Get current 2Captcha load**
95
+
96
+ ```ruby
97
+ client.load
98
+ # return an XML string with the current service load.
99
+ ```
100
+
101
+ ## New ReCaptcha
102
+
103
+ To solve captchas similar to
104
+ [reCAPTCHA v2](https://support.google.com/recaptcha/?hl=en#6262736), you can add
105
+ the param 'id_constructor: 23' to your request.
106
+
107
+ Please read the oficial documentation at https://2captcha.com/support/faq/30/ for
108
+ more information.
109
+
110
+ ```ruby
111
+ client.decode(url: 'http://bit.ly/1xXZcKo', id_constructor: 23)
112
+ ```
113
+
114
+ **Captcha (screenshot)**
115
+
116
+ > the argument is passed as *url*, *path*, *file*, *raw* or *raw64*
117
+
118
+ ![Example of a captcha based on image clicks](captchas/2.jpg)
119
+
120
+ The response will be an array containing the indexes for each image that should
121
+ be clicked counting from left to right. For the captcha above it should look
122
+ something like:
123
+
124
+ ```ruby
125
+ # captcha.indexes
126
+ [1, 9]
127
+ ```
128
+
129
+ ## Notes
130
+
131
+ #### Thread-safety
132
+
133
+ The API is thread-safe, which means it is perfectly fine to share a client
134
+ instance between multiple threads.
135
+
136
+ #### Ruby dependencies
137
+
138
+ TwoCaptcha don't require specific dependencies. That saves you memory and
139
+ avoid conflicts with other gems.
140
+
141
+ #### Input image format
142
+
143
+ Any format you use in the decode method (url, file, path, raw, raw64) will
144
+ always be converted to a raw64, which is a binary base64 encoded string. So, if
145
+ you already have this format available on your side, there's no need to do
146
+ convertions before calling the API.
147
+
148
+ > Our recomendation is to never convert your image format, unless needed. Let
149
+ > the gem convert internally. It may save you resources (CPU, memory and IO).
150
+
151
+ #### Versioning
152
+
153
+ TwoCaptcha gem uses [Semantic Versioning](http://semver.org/).
154
+
155
+ #### Ruby versions tested
156
+
157
+ * MRI 2.2.2
158
+ * MRI 2.2.0
159
+ * MRI 2.1.4
160
+ * MRI 2.0.0
161
+
162
+ # Maintainers
163
+
164
+ * [Marcelo Mita](http://github.com/marcelomita)
165
+ * [Rafael Barbolo](http://github.com/barbolo)
166
+
167
+ ## Contributing
168
+
169
+ 1. Fork it ( https://github.com/infosimples/two_captcha/fork )
170
+ 2. Create your feature branch (`git checkout -b my-new-feature`)
171
+ 3. **Run/add tests (RSpec)**
172
+ 4. Commit your changes (`git commit -am 'Add some feature'`)
173
+ 5. Push to the branch (`git push origin my-new-feature`)
174
+ 6. Create a new Pull Request
175
+ 7. Yay. Thanks for contributing :)
176
+
177
+ All contributors:
178
+ https://github.com/infosimples/two_captcha/graphs/contributors
179
+
180
+
181
+ # License
182
+
183
+ MIT License. Copyright (C) 2011-2015 Infosimples. https://infosimples.com/
@@ -0,0 +1,2 @@
1
+ require "bundler/gem_tasks"
2
+
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require "bundler/setup"
4
+ require "two_captcha"
5
+
6
+ # You can add fixtures and/or initialization code here to make experimenting
7
+ # with your gem easier. You can also use a different console, if you like.
8
+
9
+ # (If you use this, don't forget to add pry to your Gemfile!)
10
+ # require "pry"
11
+ # Pry.start
12
+
13
+ require "irb"
14
+ IRB.start
@@ -0,0 +1,7 @@
1
+ #!/bin/bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+
5
+ bundle install
6
+
7
+ # Do any other automated setup that you need to do here
Binary file
Binary file
@@ -0,0 +1,32 @@
1
+ require 'base64'
2
+ require 'json'
3
+ require 'net/http'
4
+
5
+ # The module TwoCaptcha contains all the code for the two_captcha gem.
6
+ # It acts as a safely namespace that isolates logic from TwoCaptcha from any
7
+ # project that uses it.
8
+ #
9
+ module TwoCaptcha
10
+ # Instantiate TwoCaptcha API client. This is a shortcut to
11
+ # TwoCaptcha::Client.new
12
+ #
13
+ def self.new(key, options = {})
14
+ TwoCaptcha::Client.new(key, options)
15
+ end
16
+
17
+ # Base class of a model object returned by TwoCaptcha API.
18
+ #
19
+ class Model
20
+ def initialize(values = {})
21
+ values.each do |key, value|
22
+ send("#{key}=", value) if respond_to?("#{key}=")
23
+ end
24
+ end
25
+ end
26
+ end
27
+
28
+ require 'two_captcha/client'
29
+ require 'two_captcha/errors'
30
+ require 'two_captcha/http'
31
+ require 'two_captcha/models/captcha'
32
+ require 'two_captcha/version'
@@ -0,0 +1,225 @@
1
+ module TwoCaptcha
2
+ # TwoCaptcha::Client is a client that communicates with the TwoCaptcha API:
3
+ # https://2captcha.com/.
4
+ #
5
+ class Client
6
+ BASE_URL = 'http://2captcha.com/:action.php'
7
+
8
+ attr_accessor :key, :timeout, :polling
9
+
10
+ # Create a TwoCaptcha API client.
11
+ #
12
+ # @param [String] Captcha key of the TwoCaptcha account.
13
+ # @param [Hash] options Options hash.
14
+ # @option options [Integer] :timeout (60) Seconds before giving up of a
15
+ # captcha being solved.
16
+ # @option options [Integer] :polling (5) Seconds before check_answer again
17
+ #
18
+ # @return [TwoCaptcha::Client] A Client instance.
19
+ #
20
+ def initialize(key, options = {})
21
+ self.key = key
22
+ self.timeout = options[:timeout] || 60
23
+ self.polling = options[:polling] || 5
24
+ end
25
+
26
+ # Decode the text from an image (i.e. solve a captcha).
27
+ #
28
+ # @param [Hash] options Options hash. Check docs for the method decode!.
29
+ #
30
+ # @return [TwoCaptcha::Captcha] The captcha (with solution) or an empty
31
+ # captcha instance if something goes wrong.
32
+ #
33
+ def decode(options = {})
34
+ decode!(options)
35
+ rescue TwoCaptcha::Error => ex
36
+ TwoCaptcha::Captcha.new
37
+ end
38
+
39
+ # Decode the text from an image (i.e. solve a captcha).
40
+ #
41
+ # @param [Hash] options Options hash.
42
+ # @option options [String] :url URL of the image to be decoded.
43
+ # @option options [String] :path File path of the image to be decoded.
44
+ # @option options [File] :file File instance with image to be decoded.
45
+ # @option options [String] :raw Binary content of the image to be
46
+ # decoded.
47
+ # @option options [String] :raw64 Binary content encoded in base64 of the
48
+ # image to be decoded.
49
+ # @option options [Integer] :phrase (0) https://2captcha.com/setting
50
+ # @option options [Integer] :regsense (0) https://2captcha.com/setting
51
+ # @option options [Integer] :numeric (0) https://2captcha.com/setting
52
+ # @option options [Integer] :calc (0) https://2captcha.com/setting
53
+ # @option options [Integer] :min_len (0) https://2captcha.com/setting
54
+ # @option options [Integer] :max_len (0) https://2captcha.com/setting
55
+ # @option options [Integer] :language (0) https://2captcha.com/setting
56
+ # @option options [Integer] :header_acao (0) https://2captcha.com/setting
57
+ # @option options [Integer] :id_constructor (0) 23 if new reCAPTCHA.
58
+ #
59
+ # @return [TwoCaptcha::Captcha] The captcha (with solution) if an error is
60
+ # not raised.
61
+ #
62
+ def decode!(options = {})
63
+ started_at = Time.now
64
+
65
+ raw64 = load_captcha(options)
66
+ fail(TwoCaptcha::InvalidCaptcha) if raw64.to_s.empty?
67
+
68
+ decoded_captcha = upload(options.merge(raw64: raw64))
69
+
70
+ # pool untill the answer is ready
71
+ while decoded_captcha.text.to_s.empty?
72
+ sleep(polling)
73
+ decoded_captcha = captcha(decoded_captcha.id)
74
+ fail DeathByCaptcha::Timeout if (Time.now - started_at) > timeout
75
+ end
76
+
77
+ decoded_captcha
78
+ end
79
+
80
+ # Upload a captcha to 2Captcha.
81
+ #
82
+ # This method will not return the solution. It helps on separating concerns.
83
+ #
84
+ # @return [TwoCaptcha::Captcha] The captcha object (not solved yet).
85
+ #
86
+ def upload(options = {})
87
+ args = {}
88
+ args[:body] = options[:raw64]
89
+ args[:method] = 'base64'
90
+ [:phrase, :regsense, :numeric, :calc, :min_len, :max_len, :language,
91
+ :header_acao, :id_constructor].each do |key|
92
+ args[key] = options[key] if options[key]
93
+ end
94
+ response = request('in', :multipart, args)
95
+
96
+ unless response.match(/\AOK\|/)
97
+ fail(TwoCaptcha::Error, 'Unexpected API Response')
98
+ end
99
+
100
+ TwoCaptcha::Captcha.new(
101
+ id: response.split('|', 2)[1],
102
+ api_response: response
103
+ )
104
+ end
105
+
106
+ # Retrieve information from an uploaded captcha.
107
+ #
108
+ # @param [Integer] captcha_id Numeric ID of the captcha.
109
+ #
110
+ # @return [TwoCaptcha::Captcha] The captcha object.
111
+ #
112
+ def captcha(captcha_id)
113
+ response = request('res', :get, action: 'get', id: captcha_id)
114
+
115
+ decoded_captcha = TwoCaptcha::Captcha.new(id: captcha_id)
116
+ decoded_captcha.api_response = response
117
+
118
+ if response.match(/\AOK\|/)
119
+ decoded_captcha.text = response.split('|', 2)[1]
120
+ end
121
+
122
+ decoded_captcha
123
+ end
124
+
125
+ # Report incorrectly solved captcha for refund.
126
+ #
127
+ # @param [Integer] id Numeric ID of the captcha.
128
+ #
129
+ # @return [Boolean] true if correctly reported
130
+ #
131
+ def report!(captcha_id)
132
+ response = request('res', :get, action: 'reportbad', id: captcha_id)
133
+ response == 'OK_REPORT_RECORDED'
134
+ end
135
+
136
+ # Get balance from your account.
137
+ #
138
+ # @return [Float] Balance in USD.
139
+ #
140
+ def balance
141
+ request('res', :get, action: 'getbalance').to_f
142
+ end
143
+
144
+ # Get statistics from your account.
145
+ #
146
+ # @param [Date] date Date when the statistics were collected.
147
+ #
148
+ # @return [String] Statistics from date in an XML string.
149
+ #
150
+ def stats(date)
151
+ request('res', :get, action: 'getstats', date: date.strftime('%Y-%m-%d'))
152
+ end
153
+
154
+ # Get current load from 2Captcha.
155
+ #
156
+ # @return [String] Load in an XML string.
157
+ #
158
+ def load
159
+ request('load', :get)
160
+ end
161
+
162
+ private
163
+
164
+ # Load a captcha raw content encoded in base64 from options.
165
+ #
166
+ # @param [Hash] options Options hash.
167
+ # @option options [String] :url URL of the image to be decoded.
168
+ # @option options [String] :path File path of the image to be decoded.
169
+ # @option options [File] :file File instance with image to be decoded.
170
+ # @option options [String] :raw Binary content of the image to bedecoded.
171
+ # @option options [String] :raw64 Binary content encoded in base64 of the
172
+ # image to be decoded.
173
+ #
174
+ # @return [String] The binary image base64 encoded.
175
+ #
176
+ def load_captcha(options)
177
+ if options[:raw64]
178
+ options[:raw64]
179
+ elsif options[:raw]
180
+ Base64.encode64(options[:raw])
181
+ elsif options[:file]
182
+ Base64.encode64(options[:file].read)
183
+ elsif options[:path]
184
+ Base64.encode64(File.open(options[:path], 'rb').read)
185
+ elsif options[:url]
186
+ Base64.encode64(TwoCaptcha::HTTP.open_url(options[:url]))
187
+ else
188
+ fail TwoCaptcha::ArgumentError, 'Illegal image format'
189
+ end
190
+ rescue
191
+ raise TwoCaptcha::InvalidCaptcha
192
+ end
193
+
194
+ # Perform an HTTP request to the 2Captcha API.
195
+ #
196
+ # @param [String] action API method name.
197
+ # @param [Symbol] method HTTP method (:get, :post, :multipart).
198
+ # @param [Hash] payload Data to be sent through the HTTP request.
199
+ #
200
+ # @return [String] Response from the TwoCaptcha API.
201
+ #
202
+ def request(action, method = :get, payload = {})
203
+ res = TwoCaptcha::HTTP.request(
204
+ url: BASE_URL.gsub(':action', action),
205
+ timeout: timeout,
206
+ method: method,
207
+ payload: payload.merge(key: key, soft_id: 800)
208
+ )
209
+ validate_response(res)
210
+ res
211
+ end
212
+
213
+ # Fail if the response has errors.
214
+ #
215
+ # @param [String] response The body response from TwoCaptcha API.
216
+ #
217
+ def validate_response(response)
218
+ if (error = TwoCaptcha::RESPONSE_ERRORS[response])
219
+ fail(error)
220
+ elsif response.to_s.empty? || response.match(/\AERROR\_/)
221
+ fail(TwoCaptcha::Error, response)
222
+ end
223
+ end
224
+ end
225
+ end
@@ -0,0 +1,116 @@
1
+ module TwoCaptcha
2
+ # This is the base TwoCaptcha exception class. Rescue it if you want to
3
+ # catch any exception that might be raised.
4
+ #
5
+ class Error < Exception
6
+ end
7
+
8
+ class ArgumentError < Error
9
+ end
10
+
11
+ class InvalidCaptcha < Error
12
+ def initialize
13
+ super('The captcha is empty or invalid')
14
+ end
15
+ end
16
+
17
+ class WrongUserKey < Error
18
+ def initialize
19
+ super('Wrong “key” parameter format, it should contain 32 symbols')
20
+ end
21
+ end
22
+
23
+ class InvalidUserKey < Error
24
+ def initialize
25
+ super('The “key” doesn’t exist')
26
+ end
27
+ end
28
+
29
+ class ZeroBalance < Error
30
+ def initialize
31
+ super('You don’t have enought money on your account')
32
+ end
33
+ end
34
+
35
+ class NoSlotAvailable < Error
36
+ def initialize
37
+ super('The current bid is higher than the maximum bid set for your account.')
38
+ end
39
+ end
40
+
41
+ class SmallCaptchaFilesize < Error
42
+ def initialize
43
+ super('CAPTCHA size is less than 100 bytes')
44
+ end
45
+ end
46
+
47
+ class BigCaptchaFilesize < Error
48
+ def initialize
49
+ super('CAPTCHA size is more than 100 Kbytes')
50
+ end
51
+ end
52
+
53
+ class WrongFileExtension < Error
54
+ def initialize
55
+ super('The CAPTCHA has a wrong extension. Possible extensions are: jpg,jpeg,gif,png')
56
+ end
57
+ end
58
+
59
+ class ImageNotSupported < Error
60
+ def initialize
61
+ super('The server cannot recognize the CAPTCHA file type')
62
+ end
63
+ end
64
+
65
+ class IpNotAllowed < Error
66
+ def initialize
67
+ super('The request has sent from the IP that is not on the list of your IPs. Check the list of your IPs in the system')
68
+ end
69
+ end
70
+
71
+ class IpBanned < Error
72
+ def initialize
73
+ super('The IP address you\'re trying to access our server with is banned due to many frequent attempts to access the server using wrong authorization keys. To lift the ban, please, contact our support team via email: support@2captcha.com')
74
+ end
75
+ end
76
+
77
+ class WrongIdFormat < Error
78
+ def initialize
79
+ super('Wrong format ID CAPTCHA. ID must contain only numbers')
80
+ end
81
+ end
82
+
83
+ class CaptchaUnsolvable < Error
84
+ def initialize
85
+ super('Captcha could not solve three different employee. Funds for this captcha not')
86
+ end
87
+ end
88
+
89
+ class EmptyAction < Error
90
+ def initialize
91
+ super('No action passed')
92
+ end
93
+ end
94
+
95
+ class Timeout < Error
96
+ def initialize
97
+ super('The captcha was not solved in the expected time')
98
+ end
99
+ end
100
+
101
+ RESPONSE_ERRORS = {
102
+ 'ERROR_WRONG_USER_KEY' => TwoCaptcha::WrongUserKey,
103
+ 'ERROR_KEY_DOES_NOT_EXIST' => TwoCaptcha::InvalidUserKey,
104
+ 'ERROR_ZERO_BALANCE' => TwoCaptcha::ZeroBalance,
105
+ 'ERROR_NO_SLOT_AVAILABLE' => TwoCaptcha::NoSlotAvailable,
106
+ 'ERROR_ZERO_CAPTCHA_FILESIZE' => TwoCaptcha::SmallCaptchaFilesize,
107
+ 'ERROR_TOO_BIG_CAPTCHA_FILESIZE' => TwoCaptcha::BigCaptchaFilesize,
108
+ 'ERROR_WRONG_FILE_EXTENSION' => TwoCaptcha::WrongFileExtension,
109
+ 'ERROR_IMAGE_TYPE_NOT_SUPPORTED' => TwoCaptcha::ImageNotSupported,
110
+ 'ERROR_IP_NOT_ALLOWED' => TwoCaptcha::IpNotAllowed,
111
+ 'IP_BANNED' => TwoCaptcha::IpBanned,
112
+ 'ERROR_WRONG_ID_FORMAT' => TwoCaptcha::WrongIdFormat,
113
+ 'ERROR_CAPTCHA_UNSOLVABLE' => TwoCaptcha::CaptchaUnsolvable,
114
+ 'ERROR_EMPTY_ACTION' => TwoCaptcha::EmptyAction
115
+ }
116
+ end
@@ -0,0 +1,100 @@
1
+ module TwoCaptcha
2
+ # TwoCaptcha::HTTP exposes common HTTP routines that can be used by the
3
+ # TwoCaptcha API client.
4
+ #
5
+ class HTTP
6
+ # Retrieve the contents of a captcha URL supporting HTTPS and redirects.
7
+ #
8
+ # @param [String] url The captcha URL.
9
+ #
10
+ # @return [String] The contents of the captcha URL.
11
+ #
12
+ def self.open_url(url)
13
+ uri = URI(url)
14
+
15
+ http = Net::HTTP.new(uri.host, uri.port)
16
+
17
+ if uri.scheme == 'https'
18
+ http.use_ssl = true
19
+ http.verify_mode = OpenSSL::SSL::VERIFY_NONE
20
+ end
21
+
22
+ res = http.get(uri.request_uri)
23
+
24
+ if (redirect = res.header['location'])
25
+ open_url(redirect)
26
+ else
27
+ res.body
28
+ end
29
+ end
30
+
31
+ # Perform an HTTP request with support to multipart requests.
32
+ #
33
+ # @param [Hash] options Options hash.
34
+ # @param options [String] url URL to be requested.
35
+ # @param options [Symbol] method HTTP method (:get, :post, :multipart).
36
+ # @param options [Hash] payload Data to be sent through the HTTP request.
37
+ # @param options [Integer] timeout HTTP open/read timeout in seconds.
38
+ #
39
+ # @return [String] Response body of the HTTP request.
40
+ #
41
+ def self.request(options = {})
42
+ uri = URI(options[:url])
43
+ method = options[:method] || :get
44
+ payload = options[:payload] || {}
45
+ timeout = options[:timeout] || 60
46
+ headers = { 'User-Agent' => TwoCaptcha::USER_AGENT }
47
+
48
+ case method
49
+ when :get
50
+ uri.query = URI.encode_www_form(payload)
51
+ req = Net::HTTP::Get.new(uri.request_uri, headers)
52
+
53
+ when :post
54
+ req = Net::HTTP::Post.new(uri.request_uri, headers)
55
+ req.set_form_data(payload)
56
+
57
+ when :multipart
58
+ req = Net::HTTP::Post.new(uri.request_uri, headers)
59
+ boundary, body = prepare_multipart_data(payload)
60
+ req.content_type = "multipart/form-data; boundary=#{boundary}"
61
+ req.body = body
62
+
63
+ else
64
+ fail TwoCaptcha::ArgumentError, "Illegal HTTP method (#{method})"
65
+ end
66
+
67
+ http = Net::HTTP.new(uri.hostname, uri.port)
68
+ http.use_ssl = true if (uri.scheme == 'https')
69
+ http.open_timeout = timeout
70
+ http.read_timeout = timeout
71
+ res = http.request(req)
72
+ res.body
73
+
74
+ rescue Net::OpenTimeout, Net::ReadTimeout
75
+ raise TwoCaptcha::Timeout
76
+ end
77
+
78
+ # Prepare the multipart data to be sent via a :multipart request.
79
+ #
80
+ # @param [Hash] payload Data to be prepared via a multipart post.
81
+ #
82
+ # @return [String, String] Boundary and body for the multipart post.
83
+ #
84
+ def self.prepare_multipart_data(payload)
85
+ boundary = 'randomstr' + rand(1_000_000).to_s # a random unique string
86
+
87
+ content = []
88
+ payload.each do |param, value|
89
+ content << '--' + boundary
90
+ content << "Content-Disposition: form-data; name=\"#{param}\""
91
+ content << ''
92
+ content << value
93
+ end
94
+ content << '--' + boundary + '--'
95
+ content << ''
96
+
97
+ [boundary, content.join("\r\n")]
98
+ end
99
+ end
100
+ end
@@ -0,0 +1,11 @@
1
+ module TwoCaptcha
2
+ # Model of a Captcha returned by ZeroCaptcha API.
3
+ #
4
+ class Captcha < TwoCaptcha::Model
5
+ attr_accessor :id, :text, :api_response
6
+
7
+ def indexes
8
+ text.gsub('click:', '').split(/[^0-9]/).map(&:to_i)
9
+ end
10
+ end
11
+ end
@@ -0,0 +1,4 @@
1
+ module TwoCaptcha
2
+ VERSION = '1.0.0'
3
+ USER_AGENT = "TwoCaptcha/Ruby v#{VERSION}"
4
+ end
@@ -0,0 +1,3 @@
1
+ key: my_captcha_key
2
+ captcha_id: 123456789 # use an ID of a solved captcha on your account
3
+ solution: abc123 # use the captcha_id solution
@@ -0,0 +1,72 @@
1
+ require 'spec_helper'
2
+
3
+ key = CREDENTIALS['key']
4
+ captcha_id = CREDENTIALS['captcha_id']
5
+ captcha_solution = CREDENTIALS['solution']
6
+ image64 = Base64.encode64(File.open('captchas/1.png', 'rb').read)
7
+ recaptcha64 = Base64.encode64(File.open('captchas/2.jpg', 'rb').read)
8
+
9
+ describe TwoCaptcha::Client do
10
+ describe 'create' do
11
+ context 'default' do
12
+ let(:client) { TwoCaptcha.new(key) }
13
+ it { expect(client).to be_a(TwoCaptcha::Client) }
14
+ it { expect(client.timeout).to be > 0 }
15
+ it { expect(client.polling).to be > 0 }
16
+ end
17
+
18
+ context 'timeout = 30 seconds' do
19
+ let(:timeout_client) { TwoCaptcha.new(key, timeout: 30) }
20
+ it { expect(timeout_client).to be_a(TwoCaptcha::Client) }
21
+ it { expect(timeout_client.timeout).to eq(30) }
22
+ end
23
+
24
+ context 'polling = 3 seconds' do
25
+ let(:polling_client) { TwoCaptcha.new(key, polling: 3) }
26
+ it { expect(polling_client).to be_a(TwoCaptcha::Client) }
27
+ it { expect(polling_client.polling).to eq(3) }
28
+ end
29
+ end
30
+ context 'methods' do
31
+ before(:all) { @client = TwoCaptcha.new(key) }
32
+
33
+ describe '#load_captcha' do
34
+ it { expect(@client.send(:load_captcha, url: 'http://bit.ly/1xXZcKo')).to eq(image64) }
35
+ it { expect(@client.send(:load_captcha, path: 'captchas/1.png')).to eq(image64) }
36
+ it { expect(@client.send(:load_captcha, file: File.open('captchas/1.png', 'rb'))).to eq(image64) }
37
+ it { expect(@client.send(:load_captcha, raw: File.open('captchas/1.png', 'rb').read)).to eq(image64) }
38
+ it { expect(@client.send(:load_captcha, raw64: image64)).to eq(image64) }
39
+ end
40
+
41
+ describe '#captcha' do
42
+ before(:all) { @captcha = @client.captcha(captcha_id) }
43
+ it { expect(@captcha).to be_a(TwoCaptcha::Captcha) }
44
+ it { expect(@captcha.text).to eq(captcha_solution) }
45
+ it { expect(@captcha.id).to eq(captcha_id) }
46
+ end
47
+
48
+ describe '#decode!' do
49
+ before(:all) { @captcha = @client.decode!(raw64: image64) }
50
+ it { expect(@captcha).to be_a(TwoCaptcha::Captcha) }
51
+ it { expect(@captcha.text.downcase).to eq 'infosimples' }
52
+ it { expect(@captcha.id).to match(/[0-9]{9}/) }
53
+ end
54
+
55
+ describe '#balance' do
56
+ before(:all) { @balance = @client.balance }
57
+ it { expect(@balance).to be > 0 }
58
+ end
59
+ end
60
+
61
+ context 'new reCAPTCHA' do
62
+ before(:all) { @client = TwoCaptcha.new(key) }
63
+
64
+ describe '#decode!' do
65
+ before(:all) { @captcha = @client.decode!(raw64: recaptcha64, id_constructor: 23) }
66
+
67
+ it { expect(@captcha).to be_a(TwoCaptcha::Captcha) }
68
+ it { expect(@captcha.indexes).to eq([1, 9]) }
69
+ it { expect(@captcha.id).to match(/[0-9]{9}/) }
70
+ end
71
+ end
72
+ end
@@ -0,0 +1,17 @@
1
+ RSpec.configure do |config|
2
+ # Run specs in random order to surface order dependencies. If you find an
3
+ # order dependency and want to debug it, you can fix the order by providing
4
+ # the seed, which is printed after each run.
5
+ # --seed 1234
6
+ config.order = "random"
7
+
8
+ # Only accept the new syntax of "expect" instead of "should".
9
+ config.expect_with :rspec do |c|
10
+ c.syntax = :expect
11
+ end
12
+ end
13
+
14
+ require 'yaml'
15
+ require 'two_captcha'
16
+
17
+ CREDENTIALS = YAML.load_file('spec/credentials.yml')
@@ -0,0 +1,24 @@
1
+ # coding: utf-8
2
+ lib = File.expand_path('../lib', __FILE__)
3
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4
+ require 'two_captcha/version'
5
+
6
+ Gem::Specification.new do |spec|
7
+ spec.name = "two_captcha"
8
+ spec.version = TwoCaptcha::VERSION
9
+ spec.authors = ["Marcelo Mita", "Rafael Barbolo"]
10
+ spec.email = ["team@infosimples.com.br"]
11
+ spec.summary = %q{Ruby API for 2Captcha (Captcha Solver as a Service)}
12
+ spec.description = %q{TwoCaptcha allows you to solve captchas with manual labor}
13
+ spec.homepage = "https://github.com/infosimples/two_captcha"
14
+ spec.license = "MIT"
15
+
16
+ spec.files = `git ls-files -z`.split("\x0")
17
+ spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
18
+ spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
19
+ spec.require_paths = ["lib"]
20
+
21
+ spec.add_development_dependency "bundler", "~> 1.8"
22
+ spec.add_development_dependency "rake", "~> 10.0"
23
+ spec.add_development_dependency "rspec", "~> 3.1"
24
+ end
metadata ADDED
@@ -0,0 +1,114 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: two_captcha
3
+ version: !ruby/object:Gem::Version
4
+ version: 1.0.0
5
+ platform: ruby
6
+ authors:
7
+ - Marcelo Mita
8
+ - Rafael Barbolo
9
+ autorequire:
10
+ bindir: bin
11
+ cert_chain: []
12
+ date: 2015-09-10 00:00:00.000000000 Z
13
+ dependencies:
14
+ - !ruby/object:Gem::Dependency
15
+ name: bundler
16
+ requirement: !ruby/object:Gem::Requirement
17
+ requirements:
18
+ - - "~>"
19
+ - !ruby/object:Gem::Version
20
+ version: '1.8'
21
+ type: :development
22
+ prerelease: false
23
+ version_requirements: !ruby/object:Gem::Requirement
24
+ requirements:
25
+ - - "~>"
26
+ - !ruby/object:Gem::Version
27
+ version: '1.8'
28
+ - !ruby/object:Gem::Dependency
29
+ name: rake
30
+ requirement: !ruby/object:Gem::Requirement
31
+ requirements:
32
+ - - "~>"
33
+ - !ruby/object:Gem::Version
34
+ version: '10.0'
35
+ type: :development
36
+ prerelease: false
37
+ version_requirements: !ruby/object:Gem::Requirement
38
+ requirements:
39
+ - - "~>"
40
+ - !ruby/object:Gem::Version
41
+ version: '10.0'
42
+ - !ruby/object:Gem::Dependency
43
+ name: rspec
44
+ requirement: !ruby/object:Gem::Requirement
45
+ requirements:
46
+ - - "~>"
47
+ - !ruby/object:Gem::Version
48
+ version: '3.1'
49
+ type: :development
50
+ prerelease: false
51
+ version_requirements: !ruby/object:Gem::Requirement
52
+ requirements:
53
+ - - "~>"
54
+ - !ruby/object:Gem::Version
55
+ version: '3.1'
56
+ description: TwoCaptcha allows you to solve captchas with manual labor
57
+ email:
58
+ - team@infosimples.com.br
59
+ executables:
60
+ - console
61
+ - setup
62
+ extensions: []
63
+ extra_rdoc_files: []
64
+ files:
65
+ - ".gitignore"
66
+ - ".rspec"
67
+ - ".travis.yml"
68
+ - CODE_OF_CONDUCT.md
69
+ - Gemfile
70
+ - LICENSE.txt
71
+ - README.md
72
+ - Rakefile
73
+ - bin/console
74
+ - bin/setup
75
+ - captchas/1.png
76
+ - captchas/2.jpg
77
+ - lib/two_captcha.rb
78
+ - lib/two_captcha/client.rb
79
+ - lib/two_captcha/errors.rb
80
+ - lib/two_captcha/http.rb
81
+ - lib/two_captcha/models/captcha.rb
82
+ - lib/two_captcha/version.rb
83
+ - spec/credentials.yml.sample
84
+ - spec/lib/client_spec.rb
85
+ - spec/spec_helper.rb
86
+ - two_captcha.gemspec
87
+ homepage: https://github.com/infosimples/two_captcha
88
+ licenses:
89
+ - MIT
90
+ metadata: {}
91
+ post_install_message:
92
+ rdoc_options: []
93
+ require_paths:
94
+ - lib
95
+ required_ruby_version: !ruby/object:Gem::Requirement
96
+ requirements:
97
+ - - ">="
98
+ - !ruby/object:Gem::Version
99
+ version: '0'
100
+ required_rubygems_version: !ruby/object:Gem::Requirement
101
+ requirements:
102
+ - - ">="
103
+ - !ruby/object:Gem::Version
104
+ version: '0'
105
+ requirements: []
106
+ rubyforge_project:
107
+ rubygems_version: 2.4.3
108
+ signing_key:
109
+ specification_version: 4
110
+ summary: Ruby API for 2Captcha (Captcha Solver as a Service)
111
+ test_files:
112
+ - spec/credentials.yml.sample
113
+ - spec/lib/client_spec.rb
114
+ - spec/spec_helper.rb