Skip to content

Fix top event throws uncaught exceptions #107

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Aug 16, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 0 additions & 3 deletions src/OneBot/Config/Loader/AbstractFileLoader.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,6 @@

abstract class AbstractFileLoader implements LoaderInterface
{
/**
* {@inheritDoc}
*/
public function load($source): array
{
// TODO: flexible base path
Expand Down
3 changes: 0 additions & 3 deletions src/OneBot/Config/Loader/DelegateLoader.php
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,6 @@ public function __construct(array $loaders = null)
$this->loaders = $loaders ?? self::getDefaultLoaders();
}

/**
* {@inheritDoc}
*/
public function load($source): array
{
return $this->determineLoader($source)->load($source);
Expand Down
3 changes: 0 additions & 3 deletions src/OneBot/Config/Loader/JsonFileLoader.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,6 @@

class JsonFileLoader extends AbstractFileLoader
{
/**
* {@inheritDoc}
*/
protected function loadFile(string $file)
{
try {
Expand Down
12 changes: 0 additions & 12 deletions src/OneBot/Config/Repository.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,6 @@ public function __construct(array $config = [])
$this->config = $config;
}

/**
* {@inheritDoc}
*/
public function get(string $key, $default = null)
{
// 在表层直接查找,找到就直接返回
Expand Down Expand Up @@ -51,9 +48,6 @@ public function get(string $key, $default = null)
return $data;
}

/**
* {@inheritDoc}
*/
public function set(string $key, $value): void
{
if ($value === null) {
Expand All @@ -75,17 +69,11 @@ public function set(string $key, $value): void
$data = $value;
}

/**
* {@inheritDoc}
*/
public function has(string $key): bool
{
return $this->get($key) !== null;
}

/**
* {@inheritDoc}
*/
public function all(): array
{
return $this->config;
Expand Down
3 changes: 0 additions & 3 deletions src/OneBot/Driver/Event/DriverEvent.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,6 @@ public static function getName(): string
return static::$custom_name ?? static::class;
}

/**
* {@inheritDoc}
*/
public function isPropagationStopped(): bool
{
return $this->propagation_stopped;
Expand Down
15 changes: 0 additions & 15 deletions src/OneBot/Driver/Swoole/EventLoop.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,17 +10,11 @@

class EventLoop extends DriverEventLoopBase
{
/**
* {@inheritDoc}
*/
public function addReadEvent($fd, callable $callable)
{
Event::add($fd, $callable);
}

/**
* {@inheritDoc}
*/
public function delReadEvent($fd)
{
Event::del($fd);
Expand All @@ -36,9 +30,6 @@ public function delWriteEvent($fd)
Event::del($fd);
}

/**
* {@inheritDoc}
*/
public function addTimer(int $ms, callable $callable, int $times = 1, array $arguments = []): int
{
$timer_count = 0;
Expand All @@ -54,17 +45,11 @@ public function addTimer(int $ms, callable $callable, int $times = 1, array $arg
}, ...$arguments);
}

/**
* {@inheritDoc}
*/
public function clearTimer(int $timer_id)
{
Timer::clear($timer_id);
}

/**
* {@inheritDoc}
*/
public function clearAllTimer()
{
Timer::clearAll();
Expand Down
3 changes: 0 additions & 3 deletions src/OneBot/Driver/Swoole/Socket/WSServerSocket.php
Original file line number Diff line number Diff line change
Expand Up @@ -27,9 +27,6 @@ public function close($fd): bool
return false;
}

/**
* {@inheritDoc}
*/
public function send($data, $fd): bool
{
if ($data instanceof FrameInterface) {
Expand Down
3 changes: 0 additions & 3 deletions src/OneBot/Driver/Swoole/SwooleDriver.php
Original file line number Diff line number Diff line change
Expand Up @@ -59,9 +59,6 @@ public function getEventLoop(): DriverEventLoopBase
return EventLoop::getInstance();
}

/**
* {@inheritDoc}
*/
public function initInternalDriverClasses(?array $http, ?array $http_webhook, ?array $ws, ?array $ws_reverse): array
{
if (!empty($ws)) {
Expand Down
203 changes: 106 additions & 97 deletions src/OneBot/Driver/Swoole/TopEventListener.php
Original file line number Diff line number Diff line change
Expand Up @@ -83,38 +83,38 @@ public function onWorkerExit()
*/
public function onRequest(array $config, Request $request, Response $response)
{
ob_logger()->debug('Http request: ' . $request->server['request_uri']);
if (empty($content = $request->rawContent()) && $content !== '0') { // empty 遇到纯0的请求会返回true,所以这里加上 !== '0'
$content = null;
}
$req = HttpFactory::createServerRequest(
$request->server['request_method'],
$request->server['request_uri'],
$request->header,
$content
);
$req = $req->withQueryParams($request->get ?? [])
->withCookieParams($request->cookie ?? []);
$uploaded = [];
// 上传的文件
if (!empty($request->files)) {
foreach ($request->files as $key => $value) {
$upload = new UploadedFile([
'key' => $key,
...$value,
]);
$uploaded[] = $upload;
try {
ob_logger()->debug('Http request: ' . $request->server['request_uri']);
if (empty($content = $request->rawContent()) && $content !== '0') { // empty 遇到纯0的请求会返回true,所以这里加上 !== '0'
$content = null;
}
if ($uploaded !== []) {
$req = $req->withUploadedFiles($uploaded);
$req = HttpFactory::createServerRequest(
$request->server['request_method'],
$request->server['request_uri'],
$request->header,
$content
);
$req = $req->withQueryParams($request->get ?? [])
->withCookieParams($request->cookie ?? []);
$uploaded = [];
// 上传的文件
if (!empty($request->files)) {
foreach ($request->files as $key => $value) {
$upload = new UploadedFile([
'key' => $key,
...$value,
]);
$uploaded[] = $upload;
}
if ($uploaded !== []) {
$req = $req->withUploadedFiles($uploaded);
}
}
}
// post 包体
if (!empty($request->post)) {
$req = $req->withParsedBody($request->post);
}
$event = new HttpRequestEvent($req);
try {
// post 包体
if (!empty($request->post)) {
$req = $req->withParsedBody($request->post);
}
$event = new HttpRequestEvent($req);
$event->setSocketConfig($config);
ob_event_dispatcher()->dispatch($event);
if (($psr_response = $event->getResponse()) !== null) {
Expand All @@ -128,7 +128,7 @@ public function onRequest(array $config, Request $request, Response $response)
}
} catch (\Throwable $e) {
ExceptionHandler::getInstance()->handle($e);
if (is_callable($event->getErrorHandler())) {
if (isset($event) && is_callable($event->getErrorHandler())) {
$err_response = call_user_func($event->getErrorHandler(), $e, $event);
if ($err_response instanceof ResponseInterface) {
foreach ($err_response->getHeaders() as $header => $value) {
Expand Down Expand Up @@ -164,88 +164,97 @@ public function onClose(array $config, ?Server $server, $fd)
*/
public function onHandshake(array $config, Request $request, Response $response)
{
ob_logger()->debug('WebSocket connection handahske: ' . $request->fd);
if (empty($content = $request->rawContent())) {
$content = null;
}
$event = new WebSocketOpenEvent(HttpFactory::createServerRequest(
$request->server['request_method'],
$request->server['request_uri'],
$request->header,
$content
), $request->fd);
$event->setSocketConfig($config);
ob_event_dispatcher()->dispatchWithHandler($event);
// 检查有没有制定response
if (is_object($event->getResponse())) {
$user_resp = $event->getResponse();
// 不等于 101 bu不握手
if ($user_resp->getStatusCode() !== 101) {
try {
ob_logger()->debug('WebSocket connection handahske: ' . $request->fd);
if (empty($content = $request->rawContent())) {
$content = null;
}
$event = new WebSocketOpenEvent(HttpFactory::createServerRequest(
$request->server['request_method'],
$request->server['request_uri'],
$request->header,
$content
), $request->fd);
$event->setSocketConfig($config);
ob_event_dispatcher()->dispatchWithHandler($event);
// 检查有没有制定response
if (is_object($event->getResponse())) {
$user_resp = $event->getResponse();
// 不等于 101 bu不握手
if ($user_resp->getStatusCode() !== 101) {
foreach ($user_resp->getHeaders() as $header => $value) {
if (is_array($value)) {
$response->setHeader($header, implode(';', $value));
}
}
$response->setStatusCode($user_resp->getStatusCode());
$response->end($user_resp->getBody()->getContents());
return false;
}
// 等于 101 时候,检查把 Header 合进来
$my_headers = [];
foreach ($user_resp->getHeaders() as $header => $value) {
if (is_array($value)) {
$response->setHeader($header, implode(';', $value));
$my_headers[$header] = implode(';', $value);
}
}
$response->setStatusCode($user_resp->getStatusCode());
$response->end($user_resp->getBody()->getContents());
}
// 手动实现握手
// websocket握手连接算法验证
$sec_websocket_key = $request->header['sec-websocket-key'];
$patten = '#^[+/0-9A-Za-z]{21}[AQgw]==$#';
if (preg_match($patten, $sec_websocket_key) === 0 || strlen(base64_decode($sec_websocket_key)) !== 16) {
$response->end();
return false;
}
// 等于 101 时候,检查把 Header 合进来
$my_headers = [];
foreach ($user_resp->getHeaders() as $header => $value) {
if (is_array($value)) {
$my_headers[$header] = implode(';', $value);
}
echo $request->header['sec-websocket-key'];
$key = base64_encode(
sha1(
$request->header['sec-websocket-key'] . '258EAFA5-E914-47DA-95CA-C5AB0DC85B11',
true
)
);
$headers = [
'Upgrade' => 'websocket',
'Connection' => 'Upgrade',
'Sec-WebSocket-Accept' => $key,
'Sec-WebSocket-Version' => '13',
];
if (isset($my_headers)) {
$headers = array_merge($headers, $my_headers);
}
}
// 手动实现握手
// websocket握手连接算法验证
$sec_websocket_key = $request->header['sec-websocket-key'];
$patten = '#^[+/0-9A-Za-z]{21}[AQgw]==$#';
if (preg_match($patten, $sec_websocket_key) === 0 || strlen(base64_decode($sec_websocket_key)) !== 16) {
foreach ($headers as $key => $val) {
$response->header($key, $val);
}

$response->status(101);
$response->end();
return true;
} catch (\Throwable $e) {
ExceptionHandler::getInstance()->handle($e);
return false;
}
echo $request->header['sec-websocket-key'];
$key = base64_encode(
sha1(
$request->header['sec-websocket-key'] . '258EAFA5-E914-47DA-95CA-C5AB0DC85B11',
true
)
);
$headers = [
'Upgrade' => 'websocket',
'Connection' => 'Upgrade',
'Sec-WebSocket-Accept' => $key,
'Sec-WebSocket-Version' => '13',
];
if (isset($my_headers)) {
$headers = array_merge($headers, $my_headers);
}
foreach ($headers as $key => $val) {
$response->header($key, $val);
}

$response->status(101);
$response->end();
return true;
}

/**
* Swoole 的顶层 message 事件回调(WebSocket 消息事件)
*/
public function onMessage(array $config, ?SwooleWebSocketServer $server, Frame $frame)
{
ob_logger()->debug('WebSocket message from: ' . $frame->fd);
$new_frame = new \Choir\WebSocket\Frame($frame->data, $frame->opcode, true, true);
$event = new WebSocketMessageEvent($frame->fd, $new_frame, function (int $fd, $data) use ($server) {
if ($data instanceof FrameInterface) {
return $server->push($fd, $data->getData(), $data->getOpcode());
}
return $server->push($fd, $data);
});
$event->setOriginFrame($frame);
$event->setSocketConfig($config);
ob_event_dispatcher()->dispatchWithHandler($event);
try {
ob_logger()->debug('WebSocket message from: ' . $frame->fd);
$new_frame = new \Choir\WebSocket\Frame($frame->data, $frame->opcode, true, true);
$event = new WebSocketMessageEvent($frame->fd, $new_frame, function (int $fd, $data) use ($server) {
if ($data instanceof FrameInterface) {
return $server->push($fd, $data->getData(), $data->getOpcode());
}
return $server->push($fd, $data);
});
$event->setOriginFrame($frame);
$event->setSocketConfig($config);
ob_event_dispatcher()->dispatchWithHandler($event);
} catch (\Throwable $e) {
ExceptionHandler::getInstance()->handle($e);
}
}
}
Loading