Files
withruntime-autoreg/wr_gfarm.py
T

229 lines
9.4 KiB
Python

# -*- coding: utf-8 -*-
"""wr_gfarm.py <start> <count> — авторег Runtime через Google OAuth (пул reforrm.me).
Пароли должны быть свежими (pwreset.py). Пишет wr_accounts.jsonl.
"""
import json, re, sys, time, urllib.request
import os
PROF = os.environ.get("WR_PROF") or r"C:\Users\User\tmp\wrprof2"
PROXY = os.environ.get("WR_PROXY") or ""
GPW = r"C:\Users\User\tmp\hilink\gpw.jsonl"
OUT = r"C:\Users\User\tmp\wr_accounts.jsonl"
BASE = "https://withruntime.com"
def log(*a):
print(*a, flush=True)
def usage(key):
try:
req = urllib.request.Request("https://api.withruntime.com/v1/usage")
req.add_header("Authorization", "Bearer " + key)
d = json.loads(urllib.request.urlopen(req, timeout=40).read())
return {a["pool"]: {"q": a["quantity"], "left": a["left"]} for a in (d.get("allowances") or [])}
except Exception as e:
return {"err": str(e)[:100]}
def _next(pg):
b = pg.get_by_role("button", name=re.compile("Next|Далее"))
if b.count():
try:
b.first.click(no_wait_after=True, timeout=8000)
return True
except Exception:
try:
b.first.evaluate("e=>e.click()")
return True
except Exception:
pass
pg.keyboard.press("Enter")
return False
def google_login(pg, email, pw):
pg.goto("https://accounts.google.com/signin/v2/identifier?hl=en&flowName=GlifWebSignIn", wait_until="domcontentloaded")
time.sleep(3)
body = pg.inner_text("body")
if "Choose an account" in body or "Выберите аккаунт" in body:
try:
pg.get_by_text(email, exact=False).first.click()
time.sleep(4)
except Exception:
pass
if pg.locator("input#identifierId:visible, input[type=email]:visible").count():
el = pg.locator("input#identifierId:visible, input[type=email]:visible").first
el.click(); el.type(email, delay=30); time.sleep(0.4)
_next(pg)
time.sleep(5)
for i in range(10):
if pg.locator("input[name=Passwd]:visible, input[type=password]:visible").count():
break
txt = pg.inner_text("body")
if any(k in txt for k in ("Couldn't find", "Не удалось найти", "rejected")):
log(" g: account problem:", re.sub(r"\s+", " ", txt)[:160])
return False
time.sleep(2)
if not pg.locator("input[name=Passwd]:visible, input[type=password]:visible").count():
log(" g: no pw field:", re.sub(r"\s+", " ", pg.inner_text("body"))[:160])
return False
pel = pg.locator("input[name=Passwd]:visible, input[type=password]:visible").first
pel.click(); pel.type(pw, delay=45); time.sleep(0.4)
_next(pg)
time.sleep(7)
txt = pg.inner_text("body")
if any(k in txt for k in ("2-Step", "verify it", "Verify it", "tap Yes", "Enter a code", "Подтвердите", "Неверный пароль", "Wrong password")):
log(" g: challenge/wrong pw:", re.sub(r"\s+", " ", txt)[:180])
return False
for lbl in ("I understand", "Понятно", "Accept", "Принять", "Continue", "Продолжить"):
try:
b = pg.get_by_role("button", name=lbl)
if b.count() and b.first.is_visible():
b.first.click(); time.sleep(3); log(" g: clicked", lbl)
break
except Exception:
pass
return True
def oauth_runtime(pg, email):
pg.goto(BASE + "/sign-in", wait_until="domcontentloaded")
time.sleep(3)
try:
pg.get_by_role("button", name="Continue with Google").click(no_wait_after=True, timeout=10000)
except Exception:
try:
pg.get_by_role("button", name="Continue with Google").evaluate("e=>e.click()")
except Exception as e:
log(" oauth btn err", str(e)[:80])
return False
time.sleep(5)
for step in range(10):
url = pg.url
try:
body = pg.inner_text("body")
except Exception:
body = ""
if url.startswith(BASE) and "sign-in" not in url:
return True
if "Choose an account" in body or "Выберите аккаунт" in body:
try:
pg.get_by_text(email, exact=False).first.click(); log(" chooser")
except Exception:
pass
elif pg.get_by_role("button", name=re.compile("Continue|Продолжить|Allow|Разрешить")).count():
try:
pg.get_by_role("button", name=re.compile("Continue|Продолжить|Allow|Разрешить")).first.click(); log(" consent")
except Exception:
pass
elif pg.locator("input[name=Passwd]:visible, input[type=password]:visible").count():
try:
pel = pg.locator("input[name=Passwd]:visible, input[type=password]:visible").first
pel.click(); pel.type(sys._wr_pw, delay=45); time.sleep(0.4); _next(pg)
log(" pw refilled")
except Exception:
pass
time.sleep(5)
log(" oauth stuck at", pg.url[:80])
return False
def main():
arg1 = sys.argv[1] if len(sys.argv) > 1 else "0"
start = int(arg1) if arg1.isdigit() else 0
count = int(sys.argv[2]) if len(sys.argv) > 2 else 1
rows = [json.loads(l) for l in open(GPW, encoding="utf-8") if l.strip()]
rows = [r for r in rows if (r.get("email") or "").lower().endswith("@reforrm.me")]
done = set()
try:
for l in open(OUT, encoding="utf-8"):
d = json.loads(l)
if d.get("alias", "").startswith("google:"):
done.add(d["alias"].split(":", 1)[1])
except Exception:
pass
FAILF = r"C:\Users\User\tmp\wr_gfail.json"
fails = []
try:
fails = json.load(open(FAILF, encoding="utf-8"))
except Exception:
fails = []
bad = {f[0] for f in fails}
def mark_fail(email, reason):
fails.append([email, reason, int(time.time())])
json.dump(fails, open(FAILF, "w", encoding="utf-8"), ensure_ascii=False)
if len(sys.argv) > 1 and sys.argv[1] == "left":
cnt = int(sys.argv[2]) if len(sys.argv) > 2 else 6
rows = [r for r in rows if (r.get("email") or "") not in done and (r.get("email") or "") not in bad]
start, count = 0, cnt
log("left mode: %d candidates, take %d" % (len(rows), count))
from playwright.sync_api import sync_playwright
with sync_playwright() as p:
args = ["--no-first-run", "--no-default-browser-check", "--disable-blink-features=AutomationControlled"]
if PROXY:
args.append("--proxy-server=" + PROXY)
args.append("--proxy-bypass-list=<-loopback>")
ctx = p.chromium.launch_persistent_context(
PROF, channel="chrome", headless=False, args=args,
viewport={"width": 1280, "height": 900})
pg = ctx.pages[0] if ctx.pages else ctx.new_page()
pg.set_default_timeout(30000)
for r in rows[start:start + count]:
email, pw = r["email"], r.get("password") or r.get("pw")
if not pw:
log("skip (no pw)", email)
continue
if email in done:
log("skip (done)", email)
continue
if email in bad:
log("skip (gfail)", email)
continue
log("==", email)
sys._wr_pw = pw
try:
ctx.clear_cookies()
if not google_login(pg, email, pw):
log(" RESULT google_fail")
mark_fail(email, "google_login")
continue
if not oauth_runtime(pg, email):
log(" RESULT oauth_fail")
continue
log(" landed", pg.url[:70])
js = """async (label) => {
const r = await fetch('/api/account/keys', {method:'POST', headers:{'Content-Type':'application/json'},
credentials:'include', body: JSON.stringify({action:'create', label:label, access:'full'})});
return {s: r.status, t: await r.text()};
}"""
res = pg.evaluate(js, "farm")
key = None
try:
d = json.loads(res["t"])
cred = d.get("credential") or {}
key = cred.get("plaintext") or cred.get("key") or d.get("key")
except Exception:
pass
if not key:
log(" RESULT key_fail", str(res)[:200])
continue
us = usage(key)
log(" USAGE", json.dumps(us)[:180])
with open(OUT, "a", encoding="utf-8") as f:
f.write(json.dumps({"alias": "google:" + email, "key": key, "ts": int(time.time()), "usage": us}) + "\n")
log(" SAVED", key[:22] + "...")
except Exception as e:
log(" EXC", str(e)[:180])
time.sleep(6)
try:
ctx.close()
except Exception:
pass
if __name__ == "__main__":
main()