277 lines
12 KiB
Python
277 lines
12 KiB
Python
#!/usr/bin/env python3
|
|
"""Ручной режим схем Комбайна (8106): двигать узлы, подписи, линии.
|
|
|
|
Зачем: авто-схема (svc_draw.py, :8104) строит узлы по жёсткому алгоритму и
|
|
получается нечитаемой. Здесь ту же схему можно поправить руками — позиции
|
|
узлов, подписи и произвольные линии сохраняются в
|
|
/opt/work-hub/compat/layouts/<хост>.json и переиспользуются.
|
|
|
|
Страница: /editor?host=MeetingBar%20A30&item=A40:2
|
|
Данные: /load?host=... (GET)
|
|
Сохранение:/save (POST, нужен X-Token с правом записи)
|
|
Экспорт: /render?host=... (GET, отдаёт SVG)
|
|
"""
|
|
import json
|
|
import os
|
|
import sys
|
|
|
|
sys.path.insert(0, "/root/buryan-infra/ops/work/web")
|
|
from svc_base import serve # noqa: E402
|
|
import combine_core as cc # noqa: E402
|
|
|
|
C = cc.Core()
|
|
BASE = "/opt/work-hub/compat"
|
|
LAY = os.path.join(BASE, "layouts")
|
|
os.makedirs(LAY, exist_ok=True)
|
|
W, H = 1100, 620
|
|
|
|
COLOR = {"HDMI": "#2f81f7", "USB": "#3fb950", "USB-C": "#3fb950", "VCH": "#a371f7",
|
|
"LAN": "#d29922", "3.5mm": "#8b949e", "DP": "#a371f7", "RJ-9": "#8b949e",
|
|
"—": "#484f58"}
|
|
|
|
|
|
def esc(s):
|
|
return (str(s).replace("&", "&").replace("<", "<").replace(">", ">")
|
|
.replace('"', """))
|
|
|
|
|
|
def items_of(q):
|
|
out = []
|
|
for raw in (q.get("item") or []):
|
|
if ":" in raw:
|
|
m, n = raw.rsplit(":", 1)
|
|
try:
|
|
out.append([m, int(n)])
|
|
except ValueError:
|
|
pass
|
|
else:
|
|
out.append([raw, 1])
|
|
return out
|
|
|
|
|
|
def path_of(hk):
|
|
return os.path.join(LAY, hk + ".json")
|
|
|
|
|
|
def auto_layout(hk, q):
|
|
"""Узлы и связи так же, как в авто-схеме, но в виде данных."""
|
|
if hk not in C.devices:
|
|
return None
|
|
host = C.devices[hk]["name"]
|
|
plan = C.port_plan(hk, items_of(q))
|
|
rows = [r for r in plan["rows"] if r["device"] not in ("", None)]
|
|
n = max(len(rows), 1)
|
|
nodes = []
|
|
for i, r in enumerate(rows):
|
|
step = (H - 120) / n
|
|
nodes.append({
|
|
"id": "n%d" % i,
|
|
"label": r["device"],
|
|
"sub": ("→ " + str(r["host_port"])) if r["ok"] else "нет порта",
|
|
"note": r["needs_port"] or "?",
|
|
"ok": bool(r["ok"]),
|
|
"x": 175 if i % 2 == 0 else 925,
|
|
"y": round(60 + step * i + step / 2, 1),
|
|
})
|
|
return {"host": host, "hk": hk, "nodes": nodes, "edges": [],
|
|
"texts": [], "lines": [], "W": W, "H": H,
|
|
"free_in": plan["free_in"], "free_out": plan["free_out"],
|
|
"unresolved": plan["unresolved"]}
|
|
|
|
|
|
def load(q, body):
|
|
hk = cc.norm((q.get("host") or [""])[0])
|
|
base = auto_layout(hk, q)
|
|
if not base:
|
|
return {"error": "хост не найден", "host": (q.get("host") or [""])[0]}
|
|
try:
|
|
saved = json.load(open(path_of(hk), encoding="utf-8"))
|
|
except Exception:
|
|
saved = None
|
|
if saved:
|
|
by_label = {str(n.get("label")): n for n in (saved.get("nodes") or [])}
|
|
for n in base["nodes"]:
|
|
s = by_label.get(str(n["label"]))
|
|
if s:
|
|
n["x"], n["y"] = s.get("x", n["x"]), s.get("y", n["y"])
|
|
base["texts"] = saved.get("texts") or []
|
|
base["lines"] = saved.get("lines") or []
|
|
base["saved"] = True
|
|
return base
|
|
|
|
|
|
def save(q, body):
|
|
body = body or {}
|
|
hk = cc.norm(body.get("host") or "")
|
|
if not hk:
|
|
return {"error": "не указан хост"}
|
|
data = {"host": body.get("host"), "nodes": body.get("nodes") or [],
|
|
"texts": body.get("texts") or [], "lines": body.get("lines") or [],
|
|
"updated": __import__("time").strftime("%Y-%m-%dT%H:%M:%S")}
|
|
json.dump(data, open(path_of(hk), "w", encoding="utf-8"),
|
|
ensure_ascii=False, indent=1)
|
|
return {"ok": True, "saved": path_of(hk),
|
|
"nodes": len(data["nodes"]), "texts": len(data["texts"]),
|
|
"lines": len(data["lines"])}
|
|
|
|
|
|
def render(q, body):
|
|
"""SVG из сохранённой раскладки."""
|
|
d = load(q, body)
|
|
if d.get("error"):
|
|
return d
|
|
cx, cy, bw, bh = W // 2, H // 2, 210, 110
|
|
p = ['<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 %d %d" width="%d" '
|
|
'height="%d" style="background:#0a0e13">' % (W, H, W, H)]
|
|
p.append('<rect x="%d" y="%d" width="%d" height="%d" rx="12" fill="#132239" '
|
|
'stroke="#2f81f7" stroke-width="2"/>' % (cx - bw // 2, cy - bh // 2, bw, bh))
|
|
p.append('<text x="%d" y="%d" fill="#e6edf3" font-size="14" font-weight="600">%s</text>'
|
|
% (cx - bw // 2 + 14, cy - bh // 2 + 24, esc(d["host"])[:26]))
|
|
for n in d["nodes"]:
|
|
col = "#3fb950" if n.get("ok") else "#f85149"
|
|
p.append('<path d="M %d %d L %s %s" stroke="%s" stroke-width="2" opacity="0.7" '
|
|
'fill="none"/>' % (cx, cy, n["x"], n["y"], col))
|
|
p.append('<rect x="%s" y="%s" width="210" height="60" rx="10" fill="#161b22" '
|
|
'stroke="%s" stroke-width="1.4"/>' % (n["x"] - 105, n["y"] - 30, col))
|
|
p.append('<text x="%s" y="%s" text-anchor="middle" fill="#e6edf3" font-size="12" '
|
|
'font-weight="600">%s</text>' % (n["x"], n["y"] - 6, esc(n["label"])[:24]))
|
|
p.append('<text x="%s" y="%s" text-anchor="middle" fill="#8b949e" font-size="9.5">'
|
|
'%s</text>' % (n["x"], n["y"] + 10, esc(n.get("sub", ""))))
|
|
for ln in d.get("lines") or []:
|
|
p.append('<line x1="%s" y1="%s" x2="%s" y2="%s" stroke="%s" stroke-width="2"/>'
|
|
% (ln.get("x1"), ln.get("y1"), ln.get("x2"), ln.get("y2"),
|
|
ln.get("color", "#8b949e")))
|
|
for t in d.get("texts") or []:
|
|
p.append('<text x="%s" y="%s" fill="%s" font-size="%s">%s</text>'
|
|
% (t.get("x"), t.get("y"), t.get("color", "#e6edf3"),
|
|
t.get("size", 12), esc(t.get("text", ""))))
|
|
p.append("</svg>")
|
|
return {"ok": True, "svg": "".join(p)}
|
|
|
|
|
|
EDITOR = r"""<!doctype html><html lang="ru"><head><meta charset="utf-8">
|
|
<title>Схема — ручной режим</title>
|
|
<style>
|
|
body{margin:0;background:#0a0e13;color:#e6edf3;font-family:Segoe UI,system-ui,sans-serif}
|
|
header{padding:10px 16px;background:#0d1117;border-bottom:1px solid #233040;
|
|
display:flex;gap:10px;align-items:center;flex-wrap:wrap}
|
|
button{background:#21262d;color:#e6edf3;border:1px solid #30363d;border-radius:6px;
|
|
padding:6px 10px;cursor:pointer;font-size:13px}
|
|
button.pri{background:#238636;border-color:#2ea043}
|
|
input{background:#0d1117;border:1px solid #30363d;color:#e6edf3;border-radius:6px;
|
|
padding:5px 8px;font-size:13px}
|
|
#wrap{position:relative;width:1100px;margin:14px auto}
|
|
svg{background:#0a0e13;border:1px solid #233040;border-radius:10px;display:block}
|
|
.node{cursor:move}
|
|
#hint{margin-left:auto;color:#8b949e;font-size:12px}
|
|
</style></head><body>
|
|
<header>
|
|
<b>Схема: ручной режим</b>
|
|
<span id="hostName"></span>
|
|
<button class="pri" onclick="saveAll()">Сохранить</button>
|
|
<button onclick="addText()">+ Подпись</button>
|
|
<button onclick="mode= (mode==='line'?'move':'line');this.textContent = mode==='line'?'Линия: ткни 2 точки':'+ Линия'">+ Линия</button>
|
|
<button onclick="resetLayout()">Сброс</button>
|
|
<button onclick="exportSvg()">Экспорт SVG</button>
|
|
<input id="tok" type="password" placeholder="X-Token (editor)" size="18">
|
|
<span id="hint"></span>
|
|
</header>
|
|
<div id="wrap"><svg id="svg" width="1100" height="620"></svg></div>
|
|
<script>
|
|
let L=null, mode='move', drag=null, lineStart=null;
|
|
const q=new URLSearchParams(location.search);
|
|
const svg=document.getElementById('svg');
|
|
function n(t,a){const e=document.createElementNS('http://www.w3.org/2000/svg',t);
|
|
for(const k in a)e.setAttribute(k,a[k]);return e;}
|
|
async function loadAll(){
|
|
const r=await fetch('/load?'+q.toString()); const d=await r.json();
|
|
if(d.error){document.getElementById('hint').textContent=d.error;return;}
|
|
L=d; document.getElementById('hostName').textContent=d.host;
|
|
draw(); document.getElementById('hint').textContent=d.saved?'сохранённая раскладка':'авто-раскладка';
|
|
}
|
|
function draw(){
|
|
while(svg.firstChild)svg.removeChild(svg.firstChild);
|
|
const cx=550,cy=310;
|
|
svg.appendChild(n('rect',{x:cx-105,y:cy-55,width:210,height:110,rx:12,
|
|
fill:'#132239',stroke:'#2f81f7','stroke-width':2}));
|
|
const t=n('text',{x:cx-91,y:cy-31,fill:'#e6edf3','font-size':14,'font-weight':600});
|
|
t.textContent=(L.host||'').slice(0,26); svg.appendChild(t);
|
|
(L.nodes||[]).forEach(nd=>{
|
|
const col=nd.ok?'#3fb950':'#f85149';
|
|
svg.appendChild(n('path',{d:`M ${cx} ${cy} L ${nd.x} ${nd.y}`,stroke:col,
|
|
'stroke-width':2,opacity:'0.7',fill:'none'}));
|
|
const g=n('g',{class:'node','data-id':nd.id});
|
|
g.appendChild(n('rect',{x:nd.x-105,y:nd.y-30,width:210,height:60,rx:10,
|
|
fill:'#161b22',stroke:col,'stroke-width':1.4}));
|
|
const a=n('text',{x:nd.x,y:nd.y-6,'text-anchor':'middle',fill:'#e6edf3',
|
|
'font-size':12,'font-weight':600}); a.textContent=(nd.label||'').slice(0,24); g.appendChild(a);
|
|
const b=n('text',{x:nd.x,y:nd.y+10,'text-anchor':'middle',fill:'#8b949e','font-size':9.5});
|
|
b.textContent=nd.sub||''; g.appendChild(b);
|
|
g.addEventListener('mousedown',e=>{drag={id:nd.id,dx:e.offsetX-nd.x,dy:e.offsetY-nd.y};e.preventDefault();});
|
|
svg.appendChild(g);
|
|
});
|
|
(L.lines||[]).forEach(ln=>{
|
|
svg.appendChild(n('line',{x1:ln.x1,y1:ln.y1,x2:ln.x2,y2:ln.y2,
|
|
stroke:ln.color||'#8b949e','stroke-width':2}));
|
|
});
|
|
(L.texts||[]).forEach(tx=>{
|
|
const e=n('text',{x:tx.x,y:tx.y,fill:tx.color||'#e6edf3','font-size':tx.size||12,
|
|
style:'cursor:move'});
|
|
e.textContent=tx.text||''; e.addEventListener('mousedown',ev=>{
|
|
drag={text:tx,dx:ev.offsetX-tx.x,dy:ev.offsetY-tx.y};ev.preventDefault();});
|
|
svg.appendChild(e);
|
|
});
|
|
}
|
|
svg.addEventListener('mousemove',e=>{
|
|
if(!drag)return;
|
|
if(drag.id){const nd=L.nodes.find(x=>x.id===drag.id); nd.x=e.offsetX-drag.dx; nd.y=e.offsetY-drag.dy;}
|
|
if(drag.text){drag.text.x=e.offsetX-drag.dx; drag.text.y=e.offsetY-drag.dy;}
|
|
draw();
|
|
});
|
|
svg.addEventListener('mouseup',()=>{drag=null;});
|
|
svg.addEventListener('click',e=>{
|
|
if(mode!=='line')return;
|
|
const p={x:e.offsetX,y:e.offsetY};
|
|
if(!lineStart){lineStart=p;document.getElementById('hint').textContent='вторая точка…';return;}
|
|
L.lines=L.lines||[]; L.lines.push({x1:lineStart.x,y1:lineStart.y,x2:p.x,y2:p.y,color:'#8b949e'});
|
|
lineStart=null; mode='move'; document.getElementById('hint').textContent='линия добавлена'; draw();
|
|
});
|
|
function addText(){
|
|
const s=prompt('Текст подписи:'); if(!s)return;
|
|
L.texts=L.texts||[]; L.texts.push({text:s,x:200,y:60,color:'#e6edf3',size:12}); draw();
|
|
}
|
|
async function saveAll(){
|
|
const token=document.getElementById('tok').value;
|
|
if(!token){document.getElementById('hint').textContent='нужен X-Token';return;}
|
|
const body={host:L.host,nodes:L.nodes,texts:L.texts,lines:L.lines};
|
|
const r=await fetch('/save',{method:'POST',headers:{'Content-Type':'application/json','X-Token':token},
|
|
body:JSON.stringify(body)});
|
|
const d=await r.json();
|
|
document.getElementById('hint').textContent=d.ok?('сохранено: узлов '+d.nodes+', линий '+d.lines):(d.error||'ошибка');
|
|
}
|
|
async function resetLayout(){
|
|
if(!confirm('Вернуть авто-раскладку? Сохранение сотрёт ручную.'))return;
|
|
const r=await fetch('/load?'+q.toString()+'&fresh=1'); const d=await r.json();
|
|
L.nodes=d.nodes; L.texts=[]; L.lines=[]; draw();
|
|
document.getElementById('hint').textContent='авто-раскладка (не сохранено)';
|
|
}
|
|
function exportSvg(){
|
|
const blob=new Blob([new XMLSerializer().serializeToString(svg)],{type:'image/svg+xml'});
|
|
const a=document.createElement('a'); a.href=URL.createObjectURL(blob);
|
|
a.download=(L.host||'schema')+'.svg'; a.click();
|
|
}
|
|
loadAll();
|
|
</script></body></html>"""
|
|
|
|
|
|
def editor(q, body):
|
|
return {"__html": EDITOR}
|
|
|
|
|
|
serve({
|
|
"/load": load,
|
|
"/save": save,
|
|
"/render": render,
|
|
"/editor": editor,
|
|
}, int(sys.argv[1]) if len(sys.argv) > 1 else 8106, "drawedit", before=C.reload_if_changed)
|