-
Notifications
You must be signed in to change notification settings - Fork 10
/
mz_prompt_webserver.py
68 lines (51 loc) · 1.85 KB
/
mz_prompt_webserver.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import asyncio
import uuid
from . import mz_prompt_utils
web_msg_pool = {
}
def show_toast_success(message, duration=2000):
send_message({
"type": "toast-success",
"message": message,
"duration": duration
})
def send_message(data):
global web_msg_pool
for key in web_msg_pool:
web_msg_pool[key].append(data)
def start_server():
try:
global web_msg_pool
from aiohttp import web
import server
app: web.Application = server.PromptServer.instance.app
async def message(request):
muuid = uuid.uuid4()
try:
ws = web.WebSocketResponse()
await ws.prepare(request)
web_msg_pool[muuid] = []
async for msg in ws:
if msg.type == web.WSMsgType.text:
if len(web_msg_pool[muuid]) == 0:
continue
else:
await ws.send_json(web_msg_pool[muuid])
web_msg_pool[muuid] = []
elif msg.type == web.WSMsgType.close:
break
del web_msg_pool[muuid]
mz_prompt_utils.Utils.print_log(f"connection {muuid} closed")
return ws
except Exception as e:
mz_prompt_utils.Utils.print_log(e)
del web_msg_pool[muuid]
return ws
if not any([route.get_info().get("path", "") == "/mz_webapi/message" for route in app.router.routes()]):
mz_prompt_utils.Utils.print_log("add route /mz_webapi/message")
app.router.add_get("/mz_webapi/message", message)
else:
mz_prompt_utils.Utils.print_log(
"route /mz_webapi/message is exist")
except Exception as e:
print(e)