144 lines
5.5 KiB
Python
144 lines
5.5 KiB
Python
import json
|
||
import websockets
|
||
import asyncio
|
||
#
|
||
# async def py_client(datas,client_id):
|
||
# # uri = "ws://localhost:5001"
|
||
# uri = "wss://mtworker.tech:5003/"
|
||
#
|
||
# async with websockets.connect(uri) as websocket:
|
||
# # 发送客户端ID
|
||
# client_id2 = client_id+'_pc'
|
||
# await websocket.send(client_id2)
|
||
# target_client_id = client_id+"_web"
|
||
#
|
||
# msg = f"{target_client_id}: {datas}"
|
||
# # 发送消息
|
||
# await websocket.send(msg)
|
||
#
|
||
# # 接收响应
|
||
# response = await websocket.recv()
|
||
# print(f"Received: {response}")
|
||
#
|
||
# # 关闭连接
|
||
# await websocket.close()
|
||
# return response
|
||
#
|
||
# def get_mtg(datas,dfpid):
|
||
# kkk = asyncio.get_event_loop().run_until_complete(py_client(json.dumps(datas), dfpid))
|
||
# # kkk = py_client_sync(datas,dfpid)
|
||
# data = json.loads(kkk)
|
||
# return data
|
||
|
||
import asyncio
|
||
import websockets
|
||
import json
|
||
|
||
|
||
class WebNotConnected(Exception):
|
||
"""浏览器那边没连上 —— bestbyte 回了「Error: Target client xxx_web is not connected」。
|
||
|
||
意思是:抓包脚本注入的 JS 没在浏览器里连上 bestbyte。
|
||
常见原因:浏览器关了 / 页面刷新了 / 注入的 JS 没跑起来 /
|
||
抓包脚本重开过(重启 mitmproxy 后页面要重新加载才会有注入)。
|
||
|
||
这和「账号被封」完全是两回事,绝不能当成 403 把账号标死。
|
||
"""
|
||
|
||
|
||
async def py_client(datas, client_id, timeout=15):
|
||
uri = "wss://wss.bestbyte.com.cn/"
|
||
# open_timeout:连不上时别等系统默认的几十秒
|
||
# recv 超时:bestbyte 本身连得上,但浏览器没开着就没人回签名,
|
||
# 不加超时会永久阻塞 —— 界面会卡死在那里。
|
||
async with websockets.connect(uri, open_timeout=timeout) as websocket:
|
||
# 发送客户端ID
|
||
client_id2 = client_id + '_pc'
|
||
await websocket.send(client_id2)
|
||
target_client_id = client_id + "_web"
|
||
|
||
msg = f"{target_client_id}: {datas}"
|
||
# 发送消息
|
||
await websocket.send(msg)
|
||
|
||
# 接收响应
|
||
try:
|
||
response = await asyncio.wait_for(websocket.recv(), timeout=timeout)
|
||
except asyncio.TimeoutError:
|
||
raise TimeoutError(
|
||
'等签名超时(%ss)——浏览器在线但一直没回。' % timeout)
|
||
|
||
# 关闭连接
|
||
await websocket.close()
|
||
return response
|
||
|
||
def get_mtg(datas, dfpid):
|
||
try:
|
||
loop = asyncio.get_event_loop()
|
||
except RuntimeError:
|
||
# 如果没有事件循环,则创建一个新的
|
||
loop = asyncio.new_event_loop()
|
||
asyncio.set_event_loop(loop)
|
||
if loop.is_running():
|
||
# 界面的搜索线程里没有正在跑的事件循环,正常不会走到这;
|
||
# 真到了这一步 run_until_complete 会直接报错,不如说清楚原因。
|
||
raise RuntimeError('事件循环正在运行,没法同步等签名结果')
|
||
raw = loop.run_until_complete(py_client(json.dumps(datas), dfpid))
|
||
# bestbyte 在浏览器没上线时回的是纯文本,不是 JSON:
|
||
# Error: Target client xxxx_web is not connected.
|
||
# 直接 json.loads 会抛一个看不出原因的 JSONDecodeError。
|
||
if not raw.lstrip().startswith('{'):
|
||
if 'is not connected' in raw:
|
||
raise WebNotConnected(raw.strip()[:200])
|
||
raise ValueError('签名服务返回了非 JSON 内容:%s' % raw[:200])
|
||
return json.loads(raw)
|
||
|
||
def probe(client_id, timeout=8):
|
||
"""检查浏览器那端有没有连上 bestbyte。
|
||
|
||
返回 (是否在线, 说明)。不抛异常 —— 界面要在任何情况下都能拿到结论。
|
||
"""
|
||
try:
|
||
loop = asyncio.new_event_loop()
|
||
try:
|
||
asyncio.set_event_loop(loop)
|
||
raw = loop.run_until_complete(py_client(
|
||
json.dumps({'group': 'mtgsig1', 'action': 'mtgsig1', 'datas': '{}'}),
|
||
client_id, timeout))
|
||
finally:
|
||
loop.close()
|
||
except Exception as e: # noqa: BLE001
|
||
return False, '%s: %s' % (type(e).__name__, e)
|
||
|
||
if 'is not connected' in raw:
|
||
return False, '浏览器没连上(Target client is not connected)'
|
||
if not raw.lstrip().startswith('{'):
|
||
return False, '返回非 JSON:%s' % raw[:120]
|
||
return True, '浏览器在线,能用'
|
||
|
||
|
||
def get_sign_wss(url, data33,dfpid):
|
||
daa = {'cache': False, 'dataType': 'json', 'url': url, 'type': 'POST', 'doNotShowToastr': True, 'data': data33,
|
||
'observe': {'key': 'code', 'expect': [0, -401]}, 'context': None, 'global': True,
|
||
'accepts': {'script': 'text/javascript, application/javascript, application/x-javascript',
|
||
'json': 'application/json', 'xml': 'application/xml, text/xml', 'html': 'text/html',
|
||
'text': 'text/plain'}, 'crossDomain': True, 'timeout': 0, 'processData': True,
|
||
'method': 'POST'}
|
||
|
||
datas = {
|
||
"group": "mtgsig1",
|
||
"action": "mtgsig1",
|
||
"datas": json.dumps(daa),
|
||
|
||
}
|
||
mt = get_mtg(datas,dfpid)
|
||
# 这里原本 print 了 cookie / userAgent / 整条 mtgsig,
|
||
# 在界面里会把日志刷满,排查时反而看不见有用的行。
|
||
mtgsig = mt['mtgsig']
|
||
# return cookie , userAgent , mtgsig['headers']['mtgsig']
|
||
try:
|
||
return mtgsig['headers']['mtgsig']
|
||
except (KeyError, TypeError):
|
||
raise ValueError('签名返回的结构不对,没有 mtgsig.headers:%s'
|
||
% str(mtgsig)[:120])
|