capmonster-python 3.1.0__py3-none-any.whl → 4.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. capmonster_python/__init__.py +33 -12
  2. capmonster_python/client.py +245 -0
  3. capmonster_python/exceptions.py +60 -0
  4. capmonster_python/methods.py +32 -0
  5. capmonster_python/tasks/__init__.py +42 -0
  6. capmonster_python/tasks/basilisk.py +24 -0
  7. capmonster_python/tasks/binance.py +31 -0
  8. capmonster_python/tasks/complex_image_recaptcha.py +73 -0
  9. capmonster_python/tasks/complex_image_recognition.py +33 -0
  10. capmonster_python/tasks/datadome.py +62 -0
  11. capmonster_python/tasks/geetest.py +86 -0
  12. capmonster_python/tasks/image_to_text.py +37 -0
  13. capmonster_python/tasks/imperva.py +50 -0
  14. capmonster_python/tasks/prosopo.py +27 -0
  15. capmonster_python/tasks/recaptcha_v2.py +40 -0
  16. capmonster_python/tasks/recaptcha_v2_enterprise.py +40 -0
  17. capmonster_python/tasks/recaptcha_v3.py +30 -0
  18. capmonster_python/tasks/task.py +146 -0
  19. capmonster_python/tasks/temu.py +32 -0
  20. capmonster_python/tasks/tendi.py +30 -0
  21. capmonster_python/tasks/turnstile.py +82 -0
  22. capmonster_python-4.0.0.dist-info/METADATA +150 -0
  23. capmonster_python-4.0.0.dist-info/RECORD +26 -0
  24. {capmonster_python-3.1.0.dist-info → capmonster_python-4.0.0.dist-info}/WHEEL +1 -1
  25. capmonster_python/capmonster.py +0 -253
  26. capmonster_python/compleximage.py +0 -51
  27. capmonster_python/datadome.py +0 -19
  28. capmonster_python/fun_captcha.py +0 -30
  29. capmonster_python/geetest.py +0 -26
  30. capmonster_python/hcaptcha.py +0 -36
  31. capmonster_python/image_to_text.py +0 -43
  32. capmonster_python/recaptcha_v2.py +0 -27
  33. capmonster_python/recaptcha_v2_enterprise.py +0 -30
  34. capmonster_python/recaptcha_v3.py +0 -24
  35. capmonster_python/tendi.py +0 -19
  36. capmonster_python/turnstile.py +0 -23
  37. capmonster_python/utils.py +0 -35
  38. capmonster_python-3.1.0.dist-info/METADATA +0 -120
  39. capmonster_python-3.1.0.dist-info/RECORD +0 -19
  40. {capmonster_python-3.1.0.dist-info → capmonster_python-4.0.0.dist-info/licenses}/LICENSE +0 -0
  41. {capmonster_python-3.1.0.dist-info → capmonster_python-4.0.0.dist-info}/top_level.txt +0 -0
