2020-07-04 22:51:10 +08:00
|
|
|
#!/usr/bin/env python3
|
|
|
|
# -*- coding: utf-8 -*-
|
|
|
|
|
2020-08-10 13:06:02 +08:00
|
|
|
import json
|
2020-07-04 22:51:10 +08:00
|
|
|
import logging
|
|
|
|
from ipaddress import IPv4Address
|
|
|
|
|
|
|
|
import uvicorn
|
2020-08-10 13:06:02 +08:00
|
|
|
from fastapi import FastAPI, status
|
2020-07-15 20:39:59 +08:00
|
|
|
from fastapi.security import OAuth2PasswordBearer
|
2020-07-11 17:32:03 +08:00
|
|
|
from starlette.websockets import WebSocketDisconnect
|
2020-08-10 13:06:02 +08:00
|
|
|
from fastapi import Body, Header, Response, WebSocket as FastAPIWebSocket
|
2020-07-04 22:51:10 +08:00
|
|
|
|
2020-07-05 20:39:34 +08:00
|
|
|
from nonebot.log import logger
|
2020-08-10 13:06:02 +08:00
|
|
|
from nonebot.config import Env, Config
|
|
|
|
from nonebot.utils import DataclassEncoder
|
|
|
|
from nonebot.typing import Optional, overrides
|
2020-08-06 17:19:06 +08:00
|
|
|
from nonebot.adapters.cqhttp import Bot as CQBot
|
2020-08-01 22:03:40 +08:00
|
|
|
from nonebot.drivers import BaseDriver, BaseWebSocket
|
2020-07-04 22:51:10 +08:00
|
|
|
|
|
|
|
|
|
|
|
class Driver(BaseDriver):
|
|
|
|
|
2020-08-10 13:06:02 +08:00
|
|
|
def __init__(self, env: Env, config: Config):
|
|
|
|
super().__init__(env, config)
|
2020-08-07 17:51:57 +08:00
|
|
|
|
2020-07-04 22:51:10 +08:00
|
|
|
self._server_app = FastAPI(
|
|
|
|
debug=config.debug,
|
|
|
|
openapi_url=None,
|
|
|
|
docs_url=None,
|
|
|
|
redoc_url=None,
|
|
|
|
)
|
|
|
|
|
2020-07-11 17:32:03 +08:00
|
|
|
self._server_app.post("/{adapter}/")(self._handle_http)
|
|
|
|
self._server_app.post("/{adapter}/http")(self._handle_http)
|
|
|
|
self._server_app.websocket("/{adapter}/ws")(self._handle_ws_reverse)
|
|
|
|
self._server_app.websocket("/{adapter}/ws/")(self._handle_ws_reverse)
|
2020-07-05 20:39:34 +08:00
|
|
|
|
2020-07-04 22:51:10 +08:00
|
|
|
@property
|
2020-08-07 17:51:57 +08:00
|
|
|
@overrides(BaseDriver)
|
2020-07-04 22:51:10 +08:00
|
|
|
def server_app(self):
|
|
|
|
return self._server_app
|
|
|
|
|
|
|
|
@property
|
2020-08-07 17:51:57 +08:00
|
|
|
@overrides(BaseDriver)
|
2020-07-04 22:51:10 +08:00
|
|
|
def asgi(self):
|
|
|
|
return self._server_app
|
|
|
|
|
|
|
|
@property
|
2020-08-07 17:51:57 +08:00
|
|
|
@overrides(BaseDriver)
|
2020-08-01 22:03:40 +08:00
|
|
|
def logger(self) -> logging.Logger:
|
2020-07-04 22:51:10 +08:00
|
|
|
return logging.getLogger("fastapi")
|
|
|
|
|
2020-08-07 17:51:57 +08:00
|
|
|
@overrides(BaseDriver)
|
2020-07-04 22:51:10 +08:00
|
|
|
def run(self,
|
|
|
|
host: Optional[IPv4Address] = None,
|
|
|
|
port: Optional[int] = None,
|
|
|
|
*,
|
|
|
|
app: Optional[str] = None,
|
|
|
|
**kwargs):
|
|
|
|
LOGGING_CONFIG = {
|
|
|
|
"version": 1,
|
|
|
|
"disable_existing_loggers": False,
|
|
|
|
"formatters": {
|
|
|
|
"default": {
|
|
|
|
"()": "logging.Formatter",
|
|
|
|
"fmt": "[%(asctime)s %(name)s] %(levelname)s: %(message)s",
|
|
|
|
},
|
|
|
|
},
|
|
|
|
"handlers": {
|
|
|
|
"default": {
|
|
|
|
"formatter": "default",
|
|
|
|
"class": "logging.StreamHandler",
|
|
|
|
"stream": "ext://sys.stdout",
|
|
|
|
},
|
|
|
|
},
|
|
|
|
"loggers": {
|
|
|
|
"uvicorn.error": {
|
|
|
|
"handlers": ["default"],
|
|
|
|
"level": "INFO"
|
|
|
|
},
|
|
|
|
"uvicorn.access": {
|
|
|
|
"handlers": ["default"],
|
|
|
|
"level": "INFO",
|
|
|
|
},
|
|
|
|
},
|
|
|
|
}
|
|
|
|
uvicorn.run(app or self.server_app,
|
|
|
|
host=host or str(self.config.host),
|
|
|
|
port=port or self.config.port,
|
|
|
|
reload=app and self.config.debug,
|
|
|
|
debug=self.config.debug,
|
|
|
|
log_config=LOGGING_CONFIG,
|
|
|
|
**kwargs)
|
2020-07-05 20:39:34 +08:00
|
|
|
|
2020-08-07 17:51:57 +08:00
|
|
|
@overrides(BaseDriver)
|
2020-07-15 20:39:59 +08:00
|
|
|
async def _handle_http(self,
|
|
|
|
adapter: str,
|
2020-08-10 13:06:02 +08:00
|
|
|
response: Response,
|
2020-07-15 20:39:59 +08:00
|
|
|
data: dict = Body(...),
|
2020-08-10 13:06:02 +08:00
|
|
|
x_self_id: int = Header(None),
|
2020-07-15 20:39:59 +08:00
|
|
|
access_token: str = OAuth2PasswordBearer(
|
|
|
|
"/", auto_error=False)):
|
2020-07-11 17:32:03 +08:00
|
|
|
# TODO: Check authorization
|
2020-08-10 13:06:02 +08:00
|
|
|
|
|
|
|
# Create Bot Object
|
2020-08-06 17:19:06 +08:00
|
|
|
if adapter == "cqhttp":
|
2020-08-10 13:06:02 +08:00
|
|
|
bot = CQBot("http", self.config, x_self_id)
|
|
|
|
else:
|
|
|
|
response.status_code = status.HTTP_404_NOT_FOUND
|
|
|
|
return {"status": 404, "message": "adapter not found"}
|
|
|
|
|
|
|
|
await bot.handle_message(data)
|
2020-07-05 20:39:34 +08:00
|
|
|
return {"status": 200, "message": "success"}
|
|
|
|
|
2020-08-07 17:51:57 +08:00
|
|
|
@overrides(BaseDriver)
|
2020-07-15 20:39:59 +08:00
|
|
|
async def _handle_ws_reverse(self,
|
|
|
|
adapter: str,
|
|
|
|
websocket: FastAPIWebSocket,
|
2020-08-10 13:06:02 +08:00
|
|
|
x_self_id: int = Header(None),
|
2020-07-15 20:39:59 +08:00
|
|
|
access_token: str = OAuth2PasswordBearer(
|
|
|
|
"/", auto_error=False)):
|
|
|
|
websocket = WebSocket(websocket)
|
|
|
|
|
2020-07-11 17:32:03 +08:00
|
|
|
# TODO: Check authorization
|
2020-08-01 22:03:40 +08:00
|
|
|
|
|
|
|
# Create Bot Object
|
|
|
|
if adapter == "coolq":
|
2020-08-10 13:06:02 +08:00
|
|
|
bot = CQBot("websocket",
|
|
|
|
self.config,
|
|
|
|
x_self_id,
|
|
|
|
websocket=websocket)
|
2020-08-01 22:03:40 +08:00
|
|
|
else:
|
|
|
|
await websocket.close(code=status.WS_1003_UNSUPPORTED_DATA)
|
|
|
|
return
|
|
|
|
|
2020-07-05 20:39:34 +08:00
|
|
|
await websocket.accept()
|
2020-08-10 13:06:02 +08:00
|
|
|
self._clients[x_self_id] = bot
|
2020-07-15 20:39:59 +08:00
|
|
|
|
|
|
|
while not websocket.closed:
|
|
|
|
data = await websocket.receive()
|
|
|
|
|
|
|
|
if not data:
|
2020-07-05 20:39:34 +08:00
|
|
|
continue
|
|
|
|
|
2020-08-01 22:03:40 +08:00
|
|
|
await bot.handle_message(data)
|
|
|
|
|
2020-08-10 13:06:02 +08:00
|
|
|
del self._clients[x_self_id]
|
2020-07-15 20:39:59 +08:00
|
|
|
|
|
|
|
|
|
|
|
class WebSocket(BaseWebSocket):
|
|
|
|
|
|
|
|
def __init__(self, websocket: FastAPIWebSocket):
|
|
|
|
super().__init__(websocket)
|
|
|
|
self._closed = None
|
|
|
|
|
|
|
|
@property
|
2020-08-07 17:51:57 +08:00
|
|
|
@overrides(BaseWebSocket)
|
2020-07-15 20:39:59 +08:00
|
|
|
def closed(self):
|
|
|
|
return self._closed
|
|
|
|
|
2020-08-07 17:51:57 +08:00
|
|
|
@overrides(BaseWebSocket)
|
2020-07-15 20:39:59 +08:00
|
|
|
async def accept(self):
|
|
|
|
await self.websocket.accept()
|
|
|
|
self._closed = False
|
|
|
|
|
2020-08-07 17:51:57 +08:00
|
|
|
@overrides(BaseWebSocket)
|
2020-08-01 22:03:40 +08:00
|
|
|
async def close(self, code: int = status.WS_1000_NORMAL_CLOSURE):
|
|
|
|
await self.websocket.close(code=code)
|
2020-07-15 20:39:59 +08:00
|
|
|
self._closed = True
|
|
|
|
|
2020-08-07 17:51:57 +08:00
|
|
|
@overrides(BaseWebSocket)
|
2020-07-15 20:39:59 +08:00
|
|
|
async def receive(self) -> Optional[dict]:
|
|
|
|
data = None
|
|
|
|
try:
|
|
|
|
data = await self.websocket.receive_json()
|
|
|
|
except ValueError:
|
|
|
|
logger.debug("Received an invalid json message.")
|
|
|
|
except WebSocketDisconnect:
|
|
|
|
self._closed = True
|
|
|
|
logger.error("WebSocket disconnected by peer.")
|
|
|
|
|
|
|
|
return data
|
|
|
|
|
2020-08-07 17:51:57 +08:00
|
|
|
@overrides(BaseWebSocket)
|
2020-07-15 20:39:59 +08:00
|
|
|
async def send(self, data: dict) -> None:
|
2020-08-10 13:06:02 +08:00
|
|
|
text = json.dumps(data, cls=DataclassEncoder)
|
|
|
|
await self.websocket.send({"type": "websocket.send", "text": text})
|