345 lines
12 KiB
Python
345 lines
12 KiB
Python
#!/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"<html><body><h1>{r['email']}</h1></body></html>")
|
||
code = 0
|
||
for _ in range(5):
|
||
time.sleep(4)
|
||
code = site_http(dom)
|
||
if code == 200:
|
||
break
|
||
ok += code == 200
|
||
st.setdefault(r['email'], {})['site_http'] = code
|
||
log(f" {r['email']}: deploy={'ok' if good else 'fail'} http={code}")
|
||
save_state(st)
|
||
log(f'deploy готово: {ok}/{len(recs)} отдают 200')
|
||
finally:
|
||
RUNNING['deploy'] = False
|
||
|
||
|
||
def job_token(email: str):
|
||
st = load_state()
|
||
recs = {r['email']: r for r in load_bank()}
|
||
r = recs.get(email)
|
||
if not r:
|
||
log(f'token: {email} не найден')
|
||
return
|
||
res = check_account(r, st)
|
||
save_state(st)
|
||
log(f"token: {email} -> {res['status']} {res.get('msg','')}")
|
||
|
||
|
||
def run_bg(fn, *a):
|
||
threading.Thread(target=fn, args=a, daemon=True).start()
|
||
|
||
|
||
# ---------------- API ----------------
|
||
|
||
@app.get('/api/state')
|
||
def api_state():
|
||
recs = load_bank()
|
||
st = load_state()
|
||
rows = []
|
||
for r in recs:
|
||
s = st.get(r['email']) or {}
|
||
rows.append({
|
||
'email': r['email'],
|
||
'status': s.get('status', 'unknown'),
|
||
'msg': s.get('msg', ''),
|
||
'checked': s.get('checked', ''),
|
||
'site': r.get('site_domain') or '',
|
||
'site_http': s.get('site_http', None),
|
||
'has_site': bool(r.get('site_id')),
|
||
'ts': r.get('ts', ''),
|
||
})
|
||
counts = {}
|
||
for row in rows:
|
||
counts[row['status']] = counts.get(row['status'], 0) + 1
|
||
return JSONResponse({'rows': rows, 'total': len(rows), 'counts': counts, 'running': RUNNING})
|
||
|
||
|
||
@app.post('/api/check')
|
||
def api_check(n: int = 0):
|
||
run_bg(job_check, n)
|
||
return {'ok': True}
|
||
|
||
|
||
@app.post('/api/wave')
|
||
def api_wave(n: int = 3):
|
||
run_bg(job_wave, n)
|
||
return {'ok': True}
|
||
|
||
|
||
@app.post('/api/deploy')
|
||
def api_deploy():
|
||
run_bg(job_deploy)
|
||
return {'ok': True}
|
||
|
||
|
||
@app.post('/api/token')
|
||
async def api_token(req: Request):
|
||
d = await req.json()
|
||
run_bg(job_token, d.get('email', ''))
|
||
return {'ok': True}
|
||
|
||
|
||
@app.get('/api/log')
|
||
async def api_log():
|
||
async def gen():
|
||
while True:
|
||
try:
|
||
line = LOG.get(timeout=1.0)
|
||
except queue.Empty:
|
||
yield ': ping\n\n'
|
||
continue
|
||
yield 'data: ' + json.dumps({'line': line}, ensure_ascii=False) + '\n\n'
|
||
return StreamingResponse(gen(), media_type='text/event-stream',
|
||
headers={'Cache-Control': 'no-cache', 'X-Accel-Buffering': 'no'})
|
||
|
||
|
||
HTML = """<!doctype html><html><head><meta charset="utf-8"><title>Netlify Farm</title>
|
||
<style>
|
||
*{box-sizing:border-box}
|
||
body{background:#0b0f14;color:#c9d1d9;font:13px/1.5 ui-monospace,Consolas,monospace;margin:0;padding:16px}
|
||
h2{margin:0 0 12px;font-size:16px;color:#e6edf3}
|
||
.bar{display:flex;gap:8px;flex-wrap:wrap;margin-bottom:12px;align-items:center}
|
||
button{background:#1f6feb;color:#fff;border:0;border-radius:6px;padding:7px 12px;cursor:pointer;font:inherit}
|
||
button.gray{background:#21262d;border:1px solid #30363d}
|
||
button:disabled{opacity:.5;cursor:default}
|
||
input{background:#161b22;color:#c9d1d9;border:1px solid #30363d;border-radius:6px;padding:6px 8px;width:70px;font:inherit}
|
||
.stats{display:flex;gap:14px;margin-bottom:10px;font-size:12px}
|
||
.stats b{color:#7ee787}
|
||
table{width:100%;border-collapse:collapse;font-size:12px}
|
||
th,td{text-align:left;padding:6px 8px;border-bottom:1px solid #21262d}
|
||
th{color:#8b949e;font-weight:400;position:sticky;top:0;background:#0b0f14}
|
||
.alive{color:#7ee787}.suspended{color:#ff7b72}.rate_limited{color:#e3b341}.unknown{color:#8b949e}.error{color:#ffa657}
|
||
a{color:#58a6ff;text-decoration:none}
|
||
#log{background:#010409;border:1px solid #21262d;border-radius:8px;padding:10px;height:230px;overflow:auto;white-space:pre-wrap;font-size:11.5px;margin-top:14px}
|
||
.act{background:transparent;border:1px solid #30363d;color:#8b949e;padding:2px 7px;border-radius:5px;font-size:11px;cursor:pointer}
|
||
</style></head><body>
|
||
<h2>NETLIFY FARM</h2>
|
||
<div class="stats" id="stats"></div>
|
||
<div class="bar">
|
||
<button onclick="act('/api/check',{n:0})">Проверить все</button>
|
||
<button class="gray" onclick="act('/api/check',{n:5})">Проверить 5</button>
|
||
<button onclick="act('/api/deploy')">Деплой всем</button>
|
||
<span style="margin-left:14px">Волна:</span>
|
||
<input id="waveN" value="3">
|
||
<button onclick="act('/api/wave',{n:+document.getElementById('waveN').value})">Регистрировать</button>
|
||
<button class="gray" onclick="location.reload()">Обновить</button>
|
||
</div>
|
||
<table><thead><tr><th>email</th><th>статус</th><th>сообщение</th><th>проверено</th><th>сайт</th><th>http</th><th>действия</th></tr></thead>
|
||
<tbody id="rows"></tbody></table>
|
||
<div id="log"></div>
|
||
<script>
|
||
async function act(url,body){
|
||
await fetch(url,{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(body||{})});
|
||
setTimeout(refresh,700);
|
||
}
|
||
async function refresh(){
|
||
const d=await (await fetch('/api/state')).json();
|
||
const c=d.counts||{};
|
||
document.getElementById('stats').innerHTML =
|
||
'всего <b>'+d.total+'</b> · живых <b>'+(c.alive||0)+'</b> · suspended <b>'+(c.suspended||0)+
|
||
'</b> · rate-limited <b>'+(c.rate_limited||0)+'</b> · неизвестно <b>'+(c.unknown||0)+'</b>';
|
||
document.getElementById('rows').innerHTML = d.rows.map(r=>`<tr>
|
||
<td>${r.email}</td>
|
||
<td class="${r.status}">${r.status}</td>
|
||
<td>${(r.msg||'').slice(0,40)}</td>
|
||
<td>${(r.checked||'').slice(11)}</td>
|
||
<td>${r.site? '<a href="https://'+r.site+'" target="_blank">'+r.site+'</a>':'-'}</td>
|
||
<td>${r.site_http??'-'}</td>
|
||
<td>
|
||
<button class="act" onclick="act('/api/token',{email:'${r.email}'})">токен</button>
|
||
<button class="act" onclick="act('/api/deploy')">деплой</button>
|
||
</td></tr>`).join('');
|
||
}
|
||
const es=new EventSource('/api/log');
|
||
es.onmessage=e=>{const el=document.getElementById('log');
|
||
try{const d=JSON.parse(e.data); el.textContent += d.line+'\\n'; el.scrollTop=el.scrollHeight;}catch(_){} };
|
||
refresh(); setInterval(refresh, 15000);
|
||
</script></body></html>"""
|
||
|
||
|
||
@app.get('/', response_class=HTMLResponse)
|
||
def index():
|
||
return HTML
|
||
|
||
|
||
if __name__ == '__main__':
|
||
ap = argparse.ArgumentParser()
|
||
ap.add_argument('--port', type=int, default=8791)
|
||
a = ap.parse_args()
|
||
import uvicorn
|
||
print(f'dashboard on http://127.0.0.1:{a.port}/ bank={BANK} exists={BANK.exists()}')
|
||
uvicorn.run(app, host='127.0.0.1', port=a.port, log_level='warning') |