Пример #1
0
class Http(object):
    def __init__(self, **config):
        self.grab = Grab(**(config or {}))

    def get_response_body(self):
        if PY2 is True:
            return self.grab.response.body
        return self.grab.response.body.decode('utf-8')

    def request(self, url):
        self.grab.go(url)
        return self.grab.response.code, self.get_response_body()

    def setup(self, **kwargs):
        self.grab.setup(**kwargs)

    @staticmethod
    def upload(filename):
        return UploadFile(filename)

    def reset(self):
        self.grab.reset()
Пример #2
0
class AntiGate(object):
    def __init__(self, key, captcha_file='', auto_run=True,
                 grab_config=None, send_config=None,
                 domain='antigate.com', binary=False):
        self.g = Grab()
        if grab_config:
            self.g.setup(**grab_config)
        self.key = key
        self.captcha_id = None
        self.captcha_key = None
        self.send_config = send_config
        self.domain = domain
        self.logger = getLogger(__name__)

        if auto_run and captcha_file:
            self.run(captcha_file, binary)

    def _get_domain(self, path):
        if DEBUG:
            return 'http://127.0.0.1:8000/%s' % path
        return 'http://%s/%s' % (self.domain, path)

    def _get_input_url(self):
        return self._get_domain('in.php')

    def _update_params(self, defaults, additional):
        if additional is not None and additional:
            defaults.update(additional)
        return defaults

    def _get_build_url(self, action='get', data=None):
        params = urlencode(self._update_params(
            {'key': self.key, 'action': action}, data
        ))
        return self._get_domain('res.php?%s' % params)

    def _get_result_url(self, action='get', captcha_id=None):
        return self._get_build_url(action, {
            'id': captcha_id and captcha_id or self.captcha_id})

    def _get_balance_url(self):
        return self._get_build_url('getbalance')

    def _get_stats_url(self):
        return self._get_build_url('getstats', {
            'date': datetime.now().strftime('%Y-%m-%d')})

    def _body(self, key):
        body = self.g.response.body.split('|')
        if len(body) != 2 or body[0] != 'OK':
            raise AntiGateError(body[0])
        setattr(self, key, body[1])
        return body[1]

    def _response_to_dict(self):
        return parse(self.g.response.body.lower())['response']

    def _go(self, url, err):
        self.g.go(url)
        if self.g.response.code != 200:
            raise AntiGateError('Code: %d\nMessage: %s\nBody: %s' % (
                self.g.response.code, err, self.g.response.body
            ))

    def _send(self, captcha_file, binary=False):
        if binary:
            body = base64.b64encode(captcha_file)
            self.g.setup(post=self._update_params(
                {'method': 'base64', 'key': self.key, 'body': body},
                self.send_config
            ))
        else:
            self.g.setup(multipart_post=self._update_params(
                {'key': self.key, 'file': UploadFile(captcha_file)},
                self.send_config
            ))
        self._go(self._get_input_url(), 'Can not send captcha')
        return self._body('captcha_id')

    def send(self, captcha_file, binary=False):
        self.logger.debug('Sending captcha')
        while True:
            try:
                return self._send(captcha_file, binary)
            except AntiGateError:
                msg = exc_info()[1]
                self.logger.debug(msg)
                if str(msg) != 'ERROR_NO_SLOT_AVAILABLE':
                    raise AntiGateError(msg)

    def _get(self, captcha_id=None):
        self.g.reset()
        self._go(self._get_result_url(captcha_id=captcha_id),
                 'Can not get captcha')
        return self._body('captcha_key')

    def get(self, captcha_id=None):
        self.logger.debug('Fetching result')
        sleep(10)
        while True:
            try:
                return self._get(captcha_id)
            except AntiGateError:
                msg = exc_info()[1]
                self.logger.debug(msg)
                if str(msg) == 'CAPCHA_NOT_READY':
                    sleep(5)
                else:
                    raise AntiGateError(msg)

    def _get_multi(self, ids):
        self._go(self._get_build_url(data={
            'ids': ','.join(map(str, ids))}), 'Can not get result')
        return self.g.response.body.split('|')

    def get_multi(self, ids):
        results = self._get_multi(ids)
        while 'CAPCHA_NOT_READY' in results:
            sleep(10)
            results = self._get_multi(ids)
        return results

    def abuse(self):
        self._go(self._get_result_url('reportbad'), 'Can not send report')
        return True

    def balance(self):
        self._go(self._get_balance_url(), 'Can not get balance')
        return float(self.g.response.body)

    def stats(self):
        self._go(self._get_stats_url(), 'Can not get stats')
        return [s for s in self._response_to_dict()['stats']]

    def load(self):
        self._go(self._get_domain('load.php'), 'Can not get loads')
        return self._response_to_dict()

    def run(self, captcha_file, binary=False):
        self.send(captcha_file, binary)
        self.get()

    def __str__(self):
        return self.captcha_key
