server.py 55 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330
  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 recheck import recheck_account
  13. from storage import (
  14. count_accounts,
  15. create_task,
  16. get_account,
  17. get_task,
  18. init_db,
  19. list_accounts,
  20. list_events,
  21. list_tasks,
  22. )
  23. from task_runner import get_runner, make_task_id
  24. HOST = "127.0.0.1" # main() 会读 cfg.api_host 覆盖
  25. PORT = 7791
  26. class JobManager:
  27. def __init__(self):
  28. self.lock = threading.Lock()
  29. self.full_ctx: FullRunContext | None = None
  30. self.thread: threading.Thread | None = None
  31. self.log_queue: queue.Queue[str] = queue.Queue()
  32. self.history: list[str] = []
  33. self.stage: str = ""
  34. def _log(self, msg: str):
  35. line = f"[{time.strftime('%H:%M:%S')}] {msg}"
  36. self.history.append(line)
  37. if len(self.history) > 4000:
  38. self.history = self.history[-3000:]
  39. self.log_queue.put(line)
  40. def _on_stage(self, name: str):
  41. self.stage = name
  42. # stage 也写到日志,便于复盘
  43. self._log(f"[STAGE] {name}")
  44. def start(self, cfg: AppConfig) -> str:
  45. with self.lock:
  46. if self.thread and self.thread.is_alive():
  47. return "已有任务在运行"
  48. self.history.clear()
  49. while not self.log_queue.empty():
  50. self.log_queue.get_nowait()
  51. self.stage = ""
  52. def runner():
  53. try:
  54. self.full_ctx = run_full(cfg, log=self._log, on_stage=self._on_stage)
  55. except Exception as exc:
  56. import traceback
  57. self._log(f"[server] 任务异常: {exc!r}")
  58. self._log(traceback.format_exc())
  59. self.thread = threading.Thread(target=runner, daemon=True)
  60. self.thread.start()
  61. return ""
  62. def stop(self):
  63. if self.full_ctx:
  64. self.full_ctx.state = "stopped"
  65. self._log("[user] 已请求停止")
  66. def status(self) -> dict:
  67. running = bool(self.thread and self.thread.is_alive())
  68. ctx = self.full_ctx
  69. accounts = []
  70. state = "idle"
  71. if ctx:
  72. state = ctx.state
  73. for a in ctx.accounts:
  74. accounts.append({
  75. "email": a.get("email"),
  76. "stage": a.get("stage"),
  77. "planType": a.get("planType"),
  78. "error": a.get("error"),
  79. "cpaFile": (a.get("cpa") or {}).get("fileName") if a.get("cpa") else None,
  80. })
  81. return {
  82. "running": running,
  83. "state": state,
  84. "stage": self.stage,
  85. "accounts": accounts,
  86. }
  87. JOB = JobManager()
  88. INDEX_HTML = r"""<!doctype html>
  89. <html lang="zh-CN">
  90. <head>
  91. <meta charset="utf-8" />
  92. <meta name="viewport" content="width=device-width,initial-scale=1" />
  93. <title>ChatGPT Plus 全自动注册</title>
  94. <style>
  95. :root { color-scheme: light; font-family: -apple-system,BlinkMacSystemFont,"Segoe UI","PingFang SC","Microsoft YaHei",sans-serif; }
  96. body { margin:0; background:#f5f5f7; color:#111; }
  97. .wrap { max-width: 980px; margin: 24px auto; padding: 0 16px; }
  98. .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; }
  99. h1 { margin: 0 0 6px; font-size: 22px; }
  100. h2 { margin: 0 0 10px; font-size: 16px; }
  101. p, li { color:#666; line-height:1.6; }
  102. label { display:block; margin:14px 0 6px; font-weight:600; }
  103. input, select { width:100%; box-sizing:border-box; border:1px solid #ccc; border-radius:10px; padding:9px 10px; font:inherit; background:#fff; }
  104. .grid { display:grid; grid-template-columns: 1fr 1fr; gap: 14px; }
  105. .grid-3 { display:grid; grid-template-columns: 1fr 1fr 1fr; gap: 14px; }
  106. .row { display:flex; gap:10px; align-items:center; flex-wrap:wrap; margin-top:14px; }
  107. button { border:0; border-radius:12px; background:#111; color:#fff; padding:10px 16px; font-weight:700; cursor:pointer; }
  108. button.secondary { background:#e9e9ec; color:#111; }
  109. button:disabled { opacity:.55; cursor:not-allowed; }
  110. .muted { color:#777; font-size:13px; }
  111. .chip { display:inline-block; padding:3px 10px; border-radius:999px; font-size:12px; background:#eef; color:#225; }
  112. .chip.green { background:#e6f7ec; color:#0f5f22; }
  113. .chip.red { background:#fde7e7; color:#a40000; }
  114. .chip.gray { background:#eee; color:#444; }
  115. .chip.blue { background:#e7f0ff; color:#1d4ed8; }
  116. 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; }
  117. table { width:100%; border-collapse: collapse; font-size:13px; table-layout: fixed; }
  118. th, td { padding:8px 10px; border-bottom:1px solid #eee; text-align:left; vertical-align:top; word-break: break-word; }
  119. th { background:#fafafa; font-weight:600; color:#333; }
  120. /* 已注册账号库表 */
  121. #dbTable th.col-email, #dbTable td.col-email { width: 24%; }
  122. #dbTable th.col-plan, #dbTable td.col-plan { width: 60px; }
  123. #dbTable th.col-stat, #dbTable td.col-stat { width: 110px; }
  124. #dbTable th.col-cpa, #dbTable td.col-cpa { width: 22%; font-family: ui-monospace, SFMono-Regular, Consolas, monospace; font-size: 12px; }
  125. #dbTable th.col-time, #dbTable td.col-time { width: 130px; white-space: nowrap; }
  126. #dbTable th.col-err, #dbTable td.col-err { width: 14%; color:#a40000; }
  127. #dbTable th.col-act, #dbTable td.col-act { width: 150px; white-space: nowrap; text-align: right; }
  128. #dbTable td.col-act .action-btn { display:inline-block; padding:4px 10px; border-radius:8px; font-weight:600; font-size:12px; text-decoration:none; white-space:nowrap; margin-left:6px; cursor:pointer; border:0; }
  129. #dbTable td.col-act .action-btn.detail { background:#e9e9ec; color:#111; }
  130. #dbTable td.col-act .action-btn.download { background:#e6f7ec; color:#0f5f22; }
  131. #dbTable td.col-act .action-btn.recheck { background:#fff4d6; color:#7a4f00; }
  132. #dbTable td.col-act .action-btn.retry-pay { background:#e7f0ff; color:#1d4ed8; }
  133. #dbTable td.col-act .action-btn:disabled { opacity:.6; cursor:not-allowed; }
  134. #dbTable td.col-email code { font-size: 12px; word-break: break-all; }
  135. .stage-box { padding:10px 14px; border-radius:12px; background:#fffaf0; border:1px solid #ffe2a8; color:#7a4f00; font-size:13px; min-height: 22px; }
  136. .pager { display:flex; align-items:center; gap:8px; margin-top:12px; flex-wrap:wrap; }
  137. .pager button { padding:6px 14px; border-radius:8px; font-size:13px; min-width:36px; }
  138. .pager button.active { background:#111; color:#fff; }
  139. .pager button:not(.active) { background:#e9e9ec; color:#111; }
  140. .pager .info { font-size:13px; color:#777; }
  141. </style>
  142. </head>
  143. <body>
  144. <div class="wrap">
  145. <div class="card">
  146. <h1>ChatGPT Plus 全自动注册 + CPA 上传</h1>
  147. <div class="muted">流程:a4sky 邮箱注册 → 拿 Plus 长链 → PayPal 创建账号付款 → 校验 plan=plus → 上传 CPA。手机号统一 +15822201173。</div>
  148. </div>
  149. <div class="card">
  150. <h2>配置</h2>
  151. <div class="grid">
  152. <div>
  153. <label>账号数量</label>
  154. <input id="cfg_account_count" type="number" min="1" value="1" />
  155. </div>
  156. <div>
  157. <label>浏览器模式</label>
  158. <select id="cfg_headless">
  159. <option value="false" selected>有头(推荐,方便干预)</option>
  160. <option value="true">无头</option>
  161. </select>
  162. </div>
  163. </div>
  164. <div class="grid">
  165. <div>
  166. <label>邮件助手 URL</label>
  167. <input id="cfg_mail_helper_url" placeholder="http://ali.ss5.xyz:17373" />
  168. </div>
  169. <div>
  170. <label>邮箱域名</label>
  171. <input id="cfg_mail_domain" placeholder="edu.a4sky.com" />
  172. </div>
  173. </div>
  174. <div class="grid-3">
  175. <div>
  176. <label>邮箱轮询间隔(秒)</label>
  177. <input id="cfg_mail_poll_interval_sec" type="number" min="1" value="4" />
  178. </div>
  179. <div>
  180. <label>邮箱轮询次数</label>
  181. <input id="cfg_mail_poll_max_attempts" type="number" min="5" value="60" />
  182. </div>
  183. <div>
  184. <label>使用 1 个月免费 promo</label>
  185. <select id="cfg_use_promo">
  186. <option value="true" selected>是</option>
  187. <option value="false">否</option>
  188. </select>
  189. </div>
  190. </div>
  191. <div class="grid">
  192. <div>
  193. <label>PayPal 短信手机号 (E164)</label>
  194. <input id="cfg_phone_e164" placeholder="+15822201173" />
  195. </div>
  196. <div>
  197. <label>接码 API URL</label>
  198. <input id="cfg_sms_api_url" placeholder="http://a.62-us.com/api/get_sms?key=..." />
  199. </div>
  200. </div>
  201. <div class="grid">
  202. <div>
  203. <label>CPA 地址</label>
  204. <input id="cfg_cpa_url" placeholder="http://your-cpa-host:port" />
  205. </div>
  206. <div>
  207. <label>CPA 管理密钥</label>
  208. <input id="cfg_cpa_management_key" placeholder="管理 token" />
  209. </div>
  210. </div>
  211. <h2 style="margin-top:18px">外网 API 接入</h2>
  212. <div class="grid-3">
  213. <div>
  214. <label>API 监听 host</label>
  215. <input id="cfg_api_host" placeholder="127.0.0.1 或 0.0.0.0" />
  216. </div>
  217. <div>
  218. <label>API 端口</label>
  219. <input id="cfg_api_port" type="number" min="1" max="65535" placeholder="7791" />
  220. </div>
  221. <div>
  222. <label>API Token(外网必填)</label>
  223. <input id="cfg_api_token" placeholder="留空 = 不校验" />
  224. </div>
  225. </div>
  226. <div>
  227. <label>CORS Allow-Origin</label>
  228. <input id="cfg_api_cors_origin" placeholder="* 或 https://your-frontend.com" />
  229. </div>
  230. <p class="muted" style="margin-top:6px">
  231. 在线 API 文档:<a href="/docs" target="_blank" rel="noopener">/docs</a> ·
  232. OpenAPI 规范:<a href="/openapi.json" target="_blank" rel="noopener">/openapi.json</a>
  233. </p>
  234. <div class="grid">
  235. <div>
  236. <label>全局代理(ChatGPT 注册 / 默认浏览器;留空则直连)</label>
  237. <input id="cfg_proxy_url" placeholder="http://user:pass@host:port (留空 = ChatGPT 注册直连)" />
  238. </div>
  239. <div>
  240. <label>PayPal 独立代理(仅 PayPal 阶段;留空则继承全局)</label>
  241. <input id="cfg_paypal_only_proxy" placeholder="http://user:pass@host:port" />
  242. </div>
  243. </div>
  244. <div class="grid">
  245. <div>
  246. <label>长链生成方式</label>
  247. <select id="cfg_long_link_mode">
  248. <option value="payurl">payurl.ark2.cn 中转(默认)</option>
  249. <option value="local">本地直连 ChatGPT API</option>
  250. </select>
  251. </div>
  252. <div>
  253. <label>长链生成代理(仅本地模式)</label>
  254. <input id="cfg_long_link_proxy" placeholder="http://user:pass@host:port(本地模式必填)" />
  255. </div>
  256. </div>
  257. <div class="row">
  258. <button id="save">保存配置</button>
  259. <button id="go">开始全自动</button>
  260. <button id="stop" class="secondary" disabled>停止</button>
  261. <span id="state" class="chip gray">空闲</span>
  262. </div>
  263. </div>
  264. <div class="card">
  265. <h2>当前阶段</h2>
  266. <div id="stageBox" class="stage-box">空闲</div>
  267. </div>
  268. <div class="card">
  269. <h2>账号进度</h2>
  270. <table id="accTable">
  271. <thead><tr><th>#</th><th>邮箱</th><th>阶段</th><th>planType</th><th>CPA 文件</th><th>错误</th></tr></thead>
  272. <tbody></tbody>
  273. </table>
  274. </div>
  275. <div class="card">
  276. <h2>已注册账号库</h2>
  277. <div class="row" style="margin-top:0">
  278. <button id="refreshAccounts" class="secondary">刷新</button>
  279. <select id="accFilter" style="max-width:200px">
  280. <option value="">全部状态</option>
  281. <option value="registered">已注册</option>
  282. <option value="paid">已付款</option>
  283. <option value="plus">已 Plus</option>
  284. <option value="cpa_uploaded">已上传 CPA</option>
  285. <option value="cpa_skipped">CPA 跳过</option>
  286. <option value="failed">失败</option>
  287. <option value="trial">试用 / 待付款</option>
  288. <option value="plus_check_failed">Plus 校验失败</option>
  289. <option value="cpa_failed">CPA 上传失败</option>
  290. </select>
  291. <span class="muted">数据库:<code>data/accounts.db</code></span>
  292. </div>
  293. <table id="dbTable">
  294. <thead><tr>
  295. <th class="col-email">邮箱</th>
  296. <th class="col-plan">plan</th>
  297. <th class="col-stat">状态</th>
  298. <th class="col-cpa">CPA 文件</th>
  299. <th class="col-time">注册时间</th>
  300. <th class="col-time">更新时间</th>
  301. <th class="col-err">错误</th>
  302. <th class="col-act">动作</th>
  303. </tr></thead>
  304. <tbody></tbody>
  305. </table>
  306. <div id="dbPager" class="pager"></div>
  307. <details style="margin-top:10px">
  308. <summary class="muted">点击查看选中账号详情</summary>
  309. <pre id="accDetail" class="log" style="height:240px"></pre>
  310. </details>
  311. </div>
  312. <div class="card">
  313. <h2>实时日志</h2>
  314. <pre id="log" class="log"></pre>
  315. </div>
  316. </div>
  317. <script>
  318. const $ = id => document.getElementById(id);
  319. const FIELDS = [
  320. ['cfg_account_count','account_count','int'],
  321. ['cfg_headless','headless','bool'],
  322. ['cfg_mail_helper_url','mail_helper_url','str'],
  323. ['cfg_mail_domain','mail_domain','str'],
  324. ['cfg_mail_poll_interval_sec','mail_poll_interval_sec','int'],
  325. ['cfg_mail_poll_max_attempts','mail_poll_max_attempts','int'],
  326. ['cfg_use_promo','use_promo','bool'],
  327. ['cfg_phone_e164','phone_e164','str'],
  328. ['cfg_sms_api_url','sms_api_url','str'],
  329. ['cfg_cpa_url','cpa_url','str'],
  330. ['cfg_cpa_management_key','cpa_management_key','str'],
  331. ['cfg_proxy_url','proxy_url','str'],
  332. ['cfg_paypal_only_proxy','paypal_only_proxy','str'],
  333. ['cfg_long_link_mode','long_link_mode','str'],
  334. ['cfg_long_link_proxy','long_link_proxy','str'],
  335. ['cfg_api_host','api_host','str'],
  336. ['cfg_api_port','api_port','int'],
  337. ['cfg_api_token','api_token','str'],
  338. ['cfg_api_cors_origin','api_cors_origin','str'],
  339. ];
  340. function fillForm(cfg) {
  341. for (const [domId, key, kind] of FIELDS) {
  342. const el = $(domId);
  343. if (!el || cfg[key] === undefined) continue;
  344. if (kind === 'bool') {
  345. el.value = cfg[key] ? 'true' : 'false';
  346. } else {
  347. el.value = cfg[key];
  348. }
  349. }
  350. }
  351. function readForm() {
  352. const out = {};
  353. for (const [domId, key, kind] of FIELDS) {
  354. const el = $(domId);
  355. if (!el) continue;
  356. let v = el.value;
  357. if (kind === 'int') v = Number(v) || 0;
  358. else if (kind === 'bool') v = (v === 'true' || v === true);
  359. out[key] = v;
  360. }
  361. return out;
  362. }
  363. async function loadConfig() {
  364. const r = await fetch('/api/config');
  365. const data = await r.json();
  366. fillForm(data);
  367. }
  368. async function saveConfig() {
  369. const body = readForm();
  370. const r = await fetch('/api/config', {method:'POST', headers:{'Content-Type':'application/json'}, body: JSON.stringify(body)});
  371. if (!r.ok) { alert('保存失败 HTTP ' + r.status); return; }
  372. const data = await r.json();
  373. fillForm(data);
  374. }
  375. function setState(text, cls) {
  376. const el = $('state');
  377. el.textContent = text;
  378. el.className = 'chip ' + (cls || 'gray');
  379. }
  380. let evtSource = null;
  381. function startLogStream() {
  382. if (evtSource) evtSource.close();
  383. evtSource = new EventSource('/api/log');
  384. evtSource.onmessage = e => {
  385. if (!e.data) return;
  386. const log = $('log');
  387. log.textContent += e.data + '\n';
  388. log.scrollTop = log.scrollHeight;
  389. };
  390. }
  391. function renderAccounts(accounts) {
  392. const tbody = $('accTable').querySelector('tbody');
  393. tbody.innerHTML = '';
  394. accounts.forEach((a, idx) => {
  395. const tr = document.createElement('tr');
  396. 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>`;
  397. tbody.appendChild(tr);
  398. });
  399. }
  400. async function refreshStatus() {
  401. try {
  402. const r = await fetch('/api/status');
  403. const data = await r.json();
  404. $('stageBox').textContent = data.stage || '空闲';
  405. renderAccounts(data.accounts || []);
  406. if (data.running) {
  407. setState('执行中', 'green');
  408. $('go').disabled = true;
  409. $('stop').disabled = false;
  410. } else {
  411. $('go').disabled = false;
  412. $('stop').disabled = true;
  413. if (data.state === 'done') setState('完成', 'green');
  414. else if (data.state === 'error') setState('异常', 'red');
  415. else if (data.state === 'stopped') setState('已停止', 'red');
  416. else setState('空闲', 'gray');
  417. }
  418. } catch (_) {}
  419. }
  420. setInterval(refreshStatus, 1500);
  421. refreshStatus();
  422. startLogStream();
  423. loadConfig();
  424. loadAccounts();
  425. function fmtTime(ms) {
  426. if (!ms) return '';
  427. const d = new Date(Number(ms));
  428. if (isNaN(d.getTime())) return '';
  429. const pad = n => String(n).padStart(2,'0');
  430. // 紧凑成两行:MM-DD\n HH:MM:SS(避免一行被挤断)
  431. return `${d.getFullYear()}-${pad(d.getMonth()+1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`;
  432. }
  433. let _accPage = 1;
  434. const _accPageSize = 20;
  435. async function loadAccounts(page) {
  436. if (page !== undefined) _accPage = page;
  437. const status = $('accFilter').value || '';
  438. let url = '/api/accounts?page=' + _accPage + '&pageSize=' + _accPageSize;
  439. if (status) url += '&status=' + encodeURIComponent(status);
  440. try {
  441. const r = await fetch(url);
  442. const data = await r.json();
  443. const total = data.total || 0;
  444. const totalPages = Math.max(1, Math.ceil(total / _accPageSize));
  445. if (_accPage > totalPages) _accPage = totalPages;
  446. const tbody = $('dbTable').querySelector('tbody');
  447. tbody.innerHTML = '';
  448. (data.accounts || []).forEach(a => {
  449. const tr = document.createElement('tr');
  450. const detailBtn = `<button class="action-btn detail" data-email="${a.email}" data-action="detail">详情</button>`;
  451. const dlBtn = a.cpa_file_name
  452. ? `<a class="action-btn download" href="/api/account/${encodeURIComponent(a.email)}/cpa.json" target="_blank" rel="noopener" download>下载 CPA</a>`
  453. : '';
  454. const failedStatuses = ['plus_check_failed','cpa_failed','failed','cpa_skipped','registered','paid'];
  455. const recheckBtn = failedStatuses.includes(a.final_status||'')
  456. ? `<button class="action-btn recheck" data-email="${a.email}" data-action="recheck">重新校验</button>`
  457. : '';
  458. const retryPayBtn = a.can_retry_payment
  459. ? `<button class="action-btn retry-pay" data-email="${a.email}" data-action="retry-pay">重新付款</button>`
  460. : '';
  461. const emailHtml = `<code title="${a.email||''}">${a.email||''}</code>`;
  462. const cpaHtml = a.cpa_file_name ? `<span title="${a.cpa_file_name}">${a.cpa_file_name}</span>` : '';
  463. const errHtml = a.last_error ? `<span title="${(a.last_error||'').replace(/"/g,'&quot;')}">${a.last_error}</span>` : '';
  464. const statusHtml = `${a.final_status||''}${a.trial_eligible ? ' <span class="chip blue">试用</span>' : ''}`;
  465. tr.innerHTML = `<td class="col-email">${emailHtml}</td><td class="col-plan">${a.plan_type||''}</td><td class="col-stat">${statusHtml}</td><td class="col-cpa">${cpaHtml}</td><td class="col-time">${fmtTime(a.created_at)}</td><td class="col-time">${fmtTime(a.updated_at)}</td><td class="col-err">${errHtml}</td><td class="col-act">${detailBtn}${recheckBtn}${retryPayBtn}${dlBtn}</td>`;
  466. tbody.appendChild(tr);
  467. });
  468. tbody.querySelectorAll('button[data-action="detail"]').forEach(btn => {
  469. btn.addEventListener('click', () => loadAccountDetail(btn.dataset.email));
  470. });
  471. tbody.querySelectorAll('button[data-action="recheck"]').forEach(btn => {
  472. btn.addEventListener('click', () => triggerRecheck(btn));
  473. });
  474. tbody.querySelectorAll('button[data-action="retry-pay"]').forEach(btn => {
  475. btn.addEventListener('click', () => triggerRetryPayment(btn));
  476. });
  477. renderPager(totalPages, total);
  478. } catch (e) {
  479. console.error(e);
  480. }
  481. }
  482. function renderPager(totalPages, total) {
  483. const box = $('dbPager');
  484. box.innerHTML = '';
  485. if (totalPages <= 1 && total <= _accPageSize) { box.innerHTML = `<span class="info">共 ${total} 条</span>`; return; }
  486. const info = document.createElement('span');
  487. info.className = 'info';
  488. info.textContent = `共 ${total} 条 · 第 ${_accPage}/${totalPages} 页`;
  489. box.appendChild(info);
  490. const addBtn = (label, pg, disabled) => {
  491. const b = document.createElement('button');
  492. b.textContent = label;
  493. b.disabled = disabled;
  494. if (pg === _accPage) b.classList.add('active');
  495. if (!disabled) b.addEventListener('click', () => loadAccounts(pg));
  496. box.appendChild(b);
  497. };
  498. addBtn('«', 1, _accPage <= 1);
  499. addBtn('‹', _accPage - 1, _accPage <= 1);
  500. let start = Math.max(1, _accPage - 2);
  501. let end = Math.min(totalPages, start + 4);
  502. if (end - start < 4) start = Math.max(1, end - 4);
  503. for (let i = start; i <= end; i++) addBtn(String(i), i, false);
  504. addBtn('›', _accPage + 1, _accPage >= totalPages);
  505. addBtn('»', totalPages, _accPage >= totalPages);
  506. }
  507. async function loadAccountDetail(email) {
  508. try {
  509. const r = await fetch('/api/account/' + encodeURIComponent(email));
  510. const data = await r.json();
  511. $('accDetail').textContent = JSON.stringify(data, null, 2);
  512. } catch (e) {
  513. $('accDetail').textContent = String(e);
  514. }
  515. }
  516. async function triggerRecheck(btn) {
  517. const email = btn.dataset.email;
  518. if (!email) return;
  519. const orig = btn.textContent;
  520. btn.disabled = true;
  521. btn.textContent = '校验中...';
  522. try {
  523. const r = await fetch('/api/account/' + encodeURIComponent(email) + '/recheck', {method:'POST'});
  524. const data = await r.json();
  525. if (data.ok) {
  526. const action = data.action || '';
  527. const tip = action === 'cpa_uploaded' ? '已上传 CPA'
  528. : action === 'plus_no_cpa_config' ? '已 Plus(未配置 CPA)'
  529. : '已 Plus';
  530. btn.textContent = '✓ ' + tip;
  531. } else if (data.action === 'still_not_plus') {
  532. btn.textContent = `仍非 plus(${data.planType||'?'})`;
  533. } else {
  534. btn.textContent = '✗ 失败';
  535. console.warn('recheck error', data);
  536. }
  537. setTimeout(() => loadAccounts(), 1200);
  538. } catch (e) {
  539. alert(e.message || String(e));
  540. btn.disabled = false;
  541. btn.textContent = orig;
  542. }
  543. }
  544. async function triggerRetryPayment(btn) {
  545. const email = btn.dataset.email;
  546. if (!email) return;
  547. if (!confirm(`确认为 ${email} 重新发起付款流程?`)) return;
  548. const orig = btn.textContent;
  549. btn.disabled = true;
  550. btn.textContent = '获取中...';
  551. try {
  552. const r = await fetch('/api/account/' + encodeURIComponent(email) + '/retry_payment', {method:'POST'});
  553. const data = await r.json();
  554. if (data.ok) {
  555. btn.textContent = '✓ 已提交 ' + (data.task_id || '');
  556. } else {
  557. btn.textContent = '✗ ' + (data.error || '失败');
  558. }
  559. setTimeout(() => loadAccounts(), 1500);
  560. } catch (e) {
  561. alert(e.message || String(e));
  562. btn.disabled = false;
  563. btn.textContent = orig;
  564. }
  565. }
  566. $('refreshAccounts').addEventListener('click', () => loadAccounts());
  567. $('accFilter').addEventListener('change', () => loadAccounts(1));
  568. // 全自动跑完后自动刷一次账号库
  569. const _origRefreshStatus = refreshStatus;
  570. let _wasRunning = false;
  571. async function refreshStatusWithDb() {
  572. await _origRefreshStatus();
  573. try {
  574. const r = await fetch('/api/status');
  575. const s = await r.json();
  576. if (_wasRunning && !s.running) loadAccounts();
  577. _wasRunning = !!s.running;
  578. } catch (_) {}
  579. }
  580. clearInterval(window.__statusTimer);
  581. window.__statusTimer = setInterval(refreshStatusWithDb, 1500);
  582. $('save').addEventListener('click', saveConfig);
  583. $('go').addEventListener('click', async () => {
  584. // 自动先保存一次配置
  585. await saveConfig();
  586. $('log').textContent = '';
  587. $('go').disabled = true;
  588. setState('启动中', 'gray');
  589. try {
  590. const r = await fetch('/api/start', {method:'POST'});
  591. const data = await r.json();
  592. if (data.error) {
  593. alert(data.error);
  594. $('go').disabled = false;
  595. setState('空闲', 'gray');
  596. }
  597. } catch (e) {
  598. alert(e.message || String(e));
  599. $('go').disabled = false;
  600. }
  601. });
  602. $('stop').addEventListener('click', async () => {
  603. await fetch('/api/stop', {method: 'POST'});
  604. });
  605. </script>
  606. </body>
  607. </html>"""
  608. def _read_json(handler) -> dict:
  609. length = int(handler.headers.get("content-length") or "0")
  610. if length <= 0:
  611. return {}
  612. raw = handler.rfile.read(length).decode("utf-8", errors="replace")
  613. return json.loads(raw or "{}")
  614. class Handler(BaseHTTPRequestHandler):
  615. def do_GET(self):
  616. path = self.path.split("?", 1)[0]
  617. query = self.path.split("?", 1)[1] if "?" in self.path else ""
  618. if path in ("/", "/index.html"):
  619. self._send(200, INDEX_HTML.encode("utf-8"), "text/html; charset=utf-8")
  620. return
  621. if path in ("/docs", "/docs/"):
  622. self._send(200, SWAGGER_HTML.encode("utf-8"), "text/html; charset=utf-8")
  623. return
  624. if path == "/openapi.json":
  625. self._send_json(200, _build_openapi_spec())
  626. return
  627. if not self._check_auth():
  628. return
  629. if path == "/api/status":
  630. self._send_json(200, JOB.status())
  631. return
  632. if path == "/api/config":
  633. self._send_json(200, asdict(AppConfig.load()))
  634. return
  635. if path == "/api/log":
  636. self._stream_log()
  637. return
  638. # ===== 任务化 API(GET)=====
  639. if path == "/api/tasks":
  640. from urllib.parse import parse_qs
  641. q = parse_qs(query)
  642. status = (q.get("status") or [""])[0] or None
  643. limit = int((q.get("limit") or ["100"])[0])
  644. try:
  645. tasks = list_tasks(limit=limit, status=status)
  646. self._send_json(200, {"tasks": tasks})
  647. except Exception as exc:
  648. self._send_json(500, {"error": str(exc)})
  649. return
  650. if path.startswith("/api/tasks/"):
  651. from urllib.parse import unquote
  652. task_id = unquote(path[len("/api/tasks/"):])
  653. t = get_task(task_id)
  654. if not t:
  655. self._send_json(404, {"error": "task not found"})
  656. return
  657. self._send_json(200, {"task": t})
  658. return
  659. if path == "/api/accounts":
  660. try:
  661. from urllib.parse import parse_qs
  662. q = parse_qs(query)
  663. status = (q.get("status") or [""])[0] or None
  664. page_num = max(1, int((q.get("page") or ["1"])[0]))
  665. page_size = max(1, min(100, int((q.get("pageSize") or ["20"])[0])))
  666. offset = (page_num - 1) * page_size
  667. total = count_accounts(status=status)
  668. accounts = list_accounts(limit=page_size, status=status, offset=offset)
  669. slim = []
  670. for a in accounts:
  671. slim.append({k: a.get(k) for k in (
  672. "email", "plan_type", "final_status", "cpa_file_name",
  673. "long_link", "last_error", "created_at", "updated_at",
  674. "cpa_uploaded_at", "trial_eligible", "trial_state",
  675. "is_trial_account", "can_retry_payment"
  676. )})
  677. self._send_json(200, {"accounts": slim, "total": total, "page": page_num, "pageSize": page_size})
  678. except Exception as exc:
  679. self._send_json(500, {"error": str(exc)})
  680. return
  681. if path.startswith("/api/account/") and path.endswith("/cpa.json"):
  682. from urllib.parse import unquote
  683. email = unquote(path[len("/api/account/"):-len("/cpa.json")])
  684. acc = get_account(email)
  685. if not acc:
  686. self._send_json(404, {"error": "account not found"})
  687. return
  688. session = acc.get("plus_session") or acc.get("initial_session")
  689. if not session:
  690. self._send_json(404, {"error": "该账号没有可下载的 session"})
  691. return
  692. try:
  693. payload = build_cpa_auth_payload(session, email_hint=email)
  694. except Exception as exc:
  695. self._send_json(500, {"error": f"构造 CPA auth JSON 失败: {exc}"})
  696. return
  697. file_name = acc.get("cpa_file_name") or payload["fileName"]
  698. content = json.dumps(payload["authJson"], ensure_ascii=False, indent=2).encode("utf-8")
  699. self.send_response(200)
  700. self.send_header("Content-Type", "application/json; charset=utf-8")
  701. self.send_header("Content-Disposition", f'attachment; filename="{file_name}"')
  702. self.send_header("Cache-Control", "no-store")
  703. self.send_header("Content-Length", str(len(content)))
  704. self.end_headers()
  705. self.wfile.write(content)
  706. return
  707. if path.startswith("/api/account/"):
  708. from urllib.parse import unquote
  709. email = unquote(path[len("/api/account/"):])
  710. acc = get_account(email)
  711. if not acc:
  712. self._send_json(404, {"error": "account not found"})
  713. return
  714. events = list_events(email, limit=200)
  715. self._send_json(200, {"account": acc, "events": events})
  716. return
  717. self._send_json(404, {"error": "not found"})
  718. def do_POST(self):
  719. path = self.path.split("?", 1)[0]
  720. if not self._check_auth():
  721. return
  722. if path == "/api/config":
  723. try:
  724. body = _read_json(self)
  725. cfg = AppConfig.load().update(body or {})
  726. self._send_json(200, asdict(cfg))
  727. except Exception as exc:
  728. self._send_json(500, {"error": str(exc)})
  729. return
  730. # ===== 任务化 API =====
  731. if path == "/api/tasks":
  732. try:
  733. body = _read_json(self) or {}
  734. mode = (body.get("mode") or "full").strip().lower()
  735. if mode not in ("full", "pay_only"):
  736. self._send_json(400, {"error": "mode 必须是 full 或 pay_only"})
  737. return
  738. params = body.get("params") or {}
  739. if mode == "pay_only":
  740. sess = params.get("session")
  741. if not isinstance(sess, dict) or not sess.get("accessToken"):
  742. self._send_json(400, {"error": "pay_only 需要 params.session 是 JSON 且包含 accessToken"})
  743. return
  744. max_attempts = int(body.get("max_attempts") or 3)
  745. max_attempts = max(1, min(10, max_attempts))
  746. task_id = make_task_id()
  747. t = create_task(task_id, mode, params, max_attempts=max_attempts)
  748. # 启动 runner(幂等)
  749. get_runner(log=lambda m: JOB._log(m))
  750. self._send_json(200, {"task_id": task_id, "task": t})
  751. except Exception as exc:
  752. self._send_json(500, {"error": str(exc)})
  753. return
  754. if path.startswith("/api/tasks/") and path.endswith("/cancel"):
  755. from urllib.parse import unquote
  756. task_id = unquote(path[len("/api/tasks/"):-len("/cancel")])
  757. t = get_task(task_id)
  758. if not t:
  759. self._send_json(404, {"error": "task not found"})
  760. return
  761. runner = get_runner(log=lambda m: JOB._log(m))
  762. runner.cancel(task_id)
  763. self._send_json(200, {"ok": True, "task_id": task_id})
  764. return
  765. if path == "/api/start":
  766. try:
  767. cfg = AppConfig.load()
  768. err = JOB.start(cfg)
  769. if err:
  770. self._send_json(409, {"error": err})
  771. else:
  772. self._send_json(200, {"ok": True})
  773. except Exception as exc:
  774. self._send_json(500, {"error": str(exc)})
  775. return
  776. if path.startswith("/api/account/") and path.endswith("/recheck"):
  777. from urllib.parse import unquote
  778. email = unquote(path[len("/api/account/"):-len("/recheck")])
  779. cfg = AppConfig.load()
  780. try:
  781. result = recheck_account(
  782. email,
  783. cpa_url=cfg.cpa_url,
  784. cpa_management_key=cfg.cpa_management_key,
  785. log=lambda msg: JOB._log(f"[acc:{email[:24]}] {msg}"),
  786. )
  787. self._send_json(200, result)
  788. except Exception as exc:
  789. self._send_json(500, {"error": str(exc)})
  790. return
  791. if path.startswith("/api/account/") and path.endswith("/retry_payment"):
  792. from urllib.parse import unquote
  793. email = unquote(path[len("/api/account/"):-len("/retry_payment")])
  794. acc = get_account(email)
  795. if not acc:
  796. self._send_json(404, {"error": "账号不存在"})
  797. return
  798. if not acc.get("can_retry_payment"):
  799. self._send_json(400, {"error": "该账号当前不支持直接重新付款"})
  800. return
  801. session = acc.get("plus_session") or acc.get("initial_session")
  802. if not session or not isinstance(session, dict) or not session.get("accessToken"):
  803. self._send_json(400, {"error": "该账号没有可用的 session(缺少 accessToken)"})
  804. return
  805. try:
  806. task_id = make_task_id()
  807. t = create_task(task_id, "pay_only", {"session": session, "email": email}, max_attempts=3)
  808. get_runner(log=lambda m: JOB._log(m))
  809. self._send_json(200, {"ok": True, "task_id": task_id, "task": t})
  810. except Exception as exc:
  811. self._send_json(500, {"error": str(exc)})
  812. return
  813. if path == "/api/stop":
  814. JOB.stop()
  815. self._send_json(200, {"ok": True})
  816. return
  817. self._send_json(404, {"error": "not found"})
  818. def _stream_log(self):
  819. self.send_response(200)
  820. self.send_header("Content-Type", "text/event-stream; charset=utf-8")
  821. self.send_header("Cache-Control", "no-cache")
  822. self.send_header("Connection", "keep-alive")
  823. self.end_headers()
  824. try:
  825. for line in JOB.history[-300:]:
  826. self._sse_send(line)
  827. while True:
  828. try:
  829. line = JOB.log_queue.get(timeout=15)
  830. self._sse_send(line)
  831. except queue.Empty:
  832. self.wfile.write(b": ping\n\n")
  833. self.wfile.flush()
  834. except (BrokenPipeError, ConnectionResetError):
  835. return
  836. def _sse_send(self, line: str):
  837. for piece in line.splitlines() or [""]:
  838. self.wfile.write(b"data: " + piece.encode("utf-8") + b"\n")
  839. self.wfile.write(b"\n")
  840. self.wfile.flush()
  841. def _send_json(self, status: int, payload: dict):
  842. self._send(status, json.dumps(payload, ensure_ascii=False).encode("utf-8"), "application/json; charset=utf-8")
  843. def _send(self, status: int, content: bytes, content_type: str):
  844. self.send_response(status)
  845. self.send_header("Content-Type", content_type)
  846. self.send_header("Cache-Control", "no-store")
  847. self.send_header("Content-Length", str(len(content)))
  848. # CORS(仅 /api/* 需要时由调用方决定,但统一发也无害)
  849. try:
  850. cfg = AppConfig.load()
  851. origin = (cfg.api_cors_origin or "*").strip()
  852. self.send_header("Access-Control-Allow-Origin", origin)
  853. self.send_header("Access-Control-Allow-Credentials", "true")
  854. except Exception:
  855. self.send_header("Access-Control-Allow-Origin", "*")
  856. self.end_headers()
  857. self.wfile.write(content)
  858. def do_OPTIONS(self):
  859. # CORS preflight
  860. self.send_response(204)
  861. try:
  862. cfg = AppConfig.load()
  863. origin = (cfg.api_cors_origin or "*").strip()
  864. except Exception:
  865. origin = "*"
  866. self.send_header("Access-Control-Allow-Origin", origin)
  867. self.send_header("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
  868. self.send_header("Access-Control-Allow-Headers", "Content-Type, Authorization")
  869. self.send_header("Access-Control-Max-Age", "86400")
  870. self.send_header("Access-Control-Allow-Credentials", "true")
  871. self.end_headers()
  872. def _check_auth(self) -> bool:
  873. """非空 api_token 时校验 Authorization: Bearer。返回 True 表示放行。"""
  874. try:
  875. cfg = AppConfig.load()
  876. token = (cfg.api_token or "").strip()
  877. except Exception:
  878. token = ""
  879. if not token:
  880. return True
  881. # 公开接口豁免:根页面、OpenAPI 文档、Swagger UI、static 静态
  882. path = self.path.split("?", 1)[0]
  883. public = ("/", "/index.html", "/docs", "/docs/", "/openapi.json", "/openapi.yaml")
  884. if path in public:
  885. return True
  886. auth = self.headers.get("Authorization", "")
  887. if auth == f"Bearer {token}":
  888. return True
  889. # 也支持 ?token=xxx
  890. if "token=" in (self.path.split("?", 1)[1] if "?" in self.path else ""):
  891. from urllib.parse import parse_qs
  892. q = parse_qs(self.path.split("?", 1)[1])
  893. if (q.get("token") or [""])[0] == token:
  894. return True
  895. self._send_json(401, {"error": "missing or invalid Bearer token"})
  896. return False
  897. def log_message(self, fmt, *args):
  898. return
  899. def handle_one_request(self):
  900. try:
  901. return super().handle_one_request()
  902. except (ConnectionResetError, BrokenPipeError):
  903. # 浏览器主动断开 SSE / fetch 时打印栈很碍眼,直接静音
  904. self.close_connection = True
  905. SWAGGER_HTML = r"""<!doctype html>
  906. <html lang="zh-CN">
  907. <head>
  908. <meta charset="utf-8" />
  909. <title>API 文档 · ChatGPT Plus 自动化</title>
  910. <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/swagger-ui-dist@5.17.14/swagger-ui.css" />
  911. <style>body{margin:0}#swagger-ui{max-width:1280px;margin:0 auto}</style>
  912. </head>
  913. <body>
  914. <div id="swagger-ui"></div>
  915. <script src="https://cdn.jsdelivr.net/npm/swagger-ui-dist@5.17.14/swagger-ui-bundle.js"></script>
  916. <script src="https://cdn.jsdelivr.net/npm/swagger-ui-dist@5.17.14/swagger-ui-standalone-preset.js"></script>
  917. <script>
  918. window.onload = () => {
  919. window.ui = SwaggerUIBundle({
  920. url: '/openapi.json',
  921. dom_id: '#swagger-ui',
  922. deepLinking: true,
  923. presets: [SwaggerUIBundle.presets.apis, SwaggerUIStandalonePreset],
  924. layout: 'StandaloneLayout',
  925. persistAuthorization: true,
  926. tryItOutEnabled: true,
  927. });
  928. };
  929. </script>
  930. </body>
  931. </html>"""
  932. def _build_openapi_spec() -> dict:
  933. """生成 OpenAPI 3.1 规范。"""
  934. cfg = AppConfig.load()
  935. return {
  936. "openapi": "3.1.0",
  937. "info": {
  938. "title": "ChatGPT Plus 自动化 API",
  939. "version": "1.0.0",
  940. "description": (
  941. "ChatGPT Plus 全自动注册 + PayPal 付款 + CPA 上传。\n\n"
  942. "**两种模式**:\n"
  943. "- `full` — 全自动注册新 ChatGPT 账号,注册→付款→上传 CPA\n"
  944. "- `pay_only` — 传入已有 session JSON,跳过注册直接付款→上传 CPA\n\n"
  945. "**调用流程**:\n"
  946. "1. POST `/api/tasks` 创建任务,立即拿到 `task_id`\n"
  947. "2. 轮询 GET `/api/tasks/{task_id}` 看 `status` 和 `stage`\n"
  948. "3. `status` 变 `success` 时可调 GET `/api/account/{email}/cpa.json` 下载 CPA 文件\n\n"
  949. "**重试**:每个任务整体失败会重试 `max_attempts` 次(默认 3)。"
  950. ),
  951. },
  952. "servers": [
  953. {"url": f"http://{cfg.api_host or '127.0.0.1'}:{cfg.api_port or 7791}", "description": "当前实例"},
  954. ],
  955. "components": {
  956. "securitySchemes": {
  957. "BearerAuth": {
  958. "type": "http",
  959. "scheme": "bearer",
  960. "description": "如果配置了 `api_token`,所有 /api/* 请求需带 `Authorization: Bearer <token>`。也支持 `?token=xxx` 查询参数。",
  961. }
  962. },
  963. "schemas": {
  964. "Task": {
  965. "type": "object",
  966. "properties": {
  967. "task_id": {"type": "string", "example": "t-1779470219-65e44d55"},
  968. "mode": {"type": "string", "enum": ["full", "pay_only"]},
  969. "status": {"type": "string", "enum": ["queued", "running", "success", "failed", "cancelled"]},
  970. "stage": {"type": "string", "description": "当前阶段描述"},
  971. "attempts": {"type": "integer"},
  972. "max_attempts": {"type": "integer"},
  973. "params": {"type": "object", "description": "创建任务时传入的参数(脱敏后)"},
  974. "result": {"type": "object", "nullable": True, "description": "成功时的结果(含 CPA 文件名等)"},
  975. "last_error": {"type": "string", "nullable": True},
  976. "email": {"type": "string", "nullable": True, "description": "注册成功的 ChatGPT 邮箱"},
  977. "plan_type": {"type": "string", "nullable": True, "example": "plus"},
  978. "cpa_file_name": {"type": "string", "nullable": True, "example": "codex-foo@example.com-plus.json"},
  979. "created_at": {"type": "integer", "description": "毫秒时间戳"},
  980. "updated_at": {"type": "integer"},
  981. "started_at": {"type": "integer", "nullable": True},
  982. "finished_at": {"type": "integer", "nullable": True},
  983. },
  984. },
  985. "CreateTaskRequest": {
  986. "type": "object",
  987. "required": ["mode"],
  988. "properties": {
  989. "mode": {"type": "string", "enum": ["full", "pay_only"]},
  990. "max_attempts": {"type": "integer", "default": 3, "minimum": 1, "maximum": 10},
  991. "params": {
  992. "type": "object",
  993. "description": "可覆盖全局配置;pay_only 模式必须包含 session 字段",
  994. "properties": {
  995. "session": {
  996. "type": "object",
  997. "description": "ChatGPT /api/auth/session 完整 JSON(仅 pay_only 模式必填)",
  998. "properties": {
  999. "accessToken": {"type": "string"},
  1000. "user": {"type": "object"},
  1001. "account": {"type": "object"},
  1002. },
  1003. },
  1004. "headless": {"type": "boolean"},
  1005. "use_promo": {"type": "boolean"},
  1006. "phone_e164": {"type": "string", "example": "+15822201173"},
  1007. "sms_api_url": {"type": "string"},
  1008. "cpa_url": {"type": "string"},
  1009. "cpa_management_key": {"type": "string"},
  1010. "proxy_url": {"type": "string"},
  1011. "paypal_only_proxy": {"type": "string"},
  1012. "mail_helper_url": {"type": "string"},
  1013. "mail_domain": {"type": "string"},
  1014. },
  1015. },
  1016. },
  1017. },
  1018. "Account": {
  1019. "type": "object",
  1020. "properties": {
  1021. "email": {"type": "string"},
  1022. "plan_type": {"type": "string", "nullable": True},
  1023. "final_status": {"type": "string"},
  1024. "cpa_file_name": {"type": "string", "nullable": True},
  1025. "long_link": {"type": "string", "nullable": True},
  1026. "last_error": {"type": "string", "nullable": True},
  1027. "created_at": {"type": "integer"},
  1028. "updated_at": {"type": "integer"},
  1029. "cpa_uploaded_at": {"type": "integer", "nullable": True},
  1030. },
  1031. },
  1032. "Error": {
  1033. "type": "object",
  1034. "properties": {"error": {"type": "string"}},
  1035. },
  1036. },
  1037. },
  1038. "security": [{"BearerAuth": []}] if cfg.api_token else [],
  1039. "paths": {
  1040. "/api/tasks": {
  1041. "post": {
  1042. "tags": ["Tasks"],
  1043. "summary": "创建任务",
  1044. "description": "创建一个 full 或 pay_only 任务,立即返回 task_id,任务异步执行。",
  1045. "requestBody": {
  1046. "required": True,
  1047. "content": {
  1048. "application/json": {
  1049. "schema": {"$ref": "#/components/schemas/CreateTaskRequest"},
  1050. "examples": {
  1051. "full": {
  1052. "summary": "全自动注册",
  1053. "value": {
  1054. "mode": "full",
  1055. "max_attempts": 3,
  1056. "params": {},
  1057. },
  1058. },
  1059. "pay_only": {
  1060. "summary": "传入 session 直接付款",
  1061. "value": {
  1062. "mode": "pay_only",
  1063. "max_attempts": 3,
  1064. "params": {
  1065. "session": {
  1066. "accessToken": "eyJxxx...",
  1067. "user": {"email": "user@example.com"},
  1068. "account": {"planType": "free"},
  1069. }
  1070. },
  1071. },
  1072. },
  1073. },
  1074. }
  1075. },
  1076. },
  1077. "responses": {
  1078. "200": {
  1079. "description": "任务已创建",
  1080. "content": {
  1081. "application/json": {
  1082. "schema": {
  1083. "type": "object",
  1084. "properties": {
  1085. "task_id": {"type": "string"},
  1086. "task": {"$ref": "#/components/schemas/Task"},
  1087. },
  1088. }
  1089. }
  1090. },
  1091. },
  1092. "400": {"description": "参数错误", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Error"}}}},
  1093. "401": {"description": "Bearer token 缺失或无效"},
  1094. },
  1095. },
  1096. "get": {
  1097. "tags": ["Tasks"],
  1098. "summary": "列出任务",
  1099. "parameters": [
  1100. {"name": "status", "in": "query", "schema": {"type": "string", "enum": ["queued", "running", "success", "failed", "cancelled"]}},
  1101. {"name": "limit", "in": "query", "schema": {"type": "integer", "default": 100}},
  1102. ],
  1103. "responses": {
  1104. "200": {
  1105. "content": {
  1106. "application/json": {
  1107. "schema": {
  1108. "type": "object",
  1109. "properties": {"tasks": {"type": "array", "items": {"$ref": "#/components/schemas/Task"}}},
  1110. }
  1111. }
  1112. }
  1113. }
  1114. },
  1115. },
  1116. },
  1117. "/api/tasks/{task_id}": {
  1118. "get": {
  1119. "tags": ["Tasks"],
  1120. "summary": "查询任务进度",
  1121. "description": "轮询此接口查任务实时 status 和 stage。建议 5-10 秒间隔。",
  1122. "parameters": [{"name": "task_id", "in": "path", "required": True, "schema": {"type": "string"}}],
  1123. "responses": {
  1124. "200": {"content": {"application/json": {"schema": {"type": "object", "properties": {"task": {"$ref": "#/components/schemas/Task"}}}}}},
  1125. "404": {"description": "任务不存在"},
  1126. },
  1127. }
  1128. },
  1129. "/api/tasks/{task_id}/cancel": {
  1130. "post": {
  1131. "tags": ["Tasks"],
  1132. "summary": "取消任务",
  1133. "description": "请求取消任务。如果任务已经在跑,会在下一个 stop 检查点退出。",
  1134. "parameters": [{"name": "task_id", "in": "path", "required": True, "schema": {"type": "string"}}],
  1135. "responses": {"200": {"description": "已请求取消"}, "404": {"description": "任务不存在"}},
  1136. }
  1137. },
  1138. "/api/accounts": {
  1139. "get": {
  1140. "tags": ["Accounts"],
  1141. "summary": "列出已注册账号",
  1142. "parameters": [
  1143. {"name": "status", "in": "query", "schema": {"type": "string"}, "description": "如 cpa_uploaded / plus_check_failed"},
  1144. {"name": "limit", "in": "query", "schema": {"type": "integer", "default": 200}},
  1145. ],
  1146. "responses": {
  1147. "200": {
  1148. "content": {
  1149. "application/json": {
  1150. "schema": {
  1151. "type": "object",
  1152. "properties": {"accounts": {"type": "array", "items": {"$ref": "#/components/schemas/Account"}}},
  1153. }
  1154. }
  1155. }
  1156. }
  1157. },
  1158. }
  1159. },
  1160. "/api/account/{email}": {
  1161. "get": {
  1162. "tags": ["Accounts"],
  1163. "summary": "查询账号详情(含完整 session 和事件流)",
  1164. "parameters": [{"name": "email", "in": "path", "required": True, "schema": {"type": "string"}}],
  1165. "responses": {"200": {"description": "OK"}, "404": {"description": "账号不存在"}},
  1166. }
  1167. },
  1168. "/api/account/{email}/cpa.json": {
  1169. "get": {
  1170. "tags": ["Accounts"],
  1171. "summary": "下载 CPA codex auth JSON",
  1172. "description": "返回该账号当时上传给 CPA 的完整 codex auth JSON 文件。带 Content-Disposition 头,浏览器会自动下载。",
  1173. "parameters": [{"name": "email", "in": "path", "required": True, "schema": {"type": "string"}}],
  1174. "responses": {
  1175. "200": {"description": "OK", "content": {"application/json": {}}},
  1176. "404": {"description": "账号或 session 不存在"},
  1177. },
  1178. }
  1179. },
  1180. "/api/account/{email}/recheck": {
  1181. "post": {
  1182. "tags": ["Accounts"],
  1183. "summary": "对失败账号补救",
  1184. "description": "用 DB 里存的 access_token 调 backend-api/me,若已 plus 则自动重传 CPA。",
  1185. "parameters": [{"name": "email", "in": "path", "required": True, "schema": {"type": "string"}}],
  1186. "responses": {"200": {"description": "OK"}, "404": {"description": "账号不存在"}},
  1187. }
  1188. },
  1189. "/api/config": {
  1190. "get": {"tags": ["Config"], "summary": "读取当前配置", "responses": {"200": {"description": "OK"}}},
  1191. "post": {
  1192. "tags": ["Config"],
  1193. "summary": "更新配置",
  1194. "requestBody": {"content": {"application/json": {"schema": {"type": "object"}}}},
  1195. "responses": {"200": {"description": "OK"}},
  1196. },
  1197. },
  1198. "/api/status": {
  1199. "get": {"tags": ["Misc"], "summary": "(旧)读取 UI 任务状态", "responses": {"200": {"description": "OK"}}}
  1200. },
  1201. "/api/log": {
  1202. "get": {"tags": ["Misc"], "summary": "实时日志(Server-Sent Events)", "responses": {"200": {"description": "text/event-stream"}}}
  1203. },
  1204. },
  1205. "tags": [
  1206. {"name": "Tasks", "description": "任务化 API(推荐用法)"},
  1207. {"name": "Accounts", "description": "账号库"},
  1208. {"name": "Config", "description": "服务配置"},
  1209. {"name": "Misc", "description": "其他"},
  1210. ],
  1211. }
  1212. def _silence_threading_excepthook():
  1213. """ThreadingHTTPServer 在 worker 线程里仍可能抛 ConnectionResetError;接住它。"""
  1214. import threading
  1215. prev = threading.excepthook
  1216. def hook(args):
  1217. if isinstance(args.exc_value, (ConnectionResetError, BrokenPipeError)):
  1218. return
  1219. prev(args)
  1220. threading.excepthook = hook
  1221. def main():
  1222. init_db()
  1223. _silence_threading_excepthook()
  1224. # 启动后台任务 worker(幂等)
  1225. get_runner(log=lambda m: JOB._log(m))
  1226. cfg = AppConfig.load()
  1227. host = (cfg.api_host or HOST).strip() or HOST
  1228. port = int(cfg.api_port or PORT)
  1229. server = ThreadingHTTPServer((host, port), Handler)
  1230. print(f"ChatGPT Plus Auto Console:")
  1231. print(f" Web UI: http://{host}:{port}/")
  1232. print(f" Docs: http://{host}:{port}/docs")
  1233. print(f" OpenAPI: http://{host}:{port}/openapi.json")
  1234. if cfg.api_token:
  1235. print(f" Auth: Bearer <token>(已启用)")
  1236. if host == "0.0.0.0":
  1237. print(f" ⚠️ 当前监听所有网卡,外网可访问。建议设置 api_token。")
  1238. try:
  1239. server.serve_forever()
  1240. except KeyboardInterrupt:
  1241. print("\nStopped.")
  1242. if __name__ == "__main__":
  1243. main()