| 1 |
from __future__ import absolute_import |
| 2 |
|
| 3 |
import requests |
| 4 |
try: |
| 5 |
from urlparse import urlparse |
| 6 |
except ImportError: |
| 7 |
from urllib.parse import urlparse |
| 8 |
|
| 9 |
from ..exceptions import ( |
| 10 |
CaptchaServiceUnavailable, |
| 11 |
CaptchaAPIError, |
| 12 |
CaptchaTimeout, |
| 13 |
CaptchaParameter, |
| 14 |
CaptchaBadJobID, |
| 15 |
CaptchaReportError |
| 16 |
) |
| 17 |
|
| 18 |
try: |
| 19 |
import polling2 |
| 20 |
except ImportError: |
| 21 |
raise ImportError("Please install the python module 'polling2' via pip") |
| 22 |
|
| 23 |
from . import Captcha |
| 24 |
|
| 25 |
|
| 26 |
class captchaSolver(Captcha): |
| 27 |
|
| 28 |
def __init__(self): |
| 29 |
super(captchaSolver, self).__init__('2captcha') |
| 30 |
self.host = 'https://2captcha.com' |
| 31 |
self.session = requests.Session() |
| 32 |
self.captchaType = { |
| 33 |
'reCaptcha': 'userrecaptcha', |
| 34 |
'hCaptcha': 'hcaptcha', |
| 35 |
'turnstile': 'turnstile' |
| 36 |
} |
| 37 |
|
| 38 |
# ------------------------------------------------------------------------------- # |
| 39 |
|
| 40 |
@staticmethod |
| 41 |
def checkErrorStatus(response, request_type): |
| 42 |
if response.status_code in [500, 502]: |
| 43 |
raise CaptchaServiceUnavailable(f'2Captcha: Server Side Error {response.status_code}') |
| 44 |
|
| 45 |
errors = { |
| 46 |
'in.php': { |
| 47 |
"ERROR_WRONG_USER_KEY": "You've provided api_key parameter value is in incorrect format, it should contain 32 symbols.", |
| 48 |
"ERROR_KEY_DOES_NOT_EXIST": "The api_key you've provided does not exists.", |
| 49 |
"ERROR_ZERO_BALANCE": "You don't have sufficient funds on your account.", |
| 50 |
"ERROR_PAGEURL": "pageurl parameter is missing in your request.", |
| 51 |
"ERROR_NO_SLOT_AVAILABLE": |
| 52 |
"No Slots Available.\nYou can receive this error in two cases:\n" |
| 53 |
"1. If you solve ReCaptcha: the queue of your captchas that are not distributed to workers is too long. " |
| 54 |
"Queue limit changes dynamically and depends on total amount of captchas awaiting solution and usually it's between 50 and 100 captchas.\n" |
| 55 |
"2. If you solve Normal Captcha: your maximum rate for normal captchas is lower than current rate on the server." |
| 56 |
"You can change your maximum rate in your account's settings.", |
| 57 |
"ERROR_IP_NOT_ALLOWED": "The request is sent from the IP that is not on the list of your allowed IPs.", |
| 58 |
"IP_BANNED": "Your IP address is banned due to many frequent attempts to access the server using wrong authorization keys.", |
| 59 |
"ERROR_BAD_TOKEN_OR_PAGEURL": |
| 60 |
"You can get this error code when sending ReCaptcha V2. " |
| 61 |
"That happens if your request contains invalid pair of googlekey and pageurl. " |
| 62 |
"The common reason for that is that ReCaptcha is loaded inside an iframe hosted on another domain/subdomain.", |
| 63 |
"ERROR_GOOGLEKEY": |
| 64 |
"You can get this error code when sending ReCaptcha V2. " |
| 65 |
"That means that sitekey value provided in your request is incorrect: it's blank or malformed.", |
| 66 |
"MAX_USER_TURN": "You made more than 60 requests within 3 seconds.Your account is banned for 10 seconds. Ban will be lifted automatically." |
| 67 |
}, |
| 68 |
'res.php': { |
| 69 |
"ERROR_CAPTCHA_UNSOLVABLE": |
| 70 |
"We are unable to solve your captcha - three of our workers were unable solve it " |
| 71 |
"or we didn't get an answer within 90 seconds (300 seconds for ReCaptcha V2). " |
| 72 |
"We will not charge you for that request.", |
| 73 |
"ERROR_WRONG_USER_KEY": "You've provided api_key parameter value in incorrect format, it should contain 32 symbols.", |
| 74 |
"ERROR_KEY_DOES_NOT_EXIST": "The api_key you've provided does not exists.", |
| 75 |
"ERROR_WRONG_ID_FORMAT": "You've provided captcha ID in wrong format. The ID can contain numbers only.", |
| 76 |
"ERROR_WRONG_CAPTCHA_ID": "You've provided incorrect captcha ID.", |
| 77 |
"ERROR_BAD_DUPLICATES": |
| 78 |
"Error is returned when 100% accuracy feature is enabled. " |
| 79 |
"The error means that max numbers of tries is reached but min number of matches not found.", |
| 80 |
"REPORT_NOT_RECORDED": "Error is returned to your complain request if you already complained lots of correctly solved captchas.", |
| 81 |
"ERROR_IP_ADDRES": |
| 82 |
"You can receive this error code when registering a pingback (callback) IP or domain." |
| 83 |
"That happes if your request is coming from an IP address that doesn't match the IP address of your pingback IP or domain.", |
| 84 |
"ERROR_TOKEN_EXPIRED": "You can receive this error code when sending GeeTest. That error means that challenge value you provided is expired.", |
| 85 |
"ERROR_EMPTY_ACTION": "Action parameter is missing or no value is provided for action parameter." |
| 86 |
} |
| 87 |
} |
| 88 |
|
| 89 |
rPayload = response.json() |
| 90 |
if rPayload.get('status') == 0 and rPayload.get('request') in errors.get(request_type): |
| 91 |
raise CaptchaAPIError( |
| 92 |
f"{rPayload['request']} {errors.get(request_type).get(rPayload['request'])}" |
| 93 |
) |
| 94 |
|
| 95 |
# ------------------------------------------------------------------------------- # |
| 96 |
|
| 97 |
def reportJob(self, jobID): |
| 98 |
if not jobID: |
| 99 |
raise CaptchaBadJobID( |
| 100 |
"2Captcha: Error bad job id to request Captcha." |
| 101 |
) |
| 102 |
|
| 103 |
def _checkRequest(response): |
| 104 |
self.checkErrorStatus(response, 'res.php') |
| 105 |
if response.ok and response.json().get('status') == 1: |
| 106 |
return response |
| 107 |
return None |
| 108 |
|
| 109 |
response = polling2.poll( |
| 110 |
lambda: self.session.get( |
| 111 |
f'{self.host}/res.php', |
| 112 |
params={ |
| 113 |
'key': self.api_key, |
| 114 |
'action': 'reportbad', |
| 115 |
'id': jobID, |
| 116 |
'json': '1' |
| 117 |
}, |
| 118 |
timeout=30 |
| 119 |
), |
| 120 |
check_success=_checkRequest, |
| 121 |
step=5, |
| 122 |
timeout=180 |
| 123 |
) |
| 124 |
|
| 125 |
if response: |
| 126 |
return True |
| 127 |
else: |
| 128 |
raise CaptchaReportError( |
| 129 |
"2Captcha: Error - Failed to report bad Captcha solve." |
| 130 |
) |
| 131 |
|
| 132 |
# ------------------------------------------------------------------------------- # |
| 133 |
|
| 134 |
def requestJob(self, jobID): |
| 135 |
if not jobID: |
| 136 |
raise CaptchaBadJobID("2Captcha: Error bad job id to request Captcha.") |
| 137 |
|
| 138 |
def _checkRequest(response): |
| 139 |
self.checkErrorStatus(response, 'res.php') |
| 140 |
if response.ok and response.json().get('status') == 1: |
| 141 |
return response |
| 142 |
return None |
| 143 |
|
| 144 |
response = polling2.poll( |
| 145 |
lambda: self.session.get( |
| 146 |
f'{self.host}/res.php', |
| 147 |
params={ |
| 148 |
'key': self.api_key, |
| 149 |
'action': 'get', |
| 150 |
'id': jobID, |
| 151 |
'json': '1' |
| 152 |
}, |
| 153 |
timeout=30 |
| 154 |
), |
| 155 |
check_success=_checkRequest, |
| 156 |
step=5, |
| 157 |
timeout=180 |
| 158 |
) |
| 159 |
|
| 160 |
if response: |
| 161 |
return response.json().get('request') |
| 162 |
else: |
| 163 |
raise CaptchaTimeout( |
| 164 |
"2Captcha: Error failed to solve Captcha." |
| 165 |
) |
| 166 |
|
| 167 |
# ------------------------------------------------------------------------------- # |
| 168 |
|
| 169 |
def requestSolve(self, captchaType, url, siteKey): |
| 170 |
def _checkRequest(response): |
| 171 |
self.checkErrorStatus(response, 'in.php') |
| 172 |
if response.ok and response.json().get("status") == 1 and response.json().get('request'): |
| 173 |
return response |
| 174 |
return None |
| 175 |
|
| 176 |
data = { |
| 177 |
'key': self.api_key, |
| 178 |
'pageurl': url, |
| 179 |
'json': 1, |
| 180 |
'soft_id': 2905 |
| 181 |
} |
| 182 |
|
| 183 |
data.update({ |
| 184 |
'method': self.captchaType[captchaType], |
| 185 |
'googlekey' if captchaType == 'reCaptcha' else 'sitekey': siteKey |
| 186 |
}) |
| 187 |
|
| 188 |
if self.proxy: |
| 189 |
data.update({ |
| 190 |
'proxy': self.proxy, |
| 191 |
'proxytype': self.proxyType |
| 192 |
}) |
| 193 |
|
| 194 |
response = polling2.poll( |
| 195 |
lambda: self.session.post( |
| 196 |
f'{self.host}/in.php', |
| 197 |
data=data, |
| 198 |
allow_redirects=False, |
| 199 |
timeout=30 |
| 200 |
), |
| 201 |
check_success=_checkRequest, |
| 202 |
step=5, |
| 203 |
timeout=180 |
| 204 |
) |
| 205 |
|
| 206 |
if response: |
| 207 |
return response.json().get('request') |
| 208 |
else: |
| 209 |
raise CaptchaBadJobID( |
| 210 |
'2Captcha: Error no job id was returned.' |
| 211 |
) |
| 212 |
|
| 213 |
# ------------------------------------------------------------------------------- # |
| 214 |
|
| 215 |
def getCaptchaAnswer(self, captchaType, url, siteKey, captchaParams): |
| 216 |
jobID = None |
| 217 |
|
| 218 |
if not captchaParams.get('api_key'): |
| 219 |
raise CaptchaParameter( |
| 220 |
"2Captcha: Missing api_key parameter." |
| 221 |
) |
| 222 |
|
| 223 |
self.api_key = captchaParams.get('api_key') |
| 224 |
|
| 225 |
if captchaParams.get('proxy') and not captchaParams.get('no_proxy'): |
| 226 |
hostParsed = urlparse(captchaParams.get('proxy', {}).get('https')) |
| 227 |
|
| 228 |
if not hostParsed.scheme: |
| 229 |
raise CaptchaParameter('Cannot parse proxy correctly, bad scheme') |
| 230 |
|
| 231 |
if not hostParsed.netloc: |
| 232 |
raise CaptchaParameter('Cannot parse proxy correctly, bad netloc') |
| 233 |
|
| 234 |
self.proxyType = hostParsed.scheme |
| 235 |
self.proxy = hostParsed.netloc |
| 236 |
else: |
| 237 |
self.proxy = None |
| 238 |
|
| 239 |
try: |
| 240 |
jobID = self.requestSolve(captchaType, url, siteKey) |
| 241 |
return self.requestJob(jobID) |
| 242 |
except polling2.TimeoutException: |
| 243 |
try: |
| 244 |
if jobID: |
| 245 |
self.reportJob(jobID) |
| 246 |
except polling2.TimeoutException: |
| 247 |
raise CaptchaTimeout( |
| 248 |
f"2Captcha: Captcha solve took to long and also failed reporting the job the job id {jobID}." |
| 249 |
) |
| 250 |
|
| 251 |
raise CaptchaTimeout( |
| 252 |
f"2Captcha: Captcha solve took to long to execute job id {jobID}, aborting." |
| 253 |
) |
| 254 |
|
| 255 |
|
| 256 |
# ------------------------------------------------------------------------------- # |
| 257 |
|
| 258 |
captchaSolver() |