#!/usr/bin/env python3 """farm.py [workers] [limit] Пул строк "email:imap_password". Для каждого аккаунта запускается ur_reg.py на отдельном egress. Логика пауз — главное, что экономит капчу: credit -> адрес получает +1, после 2 кредитов пауза 6 ч rate_limited -> штраф адресу 900..3600 с (растёт экспоненциально), аккаунт в очередь no_credit -> 3 пустых аккаунта на адрес без единого кредита = пауза 1 ч no_mail -> аккаунт возвращается в очередь через 40 мин любая попытка -> адрес отдыхает 150 с (иначе следующий запрос сразу ловит 429) Адреса берутся из proxies.txt (по одному в строке, допускается 'direct'). Результаты дописываются в bank.jsonl, обработанные — в done.txt. """ import json import os import subprocess import sys import threading import time from collections import deque HERE = os.path.dirname(os.path.abspath(__file__)) PY = sys.executable POOL = sys.argv[1] WORKERS = int(sys.argv[2]) if len(sys.argv) > 2 else 2 LIMIT = int(sys.argv[3]) if len(sys.argv) > 3 else 100 PROXY_FILE = os.environ.get("UR_PROXIES", os.path.join(HERE, "proxies.txt")) PROXIES = [l.strip() for l in open(PROXY_FILE, encoding="utf-8") if l.strip()] \ if os.path.exists(PROXY_FILE) else ["direct"] CAP_CREDIT = int(os.environ.get("UR_CAP_CREDIT", "2")) CONF = {"credit_cap": 21600, "rate_limited": 600, "err:ConnectionError": 1800, "captcha_fail": 120, "no_mail": 2400} rows = [l.strip() for l in open(POOL, encoding="utf-8", errors="replace") if "@" in l and ":" in l] DONE_P = os.path.join(HERE, "done.txt") BANK_P = os.path.join(HERE, "bank.jsonl") DEAD_P = os.path.join(HERE, "domains_dead.txt") def read_set(p): if not os.path.exists(p): return set() return set(l.strip() for l in open(p, encoding="utf-8", errors="replace")) done = read_set(DONE_P) dead = read_set(DEAD_P) queue = deque(r for r in rows if r not in done and r.split("@")[-1].split(":")[0].lower() not in dead) print("queue", len(queue), flush=True) if LIMIT: queue = deque(list(queue)[:LIMIT]) print("limited to", len(queue), flush=True) lock = threading.Lock() cool = {p: 0.0 for p in PROXIES} cr, pen, zc = {}, {}, {} busy = set() # предзагрузка счётчика кредитов по адресам, чтобы не превышать кап после рестарта if os.path.exists(BANK_P): for line in open(BANK_P, encoding="utf-8", errors="replace"): if line.startswith("{"): try: d = json.loads(line) except Exception: continue if d.get("result") == "credit": k = (d.get("proxy") or "?").split("@")[-1] cr[k] = cr.get(k, 0) + 1 def pick_proxy(): """Эксклюзивно бронирует адрес; при всех в паузе — ждёт, а не рекурсирует.""" while True: now = time.time() best = None with lock: for p in PROXIES: if cool[p] <= now and p not in busy: busy.add(p) return p if best is None or cool[p] < cool[best]: best = p wait = max(0.0, cool[best] - now) if best else 5.0 time.sleep(min(max(wait, 1.0), 30.0)) def worker(wid): while True: with lock: if not queue: return cred = queue.popleft() px = pick_proxy() try: r = subprocess.run([PY, os.path.join(HERE, "ur_reg.py"), cred, px], cwd=HERE, env=dict(os.environ, PYTHONIOENCODING="utf-8"), capture_output=True, text=True, timeout=1500) out = "" for l in (r.stdout or "").splitlines(): if l.startswith("{"): out = l d = json.loads(out) if out else {"result": "crash"} except Exception as e: d = {"result": "err:" + type(e).__name__} d["email"] = d.get("email") or cred.split(":")[0] d["proxy"] = px res = d.get("result", "") with lock: busy.discard(px) with open(BANK_P, "a", encoding="utf-8") as f: f.write(json.dumps(d, ensure_ascii=False) + "\n") if res in ("credit", "no_credit", "domain_blocked", "verify_error", "magiclink_fail"): with open(DONE_P, "a", encoding="utf-8") as f: f.write(cred + "\n") if res == "domain_blocked": with open(DEAD_P, "a", encoding="utf-8") as f: f.write(d.get("domain", "") + "\n") if res == "credit": k = px.split("@")[-1] cr[k] = cr.get(k, 0) + 1 if cr[k] >= CAP_CREDIT: cool[px] = time.time() + CONF["credit_cap"] print(" [cap] %s -> %d кредитов, пауза 6ч" % (k, cr[k]), flush=True) if res in ("credit", "no_credit", "no_mail", "verify_error"): cool[px] = time.time() + 150 if res in ("no_credit", "no_mail"): k = px.split("@")[-1] zc[k] = zc.get(k, 0) + 1 if zc[k] >= 3 and cr.get(k, 0) == 0: cool[px] = time.time() + 3600 print(" [zero] %s -> 3 пустых, пауза 1ч" % k, flush=True) if res == "rate_limited": k = px.split("@")[-1] pen[k] = min(max(pen.get(k, 600) * 2, 900), 3600) cool[px] = time.time() + pen[k] print(" [429] %s -> пауза %d с" % (k, pen[k]), flush=True) queue.append(cred) elif res in CONF: cool[px] = time.time() + CONF[res] queue.append(cred) print("%d %s %s %s" % (wid, d["email"], res, d.get("balance")), flush=True) threads = [threading.Thread(target=worker, args=(i,), daemon=True) for i in range(WORKERS)] for t in threads: t.start() for t in threads: t.join() print("farm done", flush=True)