Пример #3
0
class AntiGate(object):
    __slots__ = [
        'grab', 'domain', 'api_key', 'captcha_id', 'captcha_result',
        'send_config', 'logger', 'check_interval'
    ]

    def __init__(self, api_key, captcha_file=None, auto_run=True,
                 grab_config=None, send_config=None,
                 domain='antigate.com', check_interval=10):

        self.grab = Grab(**(grab_config or {}))
        self.domain = domain
        self.api_key = api_key
        self.captcha_id = None
        self.captcha_result = None
        self.send_config = send_config
        self.logger = getLogger(__name__)
        self.check_interval = check_interval

        if auto_run and captcha_file:
            self.run(captcha_file)

    @staticmethod
    def _update_params(defaults, additional):
        if additional is not None and additional:
            defaults.update(additional)
        return defaults

    @staticmethod
    def _is_base64(s):
        is_base64 = False
        if len(s) % 4 == 0:
            try:
                is_base64 = match('^[A-Za-z0-9+/]+[=]{0,2}$', s)
            except TypeError:
                is_base64 = match(b'^[A-Za-z0-9+/]+[=]{0,2}$', s)
        return is_base64 and True

    @staticmethod
    def _is_binary(s):
        try:
            is_binary = '\0' in s
        except TypeError:
            is_binary = b'\0' in s
        return is_binary

    def _get_domain(self, path):
        return 'http://%s/%s' % (self.domain, path)

    def _get_input_url(self):
        return self._get_domain('in.php')

    def _build_url(self, action='get', data=None):
        params = urlencode(self._update_params(
            {'key': self.api_key, 'action': action}, data
        ))
        return self._get_domain('res.php?%s' % params)

    def _get_result_url(self, action='get', captcha_id=None):
        return self._build_url(action, {
            'id': captcha_id or self.captcha_id
        })

    def _get_balance_url(self):
        return self._build_url('getbalance')

    def _get_stats_url(self):
        return self._build_url('getstats', {
            'date': datetime.now().strftime('%Y-%m-%d')
        })

    def _get_response_body(self):
        if PY2 is True:
            return self.grab.response.body
        return self.grab.response.body.decode('utf-8')

    def _get_response(self, key=None):
        body = self._get_response_body().split('|')
        if len(body) != 2 or body[0] != 'OK':
            raise AntiGateError(body[0])
        if key is not None:
            setattr(self, key, body[1])
        return body[1]

    def _response_to_dict(self):
        return parse(self._get_response_body().lower()).get('response', {})

    def _request(self, url, err):
        self.grab.go(url)
        if self.grab.response.code != 200:
            raise AntiGateError('Code: %d\nMessage: %s\nBody: %s' % (
                self.grab.response.code, err, self._get_response_body()
            ))

    def _send(self, captcha_file):
        is_base64 = self._is_base64(captcha_file)
        is_binary = self._is_binary(captcha_file)

        if is_binary or is_base64:
            body = b64encode(captcha_file) if not is_base64 else captcha_file
            if PY3 is True:
                body = body.decode('utf-8')
            self.grab.setup(post=self._update_params({
                'method': 'base64', 'key': self.api_key, 'body': body},
                self.send_config
            ))
        else:
            self.grab.setup(multipart_post=self._update_params({
                'method': 'post', 'key': self.api_key,
                'file': UploadFile(captcha_file)},
                self.send_config
            ))
        self._request(self._get_input_url(), 'Can not send captcha')
        return self._get_response('captcha_id')

    def _get(self, captcha_id=None):
        self.grab.reset()
        self._request(
            self._get_result_url(captcha_id=captcha_id), 'Can not get captcha')
        return self._get_response('captcha_result')

    def _get_multi(self, ids):
        self._request(self._build_url(data={
            'ids': ','.join(map(str, ids))}), 'Can not get result')
        return self._get_response_body().split('|')

    def send(self, captcha_file):
        self.logger.debug('Sending captcha')
        while True:
            try:
                return self._send(captcha_file)
            except AntiGateError:
                msg = exc_info()[1]
                if str(msg) != 'ERROR_NO_SLOT_AVAILABLE':
                    raise AntiGateError(msg)

    def get(self, captcha_id=None):
        self.logger.debug('Fetching result')
        sleep(self.check_interval)
        while True:
            try:
                return self._get(captcha_id)
            except AntiGateError:
                msg = exc_info()[1]
                if str(msg) == 'CAPCHA_NOT_READY':
                    sleep(self.check_interval / 2.0)
                else:
                    raise AntiGateError(msg)

    def get_multi(self, ids):
        self.logger.debug('Fetching multi result')
        results = self._get_multi(ids)
        while 'CAPCHA_NOT_READY' in results:
            sleep(self.check_interval)
            results = self._get_multi(ids)
        return results

    def abuse(self):
        self._request(self._get_result_url('reportbad'), 'Can not send report')
        return True

    def balance(self):
        self._request(self._get_balance_url(), 'Can not get balance')
        return float(self._get_response_body())

    def stats(self):
        self._request(self._get_stats_url(), 'Can not get stats')
        return [s for s in self._response_to_dict().get('stats', [])]

    def load(self):
        self._request(self._get_domain('load.php'), 'Can not get loads')
        return self._response_to_dict()

    def run(self, captcha_file):
        self.send(captcha_file)
        self.get()

    def __len__(self):
        if self.captcha_result:
            return len(self.captcha_result)

    def __str__(self):
        return self.captcha_result
