#!/usr/bin/env python3 # -*- coding: utf-8 -*- import argparse import csv import re import sys import time from datetime import datetime from pathlib import Path from typing import Dict, List # 确保从任何位置执行都能 import app.* PROJECT_ROOT = Path(__file__).resolve().parents[1] if str(PROJECT_ROOT) not in sys.path: sys.path.insert(0, str(PROJECT_ROOT)) from dotenv import load_dotenv from app.config.settings import Settings from app.core.context import RunContext from app.core.logger import JsonlLogger from app.core.http_client import HttpClient from app.clients.airops_web_client import AirOpsWebClient from app.clients.airops_api_client import AirOpsApiClient from app.clients.mailhub_client import build_mailhub_client from app.services.registration_service import RegistrationService from app.services.verification_service import VerificationService from app.services.workspace_service import WorkspaceService from app.services.oauth_service import OAuthService from app.services.app_execution_service import AppExecutionService from app.flows.register_bootstrap_flow import RegisterBootstrapFlow from app.flows.full_flow import FullFlow from app.integrations.account_store import AccountStore from app.integrations.registration_email_verification_flow import RegistrationEmailVerificationFlow from app.integrations.registration_failure_classifier import classify_registration_error from app.integrations.registration_retry_policy import RegistrationRetryPolicy def parse_args(): parser = argparse.ArgumentParser(description="Batch register accounts from email list.") parser.add_argument("--input", required=True, help="Email list file path. Supports: one email per line, or email,password.") parser.add_argument("--output", default="", help="CSV output path. Default: data/batch_register_result_.csv") parser.add_argument("--with-chat-test", action="store_true", help="After bootstrap, run one chat test and require success.") parser.add_argument("--sleep-sec", type=float, default=0.0, help="Sleep between accounts.") parser.add_argument("--limit", type=int, default=0, help="Max rows to process. 0 means all.") parser.add_argument("--skip-ready", action="store_true", help="Skip emails already in ready/oauth_ok/verified.") return parser.parse_args() def is_valid_email(email: str) -> bool: return bool(re.match(r"^[^@\s]+@[^@\s]+\.[^@\s]+$", email or "")) def read_accounts(path: Path) -> List[Dict[str, str]]: rows: List[Dict[str, str]] = [] for i, raw in enumerate(path.read_text(encoding="utf-8").splitlines(), start=1): line = raw.strip().lstrip("\ufeff") if not line or line.startswith("#"): continue if i == 1 and line.lower().startswith("email"): continue if "," in line: email, password = line.split(",", 1) elif "\t" in line: email, password = line.split("\t", 1) else: email, password = line, "" rows.append({"line": str(i), "email": email.strip(), "password": password.strip()}) return rows def build_flow_components(settings: Settings, email: str, password: str, account_store: AccountStore, log: JsonlLogger): http = HttpClient(settings.base_url, timeout=settings.request_timeout) web = AirOpsWebClient(http) api = AirOpsApiClient(http) reg = RegistrationService(web) if not password: password = reg.gen_password(email) ctx = RunContext(email=email, password=password) account_store.upsert(email=ctx.email, password=ctx.password, status="registering") mail_client = build_mailhub_client( settings.mailhub_base_url, settings.mailhub_api_key, settings.mailhub_password, timeout=settings.mailhub_timeout_sec, ) mail_flow = RegistrationEmailVerificationFlow(mail_client) retry = RegistrationRetryPolicy( flow=mail_flow, max_wait_sec=settings.mail_verify_max_wait_sec, initial_interval_sec=settings.mail_verify_initial_interval_sec, backoff_step_sec=settings.mail_verify_backoff_step_sec, max_interval_sec=settings.mail_verify_max_interval_sec, ) verify = VerificationService(web, retry) ws = WorkspaceService(api, ctx) oauth = OAuthService(api, ctx, settings) app_exec = AppExecutionService(api, ctx, settings) bootstrap = RegisterBootstrapFlow(log, ctx, reg, verify, web, api, ws, oauth, account_store=account_store) full = FullFlow(log, bootstrap, app_exec, ctx=ctx, account_store=account_store) return ctx, bootstrap, full def run_one(settings: Settings, email: str, password: str, account_store: AccountStore, log: JsonlLogger, with_chat_test: bool): ctx, bootstrap, full = build_flow_components(settings, email, password, account_store, log) if with_chat_test: messages = [ {"role": "system", "content": "", "id": "system"}, {"role": "user", "content": "你好,做个自我介绍", "id": "u1"}, ] final = full.run(messages) status = (final or {}).get("status") if status != "success": raise RuntimeError(f"execution_status={status}") return ctx, "ready", "" bootstrap.run() row = account_store.get_by_email(ctx.email) or {} status = str(row.get("status") or "verified") return ctx, status, "" def write_results_csv(path: Path, rows: List[Dict[str, str]]): path.parent.mkdir(parents=True, exist_ok=True) fields = [ "line", "email", "status", "retryable", "failure_code", "reason", "workspace_id", "duration_sec", "at", ] with path.open("w", encoding="utf-8", newline="") as f: writer = csv.DictWriter(f, fieldnames=fields) writer.writeheader() for row in rows: writer.writerow(row) def main(): args = parse_args() load_dotenv(dotenv_path=PROJECT_ROOT / ".env") settings = Settings() account_store = AccountStore(settings.account_store_path) input_path = Path(args.input) if not input_path.exists(): raise FileNotFoundError(f"input not found: {input_path}") if args.output: output_path = Path(args.output) else: ts = datetime.utcnow().strftime("%Y%m%d_%H%M%S") output_path = PROJECT_ROOT / "data" / f"batch_register_result_{ts}.csv" log = JsonlLogger(f"run_batch_{datetime.utcnow().strftime('%Y%m%d_%H%M%S')}.jsonl") rows = read_accounts(input_path) if args.limit and args.limit > 0: rows = rows[: args.limit] if not rows: print("[INFO] no rows to process.") return result_rows: List[Dict[str, str]] = [] ok = 0 failed = 0 skipped = 0 for idx, row in enumerate(rows, start=1): email = row["email"] password = row["password"] line_no = row["line"] print(f"\n[{idx}/{len(rows)}] email={email}") if not is_valid_email(email): failed += 1 result_rows.append( { "line": line_no, "email": email, "status": "failed_permanent", "retryable": "False", "failure_code": "invalid_email_format", "reason": "invalid email format", "workspace_id": "", "duration_sec": "0.00", "at": datetime.utcnow().isoformat(), } ) continue if args.skip_ready: old = account_store.get_by_email(email) or {} if old.get("status") in ("ready", "oauth_ok", "verified"): skipped += 1 result_rows.append( { "line": line_no, "email": email, "status": "skipped_ready", "retryable": "", "failure_code": "", "reason": "", "workspace_id": str(old.get("workspace_id") or ""), "duration_sec": "0.00", "at": datetime.utcnow().isoformat(), } ) print("[skip] already ready-like status") continue start = time.time() try: ctx, status, _ = run_one(settings, email, password, account_store, log, with_chat_test=bool(args.with_chat_test)) ok += 1 result_rows.append( { "line": line_no, "email": email, "status": status, "retryable": "", "failure_code": "", "reason": "", "workspace_id": str(ctx.workspace_id or ""), "duration_sec": f"{time.time() - start:.2f}", "at": datetime.utcnow().isoformat(), } ) print(f"[ok] status={status} workspace_id={ctx.workspace_id}") except Exception as e: failed += 1 cls = classify_registration_error(e) ws_id = "" prev = account_store.get_by_email(email) or {} if prev.get("workspace_id"): ws_id = str(prev.get("workspace_id")) account_store.upsert( email=email, password=password or str(prev.get("password") or ""), status=cls["status"], workspace_id=ws_id or None, last_error=cls["reason"], failure_code=cls["failure_code"], retryable=cls["retryable"], ) result_rows.append( { "line": line_no, "email": email, "status": cls["status"], "retryable": str(cls["retryable"]), "failure_code": cls["failure_code"], "reason": cls["reason"], "workspace_id": ws_id, "duration_sec": f"{time.time() - start:.2f}", "at": datetime.utcnow().isoformat(), } ) print( f"[failed] status={cls['status']} retryable={cls['retryable']} " f"code={cls['failure_code']} reason={cls['reason']}" ) if args.sleep_sec > 0: time.sleep(args.sleep_sec) write_results_csv(output_path, result_rows) print("\n=== BATCH DONE ===") print(f"total={len(rows)} ok={ok} failed={failed} skipped={skipped}") print(f"result_csv={output_path}") if __name__ == "__main__": main()