-
Notifications
You must be signed in to change notification settings - Fork 329
Expand file tree
/
Copy pathui.py
More file actions
1264 lines (1153 loc) · 53.3 KB
/
ui.py
File metadata and controls
1264 lines (1153 loc) · 53.3 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
"""
自动化绑卡支付 - Streamlit UI
运行: streamlit run ui.py --server.address 0.0.0.0 --server.port 8503
"""
import json
import logging
import os
import sys
import traceback
import threading
from collections import deque
import streamlit as st
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from config import Config, CardInfo, BillingInfo, CaptchaConfig
from mail_provider import MailProvider
from auth_flow import AuthFlow, AuthResult
from payment_flow import PaymentFlow
from logger import ResultStore
from database import init_db
from code_manager import validate_code, reserve_use, complete_use, update_execution, get_code_history, get_code_info
init_db()
# ── 兑换码系统开关: 在 config.json 中设置 "code_system_enabled": true 开启 ──
_ENABLE_CODE_SYSTEM = False
try:
_cfg_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "config.json")
if os.path.isfile(_cfg_path):
with open(_cfg_path, encoding="utf-8") as _f:
_ENABLE_CODE_SYSTEM = bool(json.load(_f).get("code_system_enabled", False))
except Exception:
pass
OUTPUT_DIR = "test_outputs"
def _sanitize_error(raw_error: str) -> str:
"""将技术性错误信息转为用户友好的简要提示"""
if not raw_error:
return "执行失败"
e = raw_error.lower()
if "payment element" in e or "stripe" in e and "未加载" in raw_error:
return "支付页面加载失败,请稍后重试"
if "cloudflare" in e or "请稍候" in raw_error or "just a moment" in e:
return "网络验证失败,请稍后重试"
if "支付被拒" in raw_error or "card_declined" in e or "declined" in e:
return "支付被拒,请检查卡片信息"
if "用户手动终止" in raw_error:
return "已取消"
if "session_token" in e or "sentinel" in e or "403" in raw_error:
return "登录凭证失效,请更换 Token"
if "curl" in e or "url rejected" in e or "connection" in e or "timeout" in e:
return "网络连接失败,请检查代理配置"
if "captcha" in e or "hcaptcha" in e:
return "人机验证失败,请重试"
if "oom" in e or "memory" in e:
return "服务器资源不足,请稍后重试"
if "额度" in raw_error or "已用完" in raw_error:
return raw_error # 兑换码相关信息直接显示
# 兜底: 只显示简要信息
return "执行失败,请重试"
import re as _re
# 国家名/后缀 → (country_code, currency) 映射
_COUNTRY_ALIAS = {
"UK": ("GB", "GBP"), "GB": ("GB", "GBP"), "England": ("GB", "GBP"), "United Kingdom": ("GB", "GBP"), "英国": ("GB", "GBP"),
"US": ("US", "USD"), "USA": ("US", "USD"), "United States": ("US", "USD"), "美国": ("US", "USD"),
"DE": ("DE", "EUR"), "Germany": ("DE", "EUR"), "德国": ("DE", "EUR"),
"JP": ("JP", "JPY"), "Japan": ("JP", "JPY"), "日本": ("JP", "JPY"),
"FR": ("FR", "EUR"), "France": ("FR", "EUR"), "法国": ("FR", "EUR"),
"SG": ("SG", "SGD"), "Singapore": ("SG", "SGD"), "新加坡": ("SG", "SGD"),
"HK": ("HK", "HKD"), "Hong Kong": ("HK", "HKD"), "香港": ("HK", "HKD"),
"KR": ("KR", "KRW"), "Korea": ("KR", "KRW"), "韩国": ("KR", "KRW"),
"AU": ("AU", "AUD"), "Australia": ("AU", "AUD"), "澳大利亚": ("AU", "AUD"),
"CA": ("CA", "CAD"), "Canada": ("CA", "CAD"), "加拿大": ("CA", "CAD"),
"NL": ("NL", "EUR"), "Netherlands": ("NL", "EUR"), "荷兰": ("NL", "EUR"),
"IT": ("IT", "EUR"), "Italy": ("IT", "EUR"), "意大利": ("IT", "EUR"),
"ES": ("ES", "EUR"), "Spain": ("ES", "EUR"), "西班牙": ("ES", "EUR"),
"CH": ("CH", "CHF"), "Switzerland": ("CH", "CHF"), "瑞士": ("CH", "CHF"),
}
def _parse_card_text(text: str) -> dict:
"""从粘贴文本中解析卡号、有效期、CVV、账单地址。
支持两种格式:
1) 纯文本: 卡号一行、MM/YY一行、CVV一行、账单地址一行
2) 键值对: 卡号: xxx / 有效期: MMYY / CVV: xxx / 地址: xxx / 城市: xxx / 邮编: xxx / 国家: xxx
"""
result = {}
lines = [l.strip() for l in text.strip().splitlines() if l.strip()]
# 构建键值映射 (支持 "键: 值" 和 "键:值")
kv = {}
for line in lines:
m = _re.match(r'^(.+?)\s*[::]\s*(.+)$', line)
if m:
kv[m.group(1).strip().lower()] = m.group(2).strip()
# ── 卡号 ──
# 从键值对获取
for k in ("卡号", "card number", "card", "card_number"):
if k in kv:
digits = kv[k].replace(" ", "").replace("-", "")
if digits.isdigit() and 13 <= len(digits) <= 19:
result["card_number"] = digits
break
# 检查 "cardnum MM YY CVC" 单行格式 (如 "5481087136282260 03 32 221")
if "card_number" not in result:
for line in lines:
m = _re.match(r'^(\d{13,19})\s+(0[1-9]|1[0-2])\s+(\d{2,4})\s+(\d{3,4})$', line.replace("-", "").strip())
if m:
result["card_number"] = m.group(1)
result["exp_month"] = m.group(2)
yr = m.group(3)
if len(yr) == 2:
yr = "20" + yr
result["exp_year"] = yr
result["cvv"] = m.group(4)
break
# 回退: 纯数字行
if "card_number" not in result:
for line in lines:
digits_only = line.replace(" ", "").replace("-", "")
if digits_only.isdigit() and 13 <= len(digits_only) <= 19:
result["card_number"] = digits_only
break
# ── 有效期 ──
# 从键值对获取 (支持 MMYY, MM/YY, MM/YYYY)
for k in ("有效期", "exp", "expiry", "expiration", "exp_date"):
if k in kv:
val = kv[k]
# MM/YY 或 MM/YYYY
m = _re.search(r'(0[1-9]|1[0-2])\s*/\s*(\d{2,4})', val)
if m:
result["exp_month"] = m.group(1)
yr = m.group(2)
if len(yr) == 2:
yr = "20" + yr
result["exp_year"] = yr
break
# MMYY 或 MMYYYY (无分隔符)
m = _re.search(r'^(0[1-9]|1[0-2])(\d{2,4})$', val.strip())
if m:
result["exp_month"] = m.group(1)
yr = m.group(2)
if len(yr) == 2:
yr = "20" + yr
result["exp_year"] = yr
break
# 回退: 逐行寻找 MM/YY
if "exp_month" not in result:
for line in lines:
m = _re.search(r'\b(0[1-9]|1[0-2])\s*/\s*(\d{2,4})\b', line)
if m:
result["exp_month"] = m.group(1)
yr = m.group(2)
if len(yr) == 2:
yr = "20" + yr
result["exp_year"] = yr
break
# ── CVV ──
for k in ("cvv", "cvc", "安全码"):
if k in kv:
m = _re.search(r'\b(\d{3,4})\b', kv[k])
if m:
result["cvv"] = m.group(1)
break
if "cvv" not in result:
for i, line in enumerate(lines):
if _re.search(r'(?i)\b(?:cvv|cvc|安全码)\b', line):
m = _re.search(r'\b(\d{3,4})\b', line)
if m:
result["cvv"] = m.group(1)
elif i + 1 < len(lines):
m2 = _re.search(r'\b(\d{3,4})\b', lines[i + 1])
if m2:
result["cvv"] = m2.group(1)
break
# ── 地址: 键值对模式 (地址/城市/州/邮编/国家 分字段) ──
kv_addr = None
for k in ("地址", "address", "address_line1"):
if k in kv:
kv_addr = kv[k]
break
kv_city = None
for k in ("城市", "city"):
if k in kv:
kv_city = kv[k]
break
kv_state = None
for k in ("州", "state", "省"):
if k in kv:
kv_state = kv[k]
break
kv_zip = None
for k in ("邮编", "postal_code", "zip", "zipcode", "zip_code"):
if k in kv:
kv_zip = kv[k]
break
kv_country = None
for k in ("国家", "country", "地区"):
if k in kv:
kv_country = kv[k]
break
if kv_addr:
result["address_line1"] = kv_addr
if kv_city:
result["address_city"] = kv_city
result["address_state"] = kv_state or kv_city
elif kv_state:
result["address_state"] = kv_state
if kv_zip:
result["postal_code"] = kv_zip
if kv_country:
ci = _COUNTRY_ALIAS.get(kv_country)
if ci:
result["country_code"] = ci[0]
result["currency"] = ci[1]
# 构建 raw_address
parts = [kv_addr]
if kv_city:
parts.append(kv_city)
if kv_state:
parts.append(kv_state)
if kv_zip:
parts.append(kv_zip)
if kv_country:
parts.append(kv_country)
result["raw_address"] = ", ".join(parts)
# ── 地址: 回退 "账单地址" / "billing address" 单行模式 ──
if "address_line1" not in result:
addr_text = ""
for i, line in enumerate(lines):
if _re.search(r'(?i)账单地址|billing\s*address', line):
after = _re.sub(r'(?i)^.*?(账单地址|billing\s*address)\s*[::]?\s*', '', line).strip()
if after and len(after) > 3:
addr_text = after
else:
for j in range(i + 1, min(i + 5, len(lines))):
candidate = lines[j]
if candidate and candidate not in ("复制", "copy", ""):
addr_text = candidate
break
break
if addr_text:
result["raw_address"] = addr_text
parts = [p.strip() for p in addr_text.split(",")]
if len(parts) >= 2:
last = parts[-1].strip()
country_info = _COUNTRY_ALIAS.get(last)
if country_info:
result["country_code"] = country_info[0]
result["currency"] = country_info[1]
parts = parts[:-1]
for idx, p in enumerate(parts):
if _re.search(r'\b[A-Z]{1,2}\d[A-Z\d]?\s*\d[A-Z]{2}\b', p.strip(), _re.IGNORECASE):
result["postal_code"] = p.strip()
parts.pop(idx)
break
elif _re.search(r'\b\d{5}(-\d{4})?\b', p.strip()):
result["postal_code"] = p.strip()
parts.pop(idx)
break
elif _re.search(r'\b\d{3}-\d{4}\b', p.strip()):
result["postal_code"] = p.strip()
parts.pop(idx)
break
if len(parts) == 1:
result["address_line1"] = parts[0]
elif len(parts) == 2:
result["address_line1"] = parts[0]
result["address_state"] = parts[1]
elif len(parts) >= 3:
result["address_line1"] = parts[0]
result["address_state"] = parts[1]
# ── 姓名 ──
for k in ("姓名", "name", "cardholder", "持卡人"):
if k in kv:
result["billing_name"] = kv[k]
break
# ── 纯文本多行回退: 从非卡/非地址行中提取姓名 ──
if "billing_name" not in result:
for line in lines:
# 跳过已被解析的行 (卡号行、地址行)
stripped = line.strip()
if not stripped:
continue
# 跳过纯数字/卡号行
if _re.match(r'^[\d\s/\-]+$', stripped):
continue
# 跳过含邮编/地址的行
if _re.search(r'\d{5}', stripped) and ',' in stripped:
continue
# 跳过键值对行
if _re.match(r'^.+?[::]', stripped):
continue
# 可能是姓名: 2-5 个英文单词 (首字母大写)
if _re.match(r'^[A-Z][a-z]+(\s+[A-Z][a-z]+){0,4}$', stripped):
result["billing_name"] = stripped
break
# ── 纯文本多行回退: 从第二行解析地址 (如 "38 Pearl Avenue, Louisville, MS 39339, US") ──
if "address_line1" not in result and len(lines) >= 2:
for line in lines:
stripped = line.strip()
# 跳过卡号行 (全数字+空格)
if _re.match(r'^[\d\s/\-]+$', stripped):
continue
# 候选地址行: 含逗号、有数字(门牌号或邮编)
if ',' in stripped and _re.search(r'\d', stripped):
result["raw_address"] = stripped
parts = [p.strip() for p in stripped.split(",")]
# 检查最后部分是否是国家
if len(parts) >= 2:
last = parts[-1].strip()
country_info = _COUNTRY_ALIAS.get(last)
if country_info:
result["country_code"] = country_info[0]
result["currency"] = country_info[1]
parts = parts[:-1]
# 提取邮编
for idx, p in enumerate(parts):
zip_match = _re.search(r'\b(\d{5}(?:-\d{4})?)\b', p)
if zip_match:
result["postal_code"] = zip_match.group(1)
# 带邮编的部分可能是 "MS 39339" 或 "Louisville, MS 39339"
# 提取 state 代码
state_match = _re.match(r'^([A-Z]{2})\s+\d{5}', p.strip())
if state_match:
result["address_state"] = state_match.group(1)
parts.pop(idx)
else:
# 邮编在地址部分中, 分离
clean = _re.sub(r'\s*\d{5}(?:-\d{4})?\s*', '', p).strip()
if clean:
parts[idx] = clean
else:
parts.pop(idx)
break
# 分配剩余部分
if len(parts) >= 1:
result["address_line1"] = parts[0]
if len(parts) >= 2 and "address_state" not in result:
# 可能是 city 或 city, state
city_state = parts[1].strip()
csm = _re.match(r'^(.+?)\s+([A-Z]{2})$', city_state)
if csm:
result["address_city"] = csm.group(1)
result["address_state"] = csm.group(2)
else:
result["address_city"] = city_state
elif len(parts) >= 2:
result["address_city"] = parts[1]
break
break
return result
# 国家 → (code, currency, state, address, postal_code)
COUNTRY_MAP = {
"US - 美国": ("US", "USD", "California", "123 Main St", "90001"),
"DE - 德国": ("DE", "EUR", "Berlin", "Hauptstraße 1", "10115"),
"JP - 日本": ("JP", "JPY", "Tokyo", "1-1-1 Shibuya", "150-0002"),
"GB - 英国": ("GB", "GBP", "London", "10 Downing St", "SW1A 2AA"),
"FR - 法国": ("FR", "EUR", "Paris", "1 Rue de Rivoli", "75001"),
"SG - 新加坡": ("SG", "SGD", "Singapore", "1 Raffles Place", "048616"),
"HK - 香港": ("HK", "HKD", "Hong Kong", "1 Queen's Road", "000000"),
"KR - 韩国": ("KR", "KRW", "Seoul", "1 Gangnam-daero", "06000"),
"AU - 澳大利亚": ("AU", "AUD", "NSW", "1 George St", "2000"),
"CA - 加拿大": ("CA", "CAD", "Ontario", "123 King St", "M5H 1A1"),
"NL - 荷兰": ("NL", "EUR", "Amsterdam", "Damrak 1", "1012 LG"),
"IT - 意大利": ("IT", "EUR", "Rome", "Via Roma 1", "00100"),
"ES - 西班牙": ("ES", "EUR", "Madrid", "Calle Mayor 1", "28013"),
"CH - 瑞士": ("CH", "CHF", "Zurich", "Bahnhofstrasse 1", "8001"),
}
st.set_page_config(page_title="Let's ABC", page_icon="A", layout="wide")
# ── CSS ──
st.markdown("""
<style>
.block-container { max-width: 1100px; padding-top: 1.5rem; }
/* 更精细的排版 */
.stRadio > label { font-weight: 500; letter-spacing: 0.02em; }
.stRadio [data-baseweb="radio"] { gap: 0.3rem; }
.stTabs [data-baseweb="tab-list"] { gap: 0; border-bottom: 1px solid rgba(255,255,255,0.08); }
.stTabs [data-baseweb="tab"] {
padding: 0.6rem 1.5rem; font-weight: 500; letter-spacing: 0.05em;
border-bottom: 2px solid transparent; transition: all 0.2s;
}
.stTabs [aria-selected="true"] { border-bottom-color: #7c3aed; }
/* 进度条渐变 */
.stProgress > div > div > div { background: linear-gradient(90deg, #7c3aed, #3b82f6); }
/* 按键圆角 */
.stButton > button { border-radius: 8px; font-weight: 500; letter-spacing: 0.03em; transition: all 0.15s; }
.stButton > button[kind="primary"] { background: linear-gradient(135deg, #7c3aed, #6d28d9); border: none; }
.stButton > button[kind="primary"]:hover { background: linear-gradient(135deg, #6d28d9, #5b21b6); }
/* 输入框 */
.stTextInput > div > div > input { border-radius: 6px; }
/* Expander 样式 */
.streamlit-expanderHeader { font-weight: 500; letter-spacing: 0.02em; }
/* 分割线淡化 */
hr { opacity: 0.15; }
</style>
""", unsafe_allow_html=True)
# 后台日志缓存 — 使用 cache_resource 确保跨 rerun 同一对象
@st.cache_resource
def _get_log_shared():
return {"cache": deque(maxlen=5000), "lock": threading.Lock()}
_log_shared = _get_log_shared()
# ── 日志 ──
class LogCapture(logging.Handler):
def __init__(self, shared):
super().__init__()
self._cache = shared["cache"]
self._lock = shared["lock"]
self.setFormatter(logging.Formatter("%(asctime)s [%(levelname)s] %(name)s: %(message)s", "%H:%M:%S"))
def emit(self, record):
msg = self.format(record)
with self._lock:
self._cache.append(msg)
def pull_captured_logs():
"""将后台日志搬运到 session_state,需在主线程调用。"""
if "log_buffer" not in st.session_state:
st.session_state.log_buffer = []
cache = _log_shared["cache"]
lock = _log_shared["lock"]
with lock:
if not cache:
return
st.session_state.log_buffer.extend(list(cache))
cache.clear()
def clear_captured_logs():
cache = _log_shared["cache"]
lock = _log_shared["lock"]
with lock:
cache.clear()
def init_logging():
handler = LogCapture(_log_shared)
handler.setLevel(logging.INFO)
handler._is_log_capture = True
root = logging.getLogger()
root.setLevel(logging.INFO)
root.handlers = [h for h in root.handlers if not getattr(h, '_is_log_capture', False)]
root.addHandler(handler)
# 同时输出到 stdout (systemd/journalctl 可读)
if not any(isinstance(h, logging.StreamHandler) and not getattr(h, '_is_log_capture', False) for h in root.handlers):
sh = logging.StreamHandler()
sh.setLevel(logging.INFO)
sh.setFormatter(logging.Formatter("%(asctime)s [%(levelname)s] %(name)s: %(message)s", "%H:%M:%S"))
root.addHandler(sh)
logging.getLogger("watchdog").setLevel(logging.WARNING)
for k, v in {"log_buffer": [], "running": False, "result": None}.items():
if k not in st.session_state:
st.session_state[k] = v
# 每次 rerun 先同步一次日志缓存
pull_captured_logs()
# ── widget 默认值初始化 (只在首次运行时设置) ──
_widget_defaults = {
"w_exp_month": "12",
"w_exp_year": "2030",
"w_proxy": "",
"w_billing_name": "",
}
for _dk, _dv in _widget_defaults.items():
if _dk not in st.session_state:
st.session_state[_dk] = _dv
# ── 延迟的解析结果应用 (必须在 widget 渲染之前) ──
_parse_just_applied = False
if "_pending_parse" in st.session_state:
_pp = st.session_state.pop("_pending_parse")
for _pk, _pv in _pp.items():
st.session_state[_pk] = _pv
_parse_just_applied = True
# ════════════════════════════════════════
# 顶部
# ════════════════════════════════════════
st.markdown(
'<h1 style="text-align:center;letter-spacing:3px;">'
"Let's "
'<span style="font-family:\'Courier New\',monospace;font-weight:900;'
'background:linear-gradient(135deg,#7c3aed,#3b82f6);-webkit-background-clip:text;'
'-webkit-text-fill-color:transparent;font-size:1.15em;">ABC</span>'
' <span style="font-size:0.5em;opacity:0.6;vertical-align:middle;">(Auto BindCard)</span>'
'</h1>',
unsafe_allow_html=True,
)
# ── 开发者模式: 启动时通过 -- --dev 参数开启 ──
# 用法: streamlit run ui.py -- --dev
dev_mode = "--dev" in sys.argv
# ═══════════════════════════════════════
# 兑换码验证门禁 (仅在 code_system_enabled=true 时启用)
# ═══════════════════════════════════════
if "verified_code" not in st.session_state:
st.session_state.verified_code = "" if _ENABLE_CODE_SYSTEM else "__disabled__"
if _ENABLE_CODE_SYSTEM and not st.session_state.verified_code:
st.markdown(
'<div style="text-align:center;margin:40px 0 20px;opacity:0.7">输入兑换码开始使用</div>',
unsafe_allow_html=True,
)
_code_col1, _code_col2 = st.columns([3, 1])
with _code_col1:
_input_code = st.text_input("兑换码", placeholder="XXXX-XXXX-XXXX", label_visibility="collapsed")
with _code_col2:
_verify_btn = st.button("验证", type="primary", use_container_width=True)
if _verify_btn and _input_code:
_valid, _msg = validate_code(_input_code.strip())
if _valid:
st.session_state.verified_code = _input_code.strip()
st.rerun()
else:
st.error(_msg)
st.stop()
# ── 已验证: 显示兑换码状态 ──
_code_info = get_code_info(st.session_state.verified_code) if _ENABLE_CODE_SYSTEM else None
if _code_info:
_remaining = _code_info["total_uses"] - _code_info["used_count"]
_status_col1, _status_col2 = st.columns([5, 1])
with _status_col1:
st.caption(f"兑换码: `{st.session_state.verified_code}` — 剩余 {_remaining}/{_code_info['total_uses']} 次")
with _status_col2:
if st.button("退出", key="logout_code"):
st.session_state.verified_code = ""
st.rerun()
# ── 账号来源选择 ──
# 从数据库获取当前兑换码的有 token 的执行记录 (用于「选择已有账号」)
_code_history = get_code_history(st.session_state.verified_code) if _ENABLE_CODE_SYSTEM else []
_code_success_creds = []
for _h in _code_history:
if _h.get("result_json"):
try:
_rd = json.loads(_h["result_json"])
if _rd.get("email") and _rd.get("access_token"):
_code_success_creds.append(_rd)
except Exception:
pass
acct_col, proxy_col = st.columns([3, 2])
with acct_col:
account_source = st.radio(
"账号来源",
["新注册", "选择已有账号", "手动输入 Token"],
index=1 if _code_success_creds else 0,
horizontal=True,
)
do_register = account_source == "新注册"
do_checkout = True
do_payment = True
if dev_mode:
with proxy_col:
sc1, sc2 = st.columns(2)
do_checkout = sc1.checkbox("创建 Checkout", value=True)
do_payment = sc2.checkbox("提交支付", value=True)
with proxy_col:
proxy = st.text_input("代理", placeholder="http://127.0.0.1:7897", key="w_proxy")
# ── 已有账号选择 / Token 输入 ──
cred_email = ""
cred_session_token = ""
cred_access_token = ""
cred_device_id = ""
use_existing_creds = not do_register
if account_source == "选择已有账号":
if _code_success_creds:
_cred_options = {}
for _cd in _code_success_creds:
_label = f"{_cd.get('email', '未知')}"
_cred_options[_label] = _cd
if _cred_options:
sel_label = st.selectbox("选择账号", list(_cred_options.keys()), key="w_acct_select")
_sel_data = _cred_options[sel_label]
cred_email = _sel_data.get("email", "")
cred_session_token = _sel_data.get("session_token", "")
cred_access_token = _sel_data.get("access_token", "")
cred_device_id = _sel_data.get("device_id", "")
with st.expander("查看凭证详情", expanded=False):
st.json({k: (v[:40] + "..." if isinstance(v, str) and len(v) > 50 else v) for k, v in _sel_data.items()})
else:
st.warning("未找到有效的凭证")
else:
st.warning("暂无已注册的账号,请先选择「新注册」")
elif account_source == "手动输入 Token":
cred_access_token = st.text_input("access_token", placeholder="eyJhbGciOi...", type="password", key="w_manual_at")
cred_session_token = st.text_input("session_token", placeholder="eyJhbGciOi...", type="password", key="w_manual_st",
help="浏览器 F12 → Application → Cookies → __Secure-next-auth.session-token")
cred_email = st.text_input("邮箱 (可选)", placeholder="user@example.com", key="w_manual_email")
# ── 注册模式下显示邮箱配置 ──
if do_register:
with st.expander("邮箱配置", expanded=True):
_mc1, _mc2, _mc3 = st.columns(3)
mail_worker = _mc1.text_input("Worker API", placeholder="https://mail-api.example.com", key="w_mail_worker_reg")
mail_domain = _mc2.text_input("邮箱域名", placeholder="example.com", key="w_mail_domain_reg")
mail_token = _mc3.text_input("密码", placeholder="your-mail-token", type="password", key="w_mail_token_reg")
# 默认值 (非开发者模式下不显示这些设置)
use_browser_mode = True
captcha_key = ""
captcha_api_url = ""
if not do_register:
# 非注册模式时,邮箱配置使用空默认值 (开发者模式下有单独的输入框)
mail_worker = ""
mail_domain = ""
mail_token = ""
# 计划类型选择 (始终可见)
plan_type_label = st.radio(
"选择计划",
["Business · 团队版免费试用 1 个月", "Plus · 个人版免费试用 1 个月"],
index=0,
horizontal=True,
)
plan_type = "plus" if "Plus" in plan_type_label else "team"
if plan_type == "plus":
workspace_name = ""
seat_quantity = 0
promo_campaign = "plus-1-month-free"
else:
workspace_name = "MyWorkspace"
seat_quantity = 5
promo_campaign = "team-1-month-free"
if dev_mode:
with st.expander("高级设置", expanded=False):
adv_col1, adv_col2 = st.columns(2)
with adv_col1:
payment_mode = st.radio(
"支付模式",
["浏览器模式 (推荐)", "API 模式"],
index=0,
horizontal=True,
)
use_browser_mode = payment_mode.startswith("浏览")
with adv_col2:
if use_browser_mode:
import subprocess as _sp
_xvfb_running = False
try:
_xvfb_pids = _sp.check_output(["pgrep", "-f", "Xvfb :99"], stderr=_sp.DEVNULL).decode().strip()
_xvfb_running = bool(_xvfb_pids)
except Exception:
pass
if _xvfb_running:
st.success("Xvfb 运行中 (:99)")
else:
st.info("将自动启动 Xvfb :99")
else:
st.info("API 模式")
if not use_browser_mode:
captcha_col1, captcha_col2 = st.columns([3, 1])
with captcha_col1:
captcha_key = st.text_input("YesCaptcha API Key", placeholder="your-yescaptcha-key", type="password")
with captcha_col2:
captcha_api_url = st.text_input("打码 API", value="https://api.yescaptcha.com")
st.markdown("---")
st.markdown("**邮箱 & 计划设置**")
if not do_register:
mail_worker = st.text_input("邮箱 Worker", placeholder="https://mail-api.example.com", key="w_mail_worker_dev")
adv_mc1, adv_mc2 = st.columns(2)
mail_domain = adv_mc1.text_input("邮箱域名", placeholder="example.com", key="w_mail_domain_dev")
mail_token = adv_mc2.text_input("密码", placeholder="your-mail-token", type="password", key="w_mail_token_dev")
if plan_type == "team":
adv_tc1, adv_tc2, adv_tc3 = st.columns(3)
workspace_name = adv_tc1.text_input("Workspace", value="MyWorkspace")
seat_quantity = adv_tc2.number_input("席位数", min_value=2, max_value=50, value=5)
promo_campaign = adv_tc3.text_input("活动 ID", value="team-1-month-free")
else:
promo_campaign = st.text_input("活动 ID", value="plus-1-month-free")
st.divider()
# ════════════════════════════════════════
# 配置区: 卡片信息优先
# ════════════════════════════════════════
if do_payment:
with st.expander("粘贴卡片信息", expanded=True):
paste_text = st.text_area(
"粘贴卡片/账单文本",
height=120,
placeholder="支持两种格式:\n\n格式1 (键值对):\n卡号: 4242424242424242\n有效期: 1230\nCVV: 123\n姓名: John Smith\n地址: 123 Main Street\n城市: San Francisco\n州: CA\n邮编: 94102\n国家: United States\n\n格式2 (纯文本):\n4242 4242 4242 4242\n12/30\nCVV 123",
key="paste_card_text",
)
if st.button("识别并填充", key="parse_btn", disabled=not paste_text):
parsed = _parse_card_text(paste_text)
pending = {}
if parsed.get("card_number"):
pending["w_card_number"] = parsed["card_number"]
if parsed.get("exp_month"):
pending["w_exp_month"] = parsed["exp_month"]
if parsed.get("exp_year"):
pending["w_exp_year"] = parsed["exp_year"]
if parsed.get("cvv"):
pending["w_card_cvc"] = parsed["cvv"]
if parsed.get("address_line1"):
pending["w_address_line1"] = parsed["address_line1"]
if parsed.get("address_city"):
pending["w_address_city"] = parsed["address_city"]
if parsed.get("address_state"):
pending["w_address_state"] = parsed["address_state"]
if parsed.get("postal_code"):
pending["w_postal_code"] = parsed["postal_code"]
if parsed.get("country_code"):
cc = parsed["country_code"]
for i, label in enumerate(COUNTRY_MAP.keys()):
if label.startswith(cc):
pending["w_country"] = label
break
if parsed.get("currency"):
pending["w_currency"] = parsed["currency"]
if parsed.get("billing_name"):
pending["w_billing_name"] = parsed["billing_name"]
st.session_state["_pending_parse"] = pending
filled = []
if parsed.get("card_number"):
filled.append(f"卡号: {parsed['card_number'][:4]}****{parsed['card_number'][-4:]}")
if parsed.get("exp_month"):
filled.append(f"有效期: {parsed['exp_month']}/{parsed['exp_year']}")
if parsed.get("cvv"):
filled.append(f"CVV: ***")
if parsed.get("raw_address"):
filled.append(f"地址: {parsed['raw_address']}")
if parsed.get("billing_name"):
filled.append(f"姓名: {parsed['billing_name']}")
if filled:
st.success("已识别: " + " | ".join(filled))
else:
st.warning("未能识别卡片信息,请检查文本格式")
st.rerun()
cfg_col1, cfg_col2 = st.columns(2)
with cfg_col1:
if do_payment:
with st.expander("信用卡", expanded=True):
TEST_CARDS = {
"4242 4242 4242 4242 (Visa 标准)": ("4242424242424242", "123"),
"4000 0000 0000 0002 (Visa 被拒)": ("4000000000000002", "123"),
"4000 0000 0000 0069 (Visa 过期)": ("4000000000000069", "123"),
"4000 0000 0000 9995 (Visa 余额不足)": ("4000000000009995", "123"),
"5555 5555 5555 4444 (Mastercard)": ("5555555555554444", "123"),
"5200 8282 8282 8210 (MC Debit)": ("5200828282828210", "123"),
"2223 0031 2200 3222 (MC 2系列)": ("2223003122003222", "123"),
"3782 822463 10005 (Amex)": ("378282246310005", "1234"),
}
tc_sel = st.selectbox("快速填充测试卡", ["不填充"] + list(TEST_CARDS.keys()), key="tc_sel")
if tc_sel != "不填充":
tc_num, tc_cvc = TEST_CARDS[tc_sel]
st.session_state["w_card_number"] = tc_num
st.session_state["w_card_cvc"] = tc_cvc
cc1, cc2, cc3, cc4 = st.columns([5, 2, 2, 2])
card_number = cc1.text_input("卡号", placeholder="真实卡号", key="w_card_number")
exp_month = cc2.text_input("月", key="w_exp_month")
exp_year = cc3.text_input("年", key="w_exp_year")
card_cvc = cc4.text_input("CVC", key="w_card_cvc")
if card_number and card_number.startswith("4"):
st.caption("Live 模式下所有测试卡都会被拒绝,仅用于验证流程")
else:
card_number = exp_month = exp_year = card_cvc = ""
with cfg_col2:
with st.expander("账单地址", expanded=True):
# 如果有解析出的国家,自动选择对应国家
country_label = st.selectbox("国家", list(COUNTRY_MAP.keys()), key="w_country")
country_code, default_currency, default_state, default_addr, default_zip = COUNTRY_MAP[country_label]
# 当国家变更时,更新地址默认值 (但不覆盖刚解析的值)
_prev_country = st.session_state.get("_prev_country", "")
if _prev_country and _prev_country != country_label and not _parse_just_applied:
st.session_state["w_currency"] = default_currency
st.session_state["w_address_line1"] = default_addr
st.session_state["w_address_state"] = default_state
st.session_state["w_postal_code"] = default_zip
st.session_state["_prev_country"] = country_label
bc1, bc2 = st.columns(2)
billing_name = bc1.text_input("姓名", key="w_billing_name")
if "w_currency" not in st.session_state:
st.session_state["w_currency"] = default_currency
currency = bc2.text_input("货币", key="w_currency")
bc3, bc4, bc5, bc6 = st.columns(4)
if "w_address_line1" not in st.session_state:
st.session_state["w_address_line1"] = default_addr
if "w_address_city" not in st.session_state:
st.session_state["w_address_city"] = ""
if "w_address_state" not in st.session_state:
st.session_state["w_address_state"] = default_state
if "w_postal_code" not in st.session_state:
st.session_state["w_postal_code"] = default_zip
address_line1 = bc3.text_input("地址", key="w_address_line1")
address_city = bc4.text_input("城市", key="w_address_city")
address_state = bc5.text_input("州/省", key="w_address_state")
postal_code = bc6.text_input("邮编", key="w_postal_code")
st.divider()
# ════════════════════════════════════════
# Tab
# ════════════════════════════════════════
steps_list = []
if do_register: steps_list.append("注册")
if do_checkout: steps_list.append("Checkout")
if do_payment: steps_list.append("支付")
tab_run, tab_accounts, tab_history = st.tabs(["执行", "账号", "历史"])
# 日志关键词 → 进度百分比映射
_PROGRESS_KEYWORDS = [
("使用已有凭证", 5),
("邮箱创建成功", 3),
("注册完成", 10),
("创建 Checkout Session", 12),
("Checkout 创建成功", 18),
("启动 Chrome", 22),
("Chrome ready", 28),
("通过 Cloudflare", 32),
("Cloudflare 已通过", 38),
("加载 checkout 页面", 42),
("Stripe Payment Element", 48),
("Stripe Element 已加载", 55),
("填写卡片信息", 60),
("已输入卡号", 65),
("已输入 CVC", 70),
("填写账单地址", 73),
("地址-邮编", 78),
("已点击提交按钮", 82),
("等待支付处理", 85),
("hCaptcha", 88),
("checkbox 已点击", 92),
("支付成功", 98),
("支付被拒", 98),
("支付失败", 98),
]
def _calc_progress_pct():
"""根据 session_state.log_buffer (累积) 计算当前进度百分比"""
pull_captured_logs() # 先把 _LOG_CACHE 搬运到 log_buffer
logs = st.session_state.get("log_buffer", [])
if not logs:
return 1
text = "\n".join(logs[-30:])
best = 1
for keyword, pct in _PROGRESS_KEYWORDS:
if keyword in text and pct > best:
best = pct
return best
def _run_flow_thread(rd, cs):
"""在后台线程中执行完整流程 (cs = config_snapshot)"""
try:
cfg = Config()
cfg.proxy = cs["proxy"]
cfg.mail.email_domain = cs["mail_domain"]
cfg.mail.worker_domain = cs["mail_worker"]
cfg.mail.admin_token = cs["mail_token"]
cfg.team_plan.workspace_name = cs["workspace_name"]
cfg.team_plan.seat_quantity = cs["seat_quantity"]
cfg.team_plan.promo_campaign_id = cs["promo_campaign"]
cfg.captcha = CaptchaConfig(api_url=cs["captcha_api_url"], client_key=cs["captcha_key"])
cfg.billing = BillingInfo(
name=cs["billing_name"], email="",
country=cs["country_code"], currency=cs["currency"],
address_line1=cs["address_line1"], address_state=cs["address_state"],
postal_code=cs["postal_code"])
if cs["do_payment"]:
cfg.card = CardInfo(number=cs["card_number"], cvc=cs["card_cvc"],
exp_month=cs["exp_month"], exp_year=cs["exp_year"])
store = ResultStore(output_dir=OUTPUT_DIR)
auth_result = None
af = None
if cs["do_register"]:
mp = MailProvider(worker_domain=cfg.mail.worker_domain, admin_token=cfg.mail.admin_token, email_domain=cfg.mail.email_domain)
af = AuthFlow(cfg)
auth_result = af.run_register(mp)
rd["email"] = auth_result.email
rd["session_token"] = auth_result.session_token
rd["access_token"] = auth_result.access_token
rd["device_id"] = auth_result.device_id
store.save_credentials(auth_result.to_dict())
store.append_credentials_csv(auth_result.to_dict())
elif cs["use_existing_creds"] and cs["do_checkout"]:
if not cs["cred_access_token"]:
raise RuntimeError("必须提供 access_token")
af = AuthFlow(cfg)
auth_result = af.from_existing_credentials(
session_token=cs["cred_session_token"],
access_token=cs["cred_access_token"],
device_id=cs["cred_device_id"],
)
auth_result.email = cs["cred_email"] or "unknown@example.com"
rd["email"] = auth_result.email
if cs["do_checkout"]:
if not auth_result:
raise RuntimeError("需先注册或提供凭证")
if cs["use_browser_mode"] and cs["do_payment"]:
import subprocess as _sp
_xvfb_ok = False
try:
_sp.check_output(["pgrep", "-f", "Xvfb :99"], stderr=_sp.DEVNULL)
_xvfb_ok = True
except Exception:
pass
if not _xvfb_ok:
_sp.Popen(["Xvfb", ":99", "-screen", "0", "1920x1080x24", "-ac"],
stdout=_sp.DEVNULL, stderr=_sp.DEVNULL)
import time as _t; _t.sleep(1)
os.environ["DISPLAY"] = ":99"
from browser_payment import BrowserPayment
bp = BrowserPayment(proxy=cfg.proxy, headless=False, slow_mo=80)
br = bp.run_full_flow(
session_token=auth_result.session_token,
access_token=auth_result.access_token,
device_id=auth_result.device_id,
card_number=cs["card_number"], card_exp_month=cs["exp_month"],
card_exp_year=cs["exp_year"], card_cvc=cs["card_cvc"],
billing_name=cs["billing_name"], billing_country=cs["country_code"],
billing_zip=cs["postal_code"], billing_line1=cs["address_line1"],
billing_city=cs["address_city"], billing_state=cs["address_state"],
billing_email=auth_result.email, billing_currency=cs["currency"],
chatgpt_proxy=cfg.proxy, timeout=120,
plan_type=cs["plan_type"],
)
rd["checkout_data"] = br.get("checkout_data")
rd["checkout_session_id"] = br.get("checkout_data", {}).get("checkout_session_id", "")
rd["success"] = br.get("success", False)
rd["error"] = br.get("error", "")
rd["confirm_response"] = br
else:
cfg.billing.email = auth_result.email
pf = PaymentFlow(cfg, auth_result)
if af: pf.session = af.session
cs_id = pf.create_checkout_session()
rd["checkout_session_id"] = cs_id
rd["checkout_data"] = pf.checkout_data
pf.fetch_stripe_fingerprint()
pf.extract_stripe_pk(pf.checkout_url)
if cs["do_payment"]:
pf.payment_method_id = pf.create_payment_method()
pf.fetch_payment_page_details(cs_id)
pay = pf.confirm_payment(cs_id)
rd["confirm_status"] = pay.confirm_status
rd["confirm_response"] = pay.confirm_response
rd["success"] = pay.success
rd["error"] = pay.error
else: