#!/usr/bin/env python3 """ Netlify Farm Dashboard — web control panel for the netlify-autoreg pipeline. Features * account table: email, status (alive / suspended / rate-limited / unknown), site, site HTTP code * actions: check all accounts (login probe), run a registration wave, deploy to all sites, refresh tokens * live log stream (SSE) of every background job * per-account row actions: check, deploy, open site Run: python dashboard.py --port 8791 UI: http://127.0.0.1:8791/ State is kept next to the bank file in state.json. """ import argparse, json, os, re, subprocess, sys, threading, time, queue from pathlib import Path from typing import Dict, Any, List import httpx import urllib.request, urllib.error from fastapi import FastAPI, Request from fastapi.responses import HTMLResponse, StreamingResponse, JSONResponse HERE = Path(__file__).parent.resolve() BANK = Path(os.environ.get('NETLIFY_BANK', HERE / 'netlify_bank.jsonl')) STATE = Path(os.environ.get('NETLIFY_STATE', HERE / 'state.json')) FARM = HERE / 'netlify_farm.py' PY = os.environ.get('NETLIFY_PY', r'C:\Users\User\AppData\Local\Programs\Python\Python311\python.exe') sys.path.insert(0, str(HERE)) from netlify_farm import login, api_call, deploy_static # noqa: E402 app = FastAPI(title='Netlify Farm Dashboard') LOG: "queue.Queue[str]" = queue.Queue() RUNNING: Dict[str, bool] = {'wave': False, 'check': False, 'deploy': False} def log(msg: str): line = f"[{time.strftime('%H:%M:%S')}] {msg}" LOG.put(line) try: print(line, flush=True) except Exception: try: print(line.encode('ascii', 'replace').decode(), flush=True) except Exception: pass def load_bank() -> List[Dict[str, Any]]: if not BANK.exists(): return [] return [json.loads(l) for l in BANK.read_text(encoding='utf-8').splitlines() if l.strip()] def load_state() -> Dict[str, Any]: if STATE.exists(): try: return json.loads(STATE.read_text(encoding='utf-8')) except Exception: pass return {} def save_state(st: Dict[str, Any]): STATE.write_text(json.dumps(st, ensure_ascii=False, indent=1), encoding='utf-8') def site_http(domain: str) -> int: if not domain: return 0 try: with urllib.request.urlopen('https://' + domain, timeout=12) as r: return r.status except urllib.error.HTTPError as e: return e.code except Exception: return 0 def check_account(rec: Dict[str, Any], st: Dict[str, Any]) -> Dict[str, Any]: """Login-probe one account. Updates state in place.""" email = rec['email'] prev = st.get(email) or {} try: tok, msg = login(email, rec['password']) except Exception as e: tok, msg = None, f'exc {e}' now = time.strftime('%Y-%m-%d %H:%M:%S') if tok: prev.update({'status': 'alive', 'msg': 'ok', 'token': tok, 'checked': now}) elif 'suspended' in str(msg).lower(): prev.update({'status': 'suspended', 'msg': msg, 'checked': now}) elif '429' in str(msg): prev.update({'status': 'rate_limited', 'msg': msg, 'checked': now}) else: prev.update({'status': 'error', 'msg': msg, 'checked': now}) st[email] = prev return prev def job_check(limit: int = 0, pause: float = 2.5): if RUNNING['check']: log('check: уже идёт') return RUNNING['check'] = True try: recs = load_bank() if limit: recs = recs[:limit] st = load_state() log(f'check: {len(recs)} аккаунтов') alive = susp = rl = 0 for i, r in enumerate(recs, 1): res = check_account(r, st) s = res['status'] alive += s == 'alive'; susp += s == 'suspended'; rl += s == 'rate_limited' log(f" [{i}/{len(recs)}] {r['email']}: {s} {res.get('msg','')}") save_state(st) if s == 'rate_limited': log(' login rate-limited by IP, пауза 60с') time.sleep(60) else: time.sleep(pause) log(f'check готово: alive={alive} suspended={susp} rate_limited={rl}') finally: RUNNING['check'] = False def job_wave(count: int): if RUNNING['wave']: log('wave: уже идёт') return RUNNING['wave'] = True try: log(f'wave: {count} аккаунтов') env = dict(os.environ) env.pop('PYTHONPATH', None) p = subprocess.Popen([PY, str(FARM), '--count', str(count), '--site'], cwd=str(HERE), stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, encoding='utf-8', errors='replace', env=env, bufsize=1) for line in p.stdout: log(' farm| ' + line.rstrip()) p.wait() log(f'wave готово, exit={p.returncode}') finally: RUNNING['wave'] = False def job_deploy(): if RUNNING['deploy']: log('deploy: уже идёт') return RUNNING['deploy'] = True try: recs = load_bank() st = load_state() log(f'deploy: {len(recs)} сайтов') ok = 0 for r in recs: sid, dom = r.get('site_id'), r.get('site_domain') or '' tok = (st.get(r['email']) or {}).get('token') or r.get('token') if not (sid and tok): log(f" {r['email']}: пропуск (нет site/token)") continue try: api_call(tok, f'/api/v1/sites/{sid}', 'PATCH', {'sso_login': False, 'account_sso_login': False}) except Exception: pass good, dep, state = deploy_static(tok, sid, f"
| статус | сообщение | проверено | сайт | http | действия |
|---|