# -*- coding: utf-8 -*-
"""MLH Promo Farm — dashboard (stdlib only, Python 3.10+).
Запуск: python dashboard.py → http://localhost:8000
Все данные локально: creds.json, tasks/*.log
👻 https://t.me/AlStack
"""
import json, os, sys, subprocess, threading, glob, urllib.parse
from http.server import ThreadingHTTPServer, BaseHTTPRequestHandler
BASE = os.path.dirname(os.path.abspath(__file__))
os.chdir(BASE)
CREDS = "creds.json"
os.makedirs("tasks", exist_ok=True)
SCRIPTS = {"reg": "mass_reg.py", "event": "event_reg.py", "watch": "promo_watch.py", "claim": "partner_claim.py"}
SITEKEY = "0x4AAAAAAARi-8xgLgfKOXIb"
_tasks, _lock = {}, threading.Lock()
_next = [1]
PAGE = """
MLH Promo Farm
🦀 MLH Promo Farm — Cursor Pro и партнёрская халява
1. Креды (Gmail + 2captcha)
2. Задачи
Скан почтыpromo_watch.py (одноразово; для cron — CLI)
3. Лог
4. Файлы
"""
def run_task(tid, script, args):
logf = os.path.join("tasks", str(tid) + ".log")
with open(logf, "w", encoding="utf-8") as lf:
p = subprocess.Popen([sys.executable, script] + args, stdout=lf, stderr=subprocess.STDOUT)
with _lock:
_tasks[tid]["pid"] = p.pid
rc = p.wait()
with _lock:
_tasks[tid]["running"] = False
_tasks[tid]["rc"] = rc
class H(BaseHTTPRequestHandler):
def log_message(self, *a): pass
def _send(self, code, body, ctype="application/json; charset=utf-8"):
b = body.encode("utf-8") if isinstance(body, str) else body
self.send_response(code)
self.send_header("Content-Type", ctype)
self.send_header("Content-Length", str(len(b)))
self.end_headers()
self.wfile.write(b)
def _body(self):
n = int(self.headers.get("Content-Length", 0))
return json.loads(self.rfile.read(n) or b"{}")
def do_GET(self):
u = urllib.parse.urlparse(self.path)
if u.path == "/":
return self._send(200, PAGE, "text/html; charset=utf-8")
if u.path == "/api/state":
with _lock:
tasks = [{"id": t["id"], "cmd": t["cmd"], "running": t["running"], "rc": t.get("rc")} for t in _tasks.values()]
tasks.sort(key=lambda x: -x["id"])
files = sorted(glob.glob("*.jsonl") + glob.glob("promo_*.json") + glob.glob("promo_email_*.html"))
creds_ok, imap_user = os.path.exists(CREDS), ""
if creds_ok:
try:
imap_user = json.load(open(CREDS, encoding="utf-8")).get("imap_user", "")
except Exception:
creds_ok = False
return self._send(200, json.dumps({"creds_ok": creds_ok, "imap_user": imap_user, "tasks": tasks, "files": files}))
if u.path == "/api/log":
tid = int(urllib.parse.parse_qs(u.query).get("id", [0])[0])
with _lock:
t = _tasks.get(tid)
if not t:
return self._send(404, '{"error":"no task"}')
try:
log = open(os.path.join("tasks", str(tid) + ".log"), encoding="utf-8", errors="replace").read()[-20000:]
except OSError:
log = ""
return self._send(200, json.dumps({"log": log, "running": t["running"], "rc": t.get("rc")}))
if u.path.startswith("/dl/"):
name = os.path.basename(urllib.parse.unquote(u.path[4:]))
fp = os.path.join(BASE, name)
if os.path.isfile(fp) and name != CREDS:
return self._send(200, open(fp, "rb").read(), "application/octet-stream")
return self._send(404, "not found", "text/plain")
return self._send(404, '{"error":"404"}')
def do_POST(self):
u = urllib.parse.urlparse(self.path)
if u.path == "/api/creds":
d = self._body()
cfg = {"imap_user": d.get("imap_user", ""), "imap_pass": d.get("imap_pass", ""),
"twocaptcha_key": d.get("twocaptcha_key", ""), "mlh_sitekey": SITEKEY}
if not cfg["imap_user"] or not cfg["imap_pass"]:
return self._send(400, '{"error":"imap_user/imap_pass required"}')
json.dump(cfg, open(CREDS, "w", encoding="utf-8"), ensure_ascii=False, indent=1)
return self._send(200, '{"ok":true}')
if u.path == "/api/run":
d = self._body()
kind = d.get("kind")
args = [str(a) for a in d.get("args", []) if str(a).strip()]
if kind not in SCRIPTS:
return self._send(400, '{"error":"bad kind"}')
if not os.path.exists(CREDS):
return self._send(400, '{"error":"save creds first"}')
if kind == "reg" and not args:
args = ["5"]
if kind in ("event", "claim") and len(args) < 2:
return self._send(400, '{"error":"need 2 args"}')
with _lock:
tid = _next[0]
_next[0] += 1
_tasks[tid] = {"id": tid, "cmd": SCRIPTS[kind] + " " + " ".join(args), "running": True, "rc": None}
threading.Thread(target=run_task, args=(tid, SCRIPTS[kind], args), daemon=True).start()
return self._send(200, json.dumps({"id": tid}))
return self._send(404, '{"error":"404"}')
if __name__ == "__main__":
srv = None
PORT = 8000
for port in range(8000, 8020):
try:
srv = ThreadingHTTPServer(("127.0.0.1", port), H)
PORT = port
break
except OSError:
continue
if srv is None:
print("no free port 8000-8019", flush=True)
sys.exit(1)
print("MLH Promo Farm dashboard: http://localhost:" + str(PORT), flush=True)
srv.serve_forever()