From 17d01b1050a09f573694a802ab473b259222b397 Mon Sep 17 00:00:00 2001 From: reform Date: Sat, 14 Nov 2026 22:43:41 +0200 Subject: [PATCH] acemusic.ai: HTTP autoreg, credit pool shim, farm cron --- .gitignore | 7 + README.md | 137 +++++++++++++++++ ace_shim.py | 389 +++++++++++++++++++++++++++++++++++++++++++++++ cron_farm.py | 55 +++++++ reg.py | 130 ++++++++++++++++ requirements.txt | 1 + wave.py | 148 ++++++++++++++++++ 7 files changed, 867 insertions(+) create mode 100644 .gitignore create mode 100644 README.md create mode 100644 ace_shim.py create mode 100644 cron_farm.py create mode 100644 reg.py create mode 100644 requirements.txt create mode 100644 wave.py diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..dae9a5b --- /dev/null +++ b/.gitignore @@ -0,0 +1,7 @@ +bank.jsonl +fail.jsonl +state.json +cookies*.json +*.session +__pycache__/ +*.pyc diff --git a/README.md b/README.md new file mode 100644 index 0000000..38cfa0e --- /dev/null +++ b/README.md @@ -0,0 +1,137 @@ +# acemusic-autoreg + +Автоматизация [acemusic.ai](https://acemusic.ai): регистрация аккаунтов по чистому HTTP, +пул с ротацией кредитов и OpenAI-подобный эндпоинт генерации музыки для ботов и сервисов. + +Браузер не нужен, капчи на регистрации нет вообще. + +## Что даёт + +- free-план: **20 кредитов** на аккаунт, один трек = **4 кредита** → **5 треков с аккаунта** +- кредиты месячные (`cycle: monthly`), то есть аккаунт переиспользуется каждый месяц +- трек 90–330 секунд, генерация 50–70 с (редко до 5 минут) +- mp3 отдаётся **анонимно** по прямой ссылке — Telegram и любой клиент забирают без cookies + +## Как устроена регистрация + +``` +POST /auth/signup {"email": "...", "password": "..."} -> 200, письмо с кодом +POST /auth/verify {"email": "...", "code": "123456", + "next": "/create/", "plan": null, "cycle": null} + -> cookies ace_at / ace_rt +GET /api/status -> {user:{id,credits,plan}} +``` + +Что важно знать, иначе не работает: + +- письмо приходит **не от acemusic.ai**, а от `acestudio.ai`, тема `Your ACE Music verification code`, + код 6 цифр живёт **3 минуты**; +- baseline UID в ящике надо брать **до** запроса signup — письмо приходит за секунды, + иначе свежий код отфильтруется как старый; +- матчить письмо по заголовку `To:`, а не по порядку прихода; +- вход только по cookies: `Authorization: Bearer ace_at` сервер отвергает (401 `Please log in`); +- перелогин `POST /auth/login {email,password,...}` возвращает свежие cookies — этим лечатся + протухшие токены и оживают исчерпанные аккаунты после месячного сброса. + +## Генерация + +``` +POST /api/idea {"prompt": "...", "created_at": , "references": [], "model": "acemusic-v1", + "analytics": {"attempt_id": "", "requested_model": "acemusic-v1"}, "media": []} + -> 202 {"song": {"task_id": "so_...", "status": "planning"}} + +GET /api/songs -> items[] : status planning|queued|running|succeeded|failed, + local_audio "/data/so_.mp3", + local_cover "/data/so_-cover.jpg", + result.duration_sec, meta.title + +GET /data/so_.mp3 -> 200 audio/mpeg (3–7 MB, без авторизации) +``` + +`slug` в ответе на `/api/idea` отсутствует — искать задачу надо по `task_id`. +Поллинг 6–8 секунд. + +## Файлы + +| файл | что делает | +|---|---| +| `reg.py` | регистрация одного аккаунта (или нескольких подряд) | +| `wave.py` | волна: N signup разом + один IMAP-читатель, матчинг по `To:` | +| `ace_shim.py` | HTTP-шим пула: `POST /v1/music/generations`, `GET /healthz`, ревайв аккаунтов | +| `cron_farm.py` | докорм банка до целевого размера и синк на сервер | + +## Запуск + +```bash +export ACE_IMAP_USER='you+ace1@gmail.com' # ящик для кодов (плюс-алиасы работают) +export ACE_IMAP_PASS='app-password' +pip install requests + +python wave.py 1 20 # 20 аккаунтов, банк в bank.jsonl +python ace_shim.py # ACE_PORT=48963, ACE_BANK=bank.jsonl +curl -s localhost:48963/healthz +curl -s -X POST localhost:48963/v1/music/generations \ + -H 'Content-Type: application/json' \ + -d '{"prompt":"dark phonk, heavy 808"}' +``` + +Ответ шима: + +```json +{"ok": true, "model": "ace-music", + "tracks": [{"audioUrl": "https://acemusic.ai/data/so_....mp3", + "title": "Blackout Drift", "duration": 125.03, "coverUrl": "https://.../cover.jpg"}], + "task_id": "so_....", "credits_left": 12, "account": "you+ace3@gmail.com"} +``` + +Шим сам выбирает аккаунт с запасом кредитов, помечает исчерпанные, раз в час перелогинивает +их (месячный сброс) и возвращает `502` с причиной, если пул пуст. + +## systemd + +```ini +[Unit] +Description=ACE Music shim +After=network-online.target + +[Service] +WorkingDirectory=/opt/ace-shim +Environment=ACE_PORT=48963 +Environment=ACE_BANK=/opt/ace-shim/bank.jsonl +Environment=ACE_STATE=/opt/ace-shim/state.json +ExecStart=/usr/bin/python3 /opt/ace-shim/ace_shim.py +Restart=always +RestartSec=3 + +[Install] +WantedBy=multi-user.target +``` + +## Встраивание в бота (aiogram 3) + +```python +req = urllib.request.Request("http://127.0.0.1:48963/v1/music/generations", + data=json.dumps({"prompt": prompt, "timeout": 420}).encode(), + headers={"Content-Type": "application/json"}) +data = json.load(await asyncio.to_thread(urllib.request.urlopen, req, timeout=470)) +track = data["tracks"][0] +await message.bot.send_audio(chat_id, track["audioUrl"], title=track["title"], + performer="ace", thumbnail=URLInputFile(track["coverUrl"])) +``` + +Две грабли, на которых легко потерять час: + +- `send_audio(thumb=url)` → `unexpected keyword argument 'thumb'`; + `thumbnail="https://..."` → pydantic `Input should be an instance of InputFile`. + Нужно `thumbnail=URLInputFile(url)` и фолбэк на вызов без обложки. +- если добавляете модель в существующий `if/else`-каскад, следите, чтобы новая ветка была + `elif`, а не отдельным `if` — иначе хвостовой `else` перезапишет результат. + +## Ограничения + +Free-план закрывает 5 треков на аккаунт, дальше нужен новый аккаунт или платный план. +Аккаунты регистрируются на плюс-алиасы одного ящика; при массовых волнах держите паузы +между signup (~1 с) и не запускайте два IMAP-читателя на один ящик одновременно. + +Код выложен для личного использования и изучения внутреннего API сервиса. +Проверяйте условия использования сервиса перед массовой автоматизацией. \ No newline at end of file diff --git a/ace_shim.py b/ace_shim.py new file mode 100644 index 0000000..6fde382 --- /dev/null +++ b/ace_shim.py @@ -0,0 +1,389 @@ +#!/usr/bin/env python3 +# ace-shim: пул аккаунтов acemusic.ai -> POST /v1/music/generations (stdlib, без зависимостей) +# банк: /opt/ace-shim/bank.jsonl строки {email,password,uid,credits,cookies:{ace_at,ace_rt,ace_flow}} +import json, os, sys, time, threading, uuid, urllib.request, urllib.error, urllib.parse, traceback +from http.server import ThreadingHTTPServer, BaseHTTPRequestHandler + +BASE = "https://acemusic.ai" +BANK = os.environ.get("ACE_BANK", "/opt/ace-shim/bank.jsonl") +STATE = os.environ.get("ACE_STATE", "/opt/ace-shim/state.json") +PORT = int(os.environ.get("ACE_PORT", "48960")) +UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/145.0.0.0 Safari/537.36" +SONG_COST = 4 +LOCK = threading.RLock() +BUSY = set() +STATE_LOCK = threading.Lock() +STATS = {"gen_ok": 0, "gen_fail": 0} + +def load_state(): + try: + with open(STATE) as f: + return json.load(f) + except Exception: + return {} + +STATE_D = load_state() + +def save_state(): + with STATE_LOCK: + tmp = STATE + ".tmp" + with open(tmp, "w") as f: + json.dump(STATE_D, f) + os.replace(tmp, STATE) + +def st(uid): + return STATE_D.setdefault(str(uid), {"credits": None, "ts": 0, "dead": False, "name": ""}) + +def load_bank(): + accs = [] + try: + with open(BANK) as f: + for line in f: + line = line.strip() + if not line: + continue + try: + r = json.loads(line) + except Exception: + continue + if r.get("email") and r.get("password"): + accs.append(r) + except Exception: + pass + return accs + +def save_bank(accs): + tmp = BANK + ".tmp" + with open(tmp, "w") as f: + for r in accs: + f.write(json.dumps(r) + "\n") + os.replace(tmp, BANK) + +class Acc: + def __init__(self, rec): + self.rec = rec + self.uid = str(rec.get("uid") or "") + self.email = rec.get("email") + self.pw = rec.get("password") + ck = rec.get("cookies") or {} + self.cookies = {k: v for k, v in ck.items() if v} + + def _headers(self, extra=None): + h = { + "User-Agent": UA, + "Origin": BASE, + "Referer": BASE + "/create/", + "Accept": "application/json, text/plain, */*", + "Cookie": "; ".join("%s=%s" % (k, v) for k, v in self.cookies.items()), + } + if extra: + h.update(extra) + return h + + def _raw(self, path, data=None, method=None, timeout=45): + body = None + h = self._headers() + if data is not None: + body = json.dumps(data).encode() + h["Content-Type"] = "application/json" + req = urllib.request.Request(BASE + path, data=body, headers=h, method=method or ("POST" if body else "GET")) + try: + with urllib.request.urlopen(req, timeout=timeout) as r: + return r.status, r.read().decode("utf-8", "replace"), r.headers + except urllib.error.HTTPError as e: + return e.code, e.read().decode("utf-8", "replace"), e.headers + except Exception as e: + return 0, "ERR %s" % e, {} + + def login(self): + """перелогин по email/паролю -> свежие cookies""" + body = {"email": self.email, "password": self.pw, "next": "/create/", "plan": None, "cycle": None} + req = urllib.request.Request(BASE + "/auth/login", data=json.dumps(body).encode(), + headers={"User-Agent": UA, "Content-Type": "application/json", + "Origin": BASE, "Referer": BASE + "/login/"}, method="POST") + try: + with urllib.request.urlopen(req, timeout=45) as r: + raw = r.read().decode("utf-8", "replace") + hdrs = r.headers.get_all("Set-Cookie") or [] + except urllib.error.HTTPError as e: + return False, "%s %s" % (e.code, e.read().decode("utf-8", "replace")[:120]) + except Exception as e: + return False, "login err %s" % e + got = {} + for h in hdrs: + m = h.split(";")[0] + if "=" in m: + k, v = m.split("=", 1) + if k in ("ace_at", "ace_rt", "ace_flow"): + got[k] = v + if not got.get("ace_at"): + return False, "no ace_at in login %s" % raw[:120] + self.cookies.update(got) + self.rec["cookies"] = {k: self.cookies.get(k) for k in ("ace_at", "ace_rt", "ace_flow")} + s = st(self.uid) + s["dead"] = False + save_state() + return True, "login ok" + + def status(self, timeout=30): + code, txt, _ = self._raw("/api/status", timeout=timeout) + if code == 200: + try: + return json.loads(txt) + except Exception: + return None + return None + + def idea(self, prompt, instrumental=False): + body = { + "prompt": prompt[:2000], + "created_at": int(time.time() * 1000), + "references": [], + "model": "acemusic-v1", + "analytics": {"attempt_id": str(uuid.uuid4()), "requested_model": "acemusic-v1"}, + "media": [], + } + if instrumental: + body["instrumental"] = True + return self._raw("/api/idea", data=body, timeout=60) + + def songs(self): + code, txt, _ = self._raw("/api/songs", timeout=45) + if code != 200: + return None + try: + return json.loads(txt).get("items", []) + except Exception: + return None + +def pick_acc(need=SONG_COST): + """выбирает аккаунт с запасом кредитов; под локом помечает busy""" + with LOCK: + accs = load_bank() + if not accs: + return None + # сначала те, у кого известны кредиты + cands = [] + for rec in accs: + uid = str(rec.get("uid")) + s = st(uid) + if s.get("dead") or uid in BUSY: + continue + cr = s.get("credits") + if cr is None: + cr = rec.get("credits") + if cr is not None and cr < need: + continue + cands.append((0 if cr is None else 1, -(cr or 0), rec)) + cands.sort(key=lambda x: (x[0], x[1])) + for _, _, rec in cands[:6]: + a = Acc(rec) + uid = a.uid + s = st(uid) + if s.get("credits") is None or time.time() - (s.get("ts") or 0) > 900: + snap = a.status() + if snap: + s["credits"] = snap["user"]["credits"] + s["ts"] = time.time() + s["name"] = snap["user"].get("name") or "" + save_state() + if (s.get("credits") or 0) < need: + continue + BUSY.add(uid) + return a + return None + +def release(a): + with LOCK: + BUSY.discard(a.uid) + +def generate(prompt, instrumental=False, timeout=420): + a = pick_acc() + if not a: + return {"ok": False, "error": "pool_empty", "detail": "нет аккаунтов с кредитами"} + try: + code, txt, _ = a.idea(prompt, instrumental) + if code == 401: + ok, det = a.login() + if not ok: + s = st(a.uid); s["dead"] = True; save_state() + return {"ok": False, "error": "auth", "detail": det} + code, txt, _ = a.idea(prompt, instrumental) + if code != 202: + if code in (401, 403): + s = st(a.uid); s["dead"] = True; save_state() + return {"ok": False, "error": "submit_%s" % code, "detail": txt[:200]} + try: + task_id = json.loads(txt)["song"]["task_id"] + except Exception: + return {"ok": False, "error": "parse", "detail": txt[:200]} + # списываем локально сразу + s = st(a.uid) + if s.get("credits") is not None: + s["credits"] = max(0, s["credits"] - SONG_COST) + s["ts"] = time.time() + save_state() + t0 = time.time() + while time.time() - t0 < timeout: + time.sleep(7) + items = a.songs() + if items is None: + continue + hit = [x for x in items if x.get("task_id") == task_id] + if not hit: + continue + it = hit[0] + status = it.get("status") + if status in ("succeeded", "done", "ready", "completed"): + rel = it.get("local_audio") + if not rel: + return {"ok": False, "error": "no_audio", "detail": json.dumps(it)[:300]} + dur = (it.get("result") or {}).get("duration_sec") + title = (it.get("meta") or {}).get("title") or prompt[:60] + STATS["gen_ok"] += 1 + out = { + "ok": True, + "model": "ace-music", + "tracks": [{"audioUrl": BASE + rel, "title": title, "duration": dur, + "coverUrl": (BASE + it["local_cover"]) if it.get("local_cover") else None}], + "task_id": task_id, + "duration": dur, + "credits_left": s.get("credits"), + "account": a.email, + } + try: + # освежаем реальный остаток + snap = a.status() + if snap: + s["credits"] = snap["user"]["credits"] + save_state() + out["credits_left"] = s["credits"] + except Exception: + pass + return out + if status in ("failed", "error", "canceled"): + STATS["gen_fail"] += 1 + return {"ok": False, "error": "gen_failed", "detail": json.dumps(it)[:300]} + return {"ok": False, "error": "timeout", "detail": "task %s > %ss" % (task_id, timeout)} + finally: + release(a) + +def reviver_loop(): + """раз в час: перелогин исчерпанных/помеченных dead аккаунтов (месячный сброс кредитов, протухшие cookies)""" + while True: + time.sleep(3600) + try: + accs = load_bank() + n = 0 + changed = False + for rec in accs: + uid = str(rec.get("uid")) + s = st(uid) + low = (s.get("credits") is None) or (s.get("credits") or 0) < SONG_COST + if not (s.get("dead") or low): + continue + if time.time() - (s.get("ts") or 0) < 3 * 3600: + continue + a = Acc(rec) + ok, det = a.login() + if not ok: + continue + snap = a.status() + if snap: + s["credits"] = snap["user"]["credits"] + s["ts"] = time.time() + s["dead"] = False + s["name"] = snap["user"].get("name") or "" + changed = True + n += 1 + if n % 20 == 0: + save_state() + save_state() + if changed: + save_bank(accs) + print("reviver: refreshed %d" % n, flush=True) + except Exception: + traceback.print_exc() + +def pool_status(): + accs = load_bank() + alive = 0 + total_cr = 0 + rows = [] + for rec in accs: + uid = str(rec.get("uid")) + s = st(uid) + cr = s.get("credits") + if cr is None: + cr = rec.get("credits") + if s.get("dead"): + rows.append({"uid": uid, "email": rec.get("email"), "credits": cr, "dead": True}) + continue + alive += 1 + total_cr += (cr or 0) + rows.append({"uid": uid, "email": rec.get("email"), "credits": cr, "dead": False}) + return {"ok": True, "accounts": len(accs), "alive": alive, "credits_total": total_cr, + "songs_capacity": total_cr // SONG_COST, "busy": len(BUSY), "stats": STATS, + "items": rows[:400]} + +class H(BaseHTTPRequestHandler): + protocol_version = "HTTP/1.1" + + def _send(self, code, payload, ctype="application/json"): + data = payload if isinstance(payload, bytes) else json.dumps(payload, ensure_ascii=False).encode() + self.send_response(code) + self.send_header("Content-Type", ctype) + self.send_header("Content-Length", str(len(data))) + self.send_header("Access-Control-Allow-Origin", "*") + self.end_headers() + try: + self.wfile.write(data) + except Exception: + pass + + def do_GET(self): + p = urllib.parse.urlparse(self.path).path + if p in ("/healthz", "/v1/music/health", "/"): + return self._send(200, pool_status()) + if p.startswith("/v1/music/files/"): + return self._proxy_file(p[len("/v1/music/files/"):]) + return self._send(404, {"error": "not_found"}) + + def _proxy_file(self, name): + name = urllib.parse.unquote(name) + if not name.endswith(".mp3") or "/" in name or ".." in name: + return self._send(400, {"error": "bad_name"}) + url = BASE + "/data/" + name + try: + req = urllib.request.Request(url, headers={"User-Agent": UA, "Referer": BASE + "/create/"}) + with urllib.request.urlopen(req, timeout=120) as r: + data = r.read() + return self._send(200, data, "audio/mpeg") + except Exception as e: + return self._send(502, {"error": "upstream", "detail": str(e)[:200]}) + + def do_POST(self): + p = urllib.parse.urlparse(self.path).path + n = int(self.headers.get("Content-Length") or 0) + raw = self.rfile.read(n) if n else b"{}" + try: + body = json.loads(raw.decode("utf-8", "replace") or "{}") + except Exception: + return self._send(400, {"error": "bad_json"}) + if p in ("/v1/music/generations", "/v1/audio/generations", "/generate"): + prompt = (body.get("prompt") or body.get("input") or "").strip() + if not prompt: + return self._send(400, {"ok": False, "error": "empty_prompt"}) + tmo = int(body.get("timeout") or 420) + tmo = max(60, min(tmo, 900)) + res = generate(prompt, bool(body.get("instrumental")), timeout=tmo) + return self._send(200 if res.get("ok") else 502, res) + return self._send(404, {"error": "not_found"}) + + def log_message(self, *a): + pass + +if __name__ == "__main__": + print("ace-shim on :%d bank=%s accounts=%d" % (PORT, BANK, len(load_bank())), flush=True) + threading.Thread(target=reviver_loop, daemon=True).start() + ThreadingHTTPServer(("0.0.0.0", PORT), H).serve_forever() \ No newline at end of file diff --git a/cron_farm.py b/cron_farm.py new file mode 100644 index 0000000..ea01a6d --- /dev/null +++ b/cron_farm.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +# [ACE 1114] докорм пула acemusic.ai: добивает банк до TARGET и синкает на прод +import json, os, re, subprocess, sys, time + +BASE = r"C:/Users/User/tmp/acemusic" +BANK = os.path.join(BASE, "bank.jsonl") +TARGET = int(os.environ.get("ACE_TARGET", "150")) +BATCH = int(os.environ.get("ACE_BATCH", "15")) +KEY = r"C:/Users/User/.ssh/id_ed25519" +PROD = "root@2.27.98.196" + +def count_and_max(): + n = 0; mx = 0; seen = set() + if os.path.exists(BANK): + for line in open(BANK, encoding="utf-8", errors="replace"): + line = line.strip() + if not line: + continue + try: + r = json.loads(line) + except Exception: + continue + n += 1 + seen.add(r.get("email")) + m = re.search(r"ace(\d+)@", r.get("email") or "") + if m: + mx = max(mx, int(m.group(1))) + return n, mx + +n, mx = count_and_max() +print("bank", n, "max_idx", mx, "target", TARGET, flush=True) +if n >= TARGET: + print("pool full, skip", flush=True) +else: + need = min(BATCH, TARGET - n) + start = mx + 1 + print("farming", need, "accounts from", start, flush=True) + r = subprocess.run([sys.executable, "wave.py", str(start), str(need), "ace"], cwd=BASE, + capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=1500) + tail = (r.stdout or "")[-1500:] + print(tail, flush=True) + print("wave rc", r.returncode, flush=True) + +# синк банка на прод +n2, _ = count_and_max() +scp = subprocess.run(["scp", "-o", "StrictHostKeyChecking=no", "-i", KEY, BANK, PROD + ":/opt/ace-shim/bank.jsonl"], + capture_output=True, text=True, timeout=180) +print("scp rc", scp.returncode, (scp.stderr or "")[:200], flush=True) +try: + import urllib.request + h = json.load(urllib.request.urlopen("http://2.27.98.196:48963/healthz", timeout=8)) + print("pool: accounts=%s alive=%s credits=%s songs=%s" % (h.get("accounts"), h.get("alive"), h.get("credits_total"), h.get("songs_capacity")), flush=True) +except Exception as e: + print("health err", str(e)[:120], flush=True) +print("bank_lines", n2, flush=True) \ No newline at end of file diff --git a/reg.py b/reg.py new file mode 100644 index 0000000..6176f53 --- /dev/null +++ b/reg.py @@ -0,0 +1,130 @@ +#!/usr/bin/env python3 +"""acemusic.ai — авторегистрация одного/нескольких аккаунтов по HTTP. + +Капчи нет, браузер не нужен: POST /auth/signup -> код на почту -> POST /auth/verify. + +Переменные окружения: + ACE_IMAP_HOST imap-сервер (default imap.gmail.com) + ACE_IMAP_USER ящик, куда приходят письма (например you+ace1@gmail.com) + ACE_IMAP_PASS пароль приложения + ACE_TAG метка для плюс-алиасов (default ace) + ACE_BANK файл банка (default bank.jsonl) + +Использование: + python reg.py 1 5 # зарегистрировать ace1..ace5 +""" +import email as emaillib +import imaplib +import json +import os +import random +import re +import string +import sys +import time + +import requests + +IMAP_HOST = os.environ.get("ACE_IMAP_HOST", "imap.gmail.com") +IMAP_USER = os.environ.get("ACE_IMAP_USER", "") +IMAP_PASS = os.environ.get("ACE_IMAP_PASS", "") +TAG = os.environ.get("ACE_TAG", "ace") +BANK = os.environ.get("ACE_BANK", "bank.jsonl") +BASE = "https://acemusic.ai" +UA = ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 " + "(KHTML, like Gecko) Chrome/145.0.0.0 Safari/537.36") +H = {"User-Agent": UA, "Origin": BASE, "Referer": BASE + "/signup/", + "Content-Type": "application/json"} + + +def imap_conn(): + if not (IMAP_USER and IMAP_PASS): + raise SystemExit("нужны ACE_IMAP_USER и ACE_IMAP_PASS") + m = imaplib.IMAP4_SSL(IMAP_HOST, 993) + m.login(IMAP_USER, IMAP_PASS) + m.select("INBOX", readonly=True) + return m + + +def baseline_uid(): + """ВАЖНО: вызывать ДО signup — письмо приходит за секунды и иначе отфильтруется.""" + m = imap_conn() + typ, d = m.uid("SEARCH", None, '(FROM "acestudio")') + uids = [int(x) for x in d[0].split()] if d[0] else [] + m.logout() + return max(uids) if uids else 0 + + +def fetch_code(min_uid, timeout=180): + t0 = time.time() + while time.time() - t0 < timeout: + try: + m = imap_conn() + typ, d = m.uid("SEARCH", None, f'(FROM "acestudio" UID {min_uid + 1}:*)') + uids = [int(x) for x in d[0].split()] if d[0] else [] + if uids: + uid = max(uids) + typ, dd = m.uid("FETCH", str(uid), "(RFC822)") + m.logout() + msg = emaillib.message_from_bytes(dd[0][1]) + 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) + code = (m1 or m2) + if code: + return uid, code.group(1) + else: + m.logout() + except Exception as e: # сеть/IMAP флапают — просто пробуем снова + print("imap:", e, flush=True) + time.sleep(4) + return None, None + + +def gen_password(): + body = "".join(random.choice(string.ascii_letters + string.digits) for _ in range(9)) + return body + "!" + "".join(random.choice(string.digits) for _ in range(3)) + + +def register(idx, tag=TAG): + login, _, domain = IMAP_USER.partition("@") + email = "%s+%s%d@%s" % (login, tag, idx, domain) + pw = gen_password() + s = requests.Session() + base = baseline_uid() + r = s.post(BASE + "/auth/signup", headers=H, json={"email": email, "password": pw}, timeout=30) + if r.status_code != 200: + print("signup fail", email, r.status_code, r.text[:150]) + return None + uid, code = fetch_code(base) + if not code: + print("no code", email) + return None + r = s.post(BASE + "/auth/verify", headers=H, + json={"email": email, "code": code, "next": "/create/", "plan": None, "cycle": None}, + timeout=30) + if r.status_code != 200: + print("verify fail", email, r.status_code, r.text[:150]) + return None + st = s.get(BASE + "/api/status", headers=H, timeout=30).json() + user = st["user"] + ck = s.cookies.get_dict() + rec = {"email": email, "password": pw, "uid": user["id"], "credits": user["credits"], + "plan": user["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(rec) + "\n") + print("OK", email, "uid", user["id"], "credits", user["credits"], flush=True) + return rec + + +if __name__ == "__main__": + start = int(sys.argv[1]) if len(sys.argv) > 1 else 1 + n = int(sys.argv[2]) if len(sys.argv) > 2 else 1 + for i in range(start, start + n): + register(i) + time.sleep(1.2) \ No newline at end of file diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..535409c --- /dev/null +++ b/requirements.txt @@ -0,0 +1 @@ +requests>=2.31 diff --git a/wave.py b/wave.py new file mode 100644 index 0000000..1fa0a5c --- /dev/null +++ b/wave.py @@ -0,0 +1,148 @@ +#!/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) \ No newline at end of file