forked from aceHubert/newapi-ai-check-in
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcheckin.py
More file actions
2079 lines (1807 loc) · 99.2 KB
/
Copy pathcheckin.py
File metadata and controls
2079 lines (1807 loc) · 99.2 KB
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
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
CheckIn 类
"""
import asyncio
import json
import inspect
import hashlib
import os
import tempfile
from urllib.parse import urlparse, urlencode
from curl_cffi import requests as curl_requests
from camoufox.async_api import AsyncCamoufox
from utils.config import AccountConfig, ProviderConfig
from utils.browser_utils import parse_cookies, filter_cookies, get_random_user_agent, take_screenshot, aliyun_captcha_check
from utils.get_cf_clearance import get_cf_clearance
from utils.http_utils import proxy_resolve, response_resolve
from utils.topup import topup
from utils.get_headers import get_browser_headers, get_curl_cffi_impersonate, print_browser_headers
from utils.mask_utils import mask_username
class CheckIn:
"""newapi.ai 签到管理类"""
def __init__(
self,
account_name: str,
account_config: AccountConfig,
provider_config: ProviderConfig,
global_proxy: dict | None = None,
storage_state_dir: str = "storage-states",
):
"""初始化签到管理器
Args:
account_info: account 用户配置
proxy_config: 全局代理配置(可选)
"""
self.account_name = account_name
self.safe_account_name = "".join(c if c.isalnum() else "_" for c in account_name)
self.account_config = account_config
self.provider_config = provider_config
# 将全局代理存入 account_config.extra,供 get_cdk 和 check_in_status 等函数使用
if global_proxy:
self.account_config.extra["global_proxy"] = global_proxy
# 代理优先级: 账号配置 > 全局配置
self.camoufox_proxy_config = account_config.proxy if account_config.proxy else global_proxy
# curl_cffi proxy 转换
self.http_proxy_config = proxy_resolve(self.camoufox_proxy_config)
# storage-states 目录
self.storage_state_dir = storage_state_dir
os.makedirs(self.storage_state_dir, exist_ok=True)
async def get_waf_cookies_with_browser(self) -> dict | None:
"""使用 Camoufox 获取 WAF cookies(隐私模式)"""
print(
f"ℹ️ {self.account_name}: Starting browser to get WAF cookies (using proxy: {'true' if self.camoufox_proxy_config else 'false'})"
)
with tempfile.TemporaryDirectory(prefix=f"camoufox_{self.safe_account_name}_waf_") as tmp_dir:
print(f"ℹ️ {self.account_name}: Using temporary directory: {tmp_dir}")
async with AsyncCamoufox(
persistent_context=True,
user_data_dir=tmp_dir,
headless=False,
humanize=True,
locale="en-US",
geoip=True if self.camoufox_proxy_config else False,
proxy=self.camoufox_proxy_config,
os="macos", # 强制使用 macOS 指纹,避免跨平台指纹不一致问题
) as browser:
page = await browser.new_page()
try:
print(f"ℹ️ {self.account_name}: Access login page to get initial cookies")
await page.goto(self.provider_config.get_login_url(), wait_until="networkidle")
try:
await page.wait_for_function('document.readyState === "complete"', timeout=5000)
except Exception:
await page.wait_for_timeout(3000)
if self.provider_config.aliyun_captcha:
captcha_check = await aliyun_captcha_check(page, self.account_name)
if captcha_check:
await page.wait_for_timeout(3000)
cookies = await browser.cookies()
waf_cookies = {}
print(f"ℹ️ {self.account_name}: WAF cookies")
for cookie in cookies:
cookie_name = cookie.get("name")
cookie_value = cookie.get("value")
print(f" 📚 Cookie: {cookie_name} (value: {cookie_value})")
if cookie_name in ["acw_tc", "cdn_sec_tc", "acw_sc__v2"] and cookie_value is not None:
waf_cookies[cookie_name] = cookie_value
print(f"ℹ️ {self.account_name}: Got {len(waf_cookies)} WAF cookies after step 1")
# 检查是否至少获取到一个 WAF cookie
if not waf_cookies:
print(f"❌ {self.account_name}: No WAF cookies obtained")
return None
# 显示获取到的 cookies
cookie_names = list(waf_cookies.keys())
print(f"✅ {self.account_name}: Successfully got WAF cookies: {cookie_names}")
return waf_cookies
except Exception as e:
print(f"❌ {self.account_name}: Error occurred while getting WAF cookies: {e}")
return None
finally:
await page.close()
async def get_aliyun_captcha_cookies_with_browser(self) -> dict | None:
"""使用 Camoufox 获取阿里云验证 cookies"""
print(
f"ℹ️ {self.account_name}: Starting browser to get Aliyun captcha cookies (using proxy: {'true' if self.camoufox_proxy_config else 'false'})"
)
with tempfile.TemporaryDirectory(prefix=f"camoufox_{self.safe_account_name}_aliyun_captcha_") as tmp_dir:
print(f"ℹ️ {self.account_name}: Using temporary directory: {tmp_dir}")
async with AsyncCamoufox(
persistent_context=True,
user_data_dir=tmp_dir,
headless=False,
humanize=True,
locale="en-US",
geoip=True if self.camoufox_proxy_config else False,
proxy=self.camoufox_proxy_config,
os="macos", # 强制使用 macOS 指纹,避免跨平台指纹不一致问题
) as browser:
page = await browser.new_page()
try:
print(f"ℹ️ {self.account_name}: Access login page to get initial cookies")
await page.goto(self.provider_config.get_login_url(), wait_until="networkidle")
try:
await page.wait_for_function('document.readyState === "complete"', timeout=5000)
except Exception:
await page.wait_for_timeout(3000)
# # 提取验证码相关数据
# captcha_data = await page.evaluate(
# """() => {
# const data = {};
# // 获取 traceid
# const traceElement = document.getElementById('traceid');
# if (traceElement) {
# const text = traceElement.innerText || traceElement.textContent;
# const match = text.match(/TraceID:\\s*([a-f0-9]+)/i);
# data.traceid = match ? match[1] : null;
# }
# // 获取 window.aliyun_captcha 相关字段
# for (const key in window) {
# if (key.startsWith('aliyun_captcha')) {
# data[key] = window[key];
# }
# }
# // 获取 requestInfo
# if (window.requestInfo) {
# data.requestInfo = window.requestInfo;
# }
# // 获取当前 URL
# data.currentUrl = window.location.href;
# return data;
# }"""
# )
# print(
# f"📋 {self.account_name}: Captcha data extracted: " f"\n{json.dumps(captcha_data, indent=2)}"
# )
# # 通过 WaitForSecrets 发送验证码数据并等待用户手动验证
# from utils.wait_for_secrets import WaitForSecrets
# wait_for_secrets = WaitForSecrets()
# secret_obj = {
# "CAPTCHA_NEXT_URL": {
# "name": f"{self.account_name} - Aliyun Captcha Verification",
# "description": (
# f"Aliyun captcha verification required.\n"
# f"TraceID: {captcha_data.get('traceid', 'N/A')}\n"
# f"Current URL: {captcha_data.get('currentUrl', 'N/A')}\n"
# f"Please complete the captcha manually in the browser, "
# f"then provide the next URL after verification."
# ),
# }
# }
# secrets = wait_for_secrets.get(
# secret_obj,
# timeout=300,
# notification={
# "title": "阿里云验证",
# "content": "请在浏览器中完成验证,并提供下一步的 URL。\n"
# f"{json.dumps(captcha_data, indent=2)}\n"
# "📋 操作说明:https://github.com/aceHubert/newapi-ai-check-in/docs/aliyun_captcha/README.md",
# },
# )
# if not secrets or "CAPTCHA_NEXT_URL" not in secrets:
# print(f"❌ {self.account_name}: No next URL provided " f"for captcha verification")
# return None
# next_url = secrets["CAPTCHA_NEXT_URL"]
# print(f"🔄 {self.account_name}: Navigating to next URL " f"after captcha: {next_url}")
# # 导航到新的 URL
# await page.goto(next_url, wait_until="networkidle")
try:
await page.wait_for_function('document.readyState === "complete"', timeout=5000)
except Exception:
await page.wait_for_timeout(3000)
# 再次检查是否还有 traceid
traceid_after = None
try:
traceid_after = await page.evaluate(
"""() => {
const traceElement = document.getElementById('traceid');
if (traceElement) {
const text = traceElement.innerText || traceElement.textContent;
const match = text.match(/TraceID:\\s*([a-f0-9]+)/i);
return match ? match[1] : null;
}
return null;
}"""
)
except Exception:
traceid_after = None
if traceid_after:
print(
f"❌ {self.account_name}: Captcha verification failed, "
f"traceid still present: {traceid_after}"
)
return None
print(f"✅ {self.account_name}: Captcha verification successful, " f"traceid cleared")
cookies = await browser.cookies()
aliyun_captcha_cookies = {}
print(f"ℹ️ {self.account_name}: Aliyun Captcha cookies")
for cookie in cookies:
cookie_name = cookie.get("name")
cookie_value = cookie.get("value")
print(f" 📚 Cookie: {cookie_name} (value: {cookie_value})")
# if cookie_name in ["acw_tc", "cdn_sec_tc", "acw_sc__v2"]
# and cookie_value is not None:
aliyun_captcha_cookies[cookie_name] = cookie_value
print(
f"ℹ️ {self.account_name}: "
f"Got {len(aliyun_captcha_cookies)} "
f"Aliyun Captcha cookies after step 1"
)
# 检查是否至少获取到一个 Aliyun Captcha cookie
if not aliyun_captcha_cookies:
print(f"❌ {self.account_name}: " f"No Aliyun Captcha cookies obtained")
return None
# 显示获取到的 cookies
cookie_names = list(aliyun_captcha_cookies.keys())
print(f"✅ {self.account_name}: " f"Successfully got Aliyun Captcha cookies: {cookie_names}")
return aliyun_captcha_cookies
except Exception as e:
print(f"❌ {self.account_name}: " f"Error occurred while getting Aliyun Captcha cookies, {e}")
return None
finally:
await page.close()
async def get_status_with_browser(self) -> dict | None:
"""使用 Camoufox 获取状态信息并缓存
Returns:
状态数据字典
"""
print(
f"ℹ️ {self.account_name}: Starting browser to get status (using proxy: {'true' if self.camoufox_proxy_config else 'false'})"
)
with tempfile.TemporaryDirectory(prefix=f"camoufox_{self.safe_account_name}_status_") as tmp_dir:
print(f"ℹ️ {self.account_name}: Using temporary directory: {tmp_dir}")
async with AsyncCamoufox(
user_data_dir=tmp_dir,
persistent_context=True,
headless=False,
humanize=True,
locale="en-US",
geoip=True if self.camoufox_proxy_config else False,
proxy=self.camoufox_proxy_config,
os="macos", # 强制使用 macOS 指纹,避免跨平台指纹不一致问题
) as browser:
page = await browser.new_page()
try:
print(f"ℹ️ {self.account_name}: Access status page to get status from localStorage")
await page.goto(self.provider_config.get_login_url(), wait_until="networkidle")
try:
await page.wait_for_function('document.readyState === "complete"', timeout=5000)
except Exception:
await page.wait_for_timeout(3000)
if self.provider_config.aliyun_captcha:
captcha_check = await aliyun_captcha_check(page, self.account_name)
if captcha_check:
await page.wait_for_timeout(3000)
# 从 localStorage 获取 status
status_data = None
try:
status_str = await page.evaluate("() => localStorage.getItem('status')")
if status_str:
status_data = json.loads(status_str)
print(f"✅ {self.account_name}: Got status from localStorage")
else:
print(f"⚠️ {self.account_name}: No status found in localStorage")
except Exception as e:
print(f"⚠️ {self.account_name}: Error reading status from localStorage: {e}")
return status_data
except Exception as e:
print(f"❌ {self.account_name}: Error occurred while getting status: {e}")
return None
finally:
await page.close()
async def get_auth_client_id(self, session: curl_requests.Session, headers: dict, provider: str) -> dict:
"""获取状态信息
Args:
session: curl_cffi Session 客户端
headers: 请求头
provider: 提供商类型 (github/linuxdo)
Returns:
包含 success 和 client_id 或 error 的字典
"""
try:
response = session.get(self.provider_config.get_status_url(), headers=headers, timeout=30)
if response.status_code == 200:
data = response_resolve(response, f"get_auth_client_id_{provider}", self.account_name)
if data is None:
# 尝试从浏览器 localStorage 获取状态
# print(f"ℹ️ {self.account_name}: Getting status from browser")
# try:
# status_data = await self.get_status_with_browser()
# if status_data:
# oauth = status_data.get(f"{provider}_oauth", False)
# if not oauth:
# return {
# "success": False,
# "error": f"{provider} OAuth is not enabled.",
# }
# client_id = status_data.get(f"{provider}_client_id", "")
# if client_id:
# print(f"✅ {self.account_name}: Got client ID from localStorage: " f"{client_id}")
# return {
# "success": True,
# "client_id": client_id,
# }
# except Exception as browser_err:
# print(f"⚠️ {self.account_name}: Failed to get status from browser: " f"{browser_err}")
return {
"success": False,
"error": "Failed to get client id: Invalid response type (saved to logs)",
}
if data.get("success"):
status_data = data.get("data", {})
oauth = status_data.get(f"{provider}_oauth", False)
if not oauth:
return {
"success": False,
"error": f"{provider} OAuth is not enabled.",
}
client_id = status_data.get(f"{provider}_client_id", "")
return {
"success": True,
"client_id": client_id,
}
else:
error_msg = data.get("message", "Unknown error")
return {
"success": False,
"error": f"Failed to get client id: {error_msg}",
}
return {
"success": False,
"error": f"Failed to get client id: HTTP {response.status_code}",
}
except Exception as e:
return {
"success": False,
"error": f"Failed to get client id, {e}",
}
async def get_auth_state_with_browser(self) -> dict:
"""使用 Camoufox 获取认证 URL 和 cookies
Args:
status: 要存储到 localStorage 的状态数据
wait_for_url: 要等待的 URL 模式
Returns:
包含 success、url、cookies 或 error 的字典
"""
print(
f"ℹ️ {self.account_name}: Starting browser to get auth state (using proxy: {'true' if self.camoufox_proxy_config else 'false'})"
)
with tempfile.TemporaryDirectory(prefix=f"camoufox_{self.safe_account_name}_auth_") as tmp_dir:
print(f"ℹ️ {self.account_name}: Using temporary directory: {tmp_dir}")
async with AsyncCamoufox(
user_data_dir=tmp_dir,
persistent_context=True,
headless=False,
humanize=True,
locale="en-US",
geoip=True if self.camoufox_proxy_config else False,
proxy=self.camoufox_proxy_config,
os="macos", # 强制使用 macOS 指纹,避免跨平台指纹不一致问题
) as browser:
page = await browser.new_page()
try:
# 1. Open the login page first
print(f"ℹ️ {self.account_name}: Opening login page")
await page.goto(self.provider_config.get_login_url(), wait_until="networkidle")
# Wait for page to be fully loaded
try:
await page.wait_for_function('document.readyState === "complete"', timeout=5000)
except Exception:
await page.wait_for_timeout(3000)
if self.provider_config.aliyun_captcha:
captcha_check = await aliyun_captcha_check(page, self.account_name)
if captcha_check:
await page.wait_for_timeout(3000)
response = await page.evaluate(
f"""async () => {{
try{{
const response = await fetch('{self.provider_config.get_auth_state_url()}');
const data = await response.json();
return data;
}}catch(e){{
return {{
success: false,
message: e.message
}};
}}
}}"""
)
if response and "data" in response:
cookies = await browser.cookies()
return {
"success": True,
"state": response.get("data"),
"cookies": cookies,
}
return {"success": False, "error": f"Failed to get state, \n{json.dumps(response, indent=2)}"}
except Exception as e:
print(f"❌ {self.account_name}: Failed to get state, {e}")
await take_screenshot(page, "auth_url_error", self.account_name)
return {"success": False, "error": "Failed to get state"}
finally:
await page.close()
async def get_auth_state(
self,
session: curl_requests.Session,
headers: dict,
) -> dict:
"""获取认证状态
使用 curl_cffi Session 发送请求。Session 可在创建时设置全局 impersonate。
Args:
session: curl_cffi Session 客户端(已包含 cookies,可能已设置 impersonate)
headers: 请求头
"""
try:
response = session.get(
self.provider_config.get_auth_state_url(),
headers=headers,
timeout=30,
)
if response.status_code == 200:
json_data = response_resolve(response, "get_auth_state", self.account_name)
if json_data is None:
return {
"success": False,
"error": "Failed to get auth state: Invalid response type (saved to logs)",
}
# 检查响应是否成功
if json_data.get("success"):
auth_data = json_data.get("data")
# 将 curl_cffi Cookies 转换为 Camoufox 格式
result_cookies = []
parsed_domain = urlparse(self.provider_config.origin).netloc
print(f"ℹ️ {self.account_name}: Got {len(response.cookies)} cookies from auth state request")
for cookie in response.cookies.jar:
# 从 _rest 中获取 HttpOnly 和 SameSite,确保类型正确
http_only_raw = cookie._rest.get("HttpOnly", False)
http_only = bool(http_only_raw) if http_only_raw is not None else False
same_site_raw = cookie._rest.get("SameSite", "Lax")
same_site = str(same_site_raw) if same_site_raw else "Lax"
# secure 也需要确保是布尔值
secure = bool(cookie.secure) if cookie.secure is not None else False
print(
f" 📚 Cookie: {cookie.name} (Domain: {cookie.domain}, "
f"Path: {cookie.path}, Expires: {cookie.expires}, "
f"HttpOnly: {http_only}, Secure: {secure}, "
f"SameSite: {same_site})"
)
# 构建 cookie 字典,Camoufox 要求字段类型严格
cookie_dict = {
"name": cookie.name,
"domain": cookie.domain if cookie.domain else parsed_domain,
"value": cookie.value,
"path": cookie.path if cookie.path else "/",
"secure": secure,
"httpOnly": http_only,
"sameSite": same_site,
}
# 只有当 expires 是有效的数值时才添加
if cookie.expires is not None:
cookie_dict["expires"] = float(cookie.expires)
result_cookies.append(cookie_dict)
return {
"success": True,
"state": auth_data,
"cookies": result_cookies,
}
else:
error_msg = json_data.get("message", "Unknown error")
return {
"success": False,
"error": f"Failed to get auth state: {error_msg}",
}
return {
"success": False,
"error": f"Failed to get auth state: HTTP {response.status_code}",
}
except Exception as e:
return {
"success": False,
"error": f"Failed to get auth state, {e}",
}
async def get_user_info_with_browser(self, auth_cookies: list[dict]) -> dict:
"""使用 Camoufox 获取用户信息
Returns:
包含 success、quota、used_quota 或 error 的字典
"""
print(
f"ℹ️ {self.account_name}: Starting browser to get user info (using proxy: {'true' if self.camoufox_proxy_config else 'false'})"
)
with tempfile.TemporaryDirectory(prefix=f"camoufox_{self.safe_account_name}_user_info_") as tmp_dir:
print(f"ℹ️ {self.account_name}: Using temporary directory: {tmp_dir}")
async with AsyncCamoufox(
user_data_dir=tmp_dir,
persistent_context=True,
headless=False,
humanize=True,
locale="en-US",
geoip=True if self.camoufox_proxy_config else False,
proxy=self.camoufox_proxy_config,
os="macos", # 强制使用 macOS 指纹,避免跨平台指纹不一致问题
) as browser:
page = await browser.new_page()
browser.add_cookies(auth_cookies)
try:
# 1. 打开登录页面
print(f"ℹ️ {self.account_name}: Opening main page")
await page.goto(self.provider_config.origin, wait_until="networkidle")
# 等待页面完全加载
try:
await page.wait_for_function('document.readyState === "complete"', timeout=5000)
except Exception:
await page.wait_for_timeout(3000)
if self.provider_config.aliyun_captcha:
captcha_check = await aliyun_captcha_check(page, self.account_name)
if captcha_check:
await page.wait_for_timeout(3000)
# 获取用户信息
response = await page.evaluate(
f"""async () => {{
const response = await fetch(
'{self.provider_config.get_user_info_url()}'
);
const data = await response.json();
return data;
}}"""
)
if response and "data" in response:
user_data = response.get("data", {})
quota = round(user_data.get("quota", 0) / 500000, 2)
used_quota = round(user_data.get("used_quota", 0) / 500000, 2)
bonus_quota = round(user_data.get("bonus_quota", 0) / 500000, 2)
print(
f"✅ {self.account_name}: "
f"Current balance: ${quota}, Used: ${used_quota}, Bonus: ${bonus_quota}"
)
return {
"success": True,
"quota": quota,
"used_quota": used_quota,
"bonus_quota": bonus_quota,
"display": f"Current balance: ${quota}, Used: ${used_quota}, Bonus: ${bonus_quota}",
}
return {
"success": False,
"error": f"Failed to get user info, \n{json.dumps(response, indent=2)}",
}
except Exception as e:
print(f"❌ {self.account_name}: Failed to get user info, {e}")
await take_screenshot(page, "user_info_error", self.account_name)
return {"success": False, "error": "Failed to get user info"}
finally:
await page.close()
async def get_user_info(self, session: curl_requests.Session, headers: dict) -> dict:
"""获取用户信息"""
try:
response = session.get(self.provider_config.get_user_info_url(), headers=headers, timeout=30)
if response.status_code == 200:
json_data = response_resolve(response, "get_user_info", self.account_name)
if json_data is None:
# 尝试从浏览器获取用户信息
# print(f"ℹ️ {self.account_name}: Getting user info from browser")
# try:
# user_info_result = await self.get_user_info_with_browser()
# if user_info_result.get("success"):
# return user_info_result
# else:
# error_msg = user_info_result.get("error", "Unknown error")
# print(f"⚠️ {self.account_name}: {error_msg}")
# except Exception as browser_err:
# print(
# f"⚠️ {self.account_name}: "
# f"Failed to get user info from browser: {browser_err}"
# )
return {
"success": False,
"error": "Failed to get user info: Invalid response type (saved to logs)",
}
if json_data.get("success"):
user_data = json_data.get("data", {})
quota = round(user_data.get("quota", 0) / 500000, 2)
used_quota = round(user_data.get("used_quota", 0) / 500000, 2)
bonus_quota = round(user_data.get("bonus_quota", 0) / 500000, 2)
return {
"success": True,
"quota": quota,
"used_quota": used_quota,
"bonus_quota": bonus_quota,
"display": f"Current balance: ${quota}, Used: ${used_quota}, Bonus: ${bonus_quota}",
}
else:
error_msg = json_data.get("message", "Unknown error")
return {
"success": False,
"error": f"Failed to get user info: {error_msg}",
}
return {
"success": False,
"error": f"Failed to get user info: HTTP {response.status_code}",
}
except Exception as e:
return {
"success": False,
"error": f"Failed to get user info, {e}",
}
def execute_check_in(
self,
session: curl_requests.Session,
headers: dict,
api_user: str | int,
) -> dict:
"""执行签到请求
Returns:
包含 success, message, data 等信息的字典
"""
print(f"🌐 {self.account_name}: Executing check-in")
checkin_headers = headers.copy()
checkin_headers.update({"Content-Type": "application/json", "X-Requested-With": "XMLHttpRequest"})
check_in_url = self.provider_config.get_check_in_url(api_user)
if not check_in_url:
print(f"❌ {self.account_name}: No check-in URL configured")
return {"success": False, "error": "No check-in URL configured"}
response = session.post(check_in_url, headers=checkin_headers, timeout=30)
print(f"📨 {self.account_name}: Response status code {response.status_code}")
# 尝试解析响应(200 或 400 都可能包含有效的 JSON)
if response.status_code in [200, 400]:
json_data = response_resolve(response, "execute_check_in", self.account_name)
if json_data is None:
# 如果不是 JSON 响应(可能是 HTML),检查是否包含成功标识
if "success" in response.text.lower():
print(f"✅ {self.account_name}: Check-in successful!")
return {"success": True, "message": "Check-in successful"}
else:
print(f"❌ {self.account_name}: Check-in failed - Invalid response format")
return {"success": False, "error": "Invalid response format"}
# 检查签到结果
message = json_data.get("message", json_data.get("msg", ""))
if (
json_data.get("ret") == 1
or json_data.get("code") == 0
or json_data.get("success")
or "已经签到" in message
or "签到成功" in message
):
# 提取签到数据
check_in_data = json_data.get("data", {})
checkin_date = check_in_data.get("checkin_date", "")
quota_awarded = check_in_data.get("quota_awarded", 0)
if quota_awarded:
quota_display = round(quota_awarded / 500000, 2)
print(f"✅ {self.account_name}: Check-in successful! Date: {checkin_date}, Quota awarded: ${quota_display}")
else:
print(f"✅ {self.account_name}: Check-in successful! {message}")
return {
"success": True,
"message": message or "Check-in successful",
"data": check_in_data,
}
else:
error_msg = json_data.get("msg", json_data.get("message", "Unknown error"))
print(f"❌ {self.account_name}: Check-in failed - {error_msg}")
return {"success": False, "error": error_msg}
else:
print(f"❌ {self.account_name}: Check-in failed - HTTP {response.status_code}")
return {"success": False, "error": f"HTTP {response.status_code}"}
async def execute_topup(
self,
headers: dict,
cookies: dict,
api_user: str | int,
topup_interval: int = 60,
) -> dict:
"""执行完整的 CDK 获取和充值流程
直接调用 get_cdk 生成器函数,每次 yield 一个 CDK 字符串并执行 topup
每次 topup 之间保持间隔时间,如果 topup 失败则停止
支持同步生成器和异步生成器两种类型的 get_cdk 函数
Args:
headers: 请求头
cookies: cookies 字典
api_user: API 用户 ID(通过参数传递,因为登录方式可能不同)
topup_interval: 多次 topup 之间的间隔时间(秒),默认 60 秒
Returns:
包含 success, topup_count, errors 等信息的字典
"""
# 检查是否配置了 get_cdk 函数
if not self.provider_config.get_cdk:
print(f"ℹ️ {self.account_name}: No get_cdk function configured for provider {self.provider_config.name}")
return {
"success": True,
"topup_count": 0,
"topup_success_count": 0,
"error": "",
}
# 构建 topup 请求头
topup_headers = headers.copy()
topup_headers.update({
"Referer": f"{self.provider_config.origin}/console/topup",
"Origin": self.provider_config.origin,
self.provider_config.api_user_key: f"{api_user}",
})
results = {
"success": True,
"topup_count": 0,
"topup_success_count": 0,
"error": "",
}
# 调用 get_cdk 函数,返回同步生成器或异步生成器
cdk_generator = self.provider_config.get_cdk(self.account_config)
topup_count = 0
error_msg = ""
# 内部函数:处理单个 CDK 结果
async def process_cdk_result(success: bool, data: dict) -> bool:
"""处理单个 CDK 结果,返回是否应该继续
Args:
success: 是否成功获取 CDK
data: 包含 code 或 error 的字典
Returns:
bool: True 继续处理下一个,False 停止处理
"""
nonlocal topup_count, error_msg
# 如果获取 CDK 失败,停止处理
if not success:
error_msg = data.get("error", "Failed to get CDK")
results["success"] = False
results["error"] = error_msg
print(f"❌ {self.account_name}: Failed to get CDK - {error_msg}, stopping topup process")
return False
# 获取 code
cdk = data.get("code", "")
# 如果 code 为空,表示不需要充值,继续处理下一个
if not cdk:
print(f"ℹ️ {self.account_name}: No CDK to topup (code is empty), continuing...")
return True
# 如果不是第一个 CDK,等待间隔时间
if topup_count > 0 and topup_interval > 0:
print(f"⏳ {self.account_name}: Waiting {topup_interval} seconds before next topup...")
await asyncio.sleep(topup_interval)
topup_count += 1
print(f"💰 {self.account_name}: Executing topup #{topup_count} with CDK: {cdk}")
topup_result = topup(
provider_config=self.provider_config,
account_config=self.account_config,
headers=topup_headers,
cookies=cookies,
key=cdk,
)
results["topup_count"] += 1
if topup_result.get("success"):
results["topup_success_count"] += 1
if not topup_result.get("already_used"):
print(f"✅ {self.account_name}: Topup #{topup_count} successful")
return True # 继续处理下一个
else:
# topup 失败,记录错误并停止
error_msg = topup_result.get("error", "Topup failed")
results["success"] = False
results["error"] = error_msg
print(f"❌ {self.account_name}: Topup #{topup_count} failed, stopping topup process")
return False # 停止处理
# 检查是否是异步生成器
if inspect.isasyncgen(cdk_generator):
# 异步生成器,使用 async for
async for success, data in cdk_generator:
should_continue = await process_cdk_result(success, data)
if not should_continue:
break
else:
# 同步生成器,使用普通 for
for success, data in cdk_generator:
should_continue = await process_cdk_result(success, data)
if not should_continue:
break
if topup_count == 0:
print(f"ℹ️ {self.account_name}: No CDK available for topup")
elif results["topup_success_count"] > 0:
print(f"✅ {self.account_name}: Total {results['topup_success_count']}/{results['topup_count']} topup(s) successful")
return results
async def check_in_with_cookies(
self,
cookies: dict,
common_headers: dict,
api_user: str | int,
) -> tuple[bool, dict]:
"""使用已有 cookies 执行签到操作
Args:
cookies: cookies 字典
common_headers: 公用请求头(包含 User-Agent 和可能的 Client Hints)
api_user: API 用户 ID
"""
print(
f"ℹ️ {self.account_name}: Executing check-in with existing cookies (using proxy: {'true' if self.http_proxy_config else 'false'})"
)
# 根据 User-Agent 自动推断 impersonate 值
user_agent = common_headers.get("User-Agent", "")
impersonate = get_curl_cffi_impersonate(user_agent) if user_agent else "firefox135"
session = curl_requests.Session(impersonate=impersonate, proxy=self.http_proxy_config, timeout=30)
if impersonate:
print(f"ℹ️ {self.account_name}: Using curl_cffi Session with impersonate={impersonate}")
try:
# 打印 cookies 的键和值
print(f"ℹ️ {self.account_name}: Cookies to be used:")
for key, value in cookies.items():
print(f" 📚 {key}: {value[:50] if len(value) > 50 else value}{'...' if len(value) > 50 else ''}")
session.cookies.update(cookies)
# 使用传入的公用请求头,并添加动态头部
headers = common_headers.copy()
headers[self.provider_config.api_user_key] = f"{api_user}"
headers["Referer"] = self.provider_config.get_login_url()
headers["Origin"] = self.provider_config.origin
# 检查是否需要手动签到
if self.provider_config.needs_manual_check_in():
# 如果配置了签到状态查询,先检查是否已签到
check_in_status_func = self.provider_config.get_check_in_status_func()
if check_in_status_func:
checked_in_today = check_in_status_func(
provider_config=self.provider_config,
account_config=self.account_config,
cookies=cookies,
headers=headers,
)
if checked_in_today:
print(f"ℹ️ {self.account_name}: Already checked in today, skipping check-in")
else:
# 未签到,执行签到
check_in_result = self.execute_check_in(session, headers, api_user)
if not check_in_result.get("success"):
return False, {"error": check_in_result.get("error", "Check-in failed")}
# 签到成功后再次查询状态(显示最新状态)
check_in_status_func(
provider_config=self.provider_config,
account_config=self.account_config,
cookies=cookies,
headers=headers,
)
else:
# 没有配置签到状态查询函数,直接执行签到
check_in_result = self.execute_check_in(session, headers, api_user)
if not check_in_result.get("success"):