| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644 |
- """本地 Web 控制台:网页配置 + 一键全自动注册→付款→上传 CPA。"""
- from __future__ import annotations
- import json
- import queue
- import threading
- import time
- from dataclasses import asdict
- from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
- from chatgpt_flow import FullRunContext, run_full
- from config import AppConfig
- from cpa_uploader import build_cpa_auth_payload
- from storage import get_account, init_db, list_accounts, list_events
- HOST = "127.0.0.1"
- PORT = 7791
- class JobManager:
- def __init__(self):
- self.lock = threading.Lock()
- self.full_ctx: FullRunContext | None = None
- self.thread: threading.Thread | None = None
- self.log_queue: queue.Queue[str] = queue.Queue()
- self.history: list[str] = []
- self.stage: str = ""
- def _log(self, msg: str):
- line = f"[{time.strftime('%H:%M:%S')}] {msg}"
- self.history.append(line)
- if len(self.history) > 4000:
- self.history = self.history[-3000:]
- self.log_queue.put(line)
- def _on_stage(self, name: str):
- self.stage = name
- # stage 也写到日志,便于复盘
- self._log(f"[STAGE] {name}")
- def start(self, cfg: AppConfig) -> str:
- with self.lock:
- if self.thread and self.thread.is_alive():
- return "已有任务在运行"
- self.history.clear()
- while not self.log_queue.empty():
- self.log_queue.get_nowait()
- self.stage = ""
- def runner():
- try:
- self.full_ctx = run_full(cfg, log=self._log, on_stage=self._on_stage)
- except Exception as exc:
- import traceback
- self._log(f"[server] 任务异常: {exc!r}")
- self._log(traceback.format_exc())
- self.thread = threading.Thread(target=runner, daemon=True)
- self.thread.start()
- return ""
- def stop(self):
- if self.full_ctx:
- self.full_ctx.state = "stopped"
- self._log("[user] 已请求停止")
- def status(self) -> dict:
- running = bool(self.thread and self.thread.is_alive())
- ctx = self.full_ctx
- accounts = []
- state = "idle"
- if ctx:
- state = ctx.state
- for a in ctx.accounts:
- accounts.append({
- "email": a.get("email"),
- "stage": a.get("stage"),
- "planType": a.get("planType"),
- "error": a.get("error"),
- "cpaFile": (a.get("cpa") or {}).get("fileName") if a.get("cpa") else None,
- })
- return {
- "running": running,
- "state": state,
- "stage": self.stage,
- "accounts": accounts,
- }
- JOB = JobManager()
- INDEX_HTML = r"""<!doctype html>
- <html lang="zh-CN">
- <head>
- <meta charset="utf-8" />
- <meta name="viewport" content="width=device-width,initial-scale=1" />
- <title>ChatGPT Plus 全自动注册</title>
- <style>
- :root { color-scheme: light; font-family: -apple-system,BlinkMacSystemFont,"Segoe UI","PingFang SC","Microsoft YaHei",sans-serif; }
- body { margin:0; background:#f5f5f7; color:#111; }
- .wrap { max-width: 980px; margin: 24px auto; padding: 0 16px; }
- .card { background:#fff; border:1px solid #ddd; border-radius:18px; padding:22px; box-shadow:0 14px 40px rgba(0,0,0,.06); margin-bottom:18px; }
- h1 { margin: 0 0 6px; font-size: 22px; }
- h2 { margin: 0 0 10px; font-size: 16px; }
- p, li { color:#666; line-height:1.6; }
- label { display:block; margin:14px 0 6px; font-weight:600; }
- input, select { width:100%; box-sizing:border-box; border:1px solid #ccc; border-radius:10px; padding:9px 10px; font:inherit; background:#fff; }
- .grid { display:grid; grid-template-columns: 1fr 1fr; gap: 14px; }
- .grid-3 { display:grid; grid-template-columns: 1fr 1fr 1fr; gap: 14px; }
- .row { display:flex; gap:10px; align-items:center; flex-wrap:wrap; margin-top:14px; }
- button { border:0; border-radius:12px; background:#111; color:#fff; padding:10px 16px; font-weight:700; cursor:pointer; }
- button.secondary { background:#e9e9ec; color:#111; }
- button:disabled { opacity:.55; cursor:not-allowed; }
- .muted { color:#777; font-size:13px; }
- .chip { display:inline-block; padding:3px 10px; border-radius:999px; font-size:12px; background:#eef; color:#225; }
- .chip.green { background:#e6f7ec; color:#0f5f22; }
- .chip.red { background:#fde7e7; color:#a40000; }
- .chip.gray { background:#eee; color:#444; }
- .chip.blue { background:#e7f0ff; color:#1d4ed8; }
- pre.log { height:340px; overflow:auto; background:#0b0b10; color:#d6d6dc; padding:12px; border-radius:12px; font-size:12px; line-height:1.5; white-space:pre-wrap; word-break:break-all; }
- table { width:100%; border-collapse: collapse; font-size:13px; }
- th, td { padding:8px 10px; border-bottom:1px solid #eee; text-align:left; vertical-align:top; }
- th { background:#fafafa; font-weight:600; color:#333; }
- .stage-box { padding:10px 14px; border-radius:12px; background:#fffaf0; border:1px solid #ffe2a8; color:#7a4f00; font-size:13px; min-height: 22px; }
- </style>
- </head>
- <body>
- <div class="wrap">
- <div class="card">
- <h1>ChatGPT Plus 全自动注册 + CPA 上传</h1>
- <div class="muted">流程:a4sky 邮箱注册 → 拿 Plus 长链 → PayPal 创建账号付款 → 校验 plan=plus → 上传 CPA。手机号统一 +15822201173。</div>
- </div>
- <div class="card">
- <h2>配置</h2>
- <div class="grid">
- <div>
- <label>账号数量</label>
- <input id="cfg_account_count" type="number" min="1" value="1" />
- </div>
- <div>
- <label>浏览器模式</label>
- <select id="cfg_headless">
- <option value="false" selected>有头(推荐,方便干预)</option>
- <option value="true">无头</option>
- </select>
- </div>
- </div>
- <div class="grid">
- <div>
- <label>邮件助手 URL</label>
- <input id="cfg_mail_helper_url" placeholder="http://ali.ss5.xyz:17373" />
- </div>
- <div>
- <label>邮箱域名</label>
- <input id="cfg_mail_domain" placeholder="edu.a4sky.com" />
- </div>
- </div>
- <div class="grid-3">
- <div>
- <label>邮箱轮询间隔(秒)</label>
- <input id="cfg_mail_poll_interval_sec" type="number" min="1" value="4" />
- </div>
- <div>
- <label>邮箱轮询次数</label>
- <input id="cfg_mail_poll_max_attempts" type="number" min="5" value="60" />
- </div>
- <div>
- <label>使用 1 个月免费 promo</label>
- <select id="cfg_use_promo">
- <option value="true" selected>是</option>
- <option value="false">否</option>
- </select>
- </div>
- </div>
- <div class="grid">
- <div>
- <label>PayPal 短信手机号 (E164)</label>
- <input id="cfg_phone_e164" placeholder="+15822201173" />
- </div>
- <div>
- <label>接码 API URL</label>
- <input id="cfg_sms_api_url" placeholder="http://a.62-us.com/api/get_sms?key=..." />
- </div>
- </div>
- <div class="grid">
- <div>
- <label>CPA 地址</label>
- <input id="cfg_cpa_url" placeholder="http://your-cpa-host:port" />
- </div>
- <div>
- <label>CPA 管理密钥</label>
- <input id="cfg_cpa_management_key" placeholder="管理 token" />
- </div>
- </div>
- <div class="row">
- <button id="save">保存配置</button>
- <button id="go">开始全自动</button>
- <button id="stop" class="secondary" disabled>停止</button>
- <span id="state" class="chip gray">空闲</span>
- </div>
- </div>
- <div class="card">
- <h2>当前阶段</h2>
- <div id="stageBox" class="stage-box">空闲</div>
- </div>
- <div class="card">
- <h2>账号进度</h2>
- <table id="accTable">
- <thead><tr><th>#</th><th>邮箱</th><th>阶段</th><th>planType</th><th>CPA 文件</th><th>错误</th></tr></thead>
- <tbody></tbody>
- </table>
- </div>
- <div class="card">
- <h2>已注册账号库</h2>
- <div class="row" style="margin-top:0">
- <button id="refreshAccounts" class="secondary">刷新</button>
- <select id="accFilter" style="max-width:200px">
- <option value="">全部状态</option>
- <option value="registered">已注册</option>
- <option value="paid">已付款</option>
- <option value="plus">已 Plus</option>
- <option value="cpa_uploaded">已上传 CPA</option>
- <option value="cpa_skipped">CPA 跳过</option>
- <option value="failed">失败</option>
- <option value="plus_check_failed">Plus 校验失败</option>
- <option value="cpa_failed">CPA 上传失败</option>
- </select>
- <span class="muted">数据库:<code>data/accounts.db</code></span>
- </div>
- <table id="dbTable">
- <thead><tr><th>邮箱</th><th>plan</th><th>状态</th><th>CPA 文件</th><th>注册时间</th><th>更新时间</th><th>错误</th><th>动作</th></tr></thead>
- <tbody></tbody>
- </table>
- <details style="margin-top:10px">
- <summary class="muted">点击查看选中账号详情</summary>
- <pre id="accDetail" class="log" style="height:240px"></pre>
- </details>
- </div>
- <div class="card">
- <h2>实时日志</h2>
- <pre id="log" class="log"></pre>
- </div>
- </div>
- <script>
- const $ = id => document.getElementById(id);
- const FIELDS = [
- ['cfg_account_count','account_count','int'],
- ['cfg_headless','headless','bool'],
- ['cfg_mail_helper_url','mail_helper_url','str'],
- ['cfg_mail_domain','mail_domain','str'],
- ['cfg_mail_poll_interval_sec','mail_poll_interval_sec','int'],
- ['cfg_mail_poll_max_attempts','mail_poll_max_attempts','int'],
- ['cfg_use_promo','use_promo','bool'],
- ['cfg_phone_e164','phone_e164','str'],
- ['cfg_sms_api_url','sms_api_url','str'],
- ['cfg_cpa_url','cpa_url','str'],
- ['cfg_cpa_management_key','cpa_management_key','str'],
- ];
- function fillForm(cfg) {
- for (const [domId, key, kind] of FIELDS) {
- const el = $(domId);
- if (!el || cfg[key] === undefined) continue;
- if (kind === 'bool') {
- el.value = cfg[key] ? 'true' : 'false';
- } else {
- el.value = cfg[key];
- }
- }
- }
- function readForm() {
- const out = {};
- for (const [domId, key, kind] of FIELDS) {
- const el = $(domId);
- if (!el) continue;
- let v = el.value;
- if (kind === 'int') v = Number(v) || 0;
- else if (kind === 'bool') v = (v === 'true' || v === true);
- out[key] = v;
- }
- return out;
- }
- async function loadConfig() {
- const r = await fetch('/api/config');
- const data = await r.json();
- fillForm(data);
- }
- async function saveConfig() {
- const body = readForm();
- const r = await fetch('/api/config', {method:'POST', headers:{'Content-Type':'application/json'}, body: JSON.stringify(body)});
- if (!r.ok) { alert('保存失败 HTTP ' + r.status); return; }
- const data = await r.json();
- fillForm(data);
- }
- function setState(text, cls) {
- const el = $('state');
- el.textContent = text;
- el.className = 'chip ' + (cls || 'gray');
- }
- let evtSource = null;
- function startLogStream() {
- if (evtSource) evtSource.close();
- evtSource = new EventSource('/api/log');
- evtSource.onmessage = e => {
- if (!e.data) return;
- const log = $('log');
- log.textContent += e.data + '\n';
- log.scrollTop = log.scrollHeight;
- };
- }
- function renderAccounts(accounts) {
- const tbody = $('accTable').querySelector('tbody');
- tbody.innerHTML = '';
- accounts.forEach((a, idx) => {
- const tr = document.createElement('tr');
- tr.innerHTML = `<td>${idx+1}</td><td>${a.email||''}</td><td>${a.stage||''}</td><td>${a.planType||''}</td><td>${a.cpaFile||''}</td><td style="color:#a40000">${a.error||''}</td>`;
- tbody.appendChild(tr);
- });
- }
- async function refreshStatus() {
- try {
- const r = await fetch('/api/status');
- const data = await r.json();
- $('stageBox').textContent = data.stage || '空闲';
- renderAccounts(data.accounts || []);
- if (data.running) {
- setState('执行中', 'green');
- $('go').disabled = true;
- $('stop').disabled = false;
- } else {
- $('go').disabled = false;
- $('stop').disabled = true;
- if (data.state === 'done') setState('完成', 'green');
- else if (data.state === 'error') setState('异常', 'red');
- else if (data.state === 'stopped') setState('已停止', 'red');
- else setState('空闲', 'gray');
- }
- } catch (_) {}
- }
- setInterval(refreshStatus, 1500);
- refreshStatus();
- startLogStream();
- loadConfig();
- loadAccounts();
- function fmtTime(ms) {
- if (!ms) return '';
- const d = new Date(Number(ms));
- if (isNaN(d.getTime())) return '';
- const pad = n => String(n).padStart(2,'0');
- return `${d.getFullYear()}-${pad(d.getMonth()+1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`;
- }
- async function loadAccounts() {
- const status = $('accFilter').value || '';
- const url = status ? '/api/accounts?status=' + encodeURIComponent(status) : '/api/accounts';
- try {
- const r = await fetch(url);
- const data = await r.json();
- const tbody = $('dbTable').querySelector('tbody');
- tbody.innerHTML = '';
- (data.accounts || []).forEach(a => {
- const tr = document.createElement('tr');
- const detailBtn = `<button class="secondary" data-email="${a.email}" data-action="detail" style="padding:4px 10px">详情</button>`;
- const dlBtn = a.cpa_file_name
- ? ` <a href="/api/account/${encodeURIComponent(a.email)}/cpa.json" target="_blank" rel="noopener" style="padding:4px 10px;border-radius:8px;background:#e6f7ec;color:#0f5f22;text-decoration:none;font-weight:600;font-size:12px">下载 CPA</a>`
- : '';
- tr.innerHTML = `<td><code>${a.email||''}</code></td><td>${a.plan_type||''}</td><td>${a.final_status||''}</td><td>${a.cpa_file_name||''}</td><td>${fmtTime(a.created_at)}</td><td>${fmtTime(a.updated_at)}</td><td style="color:#a40000">${a.last_error||''}</td><td>${detailBtn}${dlBtn}</td>`;
- tbody.appendChild(tr);
- });
- tbody.querySelectorAll('button[data-action="detail"]').forEach(btn => {
- btn.addEventListener('click', () => loadAccountDetail(btn.dataset.email));
- });
- } catch (e) {
- console.error(e);
- }
- }
- async function loadAccountDetail(email) {
- try {
- const r = await fetch('/api/account/' + encodeURIComponent(email));
- const data = await r.json();
- $('accDetail').textContent = JSON.stringify(data, null, 2);
- } catch (e) {
- $('accDetail').textContent = String(e);
- }
- }
- $('refreshAccounts').addEventListener('click', loadAccounts);
- $('accFilter').addEventListener('change', loadAccounts);
- // 全自动跑完后自动刷一次账号库
- const _origRefreshStatus = refreshStatus;
- let _wasRunning = false;
- async function refreshStatusWithDb() {
- await _origRefreshStatus();
- try {
- const r = await fetch('/api/status');
- const s = await r.json();
- if (_wasRunning && !s.running) loadAccounts();
- _wasRunning = !!s.running;
- } catch (_) {}
- }
- clearInterval(window.__statusTimer);
- window.__statusTimer = setInterval(refreshStatusWithDb, 1500);
- $('save').addEventListener('click', saveConfig);
- $('go').addEventListener('click', async () => {
- // 自动先保存一次配置
- await saveConfig();
- $('log').textContent = '';
- $('go').disabled = true;
- setState('启动中', 'gray');
- try {
- const r = await fetch('/api/start', {method:'POST'});
- const data = await r.json();
- if (data.error) {
- alert(data.error);
- $('go').disabled = false;
- setState('空闲', 'gray');
- }
- } catch (e) {
- alert(e.message || String(e));
- $('go').disabled = false;
- }
- });
- $('stop').addEventListener('click', async () => {
- await fetch('/api/stop', {method: 'POST'});
- });
- </script>
- </body>
- </html>"""
- def _read_json(handler) -> dict:
- length = int(handler.headers.get("content-length") or "0")
- if length <= 0:
- return {}
- raw = handler.rfile.read(length).decode("utf-8", errors="replace")
- return json.loads(raw or "{}")
- class Handler(BaseHTTPRequestHandler):
- def do_GET(self):
- path = self.path.split("?", 1)[0]
- query = self.path.split("?", 1)[1] if "?" in self.path else ""
- if path in ("/", "/index.html"):
- self._send(200, INDEX_HTML.encode("utf-8"), "text/html; charset=utf-8")
- return
- if path == "/api/status":
- self._send_json(200, JOB.status())
- return
- if path == "/api/config":
- self._send_json(200, asdict(AppConfig.load()))
- return
- if path == "/api/log":
- self._stream_log()
- return
- if path == "/api/accounts":
- try:
- from urllib.parse import parse_qs
- q = parse_qs(query)
- status = (q.get("status") or [""])[0] or None
- limit = int((q.get("limit") or ["200"])[0])
- accounts = list_accounts(limit=limit, status=status)
- # 别把 session 全文 dump 给列表,太大;列表只回主要字段
- slim = []
- for a in accounts:
- slim.append({k: a.get(k) for k in (
- "email", "plan_type", "final_status", "cpa_file_name",
- "long_link", "last_error", "created_at", "updated_at",
- "cpa_uploaded_at"
- )})
- self._send_json(200, {"accounts": slim})
- except Exception as exc:
- self._send_json(500, {"error": str(exc)})
- return
- if path.startswith("/api/account/") and path.endswith("/cpa.json"):
- from urllib.parse import unquote
- email = unquote(path[len("/api/account/"):-len("/cpa.json")])
- acc = get_account(email)
- if not acc:
- self._send_json(404, {"error": "account not found"})
- return
- session = acc.get("plus_session") or acc.get("initial_session")
- if not session:
- self._send_json(404, {"error": "该账号没有可下载的 session"})
- return
- try:
- payload = build_cpa_auth_payload(session, email_hint=email)
- except Exception as exc:
- self._send_json(500, {"error": f"构造 CPA auth JSON 失败: {exc}"})
- return
- file_name = acc.get("cpa_file_name") or payload["fileName"]
- content = json.dumps(payload["authJson"], ensure_ascii=False, indent=2).encode("utf-8")
- self.send_response(200)
- self.send_header("Content-Type", "application/json; charset=utf-8")
- self.send_header("Content-Disposition", f'attachment; filename="{file_name}"')
- self.send_header("Cache-Control", "no-store")
- self.send_header("Content-Length", str(len(content)))
- self.end_headers()
- self.wfile.write(content)
- return
- if path.startswith("/api/account/"):
- from urllib.parse import unquote
- email = unquote(path[len("/api/account/"):])
- acc = get_account(email)
- if not acc:
- self._send_json(404, {"error": "account not found"})
- return
- events = list_events(email, limit=200)
- self._send_json(200, {"account": acc, "events": events})
- return
- self._send_json(404, {"error": "not found"})
- def do_POST(self):
- path = self.path.split("?", 1)[0]
- if path == "/api/config":
- try:
- body = _read_json(self)
- cfg = AppConfig.load().update(body or {})
- self._send_json(200, asdict(cfg))
- except Exception as exc:
- self._send_json(500, {"error": str(exc)})
- return
- if path == "/api/start":
- try:
- cfg = AppConfig.load()
- err = JOB.start(cfg)
- if err:
- self._send_json(409, {"error": err})
- else:
- self._send_json(200, {"ok": True})
- except Exception as exc:
- self._send_json(500, {"error": str(exc)})
- return
- if path == "/api/stop":
- JOB.stop()
- self._send_json(200, {"ok": True})
- return
- self._send_json(404, {"error": "not found"})
- def _stream_log(self):
- self.send_response(200)
- self.send_header("Content-Type", "text/event-stream; charset=utf-8")
- self.send_header("Cache-Control", "no-cache")
- self.send_header("Connection", "keep-alive")
- self.end_headers()
- try:
- for line in JOB.history[-300:]:
- self._sse_send(line)
- while True:
- try:
- line = JOB.log_queue.get(timeout=15)
- self._sse_send(line)
- except queue.Empty:
- self.wfile.write(b": ping\n\n")
- self.wfile.flush()
- except (BrokenPipeError, ConnectionResetError):
- return
- def _sse_send(self, line: str):
- for piece in line.splitlines() or [""]:
- self.wfile.write(b"data: " + piece.encode("utf-8") + b"\n")
- self.wfile.write(b"\n")
- self.wfile.flush()
- def _send_json(self, status: int, payload: dict):
- self._send(status, json.dumps(payload, ensure_ascii=False).encode("utf-8"), "application/json; charset=utf-8")
- def _send(self, status: int, content: bytes, content_type: str):
- self.send_response(status)
- self.send_header("Content-Type", content_type)
- self.send_header("Cache-Control", "no-store")
- self.send_header("Content-Length", str(len(content)))
- self.end_headers()
- self.wfile.write(content)
- def log_message(self, fmt, *args):
- return
- def handle_one_request(self):
- try:
- return super().handle_one_request()
- except (ConnectionResetError, BrokenPipeError):
- # 浏览器主动断开 SSE / fetch 时打印栈很碍眼,直接静音
- self.close_connection = True
- def _silence_threading_excepthook():
- """ThreadingHTTPServer 在 worker 线程里仍可能抛 ConnectionResetError;接住它。"""
- import threading
- prev = threading.excepthook
- def hook(args):
- if isinstance(args.exc_value, (ConnectionResetError, BrokenPipeError)):
- return
- prev(args)
- threading.excepthook = hook
- def main():
- init_db()
- _silence_threading_excepthook()
- server = ThreadingHTTPServer((HOST, PORT), Handler)
- print(f"ChatGPT Plus Auto Console: http://{HOST}:{PORT}/")
- try:
- server.serve_forever()
- except KeyboardInterrupt:
- print("\nStopped.")
- if __name__ == "__main__":
- main()
|