server.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644
  1. """本地 Web 控制台:网页配置 + 一键全自动注册→付款→上传 CPA。"""
  2. from __future__ import annotations
  3. import json
  4. import queue
  5. import threading
  6. import time
  7. from dataclasses import asdict
  8. from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
  9. from chatgpt_flow import FullRunContext, run_full
  10. from config import AppConfig
  11. from cpa_uploader import build_cpa_auth_payload
  12. from storage import get_account, init_db, list_accounts, list_events
  13. HOST = "127.0.0.1"
  14. PORT = 7791
  15. class JobManager:
  16. def __init__(self):
  17. self.lock = threading.Lock()
  18. self.full_ctx: FullRunContext | None = None
  19. self.thread: threading.Thread | None = None
  20. self.log_queue: queue.Queue[str] = queue.Queue()
  21. self.history: list[str] = []
  22. self.stage: str = ""
  23. def _log(self, msg: str):
  24. line = f"[{time.strftime('%H:%M:%S')}] {msg}"
  25. self.history.append(line)
  26. if len(self.history) > 4000:
  27. self.history = self.history[-3000:]
  28. self.log_queue.put(line)
  29. def _on_stage(self, name: str):
  30. self.stage = name
  31. # stage 也写到日志,便于复盘
  32. self._log(f"[STAGE] {name}")
  33. def start(self, cfg: AppConfig) -> str:
  34. with self.lock:
  35. if self.thread and self.thread.is_alive():
  36. return "已有任务在运行"
  37. self.history.clear()
  38. while not self.log_queue.empty():
  39. self.log_queue.get_nowait()
  40. self.stage = ""
  41. def runner():
  42. try:
  43. self.full_ctx = run_full(cfg, log=self._log, on_stage=self._on_stage)
  44. except Exception as exc:
  45. import traceback
  46. self._log(f"[server] 任务异常: {exc!r}")
  47. self._log(traceback.format_exc())
  48. self.thread = threading.Thread(target=runner, daemon=True)
  49. self.thread.start()
  50. return ""
  51. def stop(self):
  52. if self.full_ctx:
  53. self.full_ctx.state = "stopped"
  54. self._log("[user] 已请求停止")
  55. def status(self) -> dict:
  56. running = bool(self.thread and self.thread.is_alive())
  57. ctx = self.full_ctx
  58. accounts = []
  59. state = "idle"
  60. if ctx:
  61. state = ctx.state
  62. for a in ctx.accounts:
  63. accounts.append({
  64. "email": a.get("email"),
  65. "stage": a.get("stage"),
  66. "planType": a.get("planType"),
  67. "error": a.get("error"),
  68. "cpaFile": (a.get("cpa") or {}).get("fileName") if a.get("cpa") else None,
  69. })
  70. return {
  71. "running": running,
  72. "state": state,
  73. "stage": self.stage,
  74. "accounts": accounts,
  75. }
  76. JOB = JobManager()
  77. INDEX_HTML = r"""<!doctype html>
  78. <html lang="zh-CN">
  79. <head>
  80. <meta charset="utf-8" />
  81. <meta name="viewport" content="width=device-width,initial-scale=1" />
  82. <title>ChatGPT Plus 全自动注册</title>
  83. <style>
  84. :root { color-scheme: light; font-family: -apple-system,BlinkMacSystemFont,"Segoe UI","PingFang SC","Microsoft YaHei",sans-serif; }
  85. body { margin:0; background:#f5f5f7; color:#111; }
  86. .wrap { max-width: 980px; margin: 24px auto; padding: 0 16px; }
  87. .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; }
  88. h1 { margin: 0 0 6px; font-size: 22px; }
  89. h2 { margin: 0 0 10px; font-size: 16px; }
  90. p, li { color:#666; line-height:1.6; }
  91. label { display:block; margin:14px 0 6px; font-weight:600; }
  92. input, select { width:100%; box-sizing:border-box; border:1px solid #ccc; border-radius:10px; padding:9px 10px; font:inherit; background:#fff; }
  93. .grid { display:grid; grid-template-columns: 1fr 1fr; gap: 14px; }
  94. .grid-3 { display:grid; grid-template-columns: 1fr 1fr 1fr; gap: 14px; }
  95. .row { display:flex; gap:10px; align-items:center; flex-wrap:wrap; margin-top:14px; }
  96. button { border:0; border-radius:12px; background:#111; color:#fff; padding:10px 16px; font-weight:700; cursor:pointer; }
  97. button.secondary { background:#e9e9ec; color:#111; }
  98. button:disabled { opacity:.55; cursor:not-allowed; }
  99. .muted { color:#777; font-size:13px; }
  100. .chip { display:inline-block; padding:3px 10px; border-radius:999px; font-size:12px; background:#eef; color:#225; }
  101. .chip.green { background:#e6f7ec; color:#0f5f22; }
  102. .chip.red { background:#fde7e7; color:#a40000; }
  103. .chip.gray { background:#eee; color:#444; }
  104. .chip.blue { background:#e7f0ff; color:#1d4ed8; }
  105. 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; }
  106. table { width:100%; border-collapse: collapse; font-size:13px; }
  107. th, td { padding:8px 10px; border-bottom:1px solid #eee; text-align:left; vertical-align:top; }
  108. th { background:#fafafa; font-weight:600; color:#333; }
  109. .stage-box { padding:10px 14px; border-radius:12px; background:#fffaf0; border:1px solid #ffe2a8; color:#7a4f00; font-size:13px; min-height: 22px; }
  110. </style>
  111. </head>
  112. <body>
  113. <div class="wrap">
  114. <div class="card">
  115. <h1>ChatGPT Plus 全自动注册 + CPA 上传</h1>
  116. <div class="muted">流程:a4sky 邮箱注册 → 拿 Plus 长链 → PayPal 创建账号付款 → 校验 plan=plus → 上传 CPA。手机号统一 +15822201173。</div>
  117. </div>
  118. <div class="card">
  119. <h2>配置</h2>
  120. <div class="grid">
  121. <div>
  122. <label>账号数量</label>
  123. <input id="cfg_account_count" type="number" min="1" value="1" />
  124. </div>
  125. <div>
  126. <label>浏览器模式</label>
  127. <select id="cfg_headless">
  128. <option value="false" selected>有头(推荐,方便干预)</option>
  129. <option value="true">无头</option>
  130. </select>
  131. </div>
  132. </div>
  133. <div class="grid">
  134. <div>
  135. <label>邮件助手 URL</label>
  136. <input id="cfg_mail_helper_url" placeholder="http://ali.ss5.xyz:17373" />
  137. </div>
  138. <div>
  139. <label>邮箱域名</label>
  140. <input id="cfg_mail_domain" placeholder="edu.a4sky.com" />
  141. </div>
  142. </div>
  143. <div class="grid-3">
  144. <div>
  145. <label>邮箱轮询间隔(秒)</label>
  146. <input id="cfg_mail_poll_interval_sec" type="number" min="1" value="4" />
  147. </div>
  148. <div>
  149. <label>邮箱轮询次数</label>
  150. <input id="cfg_mail_poll_max_attempts" type="number" min="5" value="60" />
  151. </div>
  152. <div>
  153. <label>使用 1 个月免费 promo</label>
  154. <select id="cfg_use_promo">
  155. <option value="true" selected>是</option>
  156. <option value="false">否</option>
  157. </select>
  158. </div>
  159. </div>
  160. <div class="grid">
  161. <div>
  162. <label>PayPal 短信手机号 (E164)</label>
  163. <input id="cfg_phone_e164" placeholder="+15822201173" />
  164. </div>
  165. <div>
  166. <label>接码 API URL</label>
  167. <input id="cfg_sms_api_url" placeholder="http://a.62-us.com/api/get_sms?key=..." />
  168. </div>
  169. </div>
  170. <div class="grid">
  171. <div>
  172. <label>CPA 地址</label>
  173. <input id="cfg_cpa_url" placeholder="http://your-cpa-host:port" />
  174. </div>
  175. <div>
  176. <label>CPA 管理密钥</label>
  177. <input id="cfg_cpa_management_key" placeholder="管理 token" />
  178. </div>
  179. </div>
  180. <div class="row">
  181. <button id="save">保存配置</button>
  182. <button id="go">开始全自动</button>
  183. <button id="stop" class="secondary" disabled>停止</button>
  184. <span id="state" class="chip gray">空闲</span>
  185. </div>
  186. </div>
  187. <div class="card">
  188. <h2>当前阶段</h2>
  189. <div id="stageBox" class="stage-box">空闲</div>
  190. </div>
  191. <div class="card">
  192. <h2>账号进度</h2>
  193. <table id="accTable">
  194. <thead><tr><th>#</th><th>邮箱</th><th>阶段</th><th>planType</th><th>CPA 文件</th><th>错误</th></tr></thead>
  195. <tbody></tbody>
  196. </table>
  197. </div>
  198. <div class="card">
  199. <h2>已注册账号库</h2>
  200. <div class="row" style="margin-top:0">
  201. <button id="refreshAccounts" class="secondary">刷新</button>
  202. <select id="accFilter" style="max-width:200px">
  203. <option value="">全部状态</option>
  204. <option value="registered">已注册</option>
  205. <option value="paid">已付款</option>
  206. <option value="plus">已 Plus</option>
  207. <option value="cpa_uploaded">已上传 CPA</option>
  208. <option value="cpa_skipped">CPA 跳过</option>
  209. <option value="failed">失败</option>
  210. <option value="plus_check_failed">Plus 校验失败</option>
  211. <option value="cpa_failed">CPA 上传失败</option>
  212. </select>
  213. <span class="muted">数据库:<code>data/accounts.db</code></span>
  214. </div>
  215. <table id="dbTable">
  216. <thead><tr><th>邮箱</th><th>plan</th><th>状态</th><th>CPA 文件</th><th>注册时间</th><th>更新时间</th><th>错误</th><th>动作</th></tr></thead>
  217. <tbody></tbody>
  218. </table>
  219. <details style="margin-top:10px">
  220. <summary class="muted">点击查看选中账号详情</summary>
  221. <pre id="accDetail" class="log" style="height:240px"></pre>
  222. </details>
  223. </div>
  224. <div class="card">
  225. <h2>实时日志</h2>
  226. <pre id="log" class="log"></pre>
  227. </div>
  228. </div>
  229. <script>
  230. const $ = id => document.getElementById(id);
  231. const FIELDS = [
  232. ['cfg_account_count','account_count','int'],
  233. ['cfg_headless','headless','bool'],
  234. ['cfg_mail_helper_url','mail_helper_url','str'],
  235. ['cfg_mail_domain','mail_domain','str'],
  236. ['cfg_mail_poll_interval_sec','mail_poll_interval_sec','int'],
  237. ['cfg_mail_poll_max_attempts','mail_poll_max_attempts','int'],
  238. ['cfg_use_promo','use_promo','bool'],
  239. ['cfg_phone_e164','phone_e164','str'],
  240. ['cfg_sms_api_url','sms_api_url','str'],
  241. ['cfg_cpa_url','cpa_url','str'],
  242. ['cfg_cpa_management_key','cpa_management_key','str'],
  243. ];
  244. function fillForm(cfg) {
  245. for (const [domId, key, kind] of FIELDS) {
  246. const el = $(domId);
  247. if (!el || cfg[key] === undefined) continue;
  248. if (kind === 'bool') {
  249. el.value = cfg[key] ? 'true' : 'false';
  250. } else {
  251. el.value = cfg[key];
  252. }
  253. }
  254. }
  255. function readForm() {
  256. const out = {};
  257. for (const [domId, key, kind] of FIELDS) {
  258. const el = $(domId);
  259. if (!el) continue;
  260. let v = el.value;
  261. if (kind === 'int') v = Number(v) || 0;
  262. else if (kind === 'bool') v = (v === 'true' || v === true);
  263. out[key] = v;
  264. }
  265. return out;
  266. }
  267. async function loadConfig() {
  268. const r = await fetch('/api/config');
  269. const data = await r.json();
  270. fillForm(data);
  271. }
  272. async function saveConfig() {
  273. const body = readForm();
  274. const r = await fetch('/api/config', {method:'POST', headers:{'Content-Type':'application/json'}, body: JSON.stringify(body)});
  275. if (!r.ok) { alert('保存失败 HTTP ' + r.status); return; }
  276. const data = await r.json();
  277. fillForm(data);
  278. }
  279. function setState(text, cls) {
  280. const el = $('state');
  281. el.textContent = text;
  282. el.className = 'chip ' + (cls || 'gray');
  283. }
  284. let evtSource = null;
  285. function startLogStream() {
  286. if (evtSource) evtSource.close();
  287. evtSource = new EventSource('/api/log');
  288. evtSource.onmessage = e => {
  289. if (!e.data) return;
  290. const log = $('log');
  291. log.textContent += e.data + '\n';
  292. log.scrollTop = log.scrollHeight;
  293. };
  294. }
  295. function renderAccounts(accounts) {
  296. const tbody = $('accTable').querySelector('tbody');
  297. tbody.innerHTML = '';
  298. accounts.forEach((a, idx) => {
  299. const tr = document.createElement('tr');
  300. 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>`;
  301. tbody.appendChild(tr);
  302. });
  303. }
  304. async function refreshStatus() {
  305. try {
  306. const r = await fetch('/api/status');
  307. const data = await r.json();
  308. $('stageBox').textContent = data.stage || '空闲';
  309. renderAccounts(data.accounts || []);
  310. if (data.running) {
  311. setState('执行中', 'green');
  312. $('go').disabled = true;
  313. $('stop').disabled = false;
  314. } else {
  315. $('go').disabled = false;
  316. $('stop').disabled = true;
  317. if (data.state === 'done') setState('完成', 'green');
  318. else if (data.state === 'error') setState('异常', 'red');
  319. else if (data.state === 'stopped') setState('已停止', 'red');
  320. else setState('空闲', 'gray');
  321. }
  322. } catch (_) {}
  323. }
  324. setInterval(refreshStatus, 1500);
  325. refreshStatus();
  326. startLogStream();
  327. loadConfig();
  328. loadAccounts();
  329. function fmtTime(ms) {
  330. if (!ms) return '';
  331. const d = new Date(Number(ms));
  332. if (isNaN(d.getTime())) return '';
  333. const pad = n => String(n).padStart(2,'0');
  334. return `${d.getFullYear()}-${pad(d.getMonth()+1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`;
  335. }
  336. async function loadAccounts() {
  337. const status = $('accFilter').value || '';
  338. const url = status ? '/api/accounts?status=' + encodeURIComponent(status) : '/api/accounts';
  339. try {
  340. const r = await fetch(url);
  341. const data = await r.json();
  342. const tbody = $('dbTable').querySelector('tbody');
  343. tbody.innerHTML = '';
  344. (data.accounts || []).forEach(a => {
  345. const tr = document.createElement('tr');
  346. const detailBtn = `<button class="secondary" data-email="${a.email}" data-action="detail" style="padding:4px 10px">详情</button>`;
  347. const dlBtn = a.cpa_file_name
  348. ? ` <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>`
  349. : '';
  350. 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>`;
  351. tbody.appendChild(tr);
  352. });
  353. tbody.querySelectorAll('button[data-action="detail"]').forEach(btn => {
  354. btn.addEventListener('click', () => loadAccountDetail(btn.dataset.email));
  355. });
  356. } catch (e) {
  357. console.error(e);
  358. }
  359. }
  360. async function loadAccountDetail(email) {
  361. try {
  362. const r = await fetch('/api/account/' + encodeURIComponent(email));
  363. const data = await r.json();
  364. $('accDetail').textContent = JSON.stringify(data, null, 2);
  365. } catch (e) {
  366. $('accDetail').textContent = String(e);
  367. }
  368. }
  369. $('refreshAccounts').addEventListener('click', loadAccounts);
  370. $('accFilter').addEventListener('change', loadAccounts);
  371. // 全自动跑完后自动刷一次账号库
  372. const _origRefreshStatus = refreshStatus;
  373. let _wasRunning = false;
  374. async function refreshStatusWithDb() {
  375. await _origRefreshStatus();
  376. try {
  377. const r = await fetch('/api/status');
  378. const s = await r.json();
  379. if (_wasRunning && !s.running) loadAccounts();
  380. _wasRunning = !!s.running;
  381. } catch (_) {}
  382. }
  383. clearInterval(window.__statusTimer);
  384. window.__statusTimer = setInterval(refreshStatusWithDb, 1500);
  385. $('save').addEventListener('click', saveConfig);
  386. $('go').addEventListener('click', async () => {
  387. // 自动先保存一次配置
  388. await saveConfig();
  389. $('log').textContent = '';
  390. $('go').disabled = true;
  391. setState('启动中', 'gray');
  392. try {
  393. const r = await fetch('/api/start', {method:'POST'});
  394. const data = await r.json();
  395. if (data.error) {
  396. alert(data.error);
  397. $('go').disabled = false;
  398. setState('空闲', 'gray');
  399. }
  400. } catch (e) {
  401. alert(e.message || String(e));
  402. $('go').disabled = false;
  403. }
  404. });
  405. $('stop').addEventListener('click', async () => {
  406. await fetch('/api/stop', {method: 'POST'});
  407. });
  408. </script>
  409. </body>
  410. </html>"""
  411. def _read_json(handler) -> dict:
  412. length = int(handler.headers.get("content-length") or "0")
  413. if length <= 0:
  414. return {}
  415. raw = handler.rfile.read(length).decode("utf-8", errors="replace")
  416. return json.loads(raw or "{}")
  417. class Handler(BaseHTTPRequestHandler):
  418. def do_GET(self):
  419. path = self.path.split("?", 1)[0]
  420. query = self.path.split("?", 1)[1] if "?" in self.path else ""
  421. if path in ("/", "/index.html"):
  422. self._send(200, INDEX_HTML.encode("utf-8"), "text/html; charset=utf-8")
  423. return
  424. if path == "/api/status":
  425. self._send_json(200, JOB.status())
  426. return
  427. if path == "/api/config":
  428. self._send_json(200, asdict(AppConfig.load()))
  429. return
  430. if path == "/api/log":
  431. self._stream_log()
  432. return
  433. if path == "/api/accounts":
  434. try:
  435. from urllib.parse import parse_qs
  436. q = parse_qs(query)
  437. status = (q.get("status") or [""])[0] or None
  438. limit = int((q.get("limit") or ["200"])[0])
  439. accounts = list_accounts(limit=limit, status=status)
  440. # 别把 session 全文 dump 给列表,太大;列表只回主要字段
  441. slim = []
  442. for a in accounts:
  443. slim.append({k: a.get(k) for k in (
  444. "email", "plan_type", "final_status", "cpa_file_name",
  445. "long_link", "last_error", "created_at", "updated_at",
  446. "cpa_uploaded_at"
  447. )})
  448. self._send_json(200, {"accounts": slim})
  449. except Exception as exc:
  450. self._send_json(500, {"error": str(exc)})
  451. return
  452. if path.startswith("/api/account/") and path.endswith("/cpa.json"):
  453. from urllib.parse import unquote
  454. email = unquote(path[len("/api/account/"):-len("/cpa.json")])
  455. acc = get_account(email)
  456. if not acc:
  457. self._send_json(404, {"error": "account not found"})
  458. return
  459. session = acc.get("plus_session") or acc.get("initial_session")
  460. if not session:
  461. self._send_json(404, {"error": "该账号没有可下载的 session"})
  462. return
  463. try:
  464. payload = build_cpa_auth_payload(session, email_hint=email)
  465. except Exception as exc:
  466. self._send_json(500, {"error": f"构造 CPA auth JSON 失败: {exc}"})
  467. return
  468. file_name = acc.get("cpa_file_name") or payload["fileName"]
  469. content = json.dumps(payload["authJson"], ensure_ascii=False, indent=2).encode("utf-8")
  470. self.send_response(200)
  471. self.send_header("Content-Type", "application/json; charset=utf-8")
  472. self.send_header("Content-Disposition", f'attachment; filename="{file_name}"')
  473. self.send_header("Cache-Control", "no-store")
  474. self.send_header("Content-Length", str(len(content)))
  475. self.end_headers()
  476. self.wfile.write(content)
  477. return
  478. if path.startswith("/api/account/"):
  479. from urllib.parse import unquote
  480. email = unquote(path[len("/api/account/"):])
  481. acc = get_account(email)
  482. if not acc:
  483. self._send_json(404, {"error": "account not found"})
  484. return
  485. events = list_events(email, limit=200)
  486. self._send_json(200, {"account": acc, "events": events})
  487. return
  488. self._send_json(404, {"error": "not found"})
  489. def do_POST(self):
  490. path = self.path.split("?", 1)[0]
  491. if path == "/api/config":
  492. try:
  493. body = _read_json(self)
  494. cfg = AppConfig.load().update(body or {})
  495. self._send_json(200, asdict(cfg))
  496. except Exception as exc:
  497. self._send_json(500, {"error": str(exc)})
  498. return
  499. if path == "/api/start":
  500. try:
  501. cfg = AppConfig.load()
  502. err = JOB.start(cfg)
  503. if err:
  504. self._send_json(409, {"error": err})
  505. else:
  506. self._send_json(200, {"ok": True})
  507. except Exception as exc:
  508. self._send_json(500, {"error": str(exc)})
  509. return
  510. if path == "/api/stop":
  511. JOB.stop()
  512. self._send_json(200, {"ok": True})
  513. return
  514. self._send_json(404, {"error": "not found"})
  515. def _stream_log(self):
  516. self.send_response(200)
  517. self.send_header("Content-Type", "text/event-stream; charset=utf-8")
  518. self.send_header("Cache-Control", "no-cache")
  519. self.send_header("Connection", "keep-alive")
  520. self.end_headers()
  521. try:
  522. for line in JOB.history[-300:]:
  523. self._sse_send(line)
  524. while True:
  525. try:
  526. line = JOB.log_queue.get(timeout=15)
  527. self._sse_send(line)
  528. except queue.Empty:
  529. self.wfile.write(b": ping\n\n")
  530. self.wfile.flush()
  531. except (BrokenPipeError, ConnectionResetError):
  532. return
  533. def _sse_send(self, line: str):
  534. for piece in line.splitlines() or [""]:
  535. self.wfile.write(b"data: " + piece.encode("utf-8") + b"\n")
  536. self.wfile.write(b"\n")
  537. self.wfile.flush()
  538. def _send_json(self, status: int, payload: dict):
  539. self._send(status, json.dumps(payload, ensure_ascii=False).encode("utf-8"), "application/json; charset=utf-8")
  540. def _send(self, status: int, content: bytes, content_type: str):
  541. self.send_response(status)
  542. self.send_header("Content-Type", content_type)
  543. self.send_header("Cache-Control", "no-store")
  544. self.send_header("Content-Length", str(len(content)))
  545. self.end_headers()
  546. self.wfile.write(content)
  547. def log_message(self, fmt, *args):
  548. return
  549. def handle_one_request(self):
  550. try:
  551. return super().handle_one_request()
  552. except (ConnectionResetError, BrokenPipeError):
  553. # 浏览器主动断开 SSE / fetch 时打印栈很碍眼,直接静音
  554. self.close_connection = True
  555. def _silence_threading_excepthook():
  556. """ThreadingHTTPServer 在 worker 线程里仍可能抛 ConnectionResetError;接住它。"""
  557. import threading
  558. prev = threading.excepthook
  559. def hook(args):
  560. if isinstance(args.exc_value, (ConnectionResetError, BrokenPipeError)):
  561. return
  562. prev(args)
  563. threading.excepthook = hook
  564. def main():
  565. init_db()
  566. _silence_threading_excepthook()
  567. server = ThreadingHTTPServer((HOST, PORT), Handler)
  568. print(f"ChatGPT Plus Auto Console: http://{HOST}:{PORT}/")
  569. try:
  570. server.serve_forever()
  571. except KeyboardInterrupt:
  572. print("\nStopped.")
  573. if __name__ == "__main__":
  574. main()