forked from Theyka/Turnstile-Solver
-
Notifications
You must be signed in to change notification settings - Fork 0
/
async_solver.py
225 lines (192 loc) · 8.2 KB
/
async_solver.py
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
import asyncio
import time
from typing import Dict, Optional
from dataclasses import dataclass
from patchright.async_api import async_playwright, Page, BrowserContext
from logmagix import Logger, Loader
from functools import wraps
DEBUG = False
def set_debug(value: bool):
global DEBUG
DEBUG = value
def debug(func_or_message, *args, **kwargs):
global DEBUG
if callable(func_or_message):
@wraps(func_or_message)
async def wrapper(*args, **kwargs):
result = await func_or_message(*args, **kwargs)
if DEBUG:
Logger().debug(f"{func_or_message.__name__} returned: {result}")
return result
return wrapper
else:
if DEBUG:
Logger().debug(f"Debug: {func_or_message}")
@dataclass
class TurnstileResult:
turnstile_value: Optional[str]
elapsed_time_seconds: float
status: str
reason: Optional[str] = None
class AsyncTurnstileSolver:
HTML_TEMPLATE = """
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Turnstile Solver</title>
<script
src="https://challenges.cloudflare.com/turnstile/v0/api.js?onload=onloadTurnstileCallback"
async=""
defer=""
></script>
</head>
<body>
<!-- cf turnstile -->
</body>
</html>
"""
def __init__(self, debug: bool = False):
global DEBUG
DEBUG = debug
self.debug = debug
self.log = Logger(github_repository="https://github.com/sexfrance/Turnstile-Solver")
self.loader = Loader(desc="Solving captcha...", timeout=0.05)
self.browser_args = [
"--disable-blink-features=AutomationControlled",
"--no-sandbox",
"--disable-dev-shm-usage",
"--disable-background-networking",
"--disable-background-timer-throttling",
"--disable-backgrounding-occluded-windows",
"--disable-renderer-backgrounding",
"--window-position=2000,2000",
]
@debug
async def _setup_page(self, context: BrowserContext, url: str, sitekey: str = None) -> Page:
"""Set up the page with or without Turnstile widget."""
page = await context.new_page()
url_with_slash = url + "/" if not url.endswith("/") else url
debug(f"Navigating to URL: {url_with_slash}")
if sitekey:
turnstile_div = f'<div class="cf-turnstile" data-sitekey="{sitekey}" data-theme="light"></div>'
page_data = self.HTML_TEMPLATE.replace("<!-- cf turnstile -->", turnstile_div)
await page.route(url_with_slash, lambda route: route.fulfill(body=page_data, status=200))
await page.goto(url_with_slash)
return page
@debug
async def _get_turnstile_response(self, page: Page, max_attempts: int = 10, invisible: bool = False) -> Optional[str]:
"""Attempt to retrieve Turnstile response."""
attempts = 0
while attempts < max_attempts:
turnstile_check = await page.eval_on_selector(
"[name=cf-turnstile-response]",
"el => el.value"
)
if turnstile_check == "":
debug(f"Attempt {attempts + 1}: No Turnstile response yet.")
if not invisible:
await page.evaluate("document.querySelector('.cf-turnstile').style.width = '70px'")
await page.click(".cf-turnstile")
await asyncio.sleep(0.5)
attempts += 1
else:
turnstile_element = await page.query_selector("[name=cf-turnstile-response]")
if turnstile_element:
return await turnstile_element.get_attribute("value")
break
return None
async def solve(self, url: str, sitekey: str = None, headless: bool = False, invisible: bool = False, cookies: dict = None) -> TurnstileResult:
"""
Solve the Turnstile challenge and return the result.
Args:
url: The URL where the Turnstile challenge is hosted
sitekey: The Turnstile sitekey
headless: Whether to run the browser in headless mode
invisible: Whether the Turnstile challenge is invisible
cookies: Optional dictionary of cookies to set
Returns:
TurnstileResult object containing the solution details
"""
self.loader.start()
start_time = time.time()
try:
async with async_playwright() as playwright:
browser = await playwright.chromium.launch(headless=headless, args=self.browser_args)
context = await browser.new_context()
if cookies:
domain = url.split("//")[-1].split("/")[0]
cookie_list = []
for name, value in cookies.items():
cookie_list.append({
"name": name,
"value": str(value),
"domain": domain,
"path": "/"
})
if cookie_list:
await context.add_cookies(cookie_list)
try:
page = await self._setup_page(context, url, sitekey)
turnstile_value = await self._get_turnstile_response(page, invisible=invisible)
elapsed_time = round(time.time() - start_time, 3)
if not turnstile_value:
result = TurnstileResult(
turnstile_value=None,
elapsed_time_seconds=elapsed_time,
status="failure",
reason="Max attempts reached without token retrieval"
)
self.log.failure("Failed to retrieve Turnstile value.")
else:
result = TurnstileResult(
turnstile_value=turnstile_value,
elapsed_time_seconds=elapsed_time,
status="success"
)
self.loader.stop()
self.log.message(
"Cloudflare",
f"Successfully solved captcha: {turnstile_value[:45]}...",
start=start_time,
end=time.time()
)
except Exception as e:
self.log.failure(f"Error during captcha solving: {str(e)}")
raise
finally:
try:
await context.close()
await browser.close()
except Exception as e:
self.log.failure(f"Error closing browser: {str(e)}")
debug(f"Elapsed time: {result.elapsed_time_seconds} seconds")
debug("Browser closed. Returning result.")
except Exception as e:
elapsed_time = round(time.time() - start_time, 3)
self.loader.stop()
return TurnstileResult(
turnstile_value=None,
elapsed_time_seconds=elapsed_time,
status="error",
reason=str(e)
)
return result
@debug
async def get_turnstile_token(headless: bool = False, url: str = None, sitekey: str = None, invisible: bool = False, cookies: dict = None) -> Dict:
"""Legacy wrapper function for backward compatibility."""
solver = AsyncTurnstileSolver()
result = await solver.solve(url=url, sitekey=sitekey, headless=headless, invisible=invisible, cookies=cookies)
return result.__dict__
if __name__ == "__main__":
async def main():
result = await get_turnstile_token(
url="https://streamlabs.com",
sitekey="0x4AAAAAAACELUBpqiwktdQ9",
invisible=True
)
print(result)
asyncio.run(main())
# Credits for the changes: github.com/sexfrance
# Credit for the original script: github.com/Theyka