cacode commited on
Commit
54051d4
·
verified ·
1 Parent(s): 1257cc2

Update register.py

Browse files
Files changed (1) hide show
  1. register.py +243 -242
register.py CHANGED
@@ -1,242 +1,243 @@
1
- """
2
- Gemini Business 自动注册模块 (Docker / HF Space 版)
3
- """
4
-
5
- # ================= 标准库 =================
6
- import json
7
- import time
8
- import random
9
- from pathlib import Path
10
- from datetime import datetime
11
- from urllib.parse import urlparse, parse_qs
12
- from concurrent.futures import ThreadPoolExecutor
13
-
14
- # ================= 第三方 =================
15
- import requests
16
- from bs4 import BeautifulSoup
17
- import undetected_chromedriver as uc
18
- from selenium.webdriver.common.by import By
19
- from selenium.webdriver.common.keys import Keys
20
- from selenium.webdriver.support.ui import WebDriverWait
21
- from selenium.webdriver.support import expected_conditions as EC
22
-
23
- # ================= 项目内 =================
24
- from logger import log
25
-
26
-
27
- # ==================== 配置 ====================
28
- LOGIN_URL = "https://auth.business.gemini.google/login?continueUrl=https:%2F%2Fbusiness.gemini.google%2F"
29
-
30
- MAIL_API = "https://mail.chatgpt.org.uk"
31
- MAIL_KEY = "gpt-test"
32
-
33
- ACCOUNTS_FILE = "accounts.json"
34
-
35
- HEADLESS_MODE = True
36
-
37
- XPATH = {
38
- "email_input": "//input[@type='email']",
39
- "continue_btn": "//button",
40
- }
41
-
42
- NAMES = [
43
- "James Smith", "John Johnson", "Robert Williams", "Michael Brown",
44
- "William Jones", "David Garcia", "Mary Miller", "Patricia Davis",
45
- "Jennifer Rodriguez", "Linda Martinez", "Elizabeth Taylor"
46
- ]
47
-
48
-
49
- # ==================== 邮箱 ====================
50
- email_queue = []
51
-
52
-
53
- def create_temp_email():
54
- try:
55
- r = requests.get(
56
- f"{MAIL_API}/api/generate-email",
57
- headers={"X-API-Key": MAIL_KEY},
58
- timeout=20
59
- )
60
- if r.status_code == 200 and r.json().get("success"):
61
- return r.json()["data"]["email"]
62
- except Exception as e:
63
- log(f"邮箱创建失败: {e}", "ERROR")
64
- return None
65
-
66
-
67
- def prefetch_email():
68
- email = create_temp_email()
69
- if email:
70
- email_queue.append(email)
71
-
72
-
73
- def get_email():
74
- if email_queue:
75
- email = email_queue.pop(0)
76
- log(f"使用预取邮箱: {email}")
77
- return email
78
- email = create_temp_email()
79
- log(f"新邮箱: {email}")
80
- return email
81
-
82
-
83
- def fetch_verification_code(email, timeout=90):
84
- log("等待验证码...")
85
- start = time.time()
86
- while time.time() - start < timeout:
87
- try:
88
- r = requests.get(
89
- f"{MAIL_API}/api/emails",
90
- params={"email": email},
91
- headers={"X-API-Key": MAIL_KEY},
92
- timeout=10
93
- )
94
- if r.status_code == 200:
95
- emails = r.json().get("data", {}).get("emails", [])
96
- if emails:
97
- soup = BeautifulSoup(
98
- emails[0].get("html_content", ""),
99
- "html.parser"
100
- )
101
- span = soup.find("span", class_="verification-code")
102
- if span:
103
- code = span.text.strip()
104
- if len(code) == 6:
105
- log(f"验证码: {code}", "OK")
106
- return code
107
- except:
108
- pass
109
- time.sleep(2)
110
-
111
- log("验证码超时", "ERROR")
112
- return None
113
-
114
-
115
- # ==================== 浏览器 ====================
116
- def create_driver():
117
- options = uc.ChromeOptions()
118
- options.add_argument("--headless=new")
119
- options.add_argument("--no-sandbox")
120
- options.add_argument("--disable-dev-shm-usage")
121
- options.add_argument("--disable-gpu")
122
- options.add_argument("--window-size=1280,800")
123
-
124
- return uc.Chrome(options=options, use_subprocess=True)
125
-
126
-
127
- # ==================== 保存配置 ====================
128
- def save_account_config(email, driver):
129
- cookies = driver.get_cookies()
130
- url = driver.current_url
131
- parsed = urlparse(url)
132
-
133
- config_id = None
134
- for p in url.split("/"):
135
- if len(p) > 10 and p.isalnum():
136
- config_id = p
137
-
138
- cookie_map = {c["name"]: c["value"] for c in cookies}
139
-
140
- csesidx = parse_qs(parsed.query).get("csesidx", [None])[0]
141
-
142
- if not all([config_id, csesidx]):
143
- log("配置提取失败", "ERROR")
144
- return None
145
-
146
- data = {
147
- "id": email,
148
- "config_id": config_id,
149
- "csesidx": csesidx,
150
- "cookies": cookie_map,
151
- "expires_at": datetime.now().strftime("%Y-%m-%d %H:%M:%S")
152
- }
153
-
154
- accounts = []
155
- if Path(ACCOUNTS_FILE).exists():
156
- accounts = json.load(open(ACCOUNTS_FILE, "r", encoding="utf-8"))
157
-
158
- accounts.append(data)
159
- json.dump(accounts, open(ACCOUNTS_FILE, "w", encoding="utf-8"), indent=2)
160
-
161
- log(f"账号保存成功: {email}", "OK")
162
- return data
163
-
164
-
165
- # ==================== 注册单个 ====================
166
- def register_single(driver, executor):
167
- email = get_email()
168
- wait = WebDriverWait(driver, 30)
169
-
170
- try:
171
- driver.get(LOGIN_URL)
172
- time.sleep(2)
173
-
174
- inp = wait.until(EC.element_to_be_clickable((By.XPATH, XPATH["email_input"])))
175
- inp.clear()
176
- inp.send_keys(email)
177
- inp.send_keys(Keys.ENTER)
178
-
179
- executor.submit(prefetch_email)
180
-
181
- code = fetch_verification_code(email)
182
- if not code:
183
- return False
184
-
185
- time.sleep(1)
186
- driver.switch_to.active_element.send_keys(code)
187
-
188
- time.sleep(2)
189
-
190
- name = random.choice(NAMES)
191
- driver.switch_to.active_element.send_keys(name)
192
- driver.switch_to.active_element.send_keys(Keys.ENTER)
193
-
194
- time.sleep(5)
195
-
196
- save_account_config(email, driver)
197
- log(f"注册成功: {email}", "OK")
198
- return True
199
-
200
- except Exception as e:
201
- log(f"注册异常: {e}", "ERROR")
202
- return False
203
-
204
-
205
- # ==================== 批量注册 ====================
206
- def run_batch_registration(target=5):
207
- if Path(ACCOUNTS_FILE).exists():
208
- Path(ACCOUNTS_FILE).unlink()
209
-
210
- driver = create_driver()
211
- executor = ThreadPoolExecutor(max_workers=2)
212
-
213
- success = 0
214
- attempts = 0
215
-
216
- executor.submit(prefetch_email)
217
-
218
- while success < target:
219
- attempts += 1
220
- log(f"开始注册第 {attempts} 次")
221
- ok = register_single(driver, executor)
222
- if ok:
223
- success += 1
224
- time.sleep(random.randint(2, 4))
225
-
226
- driver.quit()
227
- executor.shutdown(wait=False)
228
-
229
- return {
230
- "success": success,
231
- "attempts": attempts,
232
- "is_ok": success > 0
233
- }
234
-
235
-
236
- # ==================== 对外接口 ====================
237
- def handle_task_execution(count, uploader):
238
- stats = run_batch_registration(count)
239
- if stats["is_ok"]:
240
- uploader.login()
241
- uploader.upload_and_merge(ACCOUNTS_FILE)
242
- return stats
 
 
1
+ """
2
+ Gemini Business 自动注册模块 (Docker / HF Space 版)
3
+ """
4
+
5
+ # ================= 标准库 =================
6
+ import json
7
+ import time
8
+ import random
9
+ from pathlib import Path
10
+ from datetime import datetime
11
+ from urllib.parse import urlparse, parse_qs
12
+ from concurrent.futures import ThreadPoolExecutor
13
+
14
+ # ================= 第三方 =================
15
+ import requests
16
+ from bs4 import BeautifulSoup
17
+ import undetected_chromedriver as uc
18
+ from selenium.webdriver.common.by import By
19
+ from selenium.webdriver.common.keys import Keys
20
+ from selenium.webdriver.support.ui import WebDriverWait
21
+ from selenium.webdriver.support import expected_conditions as EC
22
+
23
+ # ================= 项目内 =================
24
+ from logger import log
25
+
26
+
27
+ # ==================== 配置 ====================
28
+ LOGIN_URL = "https://auth.business.gemini.google/login?continueUrl=https:%2F%2Fbusiness.gemini.google%2F"
29
+
30
+ MAIL_API = "https://mail.chatgpt.org.uk"
31
+ MAIL_KEY = "gpt-test"
32
+
33
+ ACCOUNTS_FILE = "accounts.json"
34
+
35
+ HEADLESS_MODE = False
36
+ # HEADLESS_MODE = True
37
+
38
+ XPATH = {
39
+ "email_input": "//input[@type='email']",
40
+ "continue_btn": "//button",
41
+ }
42
+
43
+ NAMES = [
44
+ "James Smith", "John Johnson", "Robert Williams", "Michael Brown",
45
+ "William Jones", "David Garcia", "Mary Miller", "Patricia Davis",
46
+ "Jennifer Rodriguez", "Linda Martinez", "Elizabeth Taylor"
47
+ ]
48
+
49
+
50
+ # ==================== 邮箱 ====================
51
+ email_queue = []
52
+
53
+
54
+ def create_temp_email():
55
+ try:
56
+ r = requests.get(
57
+ f"{MAIL_API}/api/generate-email",
58
+ headers={"X-API-Key": MAIL_KEY},
59
+ timeout=20
60
+ )
61
+ if r.status_code == 200 and r.json().get("success"):
62
+ return r.json()["data"]["email"]
63
+ except Exception as e:
64
+ log(f"邮箱创建失败: {e}", "ERROR")
65
+ return None
66
+
67
+
68
+ def prefetch_email():
69
+ email = create_temp_email()
70
+ if email:
71
+ email_queue.append(email)
72
+
73
+
74
+ def get_email():
75
+ if email_queue:
76
+ email = email_queue.pop(0)
77
+ log(f"使用预取邮箱: {email}")
78
+ return email
79
+ email = create_temp_email()
80
+ log(f"新邮箱: {email}")
81
+ return email
82
+
83
+
84
+ def fetch_verification_code(email, timeout=90):
85
+ log("等待验证码...")
86
+ start = time.time()
87
+ while time.time() - start < timeout:
88
+ try:
89
+ r = requests.get(
90
+ f"{MAIL_API}/api/emails",
91
+ params={"email": email},
92
+ headers={"X-API-Key": MAIL_KEY},
93
+ timeout=10
94
+ )
95
+ if r.status_code == 200:
96
+ emails = r.json().get("data", {}).get("emails", [])
97
+ if emails:
98
+ soup = BeautifulSoup(
99
+ emails[0].get("html_content", ""),
100
+ "html.parser"
101
+ )
102
+ span = soup.find("span", class_="verification-code")
103
+ if span:
104
+ code = span.text.strip()
105
+ if len(code) == 6:
106
+ log(f"验证码: {code}", "OK")
107
+ return code
108
+ except:
109
+ pass
110
+ time.sleep(2)
111
+
112
+ log("验证码超时", "ERROR")
113
+ return None
114
+
115
+
116
+ # ==================== 浏览器 ====================
117
+ def create_driver():
118
+ options = uc.ChromeOptions()
119
+ options.add_argument("--headless=new")
120
+ options.add_argument("--no-sandbox")
121
+ options.add_argument("--disable-dev-shm-usage")
122
+ options.add_argument("--disable-gpu")
123
+ options.add_argument("--window-size=1280,800")
124
+
125
+ return uc.Chrome(options=options, use_subprocess=True)
126
+
127
+
128
+ # ==================== 保存配置 ====================
129
+ def save_account_config(email, driver):
130
+ cookies = driver.get_cookies()
131
+ url = driver.current_url
132
+ parsed = urlparse(url)
133
+
134
+ config_id = None
135
+ for p in url.split("/"):
136
+ if len(p) > 10 and p.isalnum():
137
+ config_id = p
138
+
139
+ cookie_map = {c["name"]: c["value"] for c in cookies}
140
+
141
+ csesidx = parse_qs(parsed.query).get("csesidx", [None])[0]
142
+
143
+ if not all([config_id, csesidx]):
144
+ log("配置提取失败", "ERROR")
145
+ return None
146
+
147
+ data = {
148
+ "id": email,
149
+ "config_id": config_id,
150
+ "csesidx": csesidx,
151
+ "cookies": cookie_map,
152
+ "expires_at": datetime.now().strftime("%Y-%m-%d %H:%M:%S")
153
+ }
154
+
155
+ accounts = []
156
+ if Path(ACCOUNTS_FILE).exists():
157
+ accounts = json.load(open(ACCOUNTS_FILE, "r", encoding="utf-8"))
158
+
159
+ accounts.append(data)
160
+ json.dump(accounts, open(ACCOUNTS_FILE, "w", encoding="utf-8"), indent=2)
161
+
162
+ log(f"账号保存成功: {email}", "OK")
163
+ return data
164
+
165
+
166
+ # ==================== 注册单个 ====================
167
+ def register_single(driver, executor):
168
+ email = get_email()
169
+ wait = WebDriverWait(driver, 30)
170
+
171
+ try:
172
+ driver.get(LOGIN_URL)
173
+ time.sleep(2)
174
+
175
+ inp = wait.until(EC.element_to_be_clickable((By.XPATH, XPATH["email_input"])))
176
+ inp.clear()
177
+ inp.send_keys(email)
178
+ inp.send_keys(Keys.ENTER)
179
+
180
+ executor.submit(prefetch_email)
181
+
182
+ code = fetch_verification_code(email)
183
+ if not code:
184
+ return False
185
+
186
+ time.sleep(1)
187
+ driver.switch_to.active_element.send_keys(code)
188
+
189
+ time.sleep(2)
190
+
191
+ name = random.choice(NAMES)
192
+ driver.switch_to.active_element.send_keys(name)
193
+ driver.switch_to.active_element.send_keys(Keys.ENTER)
194
+
195
+ time.sleep(5)
196
+
197
+ save_account_config(email, driver)
198
+ log(f"注册成功: {email}", "OK")
199
+ return True
200
+
201
+ except Exception as e:
202
+ log(f"注册异常: {e}", "ERROR")
203
+ return False
204
+
205
+
206
+ # ==================== 批量注册 ====================
207
+ def run_batch_registration(target=5):
208
+ if Path(ACCOUNTS_FILE).exists():
209
+ Path(ACCOUNTS_FILE).unlink()
210
+
211
+ driver = create_driver()
212
+ executor = ThreadPoolExecutor(max_workers=2)
213
+
214
+ success = 0
215
+ attempts = 0
216
+
217
+ executor.submit(prefetch_email)
218
+
219
+ while success < target:
220
+ attempts += 1
221
+ log(f"开始注册第 {attempts} 次")
222
+ ok = register_single(driver, executor)
223
+ if ok:
224
+ success += 1
225
+ time.sleep(random.randint(2, 4))
226
+
227
+ driver.quit()
228
+ executor.shutdown(wait=False)
229
+
230
+ return {
231
+ "success": success,
232
+ "attempts": attempts,
233
+ "is_ok": success > 0
234
+ }
235
+
236
+
237
+ # ==================== 对外接口 ====================
238
+ def handle_task_execution(count, uploader):
239
+ stats = run_batch_registration(count)
240
+ if stats["is_ok"]:
241
+ uploader.login()
242
+ uploader.upload_and_merge(ACCOUNTS_FILE)
243
+ return stats