[WORK] Покрытие по зонам (сетка, % площади), роли и токены записи (viewer/editor/admin), аудит изменений, импорт проекта из CSV
This commit is contained in:
1 parent
2b1b91c9f5
commit
8abb809e24
5 files changed
+169
No files matched your search
@@ -0,0 +1,14 @@
|
||||
note: 'роли: viewer (чтение) · editor (изменение) · admin (всё)'
|
||||
roles:
|
||||
admin:
|
||||
token: adm-a06ef28b7100
|
||||
can_write: true
|
||||
editor:
|
||||
token: ed-e23aca07414f
|
||||
can_write: true
|
||||
default: viewer
|
||||
protected:
|
||||
- /save
|
||||
- /delete
|
||||
- /override
|
||||
- /import
|
||||
@@ -339,6 +339,52 @@ class Core:
|
||||
"fov_h": a.get("camera.fov_h"),
|
||||
"zoom": a.get("camera.zoom_optical") or a.get("camera.zoom_hybrid")}
|
||||
|
||||
# ── покрытие по зонам (сетка) ──
|
||||
def coverage_grid(self, host_key, items, w=8.0, l=10.0, cell=0.5):
|
||||
"""Считает покрытие микрофонами по сетке комнаты.
|
||||
|
||||
Возвращает матрицу «сколько микрофонов достаёт до точки» и процент
|
||||
площади с покрытием хотя бы одним микрофоном.
|
||||
"""
|
||||
mics = []
|
||||
for r in items:
|
||||
model, qty = r[0], int(r[1])
|
||||
p = self.attrs.get(norm(model), {}).get("audio.pickup_m")
|
||||
if p:
|
||||
mics.append({"model": model, "qty": qty, "radius": float(p)})
|
||||
built = self.attrs.get(norm(host_key), {}).get("audio.pickup_m")
|
||||
if built:
|
||||
mics.append({"model": "встроенный", "qty": 1, "radius": float(built)})
|
||||
if not mics:
|
||||
return {"ok": False, "reason": "нет данных о дальности микрофонов",
|
||||
"grid": [], "covered_pct": 0}
|
||||
nx, ny = max(1, int(w / cell)), max(1, int(l / cell))
|
||||
# считаем, что микрофоны распределены по потолку равномерно
|
||||
total_units = sum(m["radius"] and m["qty"] for m in mics) or 1
|
||||
positions = []
|
||||
idx = 0
|
||||
for m in mics:
|
||||
for _ in range(m["qty"]):
|
||||
frac = (idx + 1) / (total_units + 1)
|
||||
positions.append({"x": w * frac, "y": l * 0.5, "r": m["radius"],
|
||||
"model": m["model"]})
|
||||
idx += 1
|
||||
grid, covered = [], 0
|
||||
for j in range(ny):
|
||||
row = []
|
||||
for i in range(nx):
|
||||
cx, cy = (i + 0.5) * cell, (j + 0.5) * cell
|
||||
n = sum(1 for p in positions
|
||||
if (p["x"] - cx) ** 2 + (p["y"] - cy) ** 2 <= p["r"] ** 2)
|
||||
row.append(n)
|
||||
if n:
|
||||
covered += 1
|
||||
grid.append(row)
|
||||
return {"ok": True, "grid": grid, "nx": nx, "ny": ny, "cell": cell,
|
||||
"w": w, "l": l, "positions": positions,
|
||||
"covered_pct": round(100.0 * covered / (nx * ny), 1),
|
||||
"mics": len(positions)}
|
||||
|
||||
# ── комплектация ──
|
||||
def package(self, name):
|
||||
k = norm(name)
|
||||
|
||||
@@ -283,6 +283,45 @@ def _fresh():
|
||||
C.reload_if_changed()
|
||||
|
||||
|
||||
def zones(q, body):
|
||||
w, l = _room(q)
|
||||
items = _items(q)
|
||||
g = C.coverage_grid((q.get("host") or [""])[0], items, w, l, 0.5)
|
||||
if not g.get("ok"):
|
||||
return {"ok": False, "reason": g.get("reason"),
|
||||
"svg": '<svg xmlns="http://www.w3.org/2000/svg" width="400" height="80">'
|
||||
'<text x="10" y="40" fill="#d29922" font-size="12">'
|
||||
'нет данных о дальности микрофонов</text></svg>',
|
||||
"covered_pct": 0}
|
||||
scale = 40
|
||||
pad = 40
|
||||
W = g["nx"] * scale + pad * 2
|
||||
H = g["ny"] * scale + pad * 2
|
||||
parts = [f'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 {W} {H}">',
|
||||
f'<rect width="{W}" height="{H}" fill="#0a0e13"/>']
|
||||
for j in range(g["ny"]):
|
||||
for i in range(g["nx"]):
|
||||
n = g["grid"][j][i]
|
||||
if n >= 2:
|
||||
col = "#1f7a3f"
|
||||
elif n == 1:
|
||||
col = "#2e7d4f"
|
||||
else:
|
||||
col = "#4a1d1d"
|
||||
parts.append(f'<rect x="{pad+i*scale}" y="{pad+j*scale}" width="{scale-1}" '
|
||||
f'height="{scale-1}" fill="{col}" opacity="0.85"/>')
|
||||
for p in g["positions"]:
|
||||
cx = pad + p["x"] / g["cell"] * scale
|
||||
cy = pad + p["y"] / g["cell"] * scale
|
||||
parts.append(f'<circle cx="{cx:.0f}" cy="{cy:.0f}" r="6" fill="#3fb950"/>')
|
||||
parts.append(f'<text x="{pad}" y="{pad-12}" fill="#8b949e" font-size="11">'
|
||||
f'покрытие {g["covered_pct"]}% · микрофонов {g["mics"]} · '
|
||||
f'комната {g["w"]}×{g["l"]} м, шаг {g["cell"]} м</text>')
|
||||
parts.append("</svg>")
|
||||
return {"ok": True, "svg": "".join(parts), "covered_pct": g["covered_pct"],
|
||||
"mics": g["mics"], "grid_size": [g["nx"], g["ny"]]}
|
||||
|
||||
|
||||
serve({
|
||||
"/diagram": diagram,
|
||||
"/cables": cables,
|
||||
@@ -290,5 +329,6 @@ serve({
|
||||
"/ipplan": ipplan,
|
||||
"/layout": layout,
|
||||
"/plan": plan,
|
||||
"/zones": zones,
|
||||
"/heatmap": heatmap,
|
||||
}, int(sys.argv[1]) if len(sys.argv) > 1 else 8104, "draw", before=C.reload_if_changed)
|
||||
@@ -123,9 +123,39 @@ def remove(q, body):
|
||||
return {"error": "not found"}
|
||||
|
||||
|
||||
def import_project(q, body):
|
||||
"""Импорт проекта: CSV-текст 'model,qty' или список models."""
|
||||
body = body or {}
|
||||
text = body.get("csv") or ""
|
||||
rows = []
|
||||
if text:
|
||||
for line in text.splitlines():
|
||||
line = line.strip()
|
||||
if not line or line.lower().startswith(("model", "модель")):
|
||||
continue
|
||||
parts = [p.strip() for p in line.replace(";", ",").split(",")]
|
||||
if len(parts) < 2:
|
||||
continue
|
||||
try:
|
||||
rows.append([parts[0], int(float(parts[1]))])
|
||||
except ValueError:
|
||||
continue
|
||||
for m in body.get("models") or []:
|
||||
rows.append([m.get("model"), int(m.get("qty") or 1)])
|
||||
if not rows:
|
||||
return {"error": "нечего импортировать"}
|
||||
payload = {"name": body.get("name") or "Импортированный проект",
|
||||
"host": body.get("host") or "meetingbara50",
|
||||
"items": [{"model": r[0], "qty": r[1]} for r in rows]}
|
||||
res = save(None, payload)
|
||||
res["imported"] = len(rows)
|
||||
return res
|
||||
|
||||
|
||||
serve({
|
||||
"/list": lst,
|
||||
"/get": get,
|
||||
"/save": save,
|
||||
"/delete": remove,
|
||||
"/import": import_project,
|
||||
}, int(sys.argv[1]) if len(sys.argv) > 1 else 8103, "project")
|
||||
@@ -6,6 +6,37 @@ import sys
|
||||
import urllib.parse
|
||||
from http.server import BaseHTTPRequestHandler
|
||||
|
||||
PROTECTED = ("/save", "/delete", "/override", "/import")
|
||||
AUDIT = "/opt/work-hub/compat/audit.jsonl"
|
||||
AUTH_FILE = "/opt/work-hub/compat/access.yaml"
|
||||
|
||||
|
||||
def _tokens():
|
||||
"""Читает токены и роли из access.yaml."""
|
||||
try:
|
||||
import yaml
|
||||
d = yaml.safe_load(open(AUTH_FILE, encoding="utf-8")) or {}
|
||||
except Exception:
|
||||
return {}
|
||||
out = {}
|
||||
for role, info in (d.get("roles") or {}).items():
|
||||
tok = (info or {}).get("token")
|
||||
if tok:
|
||||
out[tok] = {"role": role, "write": bool(info.get("can_write"))}
|
||||
return out
|
||||
|
||||
|
||||
def _audit(path, role, body):
|
||||
import time
|
||||
try:
|
||||
with open(AUDIT, "a", encoding="utf-8") as f:
|
||||
f.write(json.dumps({"at": time.strftime("%Y-%m-%dT%H:%M:%S"),
|
||||
"path": path, "role": role,
|
||||
"body": str(body)[:400]}, ensure_ascii=False) + "\n")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
CORS = {
|
||||
"Access-Control-Allow-Origin": "*",
|
||||
"Access-Control-Allow-Methods": "GET, POST, OPTIONS",
|
||||
@@ -47,6 +78,14 @@ def serve(routes, port, name, before=None):
|
||||
self._send({}, 204)
|
||||
|
||||
def _handle(self, body=None):
|
||||
u = urllib.parse.urlparse(self.path)
|
||||
if u.path in PROTECTED and self.command == "POST":
|
||||
tok = self.headers.get("X-Token") or ""
|
||||
info = _tokens().get(tok)
|
||||
if not info or not info.get("write"):
|
||||
return self._send({"error": "нужен токен editor/admin",
|
||||
"hint": "заголовок X-Token"}, 403)
|
||||
_audit(u.path, info.get("role"), body)
|
||||
if before is not None:
|
||||
try:
|
||||
before()
|
||||
|
||||
Reference in new issue
Block a user