@@ -1,12 +1,33 @@
1
- from .recaptcha_v2 import RecaptchaV2Task
2
- from .recaptcha_v2_enterprise import RecaptchaV2EnterpriseTask
3
- from .fun_captcha import FuncaptchaTask
4
- from .recaptcha_v3 import RecaptchaV3Task
5
- from .hcaptcha import HCaptchaTask
6
- from .image_to_text import ImageToTextTask
7
- from .geetest import GeeTestTask
8
- from .utils import CapmonsterException
9
- from .compleximage import ComplexImageTask
10
- from .datadome import DataDomeTask
11
- from .turnstile import TurnstileTask
12
- from .tendi import TenDITask
1
+ from .client import CapmonsterClient
2
+ from .exceptions import *
3
+ from .tasks import *
4
+
5
+ __all__ = [
6
+ "CapmonsterClient",
7
+ "VanillaTaskPayload",
8
+ "ProxyPayload",
9
+ "UserAgentPayload",
10
+ "BasiliskTask",
11
+ "BinanceTask",
12
+ "ComplexImageRecaptchaTask",
13
+ "ComplexImageRecaptchaMetadata",
14
+ "ComplexImageRecognitionTask",
15
+ "DataDomeTask",
16
+ "DataDomeMetadata",
17
+ "GeeTestV3Task",
18
+ "GeeTestV4Task",
19
+ "ImageToTextTask",
20
+ "ImpervaTask",
21
+ "ImpervaTaskMetadata",
22
+ "ProsopoTask",
23
+ "RecaptchaV2Task",
24
+ "RecaptchaV2EnterpriseTask",
25
+ "RecaptchaV3Task",
26
+ "TemuTask",
27
+ "TenDITask",
28
+ "TurnstileTask",
29
+ "TurnstileCloudFlareTask",
30
+ "CapmonsterException",
31
+ "CapmonsterAPIException",
32
+ "CapmonsterValidationException"
33
+ ]
@@ -0,0 +1,245 @@
1
+ import asyncio
2
+ from time import sleep
3
+ from typing import Optional
4
+
5
+ from httpx import Response, AsyncClient, Client
6
+
7
+ from .exceptions import CapmonsterAPIException, CapmonsterException
8
+ from .methods import GetBalancePayload, GetTaskResultPayload, CreateTaskPayload
9
+ from .tasks.task import TaskPayload
10
+
11
+
12
+ class CapmonsterClient:
13
+ __BASE_URL = "https://api.capmonster.cloud"
14
+ __BALANCE_URL = "/getBalance"
15
+ __TASK_RESULT_URL = "/getTaskResult"
16
+ __CREATE_TASK_URL = "/createTask"
17
+ __MAX_RETRY = 120
18
+ __PER_RETRY_DELAY = 1
19
+
20
+ def __init__(self, api_key: str, timeout: Optional[float] = 30.0) -> None:
21
+ self.api_key = api_key
22
+ self.__async_client = AsyncClient(timeout=timeout, base_url=self.__BASE_URL)
23
+ self.__sync_client = Client(timeout=timeout, base_url=self.__BASE_URL)
24
+
25
+ def get_balance(self) -> float:
26
+ """
27
+ Fetches the current balance using the provided API key.
28
+
29
+ Raises:
30
+ This method may raise exceptions if the HTTP request fails or the JSON response
31
+ format is unexpected. These exceptions are not handled within the method.
32
+
33
+ Returns:
34
+ float: The balance fetched from the external service. Defaults to 0.0 if the balance
35
+ key is not found in the response.
36
+ """
37
+ payload = GetBalancePayload(clientKey=self.api_key).model_dump()
38
+ response = self.__make_sync_request(self.__BALANCE_URL, payload).json()
39
+ return response.get("balance", 0.0)
40
+
41
+ async def get_balance_async(self) -> float:
42
+ """
43
+ Asynchronously fetches the current balance using the provided API key.
44
+
45
+ Raises:
46
+ This method may raise exceptions if the HTTP request fails or the JSON response
47
+ format is unexpected. These exceptions are not handled within the method.
48
+
49
+ Returns:
50
+ float: The balance fetched from the external service. Defaults to 0.0 if the balance
51
+ key is not found in the response.
52
+ """
53
+ payload = GetBalancePayload(clientKey=self.api_key).model_dump()
54
+ response = await self.__make_async_request(self.__BALANCE_URL, payload)
55
+ return response.json().get("balance", 0.0)
56
+
57
+ def create_task(self, task: TaskPayload, callback_url: Optional[str] = None) -> int:
58
+ """
59
+ Creates a task based on the provided payload and returns the task ID.
60
+
61
+ This method is responsible for initiating a task by preparing the request with the
62
+ provided task details and optional callback URL, sending a synchronous request to the
63
+ task creation endpoint, and parsing the response to retrieve the task ID.
64
+
65
+ Args:
66
+ task: The task configuration payload that defines the specifics of the task to be
67
+ created.
68
+ callback_url: An optional URL to be called back upon task completion or update.
69
+
70
+ Returns:
71
+ The unique identifier of the created task.
72
+
73
+ Raises:
74
+ CapmonsterException: If the task creation request fails or the response is not contains valid task id.
75
+ """
76
+ payload = CreateTaskPayload(clientKey=self.api_key, task=task, callbackUrl=callback_url).model_dump(
77
+ exclude_none=True)
78
+ payload["softId"] = 30
79
+ response = self.__make_sync_request(self.__CREATE_TASK_URL, payload).json()
80
+ return response.get("taskId", 0)
81
+
82
+ async def create_task_async(self, task: TaskPayload, callback_url: Optional[str] = None) -> int:
83
+ """
84
+ Asynchronously creates a task based on the provided payload and returns the task ID.
85
+
86
+ This method is responsible for initiating a task by preparing the request with the
87
+ provided task details and optional callback URL, sending a synchronous request to the
88
+ task creation endpoint, and parsing the response to retrieve the task ID.
89
+
90
+ Args:
91
+ task: The task configuration payload that defines the specifics of the task to be
92
+ created.
93
+ callback_url: An optional URL to be called back upon task completion or update.
94
+
95
+ Returns:
96
+ The unique identifier of the created task.
97
+
98
+ Raises:
99
+ CapmonsterException: If the task creation request fails or the response is not contains valid task id.
100
+ """
101
+ payload = CreateTaskPayload(clientKey=self.api_key, task=task, callbackUrl=callback_url).model_dump(
102
+ exclude_none=True)
103
+ payload["softId"] = 30
104
+ request = await self.__make_async_request(self.__CREATE_TASK_URL, payload)
105
+ response = request.json()
106
+ return response.get("taskId", 0)
107
+
108
+ def get_task_result(self, task_id: int) -> dict:
109
+ """
110
+ Fetches the result of a specific task by its identifier.
111
+
112
+ This function interacts with API to retrieve the results of a
113
+ previously submitted task. The function uses the provided task ID and
114
+ sends a request to the API endpoint to get the result. It returns the
115
+ solution data extracted from the API response or an empty dictionary if
116
+ no solution data is found.
117
+
118
+ Args:
119
+ task_id (int): An integer representing the unique identifier of the task.
120
+
121
+ Returns:
122
+ dict: A dictionary containing the solution data retrieved from the task
123
+ result API endpoint. If the solution is not found in the response, an empty
124
+ dictionary is returned.
125
+ """
126
+ payload = GetTaskResultPayload(clientKey=self.api_key, taskId=task_id).model_dump()
127
+ response = self.__make_sync_request(self.__TASK_RESULT_URL, payload).json()
128
+ return response.get("solution", {})
129
+
130
+ async def get_task_result_async(self, task_id: int) -> dict:
131
+ """
132
+ Asynchronously fetches the result of a specific task by its identifier.
133
+
134
+ This function interacts with API to retrieve the results of a
135
+ previously submitted task. The function uses the provided task ID and
136
+ sends a request to the API endpoint to get the result. It returns the
137
+ solution data extracted from the API response or an empty dictionary if
138
+ no solution data is found.
139
+
140
+ Args:
141
+ task_id (int): An integer representing the unique identifier of the task.
142
+
143
+ Returns:
144
+ dict: A dictionary containing the solution data retrieved from the task
145
+ result API endpoint. If the solution is not found in the response, an empty
146
+ dictionary is returned.
147
+ """
148
+ payload = GetTaskResultPayload(clientKey=self.api_key, taskId=task_id).model_dump()
149
+ request = await self.__make_async_request(self.__TASK_RESULT_URL, payload)
150
+ response = request.json()
151
+ return response.get("solution", {})
152
+
153
+ def join_task_result(self, task_id: int) -> dict:
154
+ """
155
+ Joins and retrieves the result of a task given its ID, retrying a specified number
156
+ of times if the result is not immediately available.
157
+
158
+ Args:
159
+ task_id: The identifier of the task for which the result needs to be retrieved.
160
+
161
+ Returns:
162
+ dict:
163
+ The result of the task if successfully retrieved within the maximum retries.
164
+
165
+ Raises:
166
+ CapmonsterException:
167
+ If the maximum retry limit is exceeded without obtaining the task result.
168
+ """
169
+ for _ in range(0, self.__MAX_RETRY + 1):
170
+ result = self.get_task_result(task_id)
171
+ if result:
172
+ return result
173
+ elif not result:
174
+ sleep(self.__PER_RETRY_DELAY)
175
+ raise CapmonsterAPIException(
176
+ 61, "ERROR_MAXIMUM_TIME_EXCEED", "Maximum time is exceed.")
177
+
178
+ async def join_task_result_async(self, task_id: int):
179
+ """
180
+ Asynchronously joins and retrieves the result of a task given its ID, retrying a specified number
181
+ of times if the result is not immediately available.
182
+
183
+ Args:
184
+ task_id: The identifier of the task for which the result needs to be retrieved.
185
+
186
+ Returns:
187
+ dict:
188
+ The result of the task if successfully retrieved within the maximum retries.
189
+
190
+ Raises:
191
+ CapmonsterException:
192
+ If the maximum retry limit is exceeded without obtaining the task result.
193
+ """
194
+ for _ in range(0, self.__MAX_RETRY + 1):
195
+ result = await self.get_task_result_async(task_id)
196
+ if result:
197
+ return result
198
+ elif not result:
199
+ await asyncio.sleep(self.__PER_RETRY_DELAY)
200
+ raise CapmonsterAPIException(
201
+ 61, "ERROR_MAXIMUM_TIME_EXCEED", "Maximum time is exceed.")
202
+
203
+ def __make_sync_request(self, url: str, payload: dict) -> Response:
204
+ try:
205
+ response = self.__sync_client.post(url, json=payload)
206
+ return self.__check_response(response)
207
+ except Exception as e:
208
+ raise CapmonsterException(-1, type(e).__name__, str(e))
209
+
210
+ async def __make_async_request(self, url: str, payload: dict) -> Response:
211
+ try:
212
+ post = await self.__async_client.post(url, json=payload)
213
+ return self.__check_response(post)
214
+ except Exception as e:
215
+ raise CapmonsterException(-1, type(e).__name__, str(e))
216
+
217
+ @staticmethod
218
+ def __is_ready(response: dict):
219
+ status = response.get("status")
220
+ if status == "processing":
221
+ return False
222
+ elif status == "ready":
223
+ return True
224
+ else:
225
+ raise CapmonsterAPIException(error_id=-1,
226
+ error_code="CAPMONSTER_API_ERROR",
227
+ error_description="Sometimes can be happen if Capmonster "
228
+ "servers there is too much intensity")
229
+
230
+ @staticmethod
231
+ def __check_response(data: Response) -> Response:
232
+ response = data.json()
233
+ if type(response) is dict:
234
+ if response.get("errorId", 0) != 0:
235
+ raise CapmonsterAPIException(
236
+ response.get("errorId"),
237
+ response.get("errorCode", response.get("errorCode", "UNKNOWN_ERROR")),
238
+ response.get("errorDescription", response.get("errorDescription", "Unknown error"))
239
+ )
240
+ return data
241
+ else:
242
+ raise CapmonsterAPIException(error_id=-1,
243
+ error_code="CAPMONSTER_API_ERROR",
244
+ error_description="Sometimes can be happen if Capmonster "
245
+ "servers there is too much intensity")
@@ -0,0 +1,60 @@
1
+ class CapmonsterException(Exception):
2
+ """
3
+ Generic exception class for all errors.
4
+
5
+ Notes:
6
+ This will be raised for errors that are not caught elsewhere.
7
+ These errors can be related HTTP requests, API responses, or other issues.
8
+ """
9
+ pass
10
+
11
+
12
+ class CapmonsterAPIException(CapmonsterException):
13
+ """
14
+ Raised when the Capmonster API returns an error.
15
+
16
+ Attributes:
17
+ error_id: The error ID returned by the API.
18
+ error_code: The error code returned by the API.
19
+ error_description: The error description returned by the API.
20
+
21
+ Notes:
22
+ - Error codes are defined in the API documentation.
23
+ """
24
+
25
+ def __init__(self, error_id, error_code, error_description, *args, **kwargs):
26
+ super(CapmonsterAPIException, self).__init__("[{}:{}]{}".format(error_code, error_id, error_description))
27
+ self.error_description = error_description
28
+ self.error_id = error_id
29
+ self.error_code = error_code
30
+
31
+ def __str__(self):
32
+ return "[{}] {}".format(self.error_code, self.error_description)
33
+
34
+
35
+ class CapmonsterValidationException(CapmonsterException):
36
+ """
37
+ Raised when a Capmonster task configuration is invalid.
38
+
39
+ Attributes:
40
+ message: The error message describing the invalid configuration.
41
+ field: The field in the configuration that caused the error, if applicable.
42
+ task: The task type that caused the error, if applicable.
43
+
44
+ Notes:
45
+ - This error only raises when the validation fails within the SDK task creation.
46
+ """
47
+
48
+ def __init__(self, message: str, *, field: str = None, task: str = None):
49
+ self.message = message
50
+ self.field = field
51
+ self.task = task
52
+ super().__init__(self._format_message())
53
+
54
+ def _format_message(self) -> str:
55
+ base = f"[CapmonsterValidationError] {self.message}"
56
+ if self.field:
57
+ base += f" (field: {self.field})"
58
+ if self.task:
59
+ base += f" [task: {self.task}]"
60
+ return base
@@ -0,0 +1,32 @@
1
+ from typing import Optional
2
+
3
+ from pydantic import BaseModel, Field, field_serializer
4
+
5
+ from .tasks.task import TaskPayload
6
+
7
+
8
+ class GetBalancePayload(BaseModel):
9
+ """
10
+ Represents a payload for retrieving the balance.
11
+
12
+ Attributes:
13
+ clientKey (str): The key representing the client, used for identifying
14
+ the client in balance-related operations.
15
+ """
16
+ clientKey: str = Field(..., description="Client key")
17
+
18
+
19
+ class GetTaskResultPayload(BaseModel):
20
+ clientKey: str = Field(..., description="Client key")
21
+ taskId: int = Field(..., description="ID which was obtained from create task method.")
22
+
23
+
24
+ class CreateTaskPayload(BaseModel):
25
+ clientKey: str = Field(..., description="Client key")
26
+ task: TaskPayload = Field(..., description="Task data")
27
+ callbackUrl: Optional[str] = Field(default=None,
28
+ description="Web address for sending the captcha task result. Data is sent by POST request.")
29
+
30
+ @field_serializer("task")
31
+ def serialize_task(self, task: TaskPayload, _info) -> dict:
32
+ return task.to_request()
@@ -0,0 +1,42 @@
1
+ from .basilisk import BasiliskTask
2
+ from .binance import BinanceTask
3
+ from .complex_image_recaptcha import ComplexImageRecaptchaTask, ComplexImageRecaptchaMetadata
4
+ from .complex_image_recognition import ComplexImageRecognitionTask
5
+ from .datadome import DataDomeTask, DataDomeMetadata
6
+ from .geetest import GeeTestV4Task, GeeTestV3Task
7
+ from .image_to_text import ImageToTextTask
8
+ from .imperva import ImpervaTask, ImpervaTaskMetadata
9
+ from .prosopo import ProsopoTask
10
+ from .recaptcha_v2 import RecaptchaV2Task
11
+ from .recaptcha_v2_enterprise import RecaptchaV2EnterpriseTask
12
+ from .recaptcha_v3 import RecaptchaV3Task
13
+ from .task import VanillaTaskPayload, ProxyPayload, UserAgentPayload
14
+ from .temu import TemuTask
15
+ from .tendi import TenDITask
16
+ from .turnstile import TurnstileTask, TurnstileCloudFlareTask
17
+
18
+ __all__ = [
19
+ "VanillaTaskPayload",
20
+ "ProxyPayload",
21
+ "UserAgentPayload",
22
+ "BasiliskTask",
23
+ "BinanceTask",
24
+ "ComplexImageRecaptchaTask",
25
+ "ComplexImageRecaptchaMetadata",
26
+ "ComplexImageRecognitionTask",
27
+ "DataDomeTask",
28
+ "DataDomeMetadata",
29
+ "GeeTestV3Task",
30
+ "GeeTestV4Task",
31
+ "ImageToTextTask",
32
+ "ImpervaTask",
33
+ "ImpervaTaskMetadata",
34
+ "ProsopoTask",
35
+ "RecaptchaV2Task",
36
+ "RecaptchaV2EnterpriseTask",
37
+ "RecaptchaV3Task",
38
+ "TemuTask",
39
+ "TenDITask",
40
+ "TurnstileTask",
41
+ "TurnstileCloudFlareTask"
42
+ ]
@@ -0,0 +1,24 @@
1
+ from typing import Any
2
+
3
+ from pydantic import Field
4
+
5
+ from .task import TaskPayload, UserAgentPayload
6
+
7
+
8
+ class BasiliskTask(TaskPayload, UserAgentPayload):
9
+ """
10
+ BasiliskTask represents a specific task payload used for solving captcha on a given website.
11
+
12
+ Attributes:
13
+ websiteURL (str): The address of the main page where the captcha is solved.
14
+ websiteKey (str): Can be found in the html code in the attribute data-sitekey of the captcha container or in
15
+ the payload of a POST request to the https://basiliskcaptcha.com/challenge/check-site in the field site_key.
16
+ """
17
+ type: str = Field(default="CustomTask", frozen=True)
18
+ class_: str = Field(default="Basilisk", alias="class", frozen=True)
19
+ websiteURL: str = Field(..., description="The address of the main page where the captcha is solved.")
20
+ websiteKey: str = Field(...,
21
+ description="Can be found in the html code in the attribute data-sitekey of the captcha container.")
22
+
23
+ def to_request(self) -> dict[str, Any]:
24
+ return self.model_dump(exclude_none=True, by_alias=True)
@@ -0,0 +1,31 @@
1
+ from typing import Optional, Any
2
+
3
+ from pydantic import Field
4
+
5
+ from .task import TaskPayload, UserAgentPayload, ProxyPayload
6
+
7
+
8
+ class BinanceTask(TaskPayload, UserAgentPayload):
9
+ """
10
+ Represents a Binance task to solve captcha challenges with a specific payload. Use only to log in with your account.
11
+
12
+ Attributes:
13
+ websiteURL: The address of the main page where the captcha is solved.
14
+ websiteKey: A unique parameter for your website's section.
15
+ validateId: A dynamic key representing the value of the parameter validateId, securityId, or
16
+ securityCheckResponseValidateId.
17
+ proxy: Optional proxy settings used for handling requests during captcha solving.
18
+ """
19
+ type: str = Field(default="BinanceTask", frozen=True)
20
+ websiteURL: str = Field(..., description="The address of the main page where the captcha is solved.")
21
+ websiteKey: str = Field(..., description="A unique parameter for your website's section.")
22
+ validateId: str = Field(..., description="A dynamic key. The value of the parameter validateId, securityId, "
23
+ "or securityCheckResponseValidateId.")
24
+ proxy: Optional[ProxyPayload] = Field(default=None, description="Proxy settings.")
25
+
26
+ def to_request(self) -> dict[str, Any]:
27
+ base = self.model_dump(exclude_none=True, by_alias=True)
28
+ proxy_dict = base.pop("proxy", {})
29
+ if proxy_dict:
30
+ base.update(proxy_dict)
31
+ return base
@@ -0,0 +1,73 @@
1
+ from typing import List, Literal, Optional, Any
2
+
3
+ from pydantic import Field, BaseModel, model_validator
4
+
5
+ from .task import TaskPayload
6
+ from ..exceptions import CapmonsterValidationException
7
+
8
+
9
+ class ComplexImageRecaptchaMetadata(BaseModel):
10
+ """
11
+ Represents metadata for a complex image-based CAPTCHA task.
12
+
13
+ Attributes:
14
+ task: Optional. Represents the textual description of the CAPTCHA task
15
+ (e.g., "Click on traffic lights"). Only one of `task` or `taskDefinition`
16
+ must be set.
17
+ taskDefinition: Optional. Represents the technical value defining the CAPTCHA
18
+ task type. Only one of `task` or `taskDefinition` must be set.
19
+ grid: Required. Specifies the grid size of the CAPTCHA. It must be one of
20
+ the possible values: "4x4", "3x3", or "1x1".
21
+ """
22
+ task: Optional[str] = Field(default=None, alias="Task",
23
+ description="Possible values: \"Click on traffic lights\" and others.")
24
+ taskDefinition: Optional[str] = Field(default=None, alias="TaskDefinition",
25
+ description="Technical value that defines the task type.")
26
+ grid: Literal["4x4", "3x3", "1x1"] = Field(..., alias="Grid",
27
+ description="Grid size of the captcha part.")
28
+
29
+ @model_validator(mode="after")
30
+ def check_fields_match_type(self) -> "ComplexImageRecaptchaMetadata":
31
+ if self.task is None and self.taskDefinition is None:
32
+ raise ValueError("task or taskDefinition must be set")
33
+ if self.task is not None and self.taskDefinition is not None:
34
+ raise ValueError("only one of task or taskDefinition must be set")
35
+ return self
36
+
37
+
38
+ class ComplexImageRecaptchaTask(TaskPayload):
39
+ """
40
+ Represents a task payload for solving complex image-based recaptcha challenges.
41
+
42
+ Attributes:
43
+ imageUrls: Optional list of image URLs associated with the captcha. These may
44
+ correspond to a single image captcha of formats 4x4, 3x3, or other new
45
+ configurations.
46
+ imagesBase64: Optional list of base64-encoded images. Similar to imageUrls,
47
+ these represent segments of the captcha in various formats such as 4x4,
48
+ 3x3, or others.
49
+ metadata: Metadata describing additional details required for solving the recaptcha
50
+ challenge. This attribute must be provided.
51
+
52
+ Raises:
53
+ CapmonsterValidationException: If neither `imageUrls` nor `imagesBase64` is provided,
54
+ or if both are provided at the same time.
55
+ """
56
+ type: str = Field(default="ComplexImageTask", frozen=True)
57
+ class_: str = Field(default="recaptcha", alias="class", frozen=True)
58
+ imageUrls: Optional[List[str]] = Field(default=None,
59
+ description="Single image 4x4, 3x3 or a new 1x1 captcha part (in an array).")
60
+ imagesBase64: Optional[List[str]] = Field(default=None,
61
+ description="Single image 4x4, 3x3 or a new 1x1 captcha part in base64 format (in an array).")
62
+ metadata: ComplexImageRecaptchaMetadata = Field(..., description="Metadata for the task.")
63
+
64
+ @model_validator(mode="after")
65
+ def check_fields_match_type(self) -> "ComplexImageRecaptchaTask":
66
+ if self.imageUrls is None and self.imagesBase64 is None:
67
+ raise CapmonsterValidationException("imageUrls or imagesBase64 must be set")
68
+ if self.imageUrls is not None and self.imagesBase64 is not None:
69
+ raise CapmonsterValidationException("only one of imageUrls or imagesBase64 must be set")
70
+ return self
71
+
72
+ def to_request(self) -> dict[str, Any]:
73
+ return self.model_dump(exclude_none=True, by_alias=True)
@@ -0,0 +1,33 @@
1
+ from typing import List, Literal, Any
2
+
3
+ from pydantic import Field
4
+
5
+ from .task import TaskPayload
6
+
7
+
8
+ class ComplexImageRecognitionTask(TaskPayload):
9
+ """
10
+ Represents a complex image recognition task payload.
11
+
12
+ Attributes:
13
+ imagesBase64: List of base64 encoded images. This is required and contains
14
+ raw image data in base64 format.
15
+ task: A string indicating one of the predefined types of recognition
16
+ task. This must be one of "oocl_rotate_new", "oocl_rotate_double_new",
17
+ "betpunch_3x3_rotate", "bls", "shein".
18
+ """
19
+ type: str = Field(default="ComplexImageTask", frozen=True)
20
+ class_: str = Field(default="recognition", alias="class", frozen=True)
21
+ imagesBase64: List[str] = Field(..., description="List of base64 encoded images.")
22
+ task: Literal["oocl_rotate_new", "oocl_rotate_double_new", "betpunch_3x3_rotate", "bls", "shein"] = Field(...,
23
+ description="Type of task.")
24
+
25
+ def to_request(self) -> dict[str, Any]:
26
+ base = self.model_dump(exclude_none=True, by_alias=True)
27
+ task = base.pop("task")
28
+
29
+ if "metadata" not in base:
30
+ base["metadata"] = {}
31
+
32
+ base["metadata"]["Task"] = task
33
+ return base
@@ -0,0 +1,62 @@
1
+ from typing import Optional, Any
2
+
3
+ from pydantic import Field, BaseModel, model_validator
4
+
5
+ from .task import TaskPayload, UserAgentPayload, ProxyPayload
6
+ from ..exceptions import CapmonsterValidationException
7
+
8
+
9
+ class DataDomeMetadata(BaseModel):
10
+ """
11
+ Represents metadata related to DataDome.
12
+
13
+ Attributes:
14
+ htmlPageBase64: Optional; Contains additional data about the captcha in
15
+ Base64-encoded format.
16
+ captchaUrl: Optional; URL pointing to the captcha, typically formatted
17
+ like: "https://geo.captcha-delivery.com/captcha/?initialCid=...".
18
+ datadomeCookie: Mandatory; Stores the DataDome cookies, retrievable on
19
+ the page using `document.cookie`.
20
+
21
+ Raises:
22
+ CapmonsterValidationException: If neither `htmlPageBase64` nor `captchaUrl` is provided,
23
+ or if both are provided at the same time.
24
+ """
25
+ htmlPageBase64: Optional[str] = Field(default=None,
26
+ description="Object that contains additional data about the captcha.")
27
+ captchaUrl: Optional[str] = Field(default=None,
28
+ description="\"captchaUrl\" - link to the captcha. Usually it looks like this: \"https://geo.captcha-delivery.com/captcha/?initialCid=...\"")
29
+ datadomeCookie: str = Field(...,
30
+ description="Your cookies from datadome. You can get it on the page using document.cookie")
31
+
32
+ @model_validator(mode="after")
33
+ def validate_fields(self) -> "DataDomeMetadata":
34
+ if self.htmlPageBase64 is None and self.captchaUrl is None:
35
+ raise CapmonsterValidationException("htmlPageBase64 or captchaUrl required.")
36
+ if self.htmlPageBase64 is not None and self.captchaUrl is not None:
37
+ raise CapmonsterValidationException("htmlPageBase64 and captchaUrl are mutually exclusive.")
38
+ return self
39
+
40
+
41
+ class DataDomeTask(TaskPayload, UserAgentPayload):
42
+ """
43
+ Represents a task payload for solving captchas on the DataDome platform.
44
+
45
+ Attributes:
46
+ websiteURL: A string that contains the address of the page where the captcha is solved.
47
+ proxy: Optional proxy settings, represented as a ProxyPayload. Defaults to None.
48
+ metadata: Additional metadata about the captcha, represented as a DataDomeMetadata.
49
+ Defaults to None.
50
+ """
51
+ type: str = Field(default="CustomTask", frozen=True)
52
+ class_: str = Field(default="DataDome", alias="class", frozen=True)
53
+ websiteURL: str = Field(..., description="Address of the page on which the captcha is solved.")
54
+ proxy: Optional[ProxyPayload] = Field(default=None, description="Proxy settings.")
55
+ metadata: DataDomeMetadata = Field(default=None, description="Additional data about the captcha.")
56
+
57
+ def to_request(self) -> dict[str, Any]:
58
+ base = self.model_dump(exclude_none=True, by_alias=True)
59
+ proxy_dict = base.pop("proxy", {})
60
+ if proxy_dict:
61
+ base.update(proxy_dict)
62
+ return base