-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
76 lines (64 loc) · 2.28 KB
/
Copy pathserver.py
File metadata and controls
76 lines (64 loc) · 2.28 KB
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
69
70
71
72
73
74
75
76
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
APPanel 服务器模块
"""
import asyncio, json, threading, socket as _sk, logging
from flask import Flask
import websockets
from config import HOST, WS_PORT, FLASK_PORT, FLASK_FALLBACK_PORT
from collectors.ws import WS_CLIENTS, CACHE
from routes import register_all
app = Flask(__name__)
register_all(app)
# 抑制 Werkzeug 开发服务器警告
logging.getLogger('werkzeug').setLevel(logging.ERROR)
async def ws_handler(ws) -> None:
WS_CLIENTS.add(ws)
try:
if CACHE:
from collectors.shared import _CPU_MAP
payload = dict(CACHE)
payload["_pkg_map"] = _CPU_MAP.get("packages", {})
payload["_hidden_procs"] = _CPU_MAP.get("hidden_procs", {})
try:
from collectors.adb_shell import get_channel_adb_pids, get_channel_local_pids
payload["_adb_pids"] = get_channel_adb_pids()
payload["_local_pids"] = get_channel_local_pids()
except Exception:
pass
await ws.send(json.dumps(payload))
async for msg in ws:
try:
data = json.loads(msg)
pass
except json.JSONDecodeError:
pass
finally:
WS_CLIENTS.discard(ws)
async def ws_server() -> None:
async with websockets.serve(ws_handler, HOST, WS_PORT, compression=None):
await asyncio.Future()
def start_ws() -> None:
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
loop.run_until_complete(ws_server())
def run() -> None:
port = FLASK_PORT
# 先尝试绑定(含 SO_REUSEADDR 解决重启后 TIME_WAIT)
try:
with _sk.socket(_sk.AF_INET, _sk.SOCK_STREAM) as s:
s.setsockopt(_sk.SOL_SOCKET, _sk.SO_REUSEADDR, 1)
s.bind((HOST, port))
s.close()
except (OSError, PermissionError):
port = FLASK_FALLBACK_PORT
else:
with _sk.socket(_sk.AF_INET, _sk.SOCK_STREAM) as s:
try:
s.bind((HOST, port))
s.close()
except (OSError, PermissionError):
port = FLASK_FALLBACK_PORT
print(f"[SERVER] port {FLASK_PORT} no permission, fallback to {port}")
app.run(host=HOST, port=port, debug=False)