220 lines
9.1 KiB
Python
220 lines
9.1 KiB
Python
# One coarena account -> one working coa_ key. Usage: python coa_one.py <idx>
|
|
# Env: COA_HOME (dir with gmail_bank.jsonl, default C:/Users/User/tmp/coarena)
|
|
# COA_CHROME_UP (chrome_up.py path), COA_PY (python exe), OA_PORT_BASE (default 9400)
|
|
import json
|
|
import os
|
|
import subprocess
|
|
import sys
|
|
import time
|
|
|
|
import psutil
|
|
from playwright.sync_api import sync_playwright
|
|
|
|
BASE = os.environ.get("COA_HOME", "C:/Users/User/tmp/coarena")
|
|
PY = os.environ.get("COA_PY", r"C:/Users/User/AppData/Local/Programs/Python/Python311/python.exe")
|
|
CHROME_UP = os.environ.get("COA_CHROME_UP", "C:/Users/User/tmp/ctxdev/chrome_up.py")
|
|
PORT_BASE = int(os.environ.get("OA_PORT_BASE", "9400"))
|
|
BANK = BASE + "/keys_bank.jsonl"
|
|
FAIL = BASE + "/keys_fail.jsonl"
|
|
NL2 = chr(10) + "---" + chr(10)
|
|
PROXY_FILE = "C:/Users/User/tmp/proxfarm/proxies_https.txt"
|
|
|
|
|
|
ZTE = "http://127.0.0.1:8899" # мобильный 89.209.x — проходит Google
|
|
|
|
|
|
def proxy_candidates(idx, n=3):
|
|
"""Список прокси: сначала свой по idx, затем следующие по кругу."""
|
|
import socket
|
|
try:
|
|
pool = [l.strip() for l in open(PROXY_FILE, encoding="utf8") if l.strip()]
|
|
except FileNotFoundError:
|
|
pool = []
|
|
out = []
|
|
if pool:
|
|
for k in range(n):
|
|
out.append("http://" + pool[(idx + k) % len(pool)])
|
|
try:
|
|
s = socket.create_connection(("127.0.0.1", 8899), timeout=3)
|
|
s.close()
|
|
out.append(ZTE)
|
|
except Exception:
|
|
pass
|
|
return out
|
|
|
|
|
|
def proxy_works(px, timeout=6):
|
|
"""Прокси реально тянет HTTPS к Google?"""
|
|
import socket
|
|
try:
|
|
host, _, port = px.replace("http://", "").rpartition(":")
|
|
s = socket.create_connection((host, int(port)), timeout=timeout)
|
|
s.settimeout(timeout)
|
|
s.sendall(b"CONNECT www.google.com:443 HTTP/1.1" + chr(13) + chr(10)
|
|
+ b"Host: www.google.com:443" + chr(13) + chr(10) + chr(13) + chr(10))
|
|
resp = s.recv(200)
|
|
s.close()
|
|
return b" 200" in resp
|
|
except Exception:
|
|
return False
|
|
|
|
|
|
def pick_working_proxy(idx):
|
|
for px in proxy_candidates(idx, 3):
|
|
if proxy_works(px):
|
|
return px
|
|
return ""
|
|
|
|
|
|
def log(msg):
|
|
with open(BASE + "/wave.log", "a", encoding="utf8") as fh:
|
|
fh.write(time.strftime("%H:%M:%S ") + msg + "\n")
|
|
|
|
|
|
def kill_chrome(tag):
|
|
"""Stale chrome on the same profile = ECONNREFUSED on every later step."""
|
|
for pr in psutil.process_iter(["pid", "cmdline"]):
|
|
cmd = " ".join(pr.info["cmdline"] or [])
|
|
if "chrome.exe" in cmd and tag in cmd:
|
|
try:
|
|
pr.kill()
|
|
except Exception:
|
|
pass
|
|
|
|
|
|
def boot(prof, port, proxy=""):
|
|
env = dict(os.environ)
|
|
env["CTX_CHROME_PROF"] = prof
|
|
env["CTX_CDP_PORT"] = str(port)
|
|
if proxy:
|
|
env["CTX_CHROME_PROXY"] = proxy
|
|
env.pop("PYTHONPATH", None)
|
|
try:
|
|
subprocess.run([PY, CHROME_UP], env=env, timeout=120, capture_output=True)
|
|
except Exception:
|
|
pass
|
|
import urllib.request
|
|
for _ in range(40):
|
|
try:
|
|
with urllib.request.urlopen("http://127.0.0.1:%d/json/version" % port, timeout=3) as r:
|
|
if r.status == 200:
|
|
return True
|
|
except Exception:
|
|
time.sleep(1)
|
|
return False
|
|
|
|
|
|
def main():
|
|
idx = int(sys.argv[1])
|
|
rec = [json.loads(l) for l in open(BASE + "/gmail_bank.jsonl", encoding="utf8") if l.strip()][idx]
|
|
prof, port = "%s/prof/%d" % (BASE, idx), PORT_BASE + idx
|
|
os.makedirs(prof, exist_ok=True)
|
|
kill_chrome(prof)
|
|
px = pick_working_proxy(idx)
|
|
boot(prof, port, px)
|
|
out = {"email": rec["email"], "key": None, "ok": False, "stage": "start", "idx": idx, "proxy": px}
|
|
try:
|
|
with sync_playwright() as p:
|
|
ctx = p.chromium.connect_over_cdp("http://127.0.0.1:%d" % port).contexts[0]
|
|
page = ctx.pages[0] if ctx.pages else ctx.new_page()
|
|
# ШАГ 1: прямой логин в Google (форма OAuth-попапа не принимает ввод)
|
|
page.goto("https://accounts.google.com/ServiceLogin?hl=en", wait_until="domcontentloaded", timeout=60000)
|
|
page.wait_for_timeout(2500)
|
|
if page.locator("input[name=identifier], input[type=email]").count():
|
|
el = page.wait_for_selector("input[name=identifier], input[type=email]", state="visible", timeout=30000)
|
|
el.click()
|
|
el.type(rec["email"], delay=35)
|
|
page.wait_for_timeout(500)
|
|
el.press("Enter")
|
|
page.wait_for_timeout(6000)
|
|
pw = page.wait_for_selector("input[name=Passwd], input[type=password]:not([name=hiddenPassword])", state="visible", timeout=30000)
|
|
pw.click()
|
|
pw.type(rec["password"], delay=35)
|
|
page.wait_for_timeout(500)
|
|
pw.press("Enter")
|
|
page.wait_for_timeout(8000)
|
|
out["stage"] = "g_logged"
|
|
# ШАГ 2: coarena OAuth по готовой сессии
|
|
page.goto("https://coarena.ai/account/api/keys", wait_until="domcontentloaded", timeout=60000)
|
|
page.wait_for_timeout(3000)
|
|
if page.locator("text=Continue with Google").count():
|
|
page.locator("text=Continue with Google").first.click()
|
|
page.wait_for_timeout(7000)
|
|
if len(ctx.pages) > 1:
|
|
page = ctx.pages[-1]
|
|
for sel in ("div[data-identifier]", "li:has-text('@')", "div[role=link]:has-text('@')"):
|
|
try:
|
|
loc = page.locator(sel).first
|
|
if loc.count() and loc.is_visible():
|
|
loc.click()
|
|
page.wait_for_timeout(6000)
|
|
break
|
|
except Exception:
|
|
pass
|
|
for sel in ("button:has-text('Continue')", "button:has-text('Продолжить')", "button:has-text('Allow')"):
|
|
try:
|
|
loc = page.locator(sel).first
|
|
if loc.count() and loc.is_visible():
|
|
loc.click()
|
|
page.wait_for_timeout(5000)
|
|
break
|
|
except Exception:
|
|
pass
|
|
page.wait_for_timeout(4000)
|
|
if "coarena.ai" not in page.url:
|
|
page.goto("https://coarena.ai/account/api/keys", wait_until="domcontentloaded", timeout=60000)
|
|
page.wait_for_timeout(2500)
|
|
out["stage"] = "at_keys"
|
|
body = page.evaluate("() => document.body.innerText.slice(0,120)")
|
|
if "Sign in" in body and "Continue with Google" in body:
|
|
out["stage"] = "not_logged"
|
|
else:
|
|
# МУЛЬТИКЛЮЧ: до 10 ключей за прогон (coarena лимит 10/аккаунт)
|
|
keys = []
|
|
last_err = ""
|
|
for _ki in range(10):
|
|
res = page.evaluate("""async () => {
|
|
const r = await fetch('/api/me/keys', {method:'POST', headers:{'Content-Type':'application/json'},
|
|
body: JSON.stringify({name:'ii-' + Math.random().toString(36).slice(2,8), acceptModelApiTerms:'2026-11-04'})});
|
|
return {s: r.status, t: await r.text()};
|
|
}""")
|
|
if res["s"] == 201:
|
|
try:
|
|
tok = json.loads(res["t"]).get("token")
|
|
except Exception:
|
|
tok = None
|
|
if tok and "\\u2026" not in tok and "..." not in tok:
|
|
keys.append(tok)
|
|
page.wait_for_timeout(600)
|
|
else:
|
|
last_err = "masked"
|
|
break
|
|
else:
|
|
last_err = "s=%s %s" % (res["s"], res["t"][:70])
|
|
break
|
|
out["keys"] = keys
|
|
if keys:
|
|
out["key"], out["ok"], out["stage"] = keys[0], True, "key"
|
|
out["stage"] = "keyx%d" % len(keys)
|
|
elif last_err:
|
|
out["stage"] = "key_fail:%s" % last_err
|
|
try:
|
|
with open(BASE + "/key_fail_body.txt", "a", encoding="utf8") as fh:
|
|
fh.write("%s [%s] %s" % (rec["email"], res["s"], res["t"][:1500]) + NL2)
|
|
except Exception:
|
|
pass
|
|
except Exception as e:
|
|
out["stage"] = "err:" + str(e)[:100]
|
|
finally:
|
|
kill_chrome(prof)
|
|
with open(BANK if out["ok"] else FAIL, "a", encoding="utf8") as fh:
|
|
for _k in (out.get("keys") or [None]):
|
|
rec_out = dict(out)
|
|
rec_out["key"] = _k
|
|
fh.write(json.dumps(rec_out, ensure_ascii=False) + "\n")
|
|
log("%s %s key=%s px=%s" % (out["email"], out["stage"], bool(out["key"]), (px or "direct")[:26]))
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|