Files

148 lines
5.5 KiB
Python

#!/usr/bin/env python3
"""acemusic.ai — волна регистрации: N аккаунтов за один проход IMAP.
Почему волной: один IMAP-ящик читается пачкой, письма матчатся по заголовку To,
а не по порядку — так 40 аккаунтов регистрируются за ~4 минуты вместо часа.
Переменные окружения те же, что у reg.py, плюс:
ACE_IMAP_FROM отправитель писем (default acestudio)
python wave.py 5 40 # зарегистрировать ace5..ace44
"""
import email as emaillib
import imaplib
import json
import os
import re
import sys
import time
import requests
from reg import BANK, BASE, H, IMAP_HOST, IMAP_PASS, IMAP_USER, TAG, gen_password
IMAP_FROM = os.environ.get("ACE_IMAP_FROM", "acestudio")
FAIL = os.environ.get("ACE_FAIL", "fail.jsonl")
def imap_conn():
m = imaplib.IMAP4_SSL(IMAP_HOST, 993)
m.login(IMAP_USER, IMAP_PASS)
m.select("INBOX", readonly=True)
return m
def baseline():
m = imap_conn()
typ, d = m.uid("SEARCH", None, '(FROM "%s")' % IMAP_FROM)
uids = [int(x) for x in d[0].split()] if d[0] else []
m.logout()
return max(uids) if uids else 0
def new_mails(min_uid):
"""[(to_addr, code, uid)] по письмам новее min_uid"""
out = []
m = imap_conn()
typ, d = m.uid("SEARCH", None, '(FROM "%s" UID %d:*)' % (IMAP_FROM, min_uid + 1))
uids = [int(x) for x in d[0].split()] if d[0] else []
for uid in uids:
typ, dd = m.uid("FETCH", str(uid), "(RFC822)")
try:
msg = emaillib.message_from_bytes(dd[0][1])
except Exception:
continue
to = (msg.get("To") or "").strip()
mt = re.search(r"[\w.+\-]+@[\w.\-]+", to)
to_addr = mt.group(0).lower() if mt else ""
body = ""
for part in msg.walk():
if part.get_content_type() == "text/html":
body = part.get_payload(decode=True).decode("utf-8", "replace")
break
m1 = re.search(r"letter-spacing:\s*8px[^>]*>\s*(\d{6})\s*<", body)
m2 = re.search(r"font-size:\s*32px[^>]*>\s*(\d{6})", body)
if m1 or m2:
out.append((to_addr, (m1 or m2).group(1), uid))
m.logout()
return out
def run(start, n, tag=TAG, timeout=900):
seen = set()
if os.path.exists(BANK):
for line in open(BANK):
try:
seen.add(json.loads(line)["email"])
except Exception:
pass
base = baseline()
print("baseline_uid", base, flush=True)
pending = {}
login, _, domain = IMAP_USER.partition("@")
for i in range(start, start + n):
email = "%s+%s%d@%s" % (login, tag, i, domain)
if email in seen:
continue
pw = gen_password()
s = requests.Session()
try:
r = s.post(BASE + "/auth/signup", headers=H, json={"email": email, "password": pw}, timeout=30)
except Exception as e:
print("signup err", email, e, flush=True)
continue
if r.status_code != 200:
print("signup fail", email, r.status_code, r.text[:120], flush=True)
with open(FAIL, "a") as f:
f.write(json.dumps({"email": email, "stage": "signup", "code": r.status_code}) + "\n")
continue
pending[email] = {"pw": pw, "s": s}
print("signup ok", email, flush=True)
time.sleep(1.2)
print("pending", len(pending), flush=True)
t0 = time.time()
last = base
while pending and time.time() - t0 < timeout:
time.sleep(6)
try:
mails = new_mails(last)
except Exception as e:
print("imap err", e, flush=True)
time.sleep(10)
continue
for to_addr, code, uid in mails:
last = max(last, uid)
hit = [e for e in pending if e.lower() == to_addr]
if not hit:
continue
email = hit[0]
rec = pending[email]
try:
r = rec["s"].post(BASE + "/auth/verify", headers=H,
json={"email": email, "code": code, "next": "/create/",
"plan": None, "cycle": None}, timeout=30)
except Exception as e:
print("verify err", email, e, flush=True)
continue
if r.status_code != 200:
print("verify fail", email, r.status_code, r.text[:150], flush=True)
with open(FAIL, "a") as f:
f.write(json.dumps({"email": email, "stage": "verify", "code": r.status_code}) + "\n")
pending.pop(email, None)
continue
st = rec["s"].get(BASE + "/api/status", headers=H, timeout=30).json()
u = st["user"]
ck = rec["s"].cookies.get_dict()
out = {"email": email, "password": rec["pw"], "uid": u["id"], "credits": u["credits"],
"plan": u["plan"], "cookies": {k: ck.get(k) for k in ("ace_at", "ace_rt", "ace_flow")},
"ts": int(time.time())}
with open(BANK, "a") as f:
f.write(json.dumps(out) + "\n")
pending.pop(email, None)
print("ACCOUNT OK", email, "uid", u["id"], "credits", u["credits"], flush=True)
print("done, left", len(pending), flush=True)
if __name__ == "__main__":
run(int(sys.argv[1]), int(sys.argv[2]), sys.argv[3] if len(sys.argv) > 3 else TAG)