bobocup commited on
Commit
b24824e
·
verified ·
1 Parent(s): 5313625

Create nb2.py

Browse files
Files changed (1) hide show
  1. nb2.py +331 -0
nb2.py ADDED
@@ -0,0 +1,331 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from selenium import webdriver
2
+ from selenium.webdriver.chrome.service import Service
3
+ from selenium.webdriver.chrome.options import Options
4
+ from selenium.webdriver.common.by import By
5
+ from selenium.webdriver.support.ui import WebDriverWait
6
+ from selenium.webdriver.support import expected_conditions as EC
7
+ from selenium.common.exceptions import TimeoutException
8
+ from selenium.webdriver.common.keys import Keys
9
+ import time
10
+ import random
11
+ import string
12
+ import logging
13
+ import requests
14
+ import json
15
+ import re
16
+ import os
17
+ from fastapi import FastAPI
18
+ import uvicorn
19
+
20
+ # 配置日志
21
+ logging.basicConfig(
22
+ level=logging.INFO,
23
+ format='%(asctime)s - %(levelname)s - %(message)s'
24
+ )
25
+ logger = logging.getLogger(__name__)
26
+
27
+ # FastAPI应用
28
+ app = FastAPI()
29
+
30
+ class MailGw:
31
+ def __init__(self):
32
+ self.base_url = "https://api.mail.gw"
33
+ self.token = None
34
+ self.email = None
35
+ self.password = "Temp123!@#"
36
+
37
+ def create_email(self):
38
+ try:
39
+ # 获取可用域名列表
40
+ domains_response = requests.get(f"{self.base_url}/domains")
41
+ domains = domains_response.json()['hydra:member']
42
+
43
+ # 打印所有可用域名
44
+ logger.info(f"可用域名列表: {[d['domain'] for d in domains]}")
45
+
46
+ # 随机选择一个域名
47
+ domain = random.choice(domains)['domain']
48
+ logger.info(f"选择的域名: {domain}")
49
+
50
+ # 生成随机邮箱地址
51
+ random_name = ''.join(random.choices(string.ascii_lowercase + string.digits, k=10))
52
+ email = f"{random_name}@{domain}"
53
+
54
+ # 创建邮箱账户
55
+ account_response = requests.post(
56
+ f"{self.base_url}/accounts",
57
+ json={
58
+ "address": email,
59
+ "password": self.password
60
+ }
61
+ )
62
+
63
+ if account_response.status_code != 201:
64
+ logger.error(f"创建邮箱失败: {account_response.text}")
65
+ return None
66
+
67
+ self.email = email
68
+
69
+ # 获取token
70
+ token_response = requests.post(
71
+ f"{self.base_url}/token",
72
+ json={
73
+ "address": email,
74
+ "password": self.password
75
+ }
76
+ )
77
+
78
+ if token_response.status_code != 200:
79
+ logger.error(f"获取token失败: {token_response.text}")
80
+ return None
81
+
82
+ self.token = token_response.json()['token']
83
+ logger.info(f"创建邮箱成功: {email}")
84
+ return email
85
+
86
+ except Exception as e:
87
+ logger.error(f"创建邮箱时发生错误: {str(e)}")
88
+ return None
89
+
90
+ def get_verification_code(self, max_retries=10, delay=2):
91
+ if not self.token:
92
+ logger.error("Token不存在")
93
+ return None
94
+
95
+ headers = {"Authorization": f"Bearer {self.token}"}
96
+
97
+ for _ in range(max_retries):
98
+ try:
99
+ # 获取邮件列表
100
+ messages_response = requests.get(
101
+ f"{self.base_url}/messages",
102
+ headers=headers
103
+ )
104
+
105
+ messages = messages_response.json()['hydra:member']
106
+
107
+ if messages:
108
+ # 获取最新邮件的ID
109
+ message_id = messages[0]['id']
110
+
111
+ # 获取邮件内容
112
+ message_response = requests.get(
113
+ f"{self.base_url}/messages/{message_id}",
114
+ headers=headers
115
+ )
116
+
117
+ # 从邮件内容中提取验证码
118
+ text = message_response.json()['text']
119
+
120
+ # 使用正则表达式匹配6位数字验证码
121
+ match = re.search(r'\b\d{6}\b', text)
122
+ if match:
123
+ verification_code = match.group(0)
124
+ logger.info(f"获取到验证码: {verification_code}")
125
+ return verification_code
126
+
127
+ except Exception as e:
128
+ logger.error(f"获取验证码时发生错误: {str(e)}")
129
+
130
+ time.sleep(delay)
131
+ logger.info(f"等待验证码,重试第 {_ + 1} 次")
132
+
133
+ logger.error("未能获取到验证码")
134
+ return None
135
+
136
+ def setup_driver():
137
+ """设置Chrome驱动"""
138
+ chrome_options = Options()
139
+ chrome_options.add_argument('--headless')
140
+ chrome_options.add_argument('--no-sandbox')
141
+ chrome_options.add_argument('--disable-dev-shm-usage')
142
+ chrome_options.binary_location = os.getenv('CHROME_BIN', '/usr/bin/chromium')
143
+
144
+ service = Service(os.getenv('CHROMEDRIVER_PATH', '/usr/bin/chromedriver'))
145
+ driver = webdriver.Chrome(service=service, options=chrome_options)
146
+ return driver
147
+
148
+ def get_cookie(driver):
149
+ try:
150
+ cookie_script = """
151
+ var cookieString = document.cookie;
152
+ var essentialCookies = cookieString.split('; ').filter(function(cookie) {
153
+ return cookie.startsWith('daily_query_') ||
154
+ cookie.startsWith('DSR=') ||
155
+ cookie.startsWith('DS=') ||
156
+ cookie.startsWith('uuid_guest=') ||
157
+ cookie.startsWith('ai_model=');
158
+ }).join('; ');
159
+ console.log('Essential Cookies:', essentialCookies);
160
+ return essentialCookies;
161
+ """
162
+ cookie = driver.execute_script(cookie_script)
163
+
164
+ logger.info(f"获取的 Cookie: {cookie}")
165
+
166
+ with open('cookies.txt', 'a') as file:
167
+ file.write(f" - '{cookie}'\n")
168
+
169
+ logger.info("Cookie 已追加到 cookies.txt 文件")
170
+ return cookie
171
+ except Exception as e:
172
+ logger.error(f"获取cookie错误: {str(e)}")
173
+ return None
174
+
175
+ def wait_for_url(driver, url, timeout=10):
176
+ try:
177
+ start_time = time.time()
178
+ while time.time() - start_time < timeout:
179
+ current_url = driver.current_url.rstrip('/')
180
+ target_url = url.rstrip('/')
181
+ if current_url == target_url:
182
+ return True
183
+ time.sleep(0.5)
184
+ return False
185
+ except TimeoutException:
186
+ return False
187
+
188
+ def wait_for_email_input(driver, timeout=10):
189
+ """等待邮箱输入框出现并返回"""
190
+ start_time = time.time()
191
+ while time.time() - start_time < timeout:
192
+ try:
193
+ input_js = """
194
+ return document.querySelector("#AppProvider_Wrapper > form > descope-wc")
195
+ .shadowRoot.querySelector("#TExZpnv5m6")
196
+ .shadowRoot.querySelector("#input-vaadin-email-field-3")
197
+ """
198
+ email_input = driver.execute_script(input_js)
199
+ if email_input:
200
+ logger.info("邮箱输入框已加载")
201
+ return True
202
+ except Exception:
203
+ pass
204
+ time.sleep(0.5)
205
+ logger.error("邮箱输入框未出现")
206
+ return False
207
+
208
+ def input_email(driver, email):
209
+ """使用JavaScript输入邮箱"""
210
+ try:
211
+ input_js = f"""
212
+ var input = document.querySelector("#AppProvider_Wrapper > form > descope-wc")
213
+ .shadowRoot.querySelector("#TExZpnv5m6")
214
+ .shadowRoot.querySelector("#input-vaadin-email-field-3");
215
+ input.value = "{email}";
216
+ input.dispatchEvent(new Event('input', {{ bubbles: true }}));
217
+ input.dispatchEvent(new Event('change', {{ bubbles: true }}));
218
+ """
219
+ driver.execute_script(input_js)
220
+ logger.info("输入邮箱成功")
221
+ return True
222
+ except Exception as e:
223
+ logger.error(f"输入邮箱失败: {str(e)}")
224
+ return False
225
+
226
+ def input_verification_code(driver, code):
227
+ """使用JavaScript输入验证码"""
228
+ try:
229
+ input_js = f"""
230
+ var input = document.querySelector("#AppProvider_Wrapper > form > descope-wc")
231
+ .shadowRoot.querySelector("#oneTimeCodeId")
232
+ .shadowRoot.querySelector("#input-vaadin-text-field-7 > div.wrapper > descope-text-field:nth-child(1)")
233
+ .shadowRoot.querySelector("#input-vaadin-text-field-35");
234
+ input.value = "{code}";
235
+ input.dispatchEvent(new Event('input', {{ bubbles: true }}));
236
+ input.dispatchEvent(new Event('change', {{ bubbles: true }}));
237
+ """
238
+ driver.execute_script(input_js)
239
+ logger.info("输入验证码成功")
240
+ return True
241
+ except Exception as e:
242
+ logger.error(f"输入验证码失败: {str(e)}")
243
+ return False
244
+
245
+ def registration_process(driver, wait):
246
+ try:
247
+ # 创建临时邮箱
248
+ mail_client = MailGw()
249
+ email = mail_client.create_email()
250
+ if not email:
251
+ logger.error("创建临时邮箱失败")
252
+ return False
253
+
254
+ # 第一步:打开认证页面
255
+ driver.get("https://you.com/authenticate")
256
+ logger.info("打开认证页面")
257
+
258
+ # 等待邮箱输入框出现
259
+ if not wait_for_email_input(driver):
260
+ logger.error("等待邮箱输入框超时")
261
+ return False
262
+
263
+ # 输入邮箱
264
+ if not input_email(driver, email):
265
+ logger.error("输入邮箱失败")
266
+ return False
267
+
268
+ time.sleep(0.5)
269
+
270
+ # 按回车继续
271
+ actions = webdriver.ActionChains(driver)
272
+ actions.send_keys(Keys.RETURN)
273
+ actions.perform()
274
+ logger.info("按下回车键")
275
+ time.sleep(2)
276
+
277
+ # 获取验证码
278
+ verification_code = mail_client.get_verification_code()
279
+ if not verification_code:
280
+ logger.error("获取验证码失败")
281
+ return False
282
+
283
+ logger.info(f"获取验证码: {verification_code}")
284
+
285
+ # 输入验证码
286
+ if not input_verification_code(driver, verification_code):
287
+ logger.error("输入验证码失败")
288
+ return False
289
+
290
+ time.sleep(2)
291
+
292
+ # 等待URL变化并获取cookie
293
+ if wait_for_url(driver, "https://you.com"):
294
+ logger.info("URL已变更为 https://you.com")
295
+ time.sleep(1)
296
+ cookie = get_cookie(driver)
297
+ if cookie:
298
+ logger.info("成功获取cookie")
299
+ return cookie
300
+ else:
301
+ logger.error("获取cookie失败")
302
+ return None
303
+ else:
304
+ logger.error("URL未变化为预期值")
305
+ return None
306
+
307
+ except Exception as e:
308
+ logger.error(f"注册过程错误: {str(e)}")
309
+ return None
310
+
311
+ @app.get("/")
312
+ def read_root():
313
+ return {"status": "running"}
314
+
315
+ @app.get("/generate_cookie")
316
+ async def generate_cookie():
317
+ try:
318
+ driver = setup_driver()
319
+ wait = WebDriverWait(driver, 20)
320
+ cookie = registration_process(driver, wait)
321
+ driver.quit()
322
+
323
+ if cookie:
324
+ return {"status": "success", "cookie": cookie}
325
+ else:
326
+ return {"status": "error", "message": "Failed to generate cookie"}
327
+ except Exception as e:
328
+ return {"status": "error", "message": str(e)}
329
+
330
+ if __name__ == "__main__":
331
+ uvicorn.run(app, host="0.0.0.0", port=7860)