Skip to content

Commit

Permalink
Merge pull request #199 from AndreiDrang/main
Browse files Browse the repository at this point in the history
Added callbackUrl param
  • Loading branch information
AndreiDrang authored Dec 27, 2024
2 parents 2da0ead + 732fca4 commit 3add3f6
Show file tree
Hide file tree
Showing 15 changed files with 106 additions and 70 deletions.
1 change: 1 addition & 0 deletions docs/index.rst
Original file line number Diff line number Diff line change
Expand Up @@ -38,5 +38,6 @@ Check our other projects here - `RedPandaDev group <https://red-panda-dev.xyz/bl
:maxdepth: 2
:caption: Additional modules

modules/core/info.rst
modules/enum/info.rst
modules/serializer/info.rst
12 changes: 12 additions & 0 deletions docs/modules/core/info.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
Core
====

To import this module:

.. code-block:: python
from python3_anticaptcha.core import base
.. autoclass:: core.base.CaptchaParams
:members:
7 changes: 0 additions & 7 deletions src/python3_anticaptcha/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,6 @@

urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

# Адрес для создания задачи
create_task_url = "https://api.anti-captcha.com/createTask"
# Адрес для получения ответа
get_result_url = "https://api.anti-captcha.com/getTaskResult"
# ключ приложения
app_key = "867"


# Connection retry generator
def attempts_generator(amount: int = 5) -> Generator:
Expand Down
21 changes: 7 additions & 14 deletions src/python3_anticaptcha/control.py
Original file line number Diff line number Diff line change
Expand Up @@ -158,8 +158,7 @@ async def aio_get_balance(self) -> dict:
Notes:
https://anti-captcha.com/apidoc/methods/getBalance
"""
self._captcha_handling_instrument = AIOCaptchaInstrument(captcha_params=self)
return await self._captcha_handling_instrument.send_post_request(
return await AIOCaptchaInstrument.send_post_request(
url_postfix=ControlPostfixEnm.GET_BALANCE, payload={"clientKey": self.create_task_payload.clientKey}
)

Expand Down Expand Up @@ -346,8 +345,7 @@ async def aio_get_spending_stats(self, **kwargs) -> dict:
Notes:
https://anti-captcha.com/apidoc/methods/getSpendingStats
"""
self._captcha_handling_instrument = AIOCaptchaInstrument(captcha_params=self)
return await self._captcha_handling_instrument.send_post_request(
return await AIOCaptchaInstrument.send_post_request(
url_postfix=ControlPostfixEnm.GET_SPENDING_STATS,
payload={"clientKey": self.create_task_payload.clientKey, **kwargs},
)
Expand Down Expand Up @@ -431,8 +429,7 @@ async def aio_get_app_stats(self, softId: int, mode: Optional[str] = None) -> di
Notes:
https://anti-captcha.com/apidoc/methods/getAppStats
"""
self._captcha_handling_instrument = AIOCaptchaInstrument(captcha_params=self)
return await self._captcha_handling_instrument.send_post_request(
return await AIOCaptchaInstrument.send_post_request(
url_postfix=ControlPostfixEnm.GET_APP_STATS,
payload={"clientKey": self.create_task_payload.clientKey, "softId": softId, "mode": mode},
)
Expand Down Expand Up @@ -480,8 +477,7 @@ async def aio_report_incorrect_image(self, taskId: int) -> dict:
Notes:
https://anti-captcha.com/apidoc/methods/reportIncorrectImageCaptcha
"""
self._captcha_handling_instrument = AIOCaptchaInstrument(captcha_params=self)
return await self._captcha_handling_instrument.send_post_request(
return await AIOCaptchaInstrument.send_post_request(
url_postfix=ControlPostfixEnm.REPORT_INCORRECT_IMAGE_CAPTCHA,
payload={"clientKey": self.create_task_payload.clientKey, "taskId": taskId},
)
Expand Down Expand Up @@ -529,8 +525,7 @@ async def aio_report_incorrect_recaptcha(self, taskId: int) -> dict:
Notes:
https://anti-captcha.com/apidoc/methods/reportIncorrectRecaptcha
"""
self._captcha_handling_instrument = AIOCaptchaInstrument(captcha_params=self)
return await self._captcha_handling_instrument.send_post_request(
return await AIOCaptchaInstrument.send_post_request(
url_postfix=ControlPostfixEnm.REPORT_INCORRECT_RECAPTCHA,
payload={"clientKey": self.create_task_payload.clientKey, "taskId": taskId},
)
Expand Down Expand Up @@ -578,8 +573,7 @@ async def aio_report_correct_recaptcha(self, taskId: int) -> dict:
Notes:
https://anti-captcha.com/apidoc/methods/reportCorrectRecaptcha
"""
self._captcha_handling_instrument = AIOCaptchaInstrument(captcha_params=self)
return await self._captcha_handling_instrument.send_post_request(
return await AIOCaptchaInstrument.send_post_request(
url_postfix=ControlPostfixEnm.REPORT_CORRECT_RECAPTCHA,
payload={"clientKey": self.create_task_payload.clientKey, "taskId": taskId},
)
Expand Down Expand Up @@ -627,8 +621,7 @@ async def aio_report_incorrect_hcaptcha(self, taskId: int) -> dict:
Notes:
https://anti-captcha.com/apidoc/methods/reportIncorrectHcaptcha
"""
self._captcha_handling_instrument = AIOCaptchaInstrument(captcha_params=self)
return await self._captcha_handling_instrument.send_post_request(
return await AIOCaptchaInstrument.send_post_request(
url_postfix=ControlPostfixEnm.REPORT_INCORRECT_HCAPTCHA,
payload={"clientKey": self.create_task_payload.clientKey, "taskId": taskId},
)
55 changes: 28 additions & 27 deletions src/python3_anticaptcha/core/aio_captcha_instrument.py
Original file line number Diff line number Diff line change
Expand Up @@ -101,16 +101,6 @@ async def __body_file_processing(
self.result.errorId = 12
self.result.errorCode = self.NO_CAPTCHA_ERR

async def _url_read(self, url: str, **kwargs) -> bytes:
"""
Async method read bytes from link
"""
async with aiohttp.ClientSession() as session:
async for attempt in ASYNC_RETRIES:
with attempt:
async with session.get(url=url, **kwargs) as resp:
return await resp.content.read()

async def _create_task(self, url_postfix: str = CREATE_TASK_POSTFIX) -> CreateTaskResponseSer:
"""
Function send SYNC request to service and wait for result
Expand All @@ -128,23 +118,6 @@ async def _create_task(self, url_postfix: str = CREATE_TASK_POSTFIX) -> CreateTa
logging.exception(error)
raise

@staticmethod
async def send_post_request(payload: Optional[dict] = None, url_postfix: str = CREATE_TASK_POSTFIX) -> dict:
"""
Function send ASYNC request to service and wait for result
"""

async with aiohttp.ClientSession() as session:
try:
async with session.post(parse.urljoin(BASE_REQUEST_URL, url_postfix), json=payload) as resp:
if resp.status == 200:
return await resp.json()
else:
raise ValueError(resp.reason)
except Exception as error:
logging.exception(error)
raise

async def _get_result(self, url_response: str = GET_RESULT_POSTFIX) -> dict:
attempts = attempts_generator()
# Send request for status of captcha solution.
Expand All @@ -166,3 +139,31 @@ async def _get_result(self, url_response: str = GET_RESULT_POSTFIX) -> dict:
else:
json_result.update({"taskId": self.captcha_params.get_result_params.taskId})
return json_result

@staticmethod
async def _url_read(url: str, **kwargs) -> bytes:
"""
Async method read bytes from link
"""
async with aiohttp.ClientSession() as session:
async for attempt in ASYNC_RETRIES:
with attempt:
async with session.get(url=url, **kwargs) as resp:
return await resp.content.read()

@staticmethod
async def send_post_request(payload: Optional[dict] = None, url_postfix: str = CREATE_TASK_POSTFIX) -> dict:
"""
Function send ASYNC request to service and wait for result
"""

async with aiohttp.ClientSession() as session:
try:
async with session.post(parse.urljoin(BASE_REQUEST_URL, url_postfix), json=payload) as resp:
if resp.status == 200:
return await resp.json()
else:
raise ValueError(resp.reason)
except Exception as error:
logging.exception(error)
raise
19 changes: 16 additions & 3 deletions src/python3_anticaptcha/core/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,14 @@
from .context_instr import AIOContextManager, SIOContextManager
from .captcha_instrument import CaptchaInstrument
from .aio_captcha_instrument import AIOCaptchaInstrument
from .sio_captcha_instrument import SIOCaptchaInstrument

__all__ = ("CaptchaParams",)

from .sio_captcha_instrument import SIOCaptchaInstrument


class CaptchaParams(SIOContextManager, AIOContextManager):
"""
Basic Captcha solving class
Basic Captcha params class
Args:
api_key: Capsolver API key
Expand All @@ -30,6 +29,20 @@ def __init__(self, api_key: str, sleep_time: int = 15, *args, **kwargs):

self._captcha_handling_instrument = CaptchaInstrument()

def set_callback_url(self, callbackUrl: str) -> None:
"""
Method for `callbackUrl` param set.
Args:
callbackUrl: Optional web address where we can send the results of captcha task processing.
Contents are sent by AJAX POST request and are identical
to the contents of getTaskResult method.
Notes:
https://anti-captcha.com/apidoc/methods/createTask
"""
self.create_task_payload.callbackUrl = callbackUrl

def captcha_handler(self, **additional_params) -> dict:
"""
Synchronous method for captcha solving
Expand Down
1 change: 1 addition & 0 deletions src/python3_anticaptcha/core/serializer.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ class BaseAPIRequestSer(MyBaseModel):
class CreateTaskBaseSer(BaseAPIRequestSer):
task: Dict = {}
softId: Literal[APP_KEY] = APP_KEY
callbackUrl: str = ""


class BaseAPIResponseSer(MyBaseModel):
Expand Down
38 changes: 19 additions & 19 deletions src/python3_anticaptcha/core/sio_captcha_instrument.py
Original file line number Diff line number Diff line change
Expand Up @@ -123,25 +123,6 @@ def _create_task(self, url_postfix: str = CREATE_TASK_POSTFIX) -> CreateTaskResp
logging.exception(error)
raise

@staticmethod
def send_post_request(
payload: Optional[dict] = None,
session: requests.Session = requests.Session(),
url_postfix: str = CREATE_TASK_POSTFIX,
) -> dict:
"""
Function send SYNC request to service and wait for result
"""
try:
resp = session.post(parse.urljoin(BASE_REQUEST_URL, url_postfix), json=payload)
if resp.status_code == 200:
return resp.json()
else:
raise ValueError(resp.raise_for_status())
except Exception as error:
logging.exception(error)
raise

def _url_read(self, url: str, **kwargs):
"""
Method open links
Expand All @@ -166,3 +147,22 @@ def _get_result(self, url_response: str = GET_RESULT_POSTFIX) -> dict:
else:
self.session.close()
return captcha_response.to_dict()

@staticmethod
def send_post_request(
payload: Optional[dict] = None,
session: requests.Session = requests.Session(),
url_postfix: str = CREATE_TASK_POSTFIX,
) -> dict:
"""
Function send SYNC request to service and wait for result
"""
try:
resp = session.post(parse.urljoin(BASE_REQUEST_URL, url_postfix), json=payload)
if resp.status_code == 200:
return resp.json()
else:
raise ValueError(resp.raise_for_status())
except Exception as error:
logging.exception(error)
raise
2 changes: 2 additions & 0 deletions src/python3_anticaptcha/custom_task.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
from .core.base import CaptchaParams
from .core.enum import ProxyTypeEnm, CaptchaTypeEnm

__all__ = ("CustomTask",)


class CustomTask(CaptchaParams):
def __init__(
Expand Down
2 changes: 2 additions & 0 deletions src/python3_anticaptcha/fun_captcha.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
from .core.base import CaptchaParams
from .core.enum import ProxyTypeEnm, CaptchaTypeEnm

__all__ = ("FunCaptcha",)


class FunCaptcha(CaptchaParams):
def __init__(
Expand Down
2 changes: 2 additions & 0 deletions src/python3_anticaptcha/gee_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
from .core.base import CaptchaParams
from .core.enum import ProxyTypeEnm, CaptchaTypeEnm

__all__ = ("GeeTest",)


class GeeTest(CaptchaParams):
def __init__(
Expand Down
2 changes: 2 additions & 0 deletions src/python3_anticaptcha/recaptcha_v2.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
from .core.base import CaptchaParams
from .core.enum import ProxyTypeEnm, CaptchaTypeEnm

__all__ = ("ReCaptchaV2",)


class ReCaptchaV2(CaptchaParams):
def __init__(
Expand Down
2 changes: 2 additions & 0 deletions src/python3_anticaptcha/recaptcha_v3.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
from .core.base import CaptchaParams
from .core.enum import CaptchaTypeEnm

__all__ = ("ReCaptchaV3",)


class ReCaptchaV3(CaptchaParams):
def __init__(
Expand Down
2 changes: 2 additions & 0 deletions src/python3_anticaptcha/turnstile.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
from .core.base import CaptchaParams
from .core.enum import ProxyTypeEnm, CaptchaTypeEnm

__all__ = ("Turnstile",)


class Turnstile(CaptchaParams):
def __init__(
Expand Down
10 changes: 10 additions & 0 deletions tests/test_core.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,16 @@ async def test_aio_create_base_context(self):
) as instance:
pass

def test_set_callback_url(self):
callback_string = self.get_random_string()
instance = CaptchaParams(
api_key=self.get_random_string(32),
sleep_time=self.sleep_time,
)
instance.set_callback_url(callbackUrl=callback_string)

assert instance.create_task_payload.callbackUrl == callback_string


class TestConfig(BaseTest):
def test_attempts_generator(self):
Expand Down

0 comments on commit 3add3f6

Please sign in to comment.