Files
buryan-infra/ops/work/web/services/svc_canvas.py
T

212 lines
8.4 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
"""Ручной редактор схем Комбайна на базе draw.io (embed.diagrams.net).
Зачем заменил свой редактор: он умел только таскать узлы. Владельцу нужно
добавлять устройства, рисовать кабели, подписи и свободные фигуры самому.
Взят готовый редактор draw.io — в нём это всё есть.
Как работает:
/canvas?host=...&item=... — страница с встроенным draw.io
/canvas/xml?host=... — стартовая схема (mxGraph XML из port_plan)
/canvas/save (POST) — сохранение XML в compat/layouts/<host>.drawio.xml
"""
import json
import os
import sys
import urllib.parse
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)
DRAWIO = "https://embed.diagrams.net/?embed=1&proto=json&spin=1&ui=min&libraries=1"
def esc(s):
return (str(s).replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")
.replace('"', "&quot;"))
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 xml_path(hk):
return os.path.join(LAY, hk + ".drawio.xml")
def build_xml(hk, q):
"""Стартовая схема: терминал в центре, устройства вокруг, кабели подписаны."""
if hk not in C.devices:
return None
plan = C.port_plan(hk, items_of(q))
host = plan["host"]
cells = []
cid = [2]
def cell(attrs, value=""):
i = str(cid[0])
cid[0] += 1
a = " ".join('%s="%s"' % (k, esc(v)) for k, v in attrs.items())
v = (' value="%s"' % esc(value)) if value else ""
cells.append('<mxCell id="%s" %s vertex="1" parent="1">'
'<mxGeometry x="%s" y="%s" width="%s" height="%s" as="geometry"/>'
'</mxCell>' % (i, a + v, attrs.get("x", 0), attrs.get("y", 0),
attrs.get("w", 180), attrs.get("h", 60)))
return i
def edge(src, dst, label):
i = str(cid[0])
cid[0] += 1
cells.append('<mxCell id="%s" value="%s" style="edgeStyle=orthogonalEdgeStyle;'
'rounded=1;html=1;strokeColor=#2f81f7;" edge="1" parent="1" '
'source="%s" target="%s">'
'<mxGeometry relative="1" as="geometry"/></mxCell>'
% (i, esc(label), src, dst))
host_style = "rounded=1;whiteSpace=wrap;html=1;fillColor=#132239;strokeColor=#2f81f7;fontColor=#e6edf3;"
dev_style = "rounded=1;whiteSpace=wrap;html=1;fillColor=#161b22;strokeColor=#3fb950;fontColor=#e6edf3;"
bad_style = "rounded=1;whiteSpace=wrap;html=1;fillColor=#161b22;strokeColor=#f85149;fontColor=#e6edf3;dashed=1;"
hid = cell({"x": 420, "y": 40, "w": 220, "h": 70, "style": host_style},
"%s\n(терминал)" % host)
y = 170
for r in plan["rows"]:
style = dev_style if r["ok"] else bad_style
label = r["device"] + ("\n×%s" % r["qty"] if r["qty"] > 1 else "")
if r.get("via"):
label += "\nчерез %s" % r["via"]
did = cell({"x": 420, "y": y, "w": 220, "h": 70, "style": style}, label)
port = r.get("host_port") or ""
port = port[4:] if str(port).startswith("out:") else port
edge(hid, did, "%s%s" % (port or "?", " → " + str(r.get("needs_port") or "")
if r.get("needs_port") else ""))
y += 100
body = ('<mxGraphModel dx="800" dy="600" grid="1" gridSize="10" guides="1" '
'tooltips="1" connect="1" arrows="1" fold="1" page="1" pageScale="1" '
'pageWidth="850" pageHeight="1100" math="0" shadow="0">'
'<root><mxCell id="0"/><mxCell id="1" parent="0"/>'
+ "".join(cells) + '</root></mxGraphModel>')
return body
def load_xml(q, body):
hk = cc.norm((q.get("host") or [""])[0])
try:
saved = open(xml_path(hk), encoding="utf-8").read()
return {"xml": saved, "saved": True}
except Exception:
pass
x = build_xml(hk, q)
if x is None:
return {"error": "хост не найден"}
return {"xml": x, "saved": False}
def save_xml(q, body):
body = body or {}
host = body.get("host") or ""
xml = body.get("xml") or ""
if not host or not xml:
return {"error": "нужен host и xml"}
hk = cc.norm(host)
open(xml_path(hk), "w", encoding="utf-8").write(xml)
return {"ok": True, "saved": xml_path(hk), "bytes": len(xml)}
PAGE = r"""<!doctype html><html lang="ru"><head><meta charset="utf-8">
<title>Схема — ручной режим (draw.io)</title>
<style>
html,body{margin:0;height:100%;background:#0a0e13;color:#e6edf3;
font-family:Segoe UI,system-ui,sans-serif}
#bar{height:44px;display:flex;align-items:center;gap:10px;padding:0 12px;
background:#0d1117;border-bottom:1px solid #233040;font-size:13px}
button{background:#21262d;color:#e6edf3;border:1px solid #30363d;border-radius:6px;
padding:6px 12px;cursor:pointer;font-size:13px}
button.pri{background:#238636;border-color:#2ea043}
#st{color:#8b949e;margin-left:auto}
iframe{width:100%;height:calc(100% - 45px);border:0;background:#0a0e13}
</style></head><body>
<div id="bar">
<b>Схема: ручной режим</b>
<span id="host"></span>
<button class="pri" onclick="save()">Сохранить</button>
<button onclick="exportFile()">Скачать .drawio</button>
<button onclick="resetAuto()">Сброс к авто-схеме</button>
<input id="tok" type="password" placeholder="X-Token (editor)" size="16">
<span id="st">загрузка draw.io…</span>
</div>
<iframe id="fr" src="__DRAWIO__"></iframe>
<script>
const q=new URLSearchParams(location.search);
const host=q.get('host')||'';
document.getElementById('host').textContent=host;
let xml='', frame=document.getElementById('fr');
function post(m){frame.contentWindow.postMessage(JSON.stringify(m),'*');}
window.addEventListener('message',async e=>{
if(typeof e.data!=='string')return;
let m; try{m=JSON.parse(e.data);}catch(_){return;}
if(m.event==='init'){
const r=await fetch('/canvas/xml?'+q.toString());
const d=await r.json();
if(d.error){document.getElementById('st').textContent=d.error;return;}
xml=d.xml;
post({action:'load',xml:xml,autosave:0});
document.getElementById('st').textContent=d.saved?'сохранённая схема':'авто-схема';
}
if(m.event==='save'){
xml=m.xml||xml; document.getElementById('st').textContent='сохранено в памяти';
}
if(m.event==='autosave'){ xml=m.xml||xml; }
if(m.event==='exit'){ document.getElementById('st').textContent='редактор закрыт'; }
});
async function save(){
const tok=document.getElementById('tok').value;
if(!tok){document.getElementById('st').textContent='нужен X-Token';return;}
const r=await fetch('/canvas/save',{method:'POST',
headers:{'Content-Type':'application/json','X-Token':tok},
body:JSON.stringify({host:host,xml:xml})});
const d=await r.json();
document.getElementById('st').textContent=d.ok?('сохранено '+Math.round(d.bytes/1024)+' КБ'):(d.error||'ошибка');
}
function exportFile(){
const b=new Blob([xml],{type:'application/xml'});
const a=document.createElement('a');a.href=URL.createObjectURL(b);
a.download=(host||'schema')+'.drawio';a.click();
}
async function resetAuto(){
if(!confirm('Загрузить авто-схему без сохранённых правок?'))return;
const r=await fetch('/canvas/xml?'+q.toString()+'&fresh=1');
const d=await r.json();
if(d.xml){xml=d.xml;post({action:'load',xml:xml});document.getElementById('st').textContent='авто-схема (не сохранено)';}
}
</script></body></html>"""
def canvas(q, body):
return {"__html": PAGE.replace("__DRAWIO__", DRAWIO)}
serve({
"/canvas": canvas,
"/canvas/xml": load_xml,
"/canvas/save": save_xml,
}, int(sys.argv[1]) if len(sys.argv) > 1 else 8107, "canvas",
before=C.reload_if_changed)