2021-02-06 10:46:17 +08:00
|
|
|
|
"""
|
|
|
|
|
Quart 驱动适配
|
|
|
|
|
================
|
|
|
|
|
|
|
|
|
|
后端使用方法请参考: `Quart 文档`_
|
|
|
|
|
|
|
|
|
|
.. _Quart 文档:
|
|
|
|
|
https://pgjones.gitlab.io/quart/index.html
|
|
|
|
|
"""
|
|
|
|
|
|
2021-02-06 09:41:17 +08:00
|
|
|
|
import asyncio
|
2021-06-16 00:58:47 +08:00
|
|
|
|
from dataclasses import dataclass
|
2021-09-18 16:11:03 +08:00
|
|
|
|
from typing import List, TypeVar, Callable, Optional, Coroutine
|
2021-02-06 10:34:52 +08:00
|
|
|
|
|
|
|
|
|
import uvicorn
|
2021-06-10 21:52:20 +08:00
|
|
|
|
from pydantic import BaseSettings
|
2021-02-06 09:41:17 +08:00
|
|
|
|
|
2021-09-18 16:11:03 +08:00
|
|
|
|
from nonebot.config import Env
|
2021-02-06 10:34:52 +08:00
|
|
|
|
from nonebot.log import logger
|
2021-02-06 09:41:17 +08:00
|
|
|
|
from nonebot.typing import overrides
|
2021-09-18 16:11:03 +08:00
|
|
|
|
from nonebot.utils import escape_tag
|
|
|
|
|
from nonebot.config import Config as NoneBotConfig
|
|
|
|
|
from nonebot.drivers import HTTPRequest, ReverseDriver
|
|
|
|
|
from nonebot.drivers import WebSocket as BaseWebSocket
|
2021-02-06 09:41:17 +08:00
|
|
|
|
|
|
|
|
|
try:
|
|
|
|
|
from quart import request as _request
|
2021-09-18 16:11:03 +08:00
|
|
|
|
import werkzeug.exceptions as exceptions
|
2021-02-06 09:41:17 +08:00
|
|
|
|
from quart import websocket as _websocket
|
2021-06-10 21:52:20 +08:00
|
|
|
|
from quart import Quart, Request, Response
|
|
|
|
|
from quart import Websocket as QuartWebSocket
|
2021-02-06 09:41:17 +08:00
|
|
|
|
except ImportError:
|
2021-11-22 23:21:26 +08:00
|
|
|
|
raise ValueError("Please install Quart by using `pip install nonebot2[quart]`")
|
2021-02-06 09:41:17 +08:00
|
|
|
|
|
|
|
|
|
_AsyncCallable = TypeVar("_AsyncCallable", bound=Callable[..., Coroutine])
|
|
|
|
|
|
|
|
|
|
|
2021-06-10 21:52:20 +08:00
|
|
|
|
class Config(BaseSettings):
|
|
|
|
|
"""
|
|
|
|
|
Quart 驱动框架设置
|
|
|
|
|
"""
|
2021-11-22 23:21:26 +08:00
|
|
|
|
|
2021-10-02 15:35:15 +08:00
|
|
|
|
quart_reload: Optional[bool] = None
|
2021-06-10 21:52:20 +08:00
|
|
|
|
"""
|
|
|
|
|
:类型:
|
|
|
|
|
|
2021-10-02 15:35:15 +08:00
|
|
|
|
``Optional[bool]``
|
2021-06-10 21:52:20 +08:00
|
|
|
|
|
|
|
|
|
:说明:
|
|
|
|
|
|
2021-10-02 15:35:15 +08:00
|
|
|
|
开启/关闭冷重载,默认会在配置了 app 的 debug 模式启用
|
|
|
|
|
"""
|
|
|
|
|
quart_reload_dirs: Optional[List[str]] = None
|
|
|
|
|
"""
|
|
|
|
|
:类型:
|
|
|
|
|
|
|
|
|
|
``Optional[List[str]]``
|
|
|
|
|
|
|
|
|
|
:说明:
|
|
|
|
|
|
|
|
|
|
重载监控文件夹列表,默认为 uvicorn 默认值
|
|
|
|
|
"""
|
|
|
|
|
quart_reload_delay: Optional[float] = None
|
|
|
|
|
"""
|
|
|
|
|
:类型:
|
|
|
|
|
|
|
|
|
|
``Optional[float]``
|
|
|
|
|
|
|
|
|
|
:说明:
|
|
|
|
|
|
|
|
|
|
重载延迟,默认为 uvicorn 默认值
|
|
|
|
|
"""
|
|
|
|
|
quart_reload_includes: Optional[List[str]] = None
|
|
|
|
|
"""
|
|
|
|
|
:类型:
|
|
|
|
|
|
|
|
|
|
``Optional[List[str]]``
|
|
|
|
|
|
|
|
|
|
:说明:
|
|
|
|
|
|
|
|
|
|
要监听的文件列表,支持 glob pattern,默认为 uvicorn 默认值
|
|
|
|
|
"""
|
|
|
|
|
quart_reload_excludes: Optional[List[str]] = None
|
|
|
|
|
"""
|
|
|
|
|
:类型:
|
|
|
|
|
|
|
|
|
|
``Optional[List[str]]``
|
|
|
|
|
|
|
|
|
|
:说明:
|
|
|
|
|
|
|
|
|
|
不要监听的文件列表,支持 glob pattern,默认为 uvicorn 默认值
|
2021-06-10 21:52:20 +08:00
|
|
|
|
"""
|
|
|
|
|
|
|
|
|
|
class Config:
|
|
|
|
|
extra = "ignore"
|
|
|
|
|
|
|
|
|
|
|
2021-05-22 06:43:53 +08:00
|
|
|
|
class Driver(ReverseDriver):
|
2021-02-06 10:46:17 +08:00
|
|
|
|
"""
|
|
|
|
|
Quart 驱动框架
|
|
|
|
|
|
|
|
|
|
:上报地址:
|
|
|
|
|
|
2021-02-06 11:37:57 +08:00
|
|
|
|
* ``/{adapter name}/http``: HTTP POST 上报
|
2021-02-06 10:46:17 +08:00
|
|
|
|
* ``/{adapter name}/ws``: WebSocket 上报
|
|
|
|
|
"""
|
2021-02-06 09:41:17 +08:00
|
|
|
|
|
|
|
|
|
def __init__(self, env: Env, config: NoneBotConfig):
|
|
|
|
|
super().__init__(env, config)
|
|
|
|
|
|
2021-06-10 21:52:20 +08:00
|
|
|
|
self.quart_config = Config(**config.dict())
|
|
|
|
|
|
2021-02-06 09:41:17 +08:00
|
|
|
|
self._server_app = Quart(self.__class__.__qualname__)
|
2021-11-22 23:21:26 +08:00
|
|
|
|
self._server_app.add_url_rule(
|
|
|
|
|
"/<adapter>/http", methods=["POST"], view_func=self._handle_http
|
|
|
|
|
)
|
|
|
|
|
self._server_app.add_websocket(
|
|
|
|
|
"/<adapter>/ws", view_func=self._handle_ws_reverse
|
|
|
|
|
)
|
2021-02-06 09:41:17 +08:00
|
|
|
|
|
|
|
|
|
@property
|
2021-05-22 06:43:53 +08:00
|
|
|
|
@overrides(ReverseDriver)
|
2021-02-06 09:41:17 +08:00
|
|
|
|
def type(self) -> str:
|
2021-02-06 10:46:17 +08:00
|
|
|
|
"""驱动名称: ``quart``"""
|
2021-06-10 21:52:20 +08:00
|
|
|
|
return "quart"
|
2021-02-06 09:41:17 +08:00
|
|
|
|
|
|
|
|
|
@property
|
2021-05-22 06:43:53 +08:00
|
|
|
|
@overrides(ReverseDriver)
|
2021-02-06 09:41:17 +08:00
|
|
|
|
def server_app(self) -> Quart:
|
2021-02-06 10:46:17 +08:00
|
|
|
|
"""``Quart`` 对象"""
|
2021-02-06 09:41:17 +08:00
|
|
|
|
return self._server_app
|
|
|
|
|
|
|
|
|
|
@property
|
2021-05-22 06:43:53 +08:00
|
|
|
|
@overrides(ReverseDriver)
|
2021-02-06 09:41:17 +08:00
|
|
|
|
def asgi(self):
|
2021-02-06 10:46:17 +08:00
|
|
|
|
"""``Quart`` 对象"""
|
2021-02-06 09:41:17 +08:00
|
|
|
|
return self._server_app
|
|
|
|
|
|
|
|
|
|
@property
|
2021-05-22 06:43:53 +08:00
|
|
|
|
@overrides(ReverseDriver)
|
2021-02-06 10:34:52 +08:00
|
|
|
|
def logger(self):
|
2021-06-10 21:52:20 +08:00
|
|
|
|
"""Quart 使用的 logger"""
|
2021-02-06 09:41:17 +08:00
|
|
|
|
return self._server_app.logger
|
|
|
|
|
|
2021-05-22 06:43:53 +08:00
|
|
|
|
@overrides(ReverseDriver)
|
2021-02-06 09:41:17 +08:00
|
|
|
|
def on_startup(self, func: _AsyncCallable) -> _AsyncCallable:
|
2021-06-10 21:52:20 +08:00
|
|
|
|
"""参考文档: `Startup and Shutdown`_
|
|
|
|
|
|
|
|
|
|
.. _Startup and Shutdown:
|
|
|
|
|
https://pgjones.gitlab.io/quart/how_to_guides/startup_shutdown.html
|
|
|
|
|
"""
|
2021-02-06 09:41:17 +08:00
|
|
|
|
return self.server_app.before_serving(func) # type: ignore
|
|
|
|
|
|
2021-05-22 06:43:53 +08:00
|
|
|
|
@overrides(ReverseDriver)
|
2021-02-06 09:41:17 +08:00
|
|
|
|
def on_shutdown(self, func: _AsyncCallable) -> _AsyncCallable:
|
2021-06-10 21:52:20 +08:00
|
|
|
|
"""参考文档: `Startup and Shutdown`_"""
|
2021-02-06 09:41:17 +08:00
|
|
|
|
return self.server_app.after_serving(func) # type: ignore
|
|
|
|
|
|
2021-05-22 06:43:53 +08:00
|
|
|
|
@overrides(ReverseDriver)
|
2021-11-22 23:21:26 +08:00
|
|
|
|
def run(
|
|
|
|
|
self,
|
|
|
|
|
host: Optional[str] = None,
|
|
|
|
|
port: Optional[int] = None,
|
|
|
|
|
*,
|
|
|
|
|
app: Optional[str] = None,
|
|
|
|
|
**kwargs,
|
|
|
|
|
):
|
2021-02-06 10:34:52 +08:00
|
|
|
|
"""使用 ``uvicorn`` 启动 Quart"""
|
|
|
|
|
super().run(host, port, app, **kwargs)
|
|
|
|
|
LOGGING_CONFIG = {
|
|
|
|
|
"version": 1,
|
|
|
|
|
"disable_existing_loggers": False,
|
|
|
|
|
"handlers": {
|
|
|
|
|
"default": {
|
|
|
|
|
"class": "nonebot.log.LoguruHandler",
|
|
|
|
|
},
|
|
|
|
|
},
|
|
|
|
|
"loggers": {
|
2021-11-22 23:21:26 +08:00
|
|
|
|
"uvicorn.error": {"handlers": ["default"], "level": "INFO"},
|
2021-02-06 10:34:52 +08:00
|
|
|
|
"uvicorn.access": {
|
|
|
|
|
"handlers": ["default"],
|
|
|
|
|
"level": "INFO",
|
|
|
|
|
},
|
|
|
|
|
},
|
|
|
|
|
}
|
2021-07-23 00:51:19 +08:00
|
|
|
|
uvicorn.run(
|
|
|
|
|
app or self.server_app, # type: ignore
|
|
|
|
|
host=host or str(self.config.host),
|
|
|
|
|
port=port or self.config.port,
|
2021-10-02 15:35:15 +08:00
|
|
|
|
reload=self.quart_config.quart_reload
|
2021-11-22 23:21:26 +08:00
|
|
|
|
if self.quart_config.quart_reload is not None
|
|
|
|
|
else (bool(app) and self.config.debug),
|
2021-10-02 15:35:15 +08:00
|
|
|
|
reload_dirs=self.quart_config.quart_reload_dirs,
|
|
|
|
|
reload_delay=self.quart_config.quart_reload_delay,
|
|
|
|
|
reload_includes=self.quart_config.quart_reload_includes,
|
|
|
|
|
reload_excludes=self.quart_config.quart_reload_excludes,
|
2021-07-23 00:51:19 +08:00
|
|
|
|
debug=self.config.debug,
|
|
|
|
|
log_config=LOGGING_CONFIG,
|
2021-11-22 23:21:26 +08:00
|
|
|
|
**kwargs,
|
|
|
|
|
)
|
2021-02-06 09:41:17 +08:00
|
|
|
|
|
|
|
|
|
async def _handle_http(self, adapter: str):
|
|
|
|
|
request: Request = _request
|
2021-06-10 21:52:20 +08:00
|
|
|
|
data: bytes = await request.get_data() # type: ignore
|
2021-02-06 10:34:52 +08:00
|
|
|
|
|
2021-02-06 09:41:17 +08:00
|
|
|
|
if adapter not in self._adapters:
|
2021-11-22 23:21:26 +08:00
|
|
|
|
logger.warning(
|
|
|
|
|
f"Unknown adapter {adapter}. " "Please register the adapter before use."
|
|
|
|
|
)
|
2021-02-06 09:41:17 +08:00
|
|
|
|
raise exceptions.NotFound()
|
2021-02-06 10:34:52 +08:00
|
|
|
|
|
2021-02-06 09:41:17 +08:00
|
|
|
|
BotClass = self._adapters[adapter]
|
2021-11-22 23:21:26 +08:00
|
|
|
|
http_request = HTTPRequest(
|
|
|
|
|
request.http_version,
|
|
|
|
|
request.scheme,
|
|
|
|
|
request.path,
|
|
|
|
|
request.query_string,
|
|
|
|
|
dict(request.headers),
|
|
|
|
|
request.method,
|
|
|
|
|
data,
|
|
|
|
|
)
|
2021-02-06 10:34:52 +08:00
|
|
|
|
|
2021-06-10 21:52:20 +08:00
|
|
|
|
self_id, response = await BotClass.check_permission(self, http_request)
|
|
|
|
|
|
|
|
|
|
if not self_id:
|
2021-07-26 10:41:38 +08:00
|
|
|
|
raise exceptions.Unauthorized(
|
2021-11-22 23:21:26 +08:00
|
|
|
|
description=(response and response.body or b"").decode()
|
|
|
|
|
)
|
2021-02-06 09:41:17 +08:00
|
|
|
|
if self_id in self._clients:
|
2021-11-22 23:21:26 +08:00
|
|
|
|
logger.warning(
|
|
|
|
|
"There's already a reverse websocket connection,"
|
|
|
|
|
"so the event may be handled twice."
|
|
|
|
|
)
|
2021-06-10 21:52:20 +08:00
|
|
|
|
bot = BotClass(self_id, http_request)
|
2021-02-06 09:41:17 +08:00
|
|
|
|
asyncio.create_task(bot.handle_message(data))
|
2021-11-22 23:21:26 +08:00
|
|
|
|
return Response(
|
|
|
|
|
response and response.body or "", response and response.status or 200
|
|
|
|
|
)
|
2021-02-06 09:41:17 +08:00
|
|
|
|
|
|
|
|
|
async def _handle_ws_reverse(self, adapter: str):
|
|
|
|
|
websocket: QuartWebSocket = _websocket
|
2021-11-22 23:21:26 +08:00
|
|
|
|
ws = WebSocket(
|
|
|
|
|
websocket.http_version,
|
|
|
|
|
websocket.scheme,
|
|
|
|
|
websocket.path,
|
|
|
|
|
websocket.query_string,
|
|
|
|
|
dict(websocket.headers),
|
|
|
|
|
websocket,
|
|
|
|
|
)
|
2021-06-10 21:52:20 +08:00
|
|
|
|
|
2021-02-06 09:41:17 +08:00
|
|
|
|
if adapter not in self._adapters:
|
|
|
|
|
logger.warning(
|
2021-11-22 23:21:26 +08:00
|
|
|
|
f"Unknown adapter {adapter}. Please register the adapter before use."
|
2021-02-06 09:41:17 +08:00
|
|
|
|
)
|
|
|
|
|
raise exceptions.NotFound()
|
|
|
|
|
|
|
|
|
|
BotClass = self._adapters[adapter]
|
2021-06-10 21:52:20 +08:00
|
|
|
|
self_id, response = await BotClass.check_permission(self, ws)
|
|
|
|
|
|
|
|
|
|
if not self_id:
|
2021-07-26 10:41:38 +08:00
|
|
|
|
raise exceptions.Unauthorized(
|
2021-11-22 23:21:26 +08:00
|
|
|
|
description=(response and response.body or b"").decode()
|
|
|
|
|
)
|
2021-06-10 21:52:20 +08:00
|
|
|
|
|
2021-02-06 09:41:17 +08:00
|
|
|
|
if self_id in self._clients:
|
2021-06-10 21:52:20 +08:00
|
|
|
|
logger.opt(colors=True).warning(
|
2021-08-12 16:45:22 +08:00
|
|
|
|
"There's already a websocket connection, "
|
|
|
|
|
f"<y>{escape_tag(adapter.upper())} Bot {escape_tag(self_id)}</y> ignored."
|
|
|
|
|
)
|
2021-11-22 23:21:26 +08:00
|
|
|
|
raise exceptions.Forbidden(description="Client already exists.")
|
2021-06-10 21:52:20 +08:00
|
|
|
|
|
|
|
|
|
bot = BotClass(self_id, ws)
|
2021-02-06 09:41:17 +08:00
|
|
|
|
await ws.accept()
|
|
|
|
|
logger.opt(colors=True).info(
|
2021-08-12 16:45:22 +08:00
|
|
|
|
f"WebSocket Connection from <y>{escape_tag(adapter.upper())} "
|
2021-11-22 23:21:26 +08:00
|
|
|
|
f"Bot {escape_tag(self_id)}</y> Accepted!"
|
|
|
|
|
)
|
2021-02-06 09:41:17 +08:00
|
|
|
|
self._bot_connect(bot)
|
|
|
|
|
|
|
|
|
|
try:
|
|
|
|
|
while not ws.closed:
|
2021-06-10 21:52:20 +08:00
|
|
|
|
try:
|
|
|
|
|
data = await ws.receive()
|
|
|
|
|
except asyncio.CancelledError:
|
|
|
|
|
logger.warning("WebSocket disconnected by peer.")
|
|
|
|
|
break
|
|
|
|
|
except Exception as e:
|
|
|
|
|
logger.opt(exception=e).error(
|
2021-11-22 23:21:26 +08:00
|
|
|
|
"Error when receiving data from websocket."
|
|
|
|
|
)
|
2021-06-10 21:52:20 +08:00
|
|
|
|
break
|
|
|
|
|
|
|
|
|
|
asyncio.create_task(bot.handle_message(data.encode()))
|
2021-02-06 09:41:17 +08:00
|
|
|
|
finally:
|
|
|
|
|
self._bot_disconnect(bot)
|
|
|
|
|
|
|
|
|
|
|
2021-06-16 00:58:47 +08:00
|
|
|
|
@dataclass
|
2021-02-06 09:41:17 +08:00
|
|
|
|
class WebSocket(BaseWebSocket):
|
2021-06-10 21:52:20 +08:00
|
|
|
|
websocket: QuartWebSocket = None # type: ignore
|
2021-02-06 09:41:17 +08:00
|
|
|
|
|
|
|
|
|
@property
|
|
|
|
|
@overrides(BaseWebSocket)
|
|
|
|
|
def closed(self):
|
2021-06-10 21:52:20 +08:00
|
|
|
|
# FIXME
|
|
|
|
|
return False
|
2021-02-06 09:41:17 +08:00
|
|
|
|
|
|
|
|
|
@overrides(BaseWebSocket)
|
|
|
|
|
async def accept(self):
|
|
|
|
|
await self.websocket.accept()
|
|
|
|
|
|
|
|
|
|
@overrides(BaseWebSocket)
|
|
|
|
|
async def close(self):
|
2021-06-10 21:52:20 +08:00
|
|
|
|
# FIXME
|
|
|
|
|
pass
|
2021-02-06 09:41:17 +08:00
|
|
|
|
|
|
|
|
|
@overrides(BaseWebSocket)
|
2021-06-10 21:52:20 +08:00
|
|
|
|
async def receive(self) -> str:
|
|
|
|
|
return await self.websocket.receive() # type: ignore
|
|
|
|
|
|
|
|
|
|
@overrides(BaseWebSocket)
|
|
|
|
|
async def receive_bytes(self) -> bytes:
|
|
|
|
|
return await self.websocket.receive() # type: ignore
|
|
|
|
|
|
|
|
|
|
@overrides(BaseWebSocket)
|
|
|
|
|
async def send(self, data: str):
|
|
|
|
|
await self.websocket.send(data)
|
2021-02-06 09:41:17 +08:00
|
|
|
|
|
|
|
|
|
@overrides(BaseWebSocket)
|
2021-06-10 21:52:20 +08:00
|
|
|
|
async def send_bytes(self, data: bytes):
|
|
|
|
|
await self.websocket.send(data)
|