aboutsummaryrefslogtreecommitdiffhomepage
path: root/libs/cloudscraper/reCaptcha/deathbycaptcha.py
blob: 6079c1d4eecd65067072731870ebdc5b0c29bf22 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
from __future__ import absolute_import

import json
import requests

try:
    import polling
except ImportError:
    raise ImportError(
        "Please install the python module 'polling' via pip or download it from "
        "https://github.com/justiniso/polling/"
    )

from ..exceptions import (
    reCaptchaException,
    reCaptchaServiceUnavailable,
    reCaptchaAccountError,
    reCaptchaTimeout,
    reCaptchaParameter,
    reCaptchaBadJobID,
    reCaptchaReportError
)

from . import reCaptcha


class captchaSolver(reCaptcha):

    def __init__(self):
        super(captchaSolver, self).__init__('deathbycaptcha')
        self.host = 'http://api.dbcapi.me/api'
        self.session = requests.Session()

    # ------------------------------------------------------------------------------- #

    @staticmethod
    def checkErrorStatus(response):
        errors = dict(
            [
                (400, "DeathByCaptcha: 400 Bad Request"),
                (403, "DeathByCaptcha: 403 Forbidden - Invalid credentails or insufficient credits."),
                # (500, "DeathByCaptcha: 500 Internal Server Error."),
                (503, "DeathByCaptcha: 503 Service Temporarily Unavailable.")
            ]
        )

        if response.status_code in errors:
            raise reCaptchaServiceUnavailable(errors.get(response.status_code))

    # ------------------------------------------------------------------------------- #

    def login(self, username, password):
        self.username = username
        self.password = password

        def _checkRequest(response):
            if response.ok:
                if response.json().get('is_banned'):
                    raise reCaptchaAccountError('DeathByCaptcha: Your account is banned.')

                if response.json().get('balanace') == 0:
                    raise reCaptchaAccountError('DeathByCaptcha: insufficient credits.')

                return response

            self.checkErrorStatus(response)

            return None

        response = polling.poll(
            lambda: self.session.post(
                '{}/user'.format(self.host),
                headers={'Accept': 'application/json'},
                data={
                    'username': self.username,
                    'password': self.password
                }
            ),
            check_success=_checkRequest,
            step=10,
            timeout=120
        )

        self.debugRequest(response)

    # ------------------------------------------------------------------------------- #

    def reportJob(self, jobID):
        if not jobID:
            raise reCaptchaBadJobID(
                "DeathByCaptcha: Error bad job id to report failed reCaptcha."
            )

        def _checkRequest(response):
            if response.status_code == 200:
                return response

            self.checkErrorStatus(response)

            return None

        response = polling.poll(
            lambda: self.session.post(
                '{}/captcha/{}/report'.format(self.host, jobID),
                headers={'Accept': 'application/json'},
                data={
                    'username': self.username,
                    'password': self.password
                }
            ),
            check_success=_checkRequest,
            step=10,
            timeout=180
        )

        if response:
            return True
        else:
            raise reCaptchaReportError(
                "DeathByCaptcha: Error report failed reCaptcha."
            )

    # ------------------------------------------------------------------------------- #

    def requestJob(self, jobID):
        if not jobID:
            raise reCaptchaBadJobID(
                "DeathByCaptcha: Error bad job id to request reCaptcha."
            )

        def _checkRequest(response):
            if response.ok and response.json().get('text'):
                return response

            self.checkErrorStatus(response)

            return None

        response = polling.poll(
            lambda: self.session.get(
                '{}/captcha/{}'.format(self.host, jobID),
                headers={'Accept': 'application/json'}
            ),
            check_success=_checkRequest,
            step=10,
            timeout=180
        )

        if response:
            return response.json().get('text')
        else:
            raise reCaptchaTimeout(
                "DeathByCaptcha: Error failed to solve reCaptcha."
            )

    # ------------------------------------------------------------------------------- #

    def requestSolve(self, url, siteKey):
        def _checkRequest(response):
            if response.ok and response.json().get("is_correct") and response.json().get('captcha'):
                return response

            self.checkErrorStatus(response)

            return None

        response = polling.poll(
            lambda: self.session.post(
                '{}/captcha'.format(self.host),
                headers={'Accept': 'application/json'},
                data={
                    'username': self.username,
                    'password': self.password,
                    'type': '4',
                    'token_params': json.dumps({
                        'googlekey': siteKey,
                        'pageurl': url
                    })
                },
                allow_redirects=False
            ),
            check_success=_checkRequest,
            step=10,
            timeout=180
        )

        if response:
            return response.json().get('captcha')
        else:
            raise reCaptchaBadJobID(
                'DeathByCaptcha: Error no job id was returned.'
            )

    # ------------------------------------------------------------------------------- #

    def getCaptchaAnswer(self, captchaType, url, siteKey, reCaptchaParams):
        jobID = None

        for param in ['username', 'password']:
            if not reCaptchaParams.get(param):
                raise reCaptchaParameter(
                    "DeathByCaptcha: Missing '{}' parameter.".format(param)
                )
            setattr(self, param, reCaptchaParams.get(param))

        if captchaType == 'hCaptcha':
            raise reCaptchaException(
                'Provider does not support hCaptcha.'
            )

        if reCaptchaParams.get('proxy'):
            self.session.proxies = reCaptchaParams.get('proxies')

        try:
            jobID = self.requestSolve(url, siteKey)
            return self.requestJob(jobID)
        except polling.TimeoutException:
            try:
                if jobID:
                    self.reportJob(jobID)
            except polling.TimeoutException:
                raise reCaptchaTimeout(
                    "DeathByCaptcha: reCaptcha solve took to long and also failed reporting the job id {}.".format(jobID)
                )

            raise reCaptchaTimeout(
                "DeathByCaptcha: reCaptcha solve took to long to execute job id {}, aborting.".format(jobID)
            )


# ------------------------------------------------------------------------------- #

captchaSolver()