#!/usr/bin/env python3 """th_pipeline.py — full auto pipeline: CDP watchdog + autoreg chunks + auto-deploy to VPS. Usage: python th_pipeline.py [TOTAL] [CHUNK] TOTAL — total accounts to register (default 200) CHUNK — accounts per chunk before sync (default 10) Loop: 1. ensure Chrome CDP :9222 alive (restart if dead) 2. run th_tonline_claim.py CHUNK 3. run th_sync_vps.py (deploys new keys to VPS, stops new-api during write) 4. repeat until TOTAL reached State: th_pipeline_state.json (done chunks, deployed count) """ # __portable_paths__ (auto-injected: portable, env-overridable paths) import os as _pos, sys as _psys from pathlib import Path as _PPath _ROOT = _PPath(__file__).resolve().parent _REPO = _ROOT for _ in range(4): if (_REPO / ".git").exists() or (_REPO / "README.md").exists(): break if _REPO.parent == _REPO: break _REPO = _REPO.parent _DATA = _PPath(_pos.environ.get("TOOLKIT_DATA", str(_REPO / "data"))) _WORK = _PPath(_pos.environ.get("TOOLKIT_WORK", str(_REPO / "_work"))) try: _DATA.mkdir(parents=True, exist_ok=True) _WORK.mkdir(parents=True, exist_ok=True) except Exception: pass _PY = _pos.environ.get("PYTHON_BIN") or _psys.executable _USERPROFILE = _pos.environ.get("USERPROFILE") or str(_PPath.home()) def _d(name, env=None): """Data-file path under ./data (or $TOOLKIT_DATA); optional per-file env override.""" if env and _pos.environ.get(env): return _PPath(_pos.environ[env]) return _DATA / name def _w(name=""): """Work-dir path under ./_work (or $TOOLKIT_WORK).""" return (_WORK / name) if name else _WORK # --- end portable prelude --- import json, subprocess, sys, time, urllib.request from pathlib import Path PROJ = Path(__file__).parent PY = _PY CHROME = r"C:/Program Files/Google/Chrome/Application/chrome.exe" CDP_PROFILE = str(_d(".chrome-cdp-profile")) STATE = PROJ / "th_pipeline_state.json" import os as _os, msvcrt _LF = open(Path(__file__).parent / "th_pipeline.lock", "a+") try: msvcrt.locking(_LF.fileno(), msvcrt.LK_NBLCK, 1) except OSError: print("another pipeline instance holds the lock, exiting") _os._exit(0) _LF.seek(0); _LF.truncate(); _LF.write(str(_os.getpid())); _LF.flush() TOTAL = int(sys.argv[1]) if len(sys.argv) > 1 else 200 CHUNK = int(sys.argv[2]) if len(sys.argv) > 2 else 10 def log(msg): print(f"[{time.strftime('%H:%M:%S')}] {msg}", flush=True) def cdp_alive(): try: urllib.request.urlopen("http://127.0.0.1:9222/json/version", timeout=5).read() return True except Exception: return False def start_cdp(): log("CDP dead -> starting Chrome") subprocess.Popen([CHROME, "--remote-debugging-port=9222", "--remote-allow-origins=*", f"--user-data-dir={CDP_PROFILE}", "--no-first-run", "--proxy-server=http://127.0.0.1:8077", "--no-default-browser-check", "about:blank"], creationflags=0x00000008) # DETACHED_PROCESS for _ in range(30): time.sleep(2) if cdp_alive(): log("CDP up") return True log("CDP FAILED to start") return False def run(script, args, label, timeout): log(f"RUN {label}") r = subprocess.run([PY, "-u", str(PROJ / script)] + args, capture_output=True, text=True, timeout=timeout, env={"PYTHONPATH": "", "PATH": r"C:\Windows\system32;C:\Windows;C:\Program Files\Git\usr\bin;C:\Program Files\Git\bin", "USERPROFILE": _USERPROFILE, "SYSTEMROOT": r"C:\Windows"}) out = (r.stdout or "") + (r.stderr or "") keys = out.count("KEY:") log(f"{label} done rc={r.returncode} keys={keys}") if r.returncode != 0: log("tail: " + out[-300:].replace("\n", " | ")) return keys def main(): st = json.loads(STATE.read_text()) if STATE.exists() else {"done": 0, "deployed_runs": 0} while st["done"] < TOTAL: if not cdp_alive() and not start_cdp(): log("CDP unrecoverable, sleep 120"); time.sleep(120); continue n = min(CHUNK, TOTAL - st["done"]) try: run("th_tonline_claim.py", [str(n)], f"reg chunk {n}", timeout=n * 240 + 300) except subprocess.TimeoutExpired: log("reg chunk TIMEOUT — continuing to sync anyway") st["done"] += n try: run("th_sync_vps.py", [], "sync->VPS", timeout=600) st["deployed_runs"] += 1 except subprocess.TimeoutExpired: log("sync TIMEOUT") STATE.write_text(json.dumps(st, indent=1)) log(f"progress: {st['done']}/{TOTAL}") log("PIPELINE COMPLETE") if __name__ == "__main__": main()