Пример #4
0
class AntiGate(object):
    def __init__(self, key, captcha_file='', auto_run=True,
                 grab_config=None, send_config=None,
                 domain='antigate.com', binary=False):
        self.g = Grab()
        self.g.setup(timeout=30)
        if grab_config:
            self.g.setup(**grab_config)
        self.key = key
        self.captcha_id = None
        self.captcha_key = None
        self.send_config = send_config
        self.domain = domain
        self.logger = getLogger(__name__)

        if auto_run and captcha_file:
            self.run(captcha_file, binary)

    def _get_domain(self, path):
        if DEBUG:
            return 'http://127.0.0.1:8000/%s' % path
        return 'http://%s/%s' % (self.domain, path)

    def _get_input_url(self):
        return self._get_domain('in.php')

    def _update_params(self, defaults, additional):
        if additional is not None and additional:
            defaults.update(additional)
        return defaults

    def _get_build_url(self, action='get', data=None):
        params = urlencode(self._update_params(
            {'key': self.key, 'action': action}, data
        ))
        return self._get_domain('res.php?%s' % params)

    def _get_result_url(self, action='get', captcha_id=None):
        return self._get_build_url(action, {
            'id': captcha_id and captcha_id or self.captcha_id})

    def _get_balance_url(self):
        return self._get_build_url('getbalance')

    def _get_stats_url(self):
        return self._get_build_url('getstats', {
            'date': datetime.now().strftime('%Y-%m-%d')})

    def _body(self, key):
        body = self.g.response.body.split('|')
        if len(body) != 2 or body[0] != 'OK':
            raise AntiGateError(body[0])
        setattr(self, key, body[1])
        return body[1]

    def _response_to_dict(self):
        return parse(self.g.response.body.lower())['response']

    def _go(self, url, err):
        self.g.go(url)
        if self.g.response.code != 200:
            raise AntiGateError('Code: %d\nMessage: %s\nBody: %s' % (
                self.g.response.code, err, self.g.response.body
            ))

    def _send(self, captcha_file, binary=False):
        if binary:
            body = base64.b64encode(captcha_file)
            self.g.setup(post=self._update_params(
                {'method': 'base64', 'key': self.key, 'body': body},
                self.send_config
            ))
        else:
            self.g.setup(multipart_post=self._update_params(
                {'method': 'post', 'key': self.key,
                 'file': UploadFile(captcha_file)},
                self.send_config
            ))
        self._go(self._get_input_url(), 'Can not send captcha')
        return self._body('captcha_id')

    def send(self, captcha_file, binary=False):
        self.logger.debug('Sending captcha')
        while True:
            try:
                return self._send(captcha_file, binary)
            except AntiGateError:
                msg = exc_info()[1]
                self.logger.debug(msg)
                if str(msg) != 'ERROR_NO_SLOT_AVAILABLE':
                    raise AntiGateError(msg)

    def _get(self, captcha_id=None):
        self.g.reset()
        self._go(self._get_result_url(captcha_id=captcha_id),
                 'Can not get captcha')
        return self._body('captcha_key')

    def get(self, captcha_id=None):
        self.logger.debug('Fetching result')
        sleep(10)
        while True:
            try:
                return self._get(captcha_id)
            except AntiGateError:
                msg = exc_info()[1]
                self.logger.debug(msg)
                if str(msg) == 'CAPCHA_NOT_READY':
                    sleep(5)
                else:
                    raise AntiGateError(msg)

    def _get_multi(self, ids):
        self._go(self._get_build_url(data={
            'ids': ','.join(map(str, ids))}), 'Can not get result')
        return self.g.response.body.split('|')

    def get_multi(self, ids):
        results = self._get_multi(ids)
        while 'CAPCHA_NOT_READY' in results:
            sleep(10)
            results = self._get_multi(ids)
        return results

    def abuse(self):
        self._go(self._get_result_url('reportbad'), 'Can not send report')
        return True

    def balance(self):
        self._go(self._get_balance_url(), 'Can not get balance')
        return float(self.g.response.body)

    def stats(self):
        self._go(self._get_stats_url(), 'Can not get stats')
        return [s for s in self._response_to_dict()['stats']]

    def load(self):
        self._go(self._get_domain('load.php'), 'Can not get loads')
        return self._response_to_dict()

    def run(self, captcha_file, binary=False):
        self.send(captcha_file, binary)
        self.get()

    def __str__(self):
        return self.captcha_key