init commit

This commit is contained in:
Udo
2026-12-01 10:02:27 +05:00
commit 200083e3ef
36 changed files with 5611 additions and 0 deletions
+116
View File
@@ -0,0 +1,116 @@
"""HTTP API."""
from __future__ import annotations
from flask import Blueprint, current_app, jsonify, request
from .graph import build_graph
from .positions import clean_positions, valid_key
from .remnawave import RemnawaveError
bp = Blueprint("api", __name__, url_prefix="/api")
class ProfileNotFound(LookupError):
pass
def _svc():
return current_app.extensions["rwviz"]
def _rules(profile: dict) -> list[dict]:
return ((profile.get("config") or {}).get("routing") or {}).get("rules") or []
def pick_profile(profiles: list[dict], wanted: str | None, default: str | None) -> dict | None:
profiles = [p for p in profiles if isinstance(p.get("config"), dict)]
key = (wanted or default or "").strip().lower()
if key:
for p in profiles:
if p["uuid"].lower() == key or p["name"].lower() == key:
return p
raise ProfileNotFound(wanted or default)
for p in profiles: # по умолчанию - первый профиль с vlessRoute
if any("vlessRoute" in r for r in _rules(p)):
return p
return profiles[0] if profiles else None
@bp.get("/health")
def health():
return {"status": "ok"}
@bp.get("/profiles")
def profiles():
snap, meta = _svc().cache.get()
items = [{
"uuid": p["uuid"],
"name": p["name"],
"inbounds": len(p.get("inbounds") or []),
"rules": len(_rules(p)),
"nodes": [n.get("name") for n in p.get("nodes") or []],
} for p in snap["profiles"] if isinstance(p.get("config"), dict)]
return jsonify({"profiles": items, "meta": {**meta, "fetchedAt": snap["fetchedAt"]}})
@bp.get("/graph")
def graph():
svc = _svc()
force = request.args.get("refresh", "").lower() in {"1", "true", "yes"}
snap, meta = svc.cache.get(force=force)
profile = pick_profile(snap["profiles"], request.args.get("profile"), svc.settings.default_profile)
if profile is None:
return jsonify(error="no_profiles", message="В панели нет config-профилей"), 404
try:
result = build_graph(profile, snap["hosts"], snap["nodes"])
except (KeyError, TypeError, ValueError) as e:
current_app.logger.exception("graph build failed")
return jsonify(error="graph_build_failed",
message=f"Не удалось разобрать профиль {profile['name']!r}: {type(e).__name__}: {e}"), 422
return jsonify({
"profile": {"uuid": profile["uuid"], "name": profile["name"]},
"graph": result,
"positions": svc.positions.get(profile["uuid"]),
"meta": {**meta, "fetchedAt": snap["fetchedAt"]},
})
@bp.get("/positions/<key>")
def get_positions(key: str):
if not valid_key(key):
return jsonify(error="bad_key", message="Некорректный идентификатор профиля"), 400
return jsonify({"positions": _svc().positions.get(key)})
@bp.put("/positions/<key>")
def put_positions(key: str):
if not valid_key(key):
return jsonify(error="bad_key", message="Некорректный идентификатор профиля"), 400
body = request.get_json(silent=True)
if not isinstance(body, dict) or "positions" not in body:
return jsonify(error="bad_body", message='Ожидается {"positions": {...}}'), 400
try:
positions = clean_positions(body["positions"])
except ValueError as e:
return jsonify(error="bad_positions", message=str(e)), 400
_svc().positions.put(key, positions)
return jsonify({"saved": len(positions)})
@bp.delete("/positions/<key>")
def delete_positions(key: str):
if not valid_key(key):
return jsonify(error="bad_key", message="Некорректный идентификатор профиля"), 400
_svc().positions.delete(key)
return "", 204
@bp.errorhandler(RemnawaveError)
def _upstream(e: RemnawaveError):
return jsonify(error=e.code, message=e.message), e.http_status
@bp.errorhandler(ProfileNotFound)
def _no_profile(e: ProfileNotFound):
return jsonify(error="profile_not_found", message=f"Профиль {e} не найден"), 404