mirror of
https://github.com/zhamao-robot/zhamao-framework.git
synced 2026-07-20 23:25:35 +08:00
Compare commits
68 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
eed670cb50 | ||
|
|
9e824d960f | ||
|
|
992b6020a5 | ||
|
|
d51dbef437 | ||
|
|
7f058638bd | ||
|
|
c04130fed1 | ||
|
|
7fefcb850a | ||
|
|
1fe54d4b94 | ||
|
|
13a32bec79 | ||
|
|
0f5786c8c4 | ||
|
|
4ed046769f | ||
|
|
690980f72d | ||
|
|
f025eeb34a | ||
|
|
d642f50ef1 | ||
|
|
2900754307 | ||
|
|
dffeac668d | ||
|
|
b6756179f5 | ||
|
|
1adcf76203 | ||
|
|
5b003ab575 | ||
|
|
75f6aa531e | ||
|
|
6e1f4820f8 | ||
|
|
50ce81334b | ||
|
|
0ed0aa089a | ||
|
|
102ba769ec | ||
|
|
e062f484b1 | ||
|
|
3be3e8412a | ||
|
|
ab5abf1c00 | ||
|
|
3aaa72cfb9 | ||
|
|
10f846c214 | ||
|
|
67a42c4be9 | ||
|
|
7e4e58a322 | ||
|
|
5de283d30c | ||
|
|
7513fd1a1d | ||
|
|
c635891e0b | ||
|
|
7b7a2d7010 | ||
|
|
23b1f797ad | ||
|
|
a72e0f705c | ||
|
|
504934f057 | ||
|
|
e976a96d0b | ||
|
|
dc7af105f4 | ||
|
|
fd96543268 | ||
|
|
cebc6fb310 | ||
|
|
c654cf40d5 | ||
|
|
68cc536af3 | ||
|
|
42412fee98 | ||
|
|
500ec4707e | ||
|
|
b09857e3b8 | ||
|
|
7d79126c8f | ||
|
|
a542558503 | ||
|
|
6697591a22 | ||
|
|
aad28f1ec4 | ||
|
|
f1949b1bd0 | ||
|
|
3b8aac5d8f | ||
|
|
5fd45c2542 | ||
|
|
af89c1b1f6 | ||
|
|
3287b96f30 | ||
|
|
00a8683658 | ||
|
|
c0ea068d04 | ||
|
|
9ba58ff90f | ||
|
|
1a1cf0ad30 | ||
|
|
1de93b9dc1 | ||
|
|
99e44eea3d | ||
|
|
e67958a8d1 | ||
|
|
23b3dc34e2 | ||
|
|
775672d515 | ||
|
|
40e17fab62 | ||
|
|
59fde3d075 | ||
|
|
a8183757be |
46
README.md
46
README.md
@@ -1,32 +1,45 @@
|
|||||||
# zhamao-framework
|
<div align="center">
|
||||||
|
<img src="/resources/images/logo_trans.png" height = "150" alt="炸毛框架"><br>
|
||||||
|
<h2>炸毛框架</h2>
|
||||||
|
炸毛框架 (zhamao-frameowork) 是一个协程高性能的聊天机器人 + Web 服务器开发框架<br><br>
|
||||||
|
|
||||||
[]()
|
[]()
|
||||||
[](https://github.com/zhamao-robot/zhamao-framework/blob/master/LICENSE)
|
[](https://github.com/zhamao-robot/zhamao-framework/blob/master/LICENSE)
|
||||||
[]()
|
[](https://packagist.org/packages/zhamao/framework)
|
||||||
|
[]()
|
||||||
|
[]()
|
||||||
|
|
||||||
[](https://github.com/zhamao-robot/zhamao-framework/search?q=stupid)
|
[](https://github.com/zhamao-robot/zhamao-framework/search?q=stupid)
|
||||||
[](https://github.com/zhamao-robot/zhamao-framework/search?q=TODO)
|
[](https://github.com/zhamao-robot/zhamao-framework/search?q=TODO)
|
||||||
|
|
||||||
协程高性能的 **QQ 机器人 + Web 服务器** 开发框架(炸毛框架)。
|
</div>
|
||||||
|
|
||||||
<img src="https://avatars0.githubusercontent.com/u/48620312" height = "200" alt="炸毛框架" align=center/>
|
## 开发者注意
|
||||||
|
**v2.0 版本已经开始公测了,但是文档还在光速编写中,可以现行进行测试!**
|
||||||
|
|
||||||
|
**炸毛框架目前经过实验可以直接在 PHP8 环境上运行,但是细节部分未经充分测试,如果在 PHP8 环境下运行出现问题,请及时提出 Issue,谢谢!**
|
||||||
|
|
||||||
|
**由于 CQHTTP 不再提供维护,转为 [OneBot 标准](https://github.com/howmanybots/onebot)(原 CQHTTP 插件衍生而来的机器人 HTTP 接口标准),本框架也将在未来改为兼容此标准。**
|
||||||
|
|
||||||
|
**以上涉及的变更将在下一个大版本 (v2.0.0) 更新,请关注 2.0-dev 分支 和 Project 模块!**
|
||||||
|
|
||||||
|
**v2.0版本即将到来,请持续关注 [新文档](https://docs-v2.zhamao.xin/) 进度和 Project 模块展示的测试进度!**
|
||||||
|
|
||||||
## 简介
|
## 简介
|
||||||
zhamao-framework 是一个基于 酷Q 的 PHP Swoole 的机器人框架,它会对 QQ 机器人收到的消息进行解析处理,并以模块化的形式进行开发,来完成机器人的自然语言对话等功能。
|
zhamao-framework 是一个 PHP Swoole 的聊天机器人框架,兼容 OneBot 标准,它会对微信公众号等终端收到的消息进行解析处理,并以模块化的形式进行开发,来完成机器人的自然语言对话等功能。
|
||||||
|
|
||||||
框架对接 酷Q 的桥梁是 **CQHTTP** 插件,这里是它的[项目地址](https://github.com/richardchien/coolq-http-api/)。
|
|
||||||
|
|
||||||
除了起到解析消息的作用,炸毛框架 还提供了完整的 WebSocket + HTTP 服务器,你还能用此框架构建出高性能的 API 接口服务器。
|
除了起到解析消息的作用,炸毛框架 还提供了完整的 WebSocket + HTTP 服务器,你还能用此框架构建出高性能的 API 接口服务器。
|
||||||
|
|
||||||
## 开始
|
## 开始
|
||||||
1. 你可以使用项目的 `Use this template` 功能将框架克隆到你的公开或私有仓库进行开发
|
先安装环境,环境安装见下方文档。
|
||||||
2. 你也可以直接到 **Release** 中下载最新的 phar 包,放入文件夹后快速启动框架
|
1. `composer create-project zhamao/framework-starter` 从模板新建基础文档结构进行使用
|
||||||
|
2. 你也可以直接拉取本项目,进入文件夹后 `composer update` 加载依赖后使用 `bin/start init` 快速初始化框架文件
|
||||||
3. 还可以使用 Dockerfile 构建 Docker 容器
|
3. 还可以使用 Dockerfile 构建 Docker 容器
|
||||||
|
|
||||||
## 文档
|
## 文档 (v1.x)
|
||||||
Pages托管:[https://framework.zhamao.xin/](https://framework.zhamao.xin/)
|
国内服务器:[https://docs-v1.zhamao.xin/](https://docs-v1.zhamao.xin/)
|
||||||
|
|
||||||
国内服务器:[https://framework2.zhamao.xin/](https://framework2.zhamao.xin/)
|
GitHub Pages:[https://docs-v1.zhamao.me/](https://docs-v1.zhamao.me/)
|
||||||
|
|
||||||
## 特点
|
## 特点
|
||||||
- 支持多账号
|
- 支持多账号
|
||||||
@@ -44,7 +57,6 @@ Pages托管:[https://framework.zhamao.xin/](https://framework.zhamao.xin/)
|
|||||||
|
|
||||||
| 模块名称 | 说明 | 模块地址 |
|
| 模块名称 | 说明 | 模块地址 |
|
||||||
| ------------------ | -------------------------------- | ------------------------------------------------------------ |
|
| ------------------ | -------------------------------- | ------------------------------------------------------------ |
|
||||||
| 微信公众号兼容模块 | 为框架提供微信公众号订阅号兼容层 | [zhamao-wechat-patch](https://github.com/zhamao-robot/zhamao-wechat-patch) |
|
|
||||||
| 通用模块 | 图片上传和下载模块 | [zhamao-general-tools](https://github.com/zhamao-robot/zhamao-general-tools) |
|
| 通用模块 | 图片上传和下载模块 | [zhamao-general-tools](https://github.com/zhamao-robot/zhamao-general-tools) |
|
||||||
|
|
||||||
## 计划开发内容
|
## 计划开发内容
|
||||||
@@ -78,11 +90,15 @@ Pages托管:[https://framework.zhamao.xin/](https://framework.zhamao.xin/)
|
|||||||
### 支付宝
|
### 支付宝
|
||||||

|

|
||||||
|
|
||||||
|
如果你对我们的周边感兴趣,我们还有炸毛机器人定制 logo 的雨伞,详情咨询作者 QQ,我们会作为您捐助了本项目!
|
||||||
|
|
||||||
## 关于
|
## 关于
|
||||||
框架和 SDK 是 炸毛机器人 项目的核心框架开源部分。炸毛机器人(3276124472)是作者写的一个高性能机器人,曾获全国计算机设计大赛一等奖。
|
框架和 SDK 是 炸毛机器人 项目的核心框架开源部分。炸毛机器人是作者写的一个高性能机器人,曾获全国计算机设计大赛一等奖。
|
||||||
|
|
||||||
欢迎随时在 HTTP-API 插件群里提问,当然更好的话可以加作者 QQ(627577391)或提交 Issue 进行疑难解答。
|
欢迎随时在 HTTP-API 插件群里提问,当然更好的话可以加作者 QQ(627577391)或提交 Issue 进行疑难解答。
|
||||||
|
|
||||||
本项目在更行内容时,请及时关注 GitHub 动态,更新前请将自己的模块代码做好备份。
|
本项目在更新内容时,请及时关注 GitHub 动态,更新前请将自己的模块代码做好备份。
|
||||||
|
|
||||||
项目框架采用 Apache-2.0 协议开源,在分发或重写修改等操作时需遵守协议。项目模块部分(`Module` 文件夹) 在非借鉴框架内代码时可不遵守 Apache-2.0 协议进行分发和修改(声明版权)。
|
项目框架采用 Apache-2.0 协议开源,在分发或重写修改等操作时需遵守协议。项目模块部分(`Module` 文件夹) 在非借鉴框架内代码时可不遵守 Apache-2.0 协议进行分发和修改(声明版权)。
|
||||||
|
|
||||||
|
**注意**:在你使用 mirai 等 `AGPL-3.0` 协议的机器人软件与框架连接时,使用本框架需要将你编写或修改的部分使用 `AGPL-3.0` 协议重新分发。
|
||||||
|
|||||||
@@ -4,9 +4,9 @@
|
|||||||
|
|
||||||
| Version | Supported |
|
| Version | Supported |
|
||||||
| ------- | ------------------ |
|
| ------- | ------------------ |
|
||||||
| 1.2.x | :white_check_mark: |
|
| 2.0 | :white_check_mark: |
|
||||||
| 1.1.x | :x: |
|
| 1.6.x | :white_check_mark: |
|
||||||
| 1.0.x | :x: |
|
| 1.x | :x: |
|
||||||
|
|
||||||
## Reporting a Vulnerability
|
## Reporting a Vulnerability
|
||||||
|
|
||||||
|
|||||||
File diff suppressed because one or more lines are too long
92
bin/start
92
bin/start
@@ -10,6 +10,14 @@ require __DIR__ . '/../src/Scheduler/Scheduler.php';
|
|||||||
Swoole\Coroutine::set([
|
Swoole\Coroutine::set([
|
||||||
'max_coroutine' => 30000,
|
'max_coroutine' => 30000,
|
||||||
]);
|
]);
|
||||||
|
global $vendor_mode;
|
||||||
|
$vendor_mode = false;
|
||||||
|
if (mb_strpos(__DIR__, getcwd()) !== false && substr(str_replace(getcwd(), "", __DIR__), 0, 8) == "/vendor/") {
|
||||||
|
define("LOAD_MODE", 1); //composer项目模式
|
||||||
|
define("LOAD_MODE_COMPOSER_PATH", getcwd());
|
||||||
|
} else {
|
||||||
|
define("LOAD_MODE", 0); //正常模式
|
||||||
|
}
|
||||||
|
|
||||||
date_default_timezone_set("Asia/Shanghai");
|
date_default_timezone_set("Asia/Shanghai");
|
||||||
|
|
||||||
@@ -24,13 +32,86 @@ switch ($argv[1] ?? '') {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
break;
|
break;
|
||||||
|
case 'phar-build':
|
||||||
|
array_shift($argv);
|
||||||
|
require_once 'phar-build';
|
||||||
|
break;
|
||||||
|
case 'systemd':
|
||||||
|
array_shift($argv);
|
||||||
|
require_once 'systemd';
|
||||||
|
break;
|
||||||
|
case 'init':
|
||||||
|
array_shift($argv);
|
||||||
|
if (LOAD_MODE != 1) {
|
||||||
|
echo "initialization must be started with composer-project mode!\n";
|
||||||
|
exit(1);
|
||||||
|
}
|
||||||
|
$cwd = LOAD_MODE_COMPOSER_PATH;
|
||||||
|
echo "Copying default module file ...";
|
||||||
|
@mkdir($cwd . "/config");
|
||||||
|
@mkdir($cwd . "/src");
|
||||||
|
@mkdir($cwd . "/src/Custom");
|
||||||
|
@mkdir($cwd . "/src/Module");
|
||||||
|
@mkdir($cwd . "/src/Module/Example");
|
||||||
|
@mkdir($cwd . "/src/Module/Middleware");
|
||||||
|
$ls = [
|
||||||
|
"/config/global.php",
|
||||||
|
"/.gitignore",
|
||||||
|
"/config/file_header.json",
|
||||||
|
"/config/motd.txt",
|
||||||
|
"/src/Module/Example/Hello.php",
|
||||||
|
"/src/Module/Middleware/TimerMiddleware.php",
|
||||||
|
"/src/Custom/global_function.php"
|
||||||
|
];
|
||||||
|
foreach($ls as $v) {
|
||||||
|
if(!file_exists($cwd.$v)) {
|
||||||
|
echo "Copying ".$v.PHP_EOL;
|
||||||
|
copy($cwd."/vendor/zhamao/framework".$v, $cwd.$v);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
$autoload = [
|
||||||
|
"psr-4" => [
|
||||||
|
"Module\\" => "src/Module",
|
||||||
|
"Custom\\" => "src/Custom"
|
||||||
|
],
|
||||||
|
"files" => [
|
||||||
|
"src/Custom/global_function.php"
|
||||||
|
]
|
||||||
|
];
|
||||||
|
$scripts = [
|
||||||
|
"server" => "vendor/bin/start server",
|
||||||
|
"server:log-debug" => "vendor/bin/start server --log-debug",
|
||||||
|
"server:log-verbose" => "vendor/bin/start server --log-verbose",
|
||||||
|
"server:log-info" => "vendor/bin/start server --log-info",
|
||||||
|
"server:log-warning" => "vendor/bin/start server --log-warning",
|
||||||
|
"server:debug-mode" => "vendor/bin/start server --debug-mode",
|
||||||
|
"systemd" => "vendor/bin/start systemd"
|
||||||
|
];
|
||||||
|
echo PHP_EOL;
|
||||||
|
if (file_exists($cwd . "/composer.json")) {
|
||||||
|
echo "Updating composer.json ...";
|
||||||
|
$composer = json_decode(file_get_contents($cwd . "/composer.json"), true);
|
||||||
|
if (!isset($composer["autoload"])) {
|
||||||
|
$composer["autoload"] = $autoload;
|
||||||
|
}
|
||||||
|
if (!isset($composer["scripts"])) {
|
||||||
|
$composer["scripts"] = $scripts;
|
||||||
|
}
|
||||||
|
file_put_contents($cwd . "/composer.json", json_encode($composer, 64 | 128 | 256));
|
||||||
|
echo PHP_EOL;
|
||||||
|
} else {
|
||||||
|
echo("Error occurred. Please check your updates.\n");
|
||||||
|
exit(1);
|
||||||
|
}
|
||||||
|
echo "success!\n";
|
||||||
|
break;
|
||||||
case '':
|
case '':
|
||||||
case 'framework':
|
case 'framework':
|
||||||
case 'server':
|
case 'server':
|
||||||
if(!is_dir(__DIR__.'/../vendor/')){
|
if (!is_dir(__DIR__ . '/../vendor/') && LOAD_MODE == 0) {
|
||||||
echo "Warning: you have not update composer!\n";
|
echo "Warning: you have not update composer!\n";
|
||||||
exec("composer update", $out, $var);
|
exec("composer update", $out, $var);
|
||||||
if($var != 0) {
|
if ($var != 0) {
|
||||||
echo "You need to run \"composer update\" at root of zhamao-framework!\n";
|
echo "You need to run \"composer update\" at root of zhamao-framework!\n";
|
||||||
die;
|
die;
|
||||||
}
|
}
|
||||||
@@ -39,10 +120,13 @@ switch ($argv[1] ?? '') {
|
|||||||
break;
|
break;
|
||||||
case '--help':
|
case '--help':
|
||||||
case '-h':
|
case '-h':
|
||||||
echo "\nUsage: ".$argv[0]." [OPTION]\n";
|
echo "\nUsage: " . $argv[0] . " [OPTION]\n";
|
||||||
echo "\nzhamao-framework start script, provides several startup arguments.";
|
echo "\nzhamao-framework start script, provides several startup arguments.";
|
||||||
echo "\n\n -h, --help\t\tShow this help menu";
|
echo "\n\n -h, --help\t\tShow this help menu";
|
||||||
echo "\n framework, server\tstart main framework, this is default option\n\n";
|
echo "\n framework, server\tstart main framework, this is default option";
|
||||||
|
echo "\n phar-build\t\tbuild a new phar archive";
|
||||||
|
echo "\n init\t\t\tinitialize framework structure in this directory";
|
||||||
|
echo "\n systemd\t\tgenerate a new systemd \".service\" file to use\n\n";
|
||||||
break;
|
break;
|
||||||
default:
|
default:
|
||||||
echo "Unknown option \"{$argv[1]}\"!\n\"--help\" for more information\n";
|
echo "Unknown option \"{$argv[1]}\"!\n\"--help\" for more information\n";
|
||||||
|
|||||||
11
bin/systemd
11
bin/systemd
@@ -2,7 +2,8 @@
|
|||||||
<?php /** @since 1.2 */
|
<?php /** @since 1.2 */
|
||||||
switch ($argv[1] ?? '') {
|
switch ($argv[1] ?? '') {
|
||||||
case '--generate':
|
case '--generate':
|
||||||
generate();
|
case '':
|
||||||
|
generate($argv);
|
||||||
break;
|
break;
|
||||||
case '--help':
|
case '--help':
|
||||||
case '-h':
|
case '-h':
|
||||||
@@ -14,13 +15,17 @@ switch ($argv[1] ?? '') {
|
|||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
function generate() {
|
function generate($argv) {
|
||||||
$s = "[Unit]\nDescription=zhamao-framework Daemon\nAfter=rc-local.service\n\n[Service]\nType=simple";
|
$s = "[Unit]\nDescription=zhamao-framework Daemon\nAfter=rc-local.service\n\n[Service]\nType=simple";
|
||||||
$s .= "\nUser=" . exec("whoami");
|
$s .= "\nUser=" . exec("whoami");
|
||||||
$s .= "\nGroup=" . exec("groups | awk '{print $1}'");
|
$s .= "\nGroup=" . exec("groups | awk '{print $1}'");
|
||||||
$s .= "\nWorkingDirectory=" . getcwd();
|
$s .= "\nWorkingDirectory=" . getcwd();
|
||||||
$s .= "\nExecStart=" . getcwd() . "/bin/start server --disable-console-input";
|
if ($argv[0] == "systemd" && !file_exists(getcwd() . '/systemd'))
|
||||||
|
$s .= "\nExecStart=" . getcwd() . "/vendor/bin/start server --disable-console-input";
|
||||||
|
else
|
||||||
|
$s .= "\nExecStart=" . getcwd() . "/bin/start server --disable-console-input";
|
||||||
$s .= "\nRestart=always\n\n[Install]\nWantedBy=multi-user.target\n";
|
$s .= "\nRestart=always\n\n[Install]\nWantedBy=multi-user.target\n";
|
||||||
|
@mkdir(getcwd() . "/resources/");
|
||||||
file_put_contents(getcwd() . "/resources/zhamao.service", $s);
|
file_put_contents(getcwd() . "/resources/zhamao.service", $s);
|
||||||
echo "File successfully generated. Path: " . getcwd() . "/resources/zhamao.service\n";
|
echo "File successfully generated. Path: " . getcwd() . "/resources/zhamao.service\n";
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,3 +0,0 @@
|
|||||||
#!/bin/bash
|
|
||||||
|
|
||||||
composer update
|
|
||||||
@@ -1,9 +1,9 @@
|
|||||||
{
|
{
|
||||||
"name": "zhamao/framework",
|
"name": "zhamao/framework",
|
||||||
"description": "high-performance intelligent assistant",
|
"description": "High performance QQ robot and web server development framework",
|
||||||
"minimum-stability": "stable",
|
"minimum-stability": "stable",
|
||||||
"license": "Apache-2.0",
|
"license": "Apache-2.0",
|
||||||
"version": "1.4.0",
|
"version": "1.6.4",
|
||||||
"authors": [
|
"authors": [
|
||||||
{
|
{
|
||||||
"name": "whale",
|
"name": "whale",
|
||||||
@@ -14,22 +14,26 @@
|
|||||||
"email": "hugo_swift@yahoo.com"
|
"email": "hugo_swift@yahoo.com"
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
|
"prefer-stable": true,
|
||||||
|
"bin": [
|
||||||
|
"bin/start"
|
||||||
|
],
|
||||||
"require": {
|
"require": {
|
||||||
"php": ">=7.2",
|
"php": ">=7.2",
|
||||||
"swoole/ide-helper": "@dev",
|
"swoole/ide-helper": "@dev",
|
||||||
"ext-mbstring": "*",
|
"ext-mbstring": "*",
|
||||||
"swlib/saber": "^1.0",
|
"swlib/saber": "^1.0",
|
||||||
"doctrine/annotations": "<1.10.2",
|
"doctrine/annotations": "~1.10",
|
||||||
"ext-json": "*",
|
"ext-json": "*",
|
||||||
"ext-posix": "*",
|
|
||||||
"ext-ctype": "*",
|
"ext-ctype": "*",
|
||||||
"ext-pdo": "*",
|
|
||||||
"psy/psysh": "@stable"
|
"psy/psysh": "@stable"
|
||||||
},
|
},
|
||||||
"repositories": {
|
"autoload": {
|
||||||
"packagist": {
|
"psr-4": {
|
||||||
"type": "composer",
|
"Framework\\": "src/Framework",
|
||||||
"url": "https://mirrors.aliyun.com/composer/"
|
"ZM\\": "src/ZM",
|
||||||
|
"Module\\": "src/Module",
|
||||||
|
"Custom\\": "src/Custom"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -8,26 +8,27 @@ $config['host'] = '0.0.0.0';
|
|||||||
$config['port'] = 20001;
|
$config['port'] = 20001;
|
||||||
|
|
||||||
/** 框架开到公网或外部的HTTP访问链接,通过 DataProvider::getFrameworkLink() 获取 */
|
/** 框架开到公网或外部的HTTP访问链接,通过 DataProvider::getFrameworkLink() 获取 */
|
||||||
$config['http_reverse_link'] = "http://127.0.0.1:".$config['port'];
|
$config['http_reverse_link'] = "http://127.0.0.1:" . $config['port'];
|
||||||
|
|
||||||
/** 框架是否启动debug模式 */
|
/** 框架是否启动debug模式 */
|
||||||
$config['debug_mode'] = false;
|
$config['debug_mode'] = false;
|
||||||
|
|
||||||
/** 存放框架内文件数据的目录 */
|
/** 存放框架内文件数据的目录 */
|
||||||
$config['zm_data'] = WORKING_DIR.'/zm_data/';
|
$config['zm_data'] = realpath(__DIR__ . "/../") . '/zm_data/';
|
||||||
|
|
||||||
/** 存放各个模块配置文件的目录 */
|
/** 存放各个模块配置文件的目录 */
|
||||||
$config['config_dir'] = $config['zm_data'].'config/';
|
$config['config_dir'] = $config['zm_data'] . 'config/';
|
||||||
|
|
||||||
/** 存放崩溃和运行日志的目录 */
|
/** 存放崩溃和运行日志的目录 */
|
||||||
$config['crash_dir'] = $config['zm_data'].'crash/';
|
$config['crash_dir'] = $config['zm_data'] . 'crash/';
|
||||||
|
|
||||||
/** 对应swoole的server->set参数 */
|
/** 对应swoole的server->set参数 */
|
||||||
$config['swoole'] = [
|
$config['swoole'] = [
|
||||||
'log_file' => $config['crash_dir'].'swoole_error.log',
|
'log_file' => $config['crash_dir'] . 'swoole_error.log',
|
||||||
'worker_num' => 1,
|
'worker_num' => 1,
|
||||||
'dispatch_mode' => 2,
|
'dispatch_mode' => 2,
|
||||||
'task_worker_num' => 0
|
//'task_worker_num' => 1,
|
||||||
|
//'task_enable_coroutine' => true
|
||||||
];
|
];
|
||||||
|
|
||||||
/** MySQL数据库连接信息,host留空则启动时不创建sql连接池 */
|
/** MySQL数据库连接信息,host留空则启动时不创建sql连接池 */
|
||||||
@@ -38,7 +39,13 @@ $config['sql_config'] = [
|
|||||||
'sql_database' => 'db_name',
|
'sql_database' => 'db_name',
|
||||||
'sql_password' => '',
|
'sql_password' => '',
|
||||||
'sql_enable_cache' => true,
|
'sql_enable_cache' => true,
|
||||||
'sql_reset_cache' => '0300'
|
'sql_reset_cache' => '0300',
|
||||||
|
'sql_options' => [
|
||||||
|
PDO::ATTR_STRINGIFY_FETCHES => false,
|
||||||
|
PDO::ATTR_EMULATE_PREPARES => false
|
||||||
|
],
|
||||||
|
'sql_no_exception' => false,
|
||||||
|
'sql_default_fetch_mode' => PDO::FETCH_BOTH // added in 1.5.6
|
||||||
];
|
];
|
||||||
|
|
||||||
/** CQHTTP连接约定的token */
|
/** CQHTTP连接约定的token */
|
||||||
@@ -73,10 +80,15 @@ $config['context_class'] = \ZM\Context\Context::class;
|
|||||||
/** 静态文件访问 */
|
/** 静态文件访问 */
|
||||||
$config['static_file_server'] = [
|
$config['static_file_server'] = [
|
||||||
'status' => false,
|
'status' => false,
|
||||||
'document_root' => WORKING_DIR . '/resources/html',
|
'document_root' => realpath(__DIR__ . "/../") . '/resources/html',
|
||||||
'document_index' => [
|
'document_index' => [
|
||||||
'index.html'
|
'index.html'
|
||||||
]
|
]
|
||||||
];
|
];
|
||||||
|
|
||||||
|
/** 注册 Swoole Server 事件注解的类列表 */
|
||||||
|
$config['server_event_handler_class'] = [
|
||||||
|
\Framework\ServerEventHandler::class,
|
||||||
|
];
|
||||||
|
|
||||||
return $config;
|
return $config;
|
||||||
|
|||||||
@@ -30,6 +30,8 @@ Swoole\Coroutine::set([
|
|||||||
date_default_timezone_set("Asia/Shanghai");
|
date_default_timezone_set("Asia/Shanghai");
|
||||||
|
|
||||||
define('WORKING_DIR', __DIR__);
|
define('WORKING_DIR', __DIR__);
|
||||||
|
define('FRAMEWORK_DIR', __DIR__);
|
||||||
|
define('LOAD_MODE', 2);
|
||||||
|
|
||||||
$s = new FrameworkLoader($argv);
|
$s = new FrameworkLoader($argv);
|
||||||
|
|
||||||
|
|||||||
BIN
resources/images/logo_trans.png
Normal file
BIN
resources/images/logo_trans.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 61 KiB |
@@ -1,7 +1,3 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
//这里写你的全局函数
|
//这里写你的全局函数
|
||||||
|
|
||||||
function phptest(){
|
|
||||||
echo "Nothing.\n";
|
|
||||||
}
|
|
||||||
@@ -184,7 +184,8 @@ class Console
|
|||||||
$vss->callback = function(?WSConnection $conn) use ($terminal_id){
|
$vss->callback = function(?WSConnection $conn) use ($terminal_id){
|
||||||
$req = ctx()->getRequest();
|
$req = ctx()->getRequest();
|
||||||
if($conn->getType() != "terminal") return false;
|
if($conn->getType() != "terminal") return false;
|
||||||
if(($req->header["x-terminal-id"] ?? "") != $terminal_id || ($req->header["x-pid"] ?? "") != posix_getpid()) {
|
Console::debug("Terminal fd: ".$conn->fd);
|
||||||
|
if(($req->header["x-terminal-id"] ?? "") != $terminal_id) {
|
||||||
$conn->close();
|
$conn->close();
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
@@ -195,6 +196,7 @@ class Console
|
|||||||
$vss2->type = "message";
|
$vss2->type = "message";
|
||||||
$vss2->rule = "connectType:terminal";
|
$vss2->rule = "connectType:terminal";
|
||||||
$vss2->callback = function(?WSConnection $conn){
|
$vss2->callback = function(?WSConnection $conn){
|
||||||
|
if ($conn === null) return false;
|
||||||
if($conn->getType() != "terminal") return false;
|
if($conn->getType() != "terminal") return false;
|
||||||
$cmd = ctx()->getFrame()->data;
|
$cmd = ctx()->getFrame()->data;
|
||||||
self::executeCommand($cmd);
|
self::executeCommand($cmd);
|
||||||
|
|||||||
@@ -15,12 +15,10 @@ class DataProvider
|
|||||||
}
|
}
|
||||||
|
|
||||||
public static function getWorkingDir() {
|
public static function getWorkingDir() {
|
||||||
global $is_phar;
|
if(LOAD_MODE == 0) return WORKING_DIR;
|
||||||
if ($is_phar === true) {
|
elseif (LOAD_MODE == 1) return LOAD_MODE_COMPOSER_PATH;
|
||||||
return realpath('.');
|
elseif (LOAD_MODE == 2) return realpath('.');
|
||||||
} else {
|
return null;
|
||||||
return WORKING_DIR;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public static function getDataConfig() {
|
public static function getDataConfig() {
|
||||||
|
|||||||
@@ -3,15 +3,13 @@
|
|||||||
|
|
||||||
namespace Framework;
|
namespace Framework;
|
||||||
|
|
||||||
use Co;
|
use Doctrine\Common\Annotations\AnnotationReader;
|
||||||
use Doctrine\Common\Annotations\AnnotationException;
|
use ReflectionClass;
|
||||||
use Swoole\Http\Request;
|
use ReflectionMethod;
|
||||||
use Swoole\Runtime;
|
use Swoole\Runtime;
|
||||||
use Swoole\WebSocket\Frame;
|
use ZM\Annotation\Swoole\OnEvent;
|
||||||
use ZM\Event\EventHandler;
|
|
||||||
use Exception;
|
use Exception;
|
||||||
use Swoole\WebSocket\Server;
|
use Swoole\WebSocket\Server;
|
||||||
use ZM\Http\Response;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Class FrameworkLoader
|
* Class FrameworkLoader
|
||||||
@@ -36,18 +34,47 @@ class FrameworkLoader
|
|||||||
/** @var Server */
|
/** @var Server */
|
||||||
private $server;
|
private $server;
|
||||||
|
|
||||||
public function __construct($args = []) {
|
public function __construct($args = [])
|
||||||
if (self::$instance !== null) die("Cannot run two FrameworkLoader in one process!");
|
{
|
||||||
self::$instance = $this;
|
|
||||||
|
|
||||||
|
|
||||||
$this->requireGlobalFunctions();
|
$this->requireGlobalFunctions();
|
||||||
if (!isPharMode()) {
|
if (LOAD_MODE == 0) define("WORKING_DIR", getcwd());
|
||||||
define('WORKING_DIR', getcwd());
|
elseif (LOAD_MODE == 1) define("WORKING_DIR", realpath(__DIR__ . "/../../"));
|
||||||
} else {
|
elseif (LOAD_MODE == 2) echo "Phar mode: " . WORKING_DIR . PHP_EOL;
|
||||||
echo "Phar mode: " . WORKING_DIR . PHP_EOL;
|
//$this->registerAutoloader('classLoader');
|
||||||
|
require_once "DataProvider.php";
|
||||||
|
if (file_exists(DataProvider::getWorkingDir() . "/vendor/autoload.php")) {
|
||||||
|
/** @noinspection PhpIncludeInspection */
|
||||||
|
require_once DataProvider::getWorkingDir() . "/vendor/autoload.php";
|
||||||
}
|
}
|
||||||
$this->registerAutoloader('classLoader');
|
if (LOAD_MODE == 0) {
|
||||||
|
echo "* This is repository mode.\n";
|
||||||
|
$composer = json_decode(file_get_contents(DataProvider::getWorkingDir() . "/composer.json"), true);
|
||||||
|
if (!isset($composer["autoload"]["psr-4"]["Module\\"])) {
|
||||||
|
echo "框架源码模式需要在autoload文件中添加Module目录为自动加载,是否添加?[Y/n] ";
|
||||||
|
$r = strtolower(trim(fgets(STDIN)));
|
||||||
|
if ($r === "" || $r === "y") {
|
||||||
|
$composer["autoload"]["psr-4"]["Module\\"] = "src/Module";
|
||||||
|
$composer["autoload"]["psr-4"]["Custom\\"] = "src/Custom";
|
||||||
|
$r = file_put_contents(DataProvider::getWorkingDir() . "/composer.json", json_encode($composer, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE));
|
||||||
|
if ($r !== false) {
|
||||||
|
echo "成功添加!请重新进行 composer update !\n";
|
||||||
|
exit(1);
|
||||||
|
} else {
|
||||||
|
echo "添加失败!请按任意键继续!";
|
||||||
|
fgets(STDIN);
|
||||||
|
exit(1);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
exit(1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (LOAD_MODE == 2) {
|
||||||
|
require_once FRAMEWORK_DIR . "/vendor/autoload.php";
|
||||||
|
spl_autoload_register('phar_classloader');
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
self::$settings = new GlobalConfig();
|
self::$settings = new GlobalConfig();
|
||||||
if (self::$settings->get("debug_mode") === true) {
|
if (self::$settings->get("debug_mode") === true) {
|
||||||
$args[] = "--debug-mode";
|
$args[] = "--debug-mode";
|
||||||
@@ -66,7 +93,6 @@ class FrameworkLoader
|
|||||||
$this->selfCheck();
|
$this->selfCheck();
|
||||||
try {
|
try {
|
||||||
$this->server = new Server(self::$settings->get("host"), self::$settings->get("port"));
|
$this->server = new Server(self::$settings->get("host"), self::$settings->get("port"));
|
||||||
if (in_array("--remote-shell", $args)) RemoteShell::listen($this->server, "127.0.0.1");
|
|
||||||
$settings = self::$settings->get("swoole");
|
$settings = self::$settings->get("swoole");
|
||||||
if (in_array("--daemon", $args)) {
|
if (in_array("--daemon", $args)) {
|
||||||
$settings["daemonize"] = 1;
|
$settings["daemonize"] = 1;
|
||||||
@@ -74,25 +100,38 @@ class FrameworkLoader
|
|||||||
self::$argv[] = "--disable-console-input";
|
self::$argv[] = "--disable-console-input";
|
||||||
}
|
}
|
||||||
$this->server->set($settings);
|
$this->server->set($settings);
|
||||||
$this->server->on("WorkerStart", [$this, "onWorkerStart"]);
|
$all_event_class = self::$settings->get("server_event_handler_class") ?? [];
|
||||||
$this->server->on("message", function ($server, Frame $frame) {
|
if (!in_array(ServerEventHandler::class, $all_event_class)) {
|
||||||
Console::debug("Calling Swoole \"message\" from fd=" . $frame->fd);
|
$all_event_class[] = ServerEventHandler::class;
|
||||||
EventHandler::callSwooleEvent("message", $server, $frame);
|
}
|
||||||
});
|
$event_list = [];
|
||||||
$this->server->on("request", function ($request, $response) {
|
foreach ($all_event_class as $v) {
|
||||||
$response = new Response($response);
|
$reader = new AnnotationReader();
|
||||||
Console::debug("Receiving Http request event, cid=" . Co::getCid());
|
$reflection_class = new ReflectionClass($v);
|
||||||
EventHandler::callSwooleEvent("request", $request, $response);
|
$methods = $reflection_class->getMethods(ReflectionMethod::IS_PUBLIC);
|
||||||
});
|
foreach ($methods as $vs) {
|
||||||
$this->server->on("open", function ($server, Request $request) {
|
$method_annotations = $reader->getMethodAnnotations($vs);
|
||||||
Console::debug("Calling Swoole \"open\" event from fd=" . $request->fd);
|
if ($method_annotations != []) {
|
||||||
EventHandler::callSwooleEvent("open", $server, $request);
|
$annotation = $method_annotations[0];
|
||||||
});
|
if ($annotation instanceof OnEvent) {
|
||||||
$this->server->on("close", function ($server, $fd) {
|
$annotation->class = $v;
|
||||||
Console::debug("Calling Swoole \"close\" event from fd=" . $fd);
|
$annotation->method = $vs->getName();
|
||||||
EventHandler::callSwooleEvent("close", $server, $fd);
|
$event_list[strtolower($annotation->event)] = $annotation;
|
||||||
});
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
foreach ($event_list as $k => $v) {
|
||||||
|
$this->server->on($k, function (...$param) use ($v) {
|
||||||
|
$c = $v->class;
|
||||||
|
//echo $c.PHP_EOL;
|
||||||
|
$c = new $c();
|
||||||
|
call_user_func_array([$c, $v->method], $param);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
ZMBuf::initAtomic();
|
ZMBuf::initAtomic();
|
||||||
|
if (in_array("--remote-shell", $args)) RemoteShell::listen($this->server, "127.0.0.1");
|
||||||
if (in_array("--log-error", $args)) ZMBuf::$atomics["info_level"]->set(0);
|
if (in_array("--log-error", $args)) ZMBuf::$atomics["info_level"]->set(0);
|
||||||
if (in_array("--log-warning", $args)) ZMBuf::$atomics["info_level"]->set(1);
|
if (in_array("--log-warning", $args)) ZMBuf::$atomics["info_level"]->set(1);
|
||||||
if (in_array("--log-info", $args)) ZMBuf::$atomics["info_level"]->set(2);
|
if (in_array("--log-info", $args)) ZMBuf::$atomics["info_level"]->set(2);
|
||||||
@@ -102,8 +141,8 @@ class FrameworkLoader
|
|||||||
"host: " . self::$settings->get("host") .
|
"host: " . self::$settings->get("host") .
|
||||||
", port: " . self::$settings->get("port") .
|
", port: " . self::$settings->get("port") .
|
||||||
", log_level: " . ZMBuf::$atomics["info_level"]->get() .
|
", log_level: " . ZMBuf::$atomics["info_level"]->get() .
|
||||||
", version: " . json_decode(file_get_contents(WORKING_DIR . "/composer.json"), true)["version"] .
|
", version: " . ZM_VERSION .
|
||||||
"\nworking_dir: " . (isPharMode() ? realpath('.') : WORKING_DIR)
|
"\nworking_dir: " . DataProvider::getWorkingDir()
|
||||||
);
|
);
|
||||||
global $motd;
|
global $motd;
|
||||||
if (!file_exists(DataProvider::getWorkingDir() . "/config/motd.txt")) {
|
if (!file_exists(DataProvider::getWorkingDir() . "/config/motd.txt")) {
|
||||||
@@ -121,17 +160,16 @@ class FrameworkLoader
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private function requireGlobalFunctions() {
|
private function requireGlobalFunctions()
|
||||||
|
{
|
||||||
require_once __DIR__ . '/global_functions.php';
|
require_once __DIR__ . '/global_functions.php';
|
||||||
}
|
}
|
||||||
|
|
||||||
private function registerAutoloader(string $string) {
|
private function defineProperties()
|
||||||
if (!spl_autoload_register($string)) die("Failed to register autoloader named \"$string\" !");
|
{
|
||||||
}
|
|
||||||
|
|
||||||
private function defineProperties() {
|
|
||||||
define("ZM_START_TIME", microtime(true));
|
define("ZM_START_TIME", microtime(true));
|
||||||
define("ZM_DATA", self::$settings->get("zm_data"));
|
define("ZM_DATA", self::$settings->get("zm_data"));
|
||||||
|
define("ZM_VERSION", json_decode(file_get_contents(__DIR__ . "/../../composer.json"), true)["version"] ?? "unknown");
|
||||||
define("CONFIG_DIR", self::$settings->get("config_dir"));
|
define("CONFIG_DIR", self::$settings->get("config_dir"));
|
||||||
define("CRASH_DIR", self::$settings->get("crash_dir"));
|
define("CRASH_DIR", self::$settings->get("crash_dir"));
|
||||||
@mkdir(ZM_DATA);
|
@mkdir(ZM_DATA);
|
||||||
@@ -142,13 +180,16 @@ class FrameworkLoader
|
|||||||
define("ZM_MATCH_NUMBER", 2);
|
define("ZM_MATCH_NUMBER", 2);
|
||||||
define("ZM_MATCH_SECOND", 3);
|
define("ZM_MATCH_SECOND", 3);
|
||||||
define("ZM_BREAKPOINT", 'if(in_array("--debug-mode", \Framework\FrameworkLoader::$argv)) extract(\Psy\debug(get_defined_vars(), isset($this) ? $this : @get_called_class()));');
|
define("ZM_BREAKPOINT", 'if(in_array("--debug-mode", \Framework\FrameworkLoader::$argv)) extract(\Psy\debug(get_defined_vars(), isset($this) ? $this : @get_called_class()));');
|
||||||
|
define("BP", ZM_BREAKPOINT);
|
||||||
|
define("ZM_DEFAULT_FETCH_MODE", self::$settings->get("sql_config")["sql_default_fetch_mode"] ?? 4);
|
||||||
}
|
}
|
||||||
|
|
||||||
private function selfCheck() {
|
private function selfCheck()
|
||||||
|
{
|
||||||
if (!extension_loaded("swoole")) die("Can not find swoole extension.\n");
|
if (!extension_loaded("swoole")) die("Can not find swoole extension.\n");
|
||||||
if (version_compare(SWOOLE_VERSION, "4.4.13") == -1) die("You must install swoole version >= 4.4.13 !");
|
if (version_compare(SWOOLE_VERSION, "4.4.13") == -1) die("You must install swoole version >= 4.4.13 !");
|
||||||
//if (!extension_loaded("gd")) die("Can not find gd extension.\n");
|
//if (!extension_loaded("gd")) die("Can not find gd extension.\n");
|
||||||
if (!extension_loaded("sockets")) die("Can not find sockets extension.\n");
|
//if (!extension_loaded("sockets")) die("Can not find sockets extension.\n");
|
||||||
if (!extension_loaded("ctype")) die("Can not find ctype extension.\n");
|
if (!extension_loaded("ctype")) die("Can not find ctype extension.\n");
|
||||||
if (!function_exists("mb_substr")) die("Can not find mbstring extension.\n");
|
if (!function_exists("mb_substr")) die("Can not find mbstring extension.\n");
|
||||||
if (substr(PHP_VERSION, 0, 1) != "7") die("PHP >=7 required.\n");
|
if (substr(PHP_VERSION, 0, 1) != "7") die("PHP >=7 required.\n");
|
||||||
@@ -157,17 +198,6 @@ class FrameworkLoader
|
|||||||
//if (!file_exists(CRASH_DIR . "last_error.log")) die("Can not find log file.\n");
|
//if (!file_exists(CRASH_DIR . "last_error.log")) die("Can not find log file.\n");
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* @param \Swoole\Server $server
|
|
||||||
* @param $worker_id
|
|
||||||
* @throws AnnotationException
|
|
||||||
*/
|
|
||||||
public function onWorkerStart(\Swoole\Server $server, $worker_id) {
|
|
||||||
self::$instance = $this;
|
|
||||||
self::$run_time = microtime(true);
|
|
||||||
EventHandler::callSwooleEvent("WorkerStart", $server, $worker_id);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
global $motd;
|
global $motd;
|
||||||
|
|||||||
84
src/Framework/ServerEventHandler.php
Normal file
84
src/Framework/ServerEventHandler.php
Normal file
@@ -0,0 +1,84 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
|
||||||
|
namespace Framework;
|
||||||
|
|
||||||
|
|
||||||
|
use Co;
|
||||||
|
use Doctrine\Common\Annotations\AnnotationException;
|
||||||
|
use Swoole\Http\Request;
|
||||||
|
use Swoole\Server;
|
||||||
|
use Swoole\WebSocket\Frame;
|
||||||
|
use ZM\Annotation\AnnotationParser;
|
||||||
|
use ZM\Annotation\Swoole\OnEvent;
|
||||||
|
use ZM\Connection\ConnectionManager;
|
||||||
|
use ZM\Event\EventHandler;
|
||||||
|
use ZM\Http\Response;
|
||||||
|
|
||||||
|
class ServerEventHandler
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* @OnEvent("WorkerStart")
|
||||||
|
* @param Server $server
|
||||||
|
* @param $worker_id
|
||||||
|
* @throws AnnotationException
|
||||||
|
* @throws \ReflectionException
|
||||||
|
*/
|
||||||
|
public function onWorkerStart(Server $server, $worker_id) {
|
||||||
|
if ($server->taskworker === false) {
|
||||||
|
FrameworkLoader::$run_time = microtime(true);
|
||||||
|
EventHandler::callSwooleEvent("WorkerStart", $server, $worker_id);
|
||||||
|
} else {
|
||||||
|
ob_start();
|
||||||
|
AnnotationParser::registerMods();
|
||||||
|
//加载Custom目录下的自定义的内部类
|
||||||
|
ConnectionManager::registerCustomClass();
|
||||||
|
ob_get_clean();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @OnEvent("message")
|
||||||
|
* @param $server
|
||||||
|
* @param Frame $frame
|
||||||
|
* @throws AnnotationException
|
||||||
|
*/
|
||||||
|
public function onMessage($server, Frame $frame) {
|
||||||
|
Console::debug("Calling Swoole \"message\" from fd=" . $frame->fd);
|
||||||
|
EventHandler::callSwooleEvent("message", $server, $frame);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @OnEvent("request")
|
||||||
|
* @param $request
|
||||||
|
* @param $response
|
||||||
|
* @throws AnnotationException
|
||||||
|
*/
|
||||||
|
public function onRequest($request, $response) {
|
||||||
|
$response = new Response($response);
|
||||||
|
Console::debug("Receiving Http request event, cid=" . Co::getCid());
|
||||||
|
EventHandler::callSwooleEvent("request", $request, $response);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @OnEvent("open")
|
||||||
|
* @param $server
|
||||||
|
* @param Request $request
|
||||||
|
* @throws AnnotationException
|
||||||
|
*/
|
||||||
|
public function onOpen($server, Request $request) {
|
||||||
|
Console::debug("Calling Swoole \"open\" event from fd=" . $request->fd);
|
||||||
|
EventHandler::callSwooleEvent("open", $server, $request);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @OnEvent("close")
|
||||||
|
* @param $server
|
||||||
|
* @param $fd
|
||||||
|
* @throws AnnotationException
|
||||||
|
*/
|
||||||
|
public function onClose($server, $fd) {
|
||||||
|
Console::debug("Calling Swoole \"close\" event from fd=" . $fd);
|
||||||
|
EventHandler::callSwooleEvent("close", $server, $fd);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -52,6 +52,7 @@ class ZMBuf
|
|||||||
public static $context = [];
|
public static $context = [];
|
||||||
public static $instance = [];
|
public static $instance = [];
|
||||||
public static $context_class = [];
|
public static $context_class = [];
|
||||||
|
public static $server_events = [];
|
||||||
|
|
||||||
static function get($name, $default = null) {
|
static function get($name, $default = null) {
|
||||||
return self::$cache[$name] ?? $default;
|
return self::$cache[$name] ?? $default;
|
||||||
|
|||||||
@@ -7,15 +7,13 @@ use Swoole\Coroutine\System;
|
|||||||
use ZM\Context\ContextInterface;
|
use ZM\Context\ContextInterface;
|
||||||
use ZM\Utils\ZMUtil;
|
use ZM\Utils\ZMUtil;
|
||||||
|
|
||||||
function isPharMode() {
|
|
||||||
return substr(__DIR__, 0, 7) == 'phar://';
|
|
||||||
}
|
|
||||||
|
|
||||||
function classLoader($p) {
|
function phar_classloader($p){
|
||||||
$filepath = getClassPath($p);
|
$filepath = getClassPath($p);
|
||||||
if ($filepath === null)
|
if($filepath === null) {
|
||||||
echo "F:Warning: get class path wrongs.$p\n";
|
Console::debug("F:Warning: get class path wrongs.$p");
|
||||||
//else echo "F:DBG: Found " . $p . "\n";
|
return;
|
||||||
|
}
|
||||||
try {
|
try {
|
||||||
require_once $filepath;
|
require_once $filepath;
|
||||||
} catch (Exception $e) {
|
} catch (Exception $e) {
|
||||||
@@ -72,6 +70,7 @@ function unicode_decode($str) {
|
|||||||
* @return array
|
* @return array
|
||||||
*/
|
*/
|
||||||
function getAllClasses($dir, $indoor_name) {
|
function getAllClasses($dir, $indoor_name) {
|
||||||
|
if(!is_dir($dir)) return [];
|
||||||
$list = scandir($dir);
|
$list = scandir($dir);
|
||||||
$classes = [];
|
$classes = [];
|
||||||
unset($list[0], $list[1]);
|
unset($list[0], $list[1]);
|
||||||
@@ -224,3 +223,5 @@ function zm_timer_tick($ms, callable $callable) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -3,6 +3,7 @@
|
|||||||
use Swoole\Coroutine\Http\Client;
|
use Swoole\Coroutine\Http\Client;
|
||||||
|
|
||||||
Co\run(function (){
|
Co\run(function (){
|
||||||
|
hello:
|
||||||
global $terminal_id, $port;
|
global $terminal_id, $port;
|
||||||
$client = new Client("127.0.0.1", $port);
|
$client = new Client("127.0.0.1", $port);
|
||||||
$client->set(['websocket_mask' => true]);
|
$client->set(['websocket_mask' => true]);
|
||||||
@@ -17,8 +18,9 @@ Co\run(function (){
|
|||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
if($r === false) {
|
if($r === false) {
|
||||||
echo "Unable to connect framework terminal, connection closed.\n";
|
echo "Unable to connect framework terminal, connection closed. Trying to reconnect after 5s.\n";
|
||||||
break;
|
sleep(5);
|
||||||
|
goto hello;
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
break;
|
break;
|
||||||
|
|||||||
@@ -10,7 +10,6 @@ use ZM\Annotation\Http\Middleware;
|
|||||||
use ZM\Annotation\Http\RequestMapping;
|
use ZM\Annotation\Http\RequestMapping;
|
||||||
use ZM\Annotation\Swoole\SwooleEventAt;
|
use ZM\Annotation\Swoole\SwooleEventAt;
|
||||||
use ZM\Connection\CQConnection;
|
use ZM\Connection\CQConnection;
|
||||||
use ZM\ModBase;
|
|
||||||
use ZM\Utils\ZMUtil;
|
use ZM\Utils\ZMUtil;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -18,7 +17,7 @@ use ZM\Utils\ZMUtil;
|
|||||||
* @package Module\Example
|
* @package Module\Example
|
||||||
* @since 1.0
|
* @since 1.0
|
||||||
*/
|
*/
|
||||||
class Hello extends ModBase
|
class Hello
|
||||||
{
|
{
|
||||||
/**
|
/**
|
||||||
* 在机器人连接后向终端输出信息
|
* 在机器人连接后向终端输出信息
|
||||||
@@ -29,9 +28,18 @@ class Hello extends ModBase
|
|||||||
Console::info("机器人 " . $conn->getQQ() . " 已连接!");
|
Console::info("机器人 " . $conn->getQQ() . " 已连接!");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 在机器人连接后向终端输出信息
|
||||||
|
* @SwooleEventAt("close",rule="connectType:qq")
|
||||||
|
*/
|
||||||
|
public function onDisconnect() {
|
||||||
|
$conn = ctx()->getConnection();
|
||||||
|
Console::info("机器人 " . $conn->getQQ() . " 已断开连接!");
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 向机器人发送"你好",即可回复这句话
|
* 向机器人发送"你好",即可回复这句话
|
||||||
* @CQCommand("你好")
|
* @CQCommand(match="你好",alias={"你好啊","你是谁"})
|
||||||
*/
|
*/
|
||||||
public function hello() {
|
public function hello() {
|
||||||
return "你好啊,我是由炸毛框架构建的机器人!";
|
return "你好啊,我是由炸毛框架构建的机器人!";
|
||||||
|
|||||||
@@ -56,7 +56,7 @@ class AnnotationParser
|
|||||||
$class_prefix = '';
|
$class_prefix = '';
|
||||||
$methods = $reflection_class->getMethods(ReflectionMethod::IS_PUBLIC);
|
$methods = $reflection_class->getMethods(ReflectionMethod::IS_PUBLIC);
|
||||||
$class_annotations = $reader->getClassAnnotations($reflection_class);
|
$class_annotations = $reader->getClassAnnotations($reflection_class);
|
||||||
$middleware_addon = null;
|
$middleware_addon = [];
|
||||||
foreach ($class_annotations as $vs) {
|
foreach ($class_annotations as $vs) {
|
||||||
if ($vs instanceof Closed) {
|
if ($vs instanceof Closed) {
|
||||||
continue 2;
|
continue 2;
|
||||||
@@ -98,18 +98,24 @@ class AnnotationParser
|
|||||||
ZMBuf::$events[MiddlewareClass::class][$result["name"]] = $result;
|
ZMBuf::$events[MiddlewareClass::class][$result["name"]] = $result;
|
||||||
continue 2;
|
continue 2;
|
||||||
} elseif ($vs instanceof Middleware) {
|
} elseif ($vs instanceof Middleware) {
|
||||||
$middleware_addon = $vs;
|
$middleware_addon[] = $vs;
|
||||||
|
} elseif ($vs instanceof CustomAnnotation) {
|
||||||
|
$vs->class = $reflection_class->getName();
|
||||||
|
ZMBuf::$events[get_class($vs)][] = $vs;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
foreach ($methods as $vs) {
|
foreach ($methods as $vs) {
|
||||||
if ($middleware_addon !== null) {
|
if ($middleware_addon !== []) {
|
||||||
Console::debug("Added middleware " . $middleware_addon->middleware . " to $v -> " . $vs->getName());
|
foreach($middleware_addon as $value){
|
||||||
ZMBuf::$events[MiddlewareInterface::class][$v][$vs->getName()][] = $middleware_addon->middleware;
|
Console::debug("Added middleware " . $value->middleware . " to $v -> " . $vs->getName());
|
||||||
|
ZMBuf::$events[MiddlewareInterface::class][$v][$vs->getName()][] = $value->middleware;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
$method_annotations = $reader->getMethodAnnotations($vs);
|
$method_annotations = $reader->getMethodAnnotations($vs);
|
||||||
foreach ($method_annotations as $vss) {
|
foreach ($method_annotations as $vss) {
|
||||||
if ($vss instanceof Rule) $vss = self::registerRuleEvent($vss, $vs, $reflection_class);
|
if ($vss instanceof Rule) $vss = self::registerRuleEvent($vss, $vs, $reflection_class);
|
||||||
else $vss = self::registerMethod($vss, $vs, $reflection_class);
|
else $vss = self::registerMethod($vss, $vs, $reflection_class);
|
||||||
|
Console::debug("寻找 " . $vs->getName() . " -> " . get_class($vss));
|
||||||
|
|
||||||
if ($vss instanceof SwooleEventAt) ZMBuf::$events[SwooleEventAt::class][] = $vss;
|
if ($vss instanceof SwooleEventAt) ZMBuf::$events[SwooleEventAt::class][] = $vss;
|
||||||
elseif ($vss instanceof SwooleEventAfter) ZMBuf::$events[SwooleEventAfter::class][] = $vss;
|
elseif ($vss instanceof SwooleEventAfter) ZMBuf::$events[SwooleEventAfter::class][] = $vss;
|
||||||
@@ -168,7 +174,7 @@ class AnnotationParser
|
|||||||
switch ($asp_name) {
|
switch ($asp_name) {
|
||||||
case "connectType": //websocket连接类型
|
case "connectType": //websocket连接类型
|
||||||
$func = function (?WSConnection $connection) use ($rest) {
|
$func = function (?WSConnection $connection) use ($rest) {
|
||||||
if($connection === null) return false;
|
if ($connection === null) return false;
|
||||||
return $connection->getType() == $rest ? true : false;
|
return $connection->getType() == $rest ? true : false;
|
||||||
};
|
};
|
||||||
break;
|
break;
|
||||||
@@ -326,6 +332,7 @@ class AnnotationParser
|
|||||||
$class = getAllClasses(DataProvider::getWorkingDir() . "/src/Custom/Annotation/", "Custom\\Annotation");
|
$class = getAllClasses(DataProvider::getWorkingDir() . "/src/Custom/Annotation/", "Custom\\Annotation");
|
||||||
foreach ($class as $v) {
|
foreach ($class as $v) {
|
||||||
$s = DataProvider::getWorkingDir() . '/src/' . str_replace("\\", "/", $v) . ".php";
|
$s = DataProvider::getWorkingDir() . '/src/' . str_replace("\\", "/", $v) . ".php";
|
||||||
|
Console::debug("Requiring custom annotation " . $s);
|
||||||
require_once $s;
|
require_once $s;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -19,6 +19,18 @@ class CQCommand extends AnnotationBase implements Level
|
|||||||
public $match = "";
|
public $match = "";
|
||||||
/** @var string */
|
/** @var string */
|
||||||
public $regexMatch = "";
|
public $regexMatch = "";
|
||||||
|
/** @var string */
|
||||||
|
public $fullMatch = "";
|
||||||
|
/** @var string[] */
|
||||||
|
public $alias = [];
|
||||||
|
/** @var string */
|
||||||
|
public $message_type = "";
|
||||||
|
/** @var int */
|
||||||
|
public $user_id = 0;
|
||||||
|
/** @var int */
|
||||||
|
public $group_id = 0;
|
||||||
|
/** @var int */
|
||||||
|
public $discuss_id = 0;
|
||||||
/** @var int */
|
/** @var int */
|
||||||
public $level = 20;
|
public $level = 20;
|
||||||
|
|
||||||
@@ -32,4 +44,4 @@ class CQCommand extends AnnotationBase implements Level
|
|||||||
*/
|
*/
|
||||||
public function setLevel(int $level) { $this->level = $level; }
|
public function setLevel(int $level) { $this->level = $level; }
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
24
src/ZM/Annotation/Swoole/OnEvent.php
Normal file
24
src/ZM/Annotation/Swoole/OnEvent.php
Normal file
@@ -0,0 +1,24 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
|
||||||
|
namespace ZM\Annotation\Swoole;
|
||||||
|
|
||||||
|
|
||||||
|
use Doctrine\Common\Annotations\Annotation\Required;
|
||||||
|
use Doctrine\Common\Annotations\Annotation\Target;
|
||||||
|
use ZM\Annotation\AnnotationBase;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Class OnEvent
|
||||||
|
* @package ZM\Annotation\Swoole
|
||||||
|
* @Annotation
|
||||||
|
* @Target("METHOD")
|
||||||
|
*/
|
||||||
|
class OnEvent extends AnnotationBase
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* @var string
|
||||||
|
* @Required()
|
||||||
|
*/
|
||||||
|
public $event;
|
||||||
|
}
|
||||||
15
src/ZM/Annotation/Swoole/OnTaskWorkerStart.php
Normal file
15
src/ZM/Annotation/Swoole/OnTaskWorkerStart.php
Normal file
@@ -0,0 +1,15 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
|
||||||
|
namespace ZM\Annotation\Swoole;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Class OnTaskWorkerStart
|
||||||
|
* @package ZM\Annotation\Swoole
|
||||||
|
* @Annotation
|
||||||
|
* @Target("METHOD")
|
||||||
|
*/
|
||||||
|
class OnTaskWorkerStart
|
||||||
|
{
|
||||||
|
|
||||||
|
}
|
||||||
@@ -7,6 +7,7 @@ namespace ZM\DB;
|
|||||||
use Exception;
|
use Exception;
|
||||||
use framework\Console;
|
use framework\Console;
|
||||||
use framework\ZMBuf;
|
use framework\ZMBuf;
|
||||||
|
use PDOException;
|
||||||
use PDOStatement;
|
use PDOStatement;
|
||||||
use Swoole\Coroutine;
|
use Swoole\Coroutine;
|
||||||
use Swoole\Database\PDOStatementProxy;
|
use Swoole\Database\PDOStatementProxy;
|
||||||
@@ -89,10 +90,11 @@ class DB
|
|||||||
/**
|
/**
|
||||||
* @param string $line
|
* @param string $line
|
||||||
* @param array $params
|
* @param array $params
|
||||||
|
* @param int $fetch_mode
|
||||||
* @return mixed
|
* @return mixed
|
||||||
* @throws DbException
|
* @throws DbException
|
||||||
*/
|
*/
|
||||||
public static function rawQuery(string $line, $params = []) {
|
public static function rawQuery(string $line, $params = [], $fetch_mode = ZM_DEFAULT_FETCH_MODE) {
|
||||||
if (ZMBuf::get("sql_log") === true) {
|
if (ZMBuf::get("sql_log") === true) {
|
||||||
$starttime = microtime(true);
|
$starttime = microtime(true);
|
||||||
}
|
}
|
||||||
@@ -130,9 +132,9 @@ class DB
|
|||||||
"] " . $line . " " . json_encode($params, JSON_UNESCAPED_UNICODE) . "\n";
|
"] " . $line . " " . json_encode($params, JSON_UNESCAPED_UNICODE) . "\n";
|
||||||
Coroutine::writeFile(CRASH_DIR . "sql.log", $log, FILE_APPEND);
|
Coroutine::writeFile(CRASH_DIR . "sql.log", $log, FILE_APPEND);
|
||||||
}
|
}
|
||||||
return $ps->fetchAll();
|
return $ps->fetchAll($fetch_mode);
|
||||||
}
|
}
|
||||||
} catch (DBException $e) {
|
} catch (DbException $e) {
|
||||||
if (ZMBuf::get("sql_log") === true) {
|
if (ZMBuf::get("sql_log") === true) {
|
||||||
$log =
|
$log =
|
||||||
"[" . date("Y-m-d H:i:s") .
|
"[" . date("Y-m-d H:i:s") .
|
||||||
@@ -147,6 +149,21 @@ class DB
|
|||||||
}
|
}
|
||||||
Console::warning($e->getMessage());
|
Console::warning($e->getMessage());
|
||||||
throw $e;
|
throw $e;
|
||||||
|
} catch (PDOException $e) {
|
||||||
|
if (ZMBuf::get("sql_log") === true) {
|
||||||
|
$log =
|
||||||
|
"[" . date("Y-m-d H:i:s") .
|
||||||
|
" " . round(microtime(true) - $starttime, 4) .
|
||||||
|
"] " . $line . " " . json_encode($params, JSON_UNESCAPED_UNICODE) . " (Error:" . $e->getMessage() . ")\n";
|
||||||
|
Coroutine::writeFile(CRASH_DIR . "sql.log", $log, FILE_APPEND);
|
||||||
|
}
|
||||||
|
if(mb_strpos($e->getMessage(), "has gone away") !== false) {
|
||||||
|
zm_sleep(0.2);
|
||||||
|
Console::warning("Gone away of MySQL! retrying!");
|
||||||
|
return self::rawQuery($line, $params);
|
||||||
|
}
|
||||||
|
Console::warning($e->getMessage());
|
||||||
|
throw new DbException($e->getMessage(), $e->getCode(), $e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -31,10 +31,21 @@ class SelectBody
|
|||||||
public function get() { return $this->fetchAll(); }
|
public function get() { return $this->fetchAll(); }
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
* @throws DbException
|
||||||
|
*/
|
||||||
|
public function count() {
|
||||||
|
$this->select_thing = ["count(*)"];
|
||||||
|
$str = $this->queryPrepare();
|
||||||
|
$this->result = DB::rawQuery($str[0], $str[1]);
|
||||||
|
return intval($this->result[0]["count(*)"]);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param int $fetch_mode
|
||||||
* @return null
|
* @return null
|
||||||
* @throws DbException
|
* @throws DbException
|
||||||
*/
|
*/
|
||||||
public function fetchAll() {
|
public function fetchAll($fetch_mode = ZM_DEFAULT_FETCH_MODE) {
|
||||||
if ($this->table->isCacheEnabled()) {
|
if ($this->table->isCacheEnabled()) {
|
||||||
$rr = md5(implode(",", $this->select_thing) . serialize($this->where_thing));
|
$rr = md5(implode(",", $this->select_thing) . serialize($this->where_thing));
|
||||||
if (array_key_exists($rr, $this->table->cache)) {
|
if (array_key_exists($rr, $this->table->cache)) {
|
||||||
@@ -42,7 +53,7 @@ class SelectBody
|
|||||||
return $this->table->cache[$rr]->getResult();
|
return $this->table->cache[$rr]->getResult();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
$this->execute();
|
$this->execute($fetch_mode);
|
||||||
if ($this->table->isCacheEnabled() && !in_array($rr, $this->table->cache)) {
|
if ($this->table->isCacheEnabled() && !in_array($rr, $this->table->cache)) {
|
||||||
$this->table->cache[$rr] = $this;
|
$this->table->cache[$rr] = $this;
|
||||||
}
|
}
|
||||||
@@ -71,11 +82,12 @@ class SelectBody
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
* @param int $fetch_mode
|
||||||
* @throws DbException
|
* @throws DbException
|
||||||
*/
|
*/
|
||||||
public function execute() {
|
public function execute($fetch_mode = ZM_DEFAULT_FETCH_MODE) {
|
||||||
$str = $this->queryPrepare();
|
$str = $this->queryPrepare();
|
||||||
$this->result = DB::rawQuery($str[0], $str[1]);
|
$this->result = DB::rawQuery($str[0], $str[1], $fetch_mode);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function getResult() { return $this->result; }
|
public function getResult() { return $this->result; }
|
||||||
|
|||||||
@@ -9,8 +9,8 @@ trait WhereBody
|
|||||||
protected $where_thing = [];
|
protected $where_thing = [];
|
||||||
|
|
||||||
public function where($column, $operation_or_value, $value = null) {
|
public function where($column, $operation_or_value, $value = null) {
|
||||||
if (!in_array($operation_or_value, ['=', '!='])) $this->where_thing['='][$column] = $operation_or_value;
|
if ($value !== null) $this->where_thing[$operation_or_value][$column] = $value;
|
||||||
elseif ($value !== null) $this->where_thing[$operation_or_value][$column] = $value;
|
elseif (!in_array($operation_or_value, ['=', '!=', '>', '<', '>=', '<=', 'IN', 'in'])) $this->where_thing['='][$column] = $operation_or_value;
|
||||||
else $this->where_thing['='][$column] = $operation_or_value;
|
else $this->where_thing['='][$column] = $operation_or_value;
|
||||||
return $this;
|
return $this;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -38,9 +38,9 @@ class MessageEvent
|
|||||||
* @throws AnnotationException
|
* @throws AnnotationException
|
||||||
*/
|
*/
|
||||||
public function onBefore() {
|
public function onBefore() {
|
||||||
$obj_list = ZMBuf::$events[CQBefore::class]["message"];
|
$obj_list = ZMBuf::$events[CQBefore::class]["message"] ?? [];
|
||||||
foreach ($obj_list as $v) {
|
foreach ($obj_list as $v) {
|
||||||
if($v->level < 200) break;
|
if ($v->level < 200) break;
|
||||||
EventHandler::callWithMiddleware(
|
EventHandler::callWithMiddleware(
|
||||||
$v->class,
|
$v->class,
|
||||||
$v->method,
|
$v->method,
|
||||||
@@ -65,7 +65,7 @@ class MessageEvent
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
foreach (ZMBuf::$events[CQBefore::class]["message"] ?? [] as $v) {
|
foreach (ZMBuf::$events[CQBefore::class]["message"] ?? [] as $v) {
|
||||||
if($v->level >= 200) continue;
|
if ($v->level >= 200) continue;
|
||||||
$c = $v->class;
|
$c = $v->class;
|
||||||
if (ctx()->getCache("level") != 0) continue;
|
if (ctx()->getCache("level") != 0) continue;
|
||||||
EventHandler::callWithMiddleware(
|
EventHandler::callWithMiddleware(
|
||||||
@@ -100,8 +100,12 @@ class MessageEvent
|
|||||||
$obj = [];
|
$obj = [];
|
||||||
foreach (ZMBuf::$events[CQCommand::class] ?? [] as $v) {
|
foreach (ZMBuf::$events[CQCommand::class] ?? [] as $v) {
|
||||||
/** @var CQCommand $v */
|
/** @var CQCommand $v */
|
||||||
if ($v->match == "" && $v->regexMatch == "") continue;
|
if ($v->match == "" && $v->regexMatch == "" && $v->fullMatch == "") continue;
|
||||||
else {
|
elseif (($v->user_id == 0 || ($v->user_id != 0 && $v->user_id == context()->getData()["user_id"])) &&
|
||||||
|
($v->group_id == 0 || ($v->group_id != 0 && $v->group_id == (context()->getData()["group_id"] ?? 0))) &&
|
||||||
|
($v->discuss_id == 0 || ($v->discuss_id != 0 && $v->discuss_id == (context()->getData()["discuss_id"] ?? 0))) &&
|
||||||
|
($v->message_type == '' || ($v->message_type != '' && $v->message_type == context()->getData()["message_type"]))
|
||||||
|
) {
|
||||||
$c = $v->class;
|
$c = $v->class;
|
||||||
$class_construct = [
|
$class_construct = [
|
||||||
"data" => context()->getData(),
|
"data" => context()->getData(),
|
||||||
@@ -117,6 +121,13 @@ class MessageEvent
|
|||||||
return true;
|
return true;
|
||||||
});
|
});
|
||||||
return;
|
return;
|
||||||
|
} elseif (in_array($word[0], $v->alias)) {
|
||||||
|
Console::debug("Calling $c -> {$v->method}");
|
||||||
|
$this->function_call = EventHandler::callWithMiddleware($obj[$c], $v->method, $class_construct, [$word], function ($r) {
|
||||||
|
if (is_string($r)) context()->reply($r);
|
||||||
|
return true;
|
||||||
|
});
|
||||||
|
return;
|
||||||
} elseif ($v->regexMatch != "" && ($args = matchArgs($v->regexMatch, context()->getMessage())) !== false) {
|
} elseif ($v->regexMatch != "" && ($args = matchArgs($v->regexMatch, context()->getMessage())) !== false) {
|
||||||
Console::debug("Calling $c -> {$v->method}");
|
Console::debug("Calling $c -> {$v->method}");
|
||||||
$this->function_call = EventHandler::callWithMiddleware($obj[$c], $v->method, $class_construct, [$args], function ($r) {
|
$this->function_call = EventHandler::callWithMiddleware($obj[$c], $v->method, $class_construct, [$args], function ($r) {
|
||||||
@@ -124,6 +135,14 @@ class MessageEvent
|
|||||||
return true;
|
return true;
|
||||||
});
|
});
|
||||||
return;
|
return;
|
||||||
|
} elseif ($v->fullMatch != "" && (preg_match("/".$v->fullMatch."/u", ctx()->getMessage(), $args)) != 0) {
|
||||||
|
Console::debug("Calling $c -> {$v->method}");
|
||||||
|
array_shift($args);
|
||||||
|
$this->function_call = EventHandler::callWithMiddleware($obj[$c], $v->method, $class_construct, [$args], function ($r) {
|
||||||
|
if (is_string($r)) context()->reply($r);
|
||||||
|
return true;
|
||||||
|
});
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -39,14 +39,17 @@ class EventHandler
|
|||||||
switch ($event_name) {
|
switch ($event_name) {
|
||||||
case "workerstart":
|
case "workerstart":
|
||||||
try {
|
try {
|
||||||
register_shutdown_function(function () {
|
register_shutdown_function(function () use ($param0) {
|
||||||
$error = error_get_last();
|
$error = error_get_last();
|
||||||
if ($error["type"] != 0) {
|
if ($error["type"] != 0) {
|
||||||
Console::error("Internal fatal error: " . $error["message"] . " at " . $error["file"] . "({$error["line"]})");
|
Console::error("Internal fatal error: " . $error["message"] . " at " . $error["file"] . "({$error["line"]})");
|
||||||
}
|
}
|
||||||
DataProvider::saveBuffer();
|
DataProvider::saveBuffer();
|
||||||
ZMBuf::$server->shutdown();
|
/** @var Server $param0 */
|
||||||
|
if (ZMBuf::$server === null) $param0->shutdown();
|
||||||
|
else ZMBuf::$server->shutdown();
|
||||||
});
|
});
|
||||||
|
ZMBuf::$server = $param0;
|
||||||
$r = (new WorkerStartEvent($param0, $param1))->onActivate();
|
$r = (new WorkerStartEvent($param0, $param1))->onActivate();
|
||||||
Console::log("\n=== Worker #" . $param0->worker_id . " 已启动 ===\n", "gold");
|
Console::log("\n=== Worker #" . $param0->worker_id . " 已启动 ===\n", "gold");
|
||||||
$r->onAfter();
|
$r->onAfter();
|
||||||
@@ -57,7 +60,9 @@ class EventHandler
|
|||||||
ZMUtil::stop();
|
ZMUtil::stop();
|
||||||
return;
|
return;
|
||||||
} catch (Error $e) {
|
} catch (Error $e) {
|
||||||
var_export($e);
|
Console::error("PHP Error: " . $e->getMessage() . " in " . $e->getFile() . " on line " . $e->getLine());
|
||||||
|
Console::error("Maybe it caused by your own code if in your own Module directory.");
|
||||||
|
Console::log($e->getTraceAsString(), 'gray');
|
||||||
ZMUtil::stop();
|
ZMUtil::stop();
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
@@ -85,7 +90,7 @@ class EventHandler
|
|||||||
" [" . $param1->getStatusCode() . "] " . $param0->server["request_uri"]
|
" [" . $param1->getStatusCode() . "] " . $param0->server["request_uri"]
|
||||||
);
|
);
|
||||||
if (!$param1->isEnd()) $param1->end("Internal server error: " . $e->getMessage());
|
if (!$param1->isEnd()) $param1->end("Internal server error: " . $e->getMessage());
|
||||||
Console::error("Internal server error (500), caused by uncaught exception.");
|
Console::error("Internal server exception (500), caused by " . get_class($e));
|
||||||
Console::log($e->getTraceAsString(), "gray");
|
Console::log($e->getTraceAsString(), "gray");
|
||||||
} catch (Error $e) {
|
} catch (Error $e) {
|
||||||
/** @var Response $param1 */
|
/** @var Response $param1 */
|
||||||
@@ -134,7 +139,7 @@ class EventHandler
|
|||||||
* @throws AnnotationException
|
* @throws AnnotationException
|
||||||
*/
|
*/
|
||||||
public static function callCQEvent($event_data, $conn_or_response, int $level = 0) {
|
public static function callCQEvent($event_data, $conn_or_response, int $level = 0) {
|
||||||
ctx()->setCache("level",$level);
|
ctx()->setCache("level", $level);
|
||||||
if ($level >= 5) {
|
if ($level >= 5) {
|
||||||
Console::warning("Recursive call reached " . $level . " times");
|
Console::warning("Recursive call reached " . $level . " times");
|
||||||
Console::stackTrace();
|
Console::stackTrace();
|
||||||
@@ -172,7 +177,7 @@ class EventHandler
|
|||||||
* @throws AnnotationException
|
* @throws AnnotationException
|
||||||
*/
|
*/
|
||||||
public static function callCQResponse($req) {
|
public static function callCQResponse($req) {
|
||||||
Console::debug("收到来自API连接的回复:".json_encode($req, 128|256));
|
Console::debug("收到来自API连接的回复:" . json_encode($req, 128 | 256));
|
||||||
$status = $req["status"];
|
$status = $req["status"];
|
||||||
$retcode = $req["retcode"];
|
$retcode = $req["retcode"];
|
||||||
$data = $req["data"];
|
$data = $req["data"];
|
||||||
|
|||||||
@@ -27,7 +27,8 @@ class RequestEvent implements SwooleEvent
|
|||||||
*/
|
*/
|
||||||
private $response;
|
private $response;
|
||||||
|
|
||||||
public function __construct(Request $request, Response $response) {
|
public function __construct(Request $request, Response $response)
|
||||||
|
{
|
||||||
$this->request = $request;
|
$this->request = $request;
|
||||||
$this->response = $response;
|
$this->response = $response;
|
||||||
}
|
}
|
||||||
@@ -36,19 +37,24 @@ class RequestEvent implements SwooleEvent
|
|||||||
* @return $this|SwooleEvent
|
* @return $this|SwooleEvent
|
||||||
* @throws Exception
|
* @throws Exception
|
||||||
*/
|
*/
|
||||||
public function onActivate() {
|
public function onActivate()
|
||||||
|
{
|
||||||
ZMUtil::checkWait();
|
ZMUtil::checkWait();
|
||||||
foreach (ZMBuf::globals("http_header") as $k => $v) {
|
foreach (ZMBuf::globals("http_header") as $k => $v) {
|
||||||
$this->response->setHeader($k, $v);
|
$this->response->setHeader($k, $v);
|
||||||
}
|
}
|
||||||
$uri = $this->request->server["request_uri"];
|
$uri = $this->request->server["request_uri"];
|
||||||
|
Console::verbose($this->request->server["remote_addr"] . " request " . $uri);
|
||||||
$uri = explode("/", $uri);
|
$uri = explode("/", $uri);
|
||||||
$uri = array_diff($uri, ["..", "", "."]);
|
$uri = array_diff($uri, ["..", "", "."]);
|
||||||
$node = ZMBuf::$req_mapping;
|
$node = ZMBuf::$req_mapping;
|
||||||
$params = [];
|
$params = [];
|
||||||
while (true) {
|
while (true) {
|
||||||
$r = array_shift($uri);
|
$r = array_shift($uri);
|
||||||
if ($r === null) break;
|
if ($r === null) {
|
||||||
|
if ($node == ZMBuf::$req_mapping) goto statics;
|
||||||
|
else break;
|
||||||
|
}
|
||||||
if (($cnt = count($node["son"] ?? [])) == 1) {
|
if (($cnt = count($node["son"] ?? [])) == 1) {
|
||||||
if (isset($node["param_route"])) {
|
if (isset($node["param_route"])) {
|
||||||
foreach ($node["son"] as $k => $v) {
|
foreach ($node["son"] as $k => $v) {
|
||||||
@@ -79,13 +85,18 @@ class RequestEvent implements SwooleEvent
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
statics:
|
||||||
if (ZMBuf::globals("static_file_server")["status"]) {
|
if (ZMBuf::globals("static_file_server")["status"]) {
|
||||||
$base_dir = ZMBuf::globals("static_file_server")["document_root"];
|
$base_dir = ZMBuf::globals("static_file_server")["document_root"];
|
||||||
$base_index = ZMBuf::globals("static_file_server")["document_index"];
|
$base_index = ZMBuf::globals("static_file_server")["document_index"];
|
||||||
$uri = $this->request->server["request_uri"];
|
$uri = $this->request->server["request_uri"];
|
||||||
$path = realpath($base_dir . urldecode($uri));
|
$path = realpath($base_dir . urldecode($uri));
|
||||||
if ($path !== false) {
|
if ($path !== false) {
|
||||||
|
if (is_dir($path) && mb_substr($uri, -1, 1) != "/") {
|
||||||
|
$this->response->redirect($uri . "/", 301);
|
||||||
|
$this->response->end();
|
||||||
|
return $this;
|
||||||
|
}
|
||||||
if (is_dir($path)) $path = $path . '/';
|
if (is_dir($path)) $path = $path . '/';
|
||||||
$work = realpath(DataProvider::getWorkingDir()) . '/';
|
$work = realpath(DataProvider::getWorkingDir()) . '/';
|
||||||
if (strpos($path, $work) !== 0) {
|
if (strpos($path, $work) !== 0) {
|
||||||
@@ -149,7 +160,8 @@ class RequestEvent implements SwooleEvent
|
|||||||
/**
|
/**
|
||||||
* @inheritDoc
|
* @inheritDoc
|
||||||
*/
|
*/
|
||||||
public function onAfter() {
|
public function onAfter()
|
||||||
|
{
|
||||||
foreach (ZMBuf::$events[SwooleEventAfter::class] ?? [] as $v) {
|
foreach (ZMBuf::$events[SwooleEventAfter::class] ?? [] as $v) {
|
||||||
if (strtolower($v->type) == "request" && $this->parseSwooleRule($v)) {
|
if (strtolower($v->type) == "request" && $this->parseSwooleRule($v)) {
|
||||||
$c = $v->class;
|
$c = $v->class;
|
||||||
@@ -161,12 +173,14 @@ class RequestEvent implements SwooleEvent
|
|||||||
return $this;
|
return $this;
|
||||||
}
|
}
|
||||||
|
|
||||||
private function responseStatus(int $int) {
|
private function responseStatus(int $int)
|
||||||
|
{
|
||||||
$this->response->status($int);
|
$this->response->status($int);
|
||||||
$this->response->end();
|
$this->response->end();
|
||||||
}
|
}
|
||||||
|
|
||||||
private function parseSwooleRule($v) {
|
private function parseSwooleRule($v)
|
||||||
|
{
|
||||||
switch (explode(":", $v->rule)[0]) {
|
switch (explode(":", $v->rule)[0]) {
|
||||||
case "containsGet":
|
case "containsGet":
|
||||||
case "containsPost":
|
case "containsPost":
|
||||||
|
|||||||
@@ -4,6 +4,7 @@
|
|||||||
namespace ZM\Event\Swoole;
|
namespace ZM\Event\Swoole;
|
||||||
|
|
||||||
|
|
||||||
|
use Closure;
|
||||||
use Doctrine\Common\Annotations\AnnotationException;
|
use Doctrine\Common\Annotations\AnnotationException;
|
||||||
use Framework\ZMBuf;
|
use Framework\ZMBuf;
|
||||||
use Swoole\Server;
|
use Swoole\Server;
|
||||||
@@ -11,8 +12,6 @@ use ZM\Annotation\Swoole\SwooleEventAfter;
|
|||||||
use ZM\Annotation\Swoole\SwooleEventAt;
|
use ZM\Annotation\Swoole\SwooleEventAt;
|
||||||
use ZM\Connection\ConnectionManager;
|
use ZM\Connection\ConnectionManager;
|
||||||
use ZM\Event\EventHandler;
|
use ZM\Event\EventHandler;
|
||||||
use ZM\ModBase;
|
|
||||||
use ZM\ModHandleType;
|
|
||||||
use ZM\Utils\ZMUtil;
|
use ZM\Utils\ZMUtil;
|
||||||
|
|
||||||
class WSCloseEvent implements SwooleEvent
|
class WSCloseEvent implements SwooleEvent
|
||||||
@@ -32,8 +31,7 @@ class WSCloseEvent implements SwooleEvent
|
|||||||
*/
|
*/
|
||||||
public function onActivate() {
|
public function onActivate() {
|
||||||
ZMUtil::checkWait();
|
ZMUtil::checkWait();
|
||||||
ConnectionManager::close($this->fd);
|
set_coroutine_params(["server" => $this->server, "fd" => $this->fd, "connection" => ConnectionManager::get($this->fd)]);
|
||||||
set_coroutine_params(["server" => $this->server, "fd" => $this->fd]);
|
|
||||||
foreach(ZMBuf::$events[SwooleEventAt::class] ?? [] as $v) {
|
foreach(ZMBuf::$events[SwooleEventAt::class] ?? [] as $v) {
|
||||||
if(strtolower($v->type) == "close" && $this->parseSwooleRule($v)) {
|
if(strtolower($v->type) == "close" && $this->parseSwooleRule($v)) {
|
||||||
$c = $v->class;
|
$c = $v->class;
|
||||||
@@ -41,6 +39,7 @@ class WSCloseEvent implements SwooleEvent
|
|||||||
if(context()->getCache("block_continue") === true) break;
|
if(context()->getCache("block_continue") === true) break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
ConnectionManager::close($this->fd);
|
||||||
return $this;
|
return $this;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -60,6 +59,11 @@ class WSCloseEvent implements SwooleEvent
|
|||||||
}
|
}
|
||||||
|
|
||||||
private function parseSwooleRule($v) {
|
private function parseSwooleRule($v) {
|
||||||
|
switch (explode(":", $v->rule)[0]) {
|
||||||
|
case "connectType": //websocket连接类型
|
||||||
|
if ($v->callback instanceof Closure) return call_user_func($v->callback, ConnectionManager::get($this->fd));
|
||||||
|
break;
|
||||||
|
}
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ namespace ZM\Event\Swoole;
|
|||||||
use Co;
|
use Co;
|
||||||
use Doctrine\Common\Annotations\AnnotationException;
|
use Doctrine\Common\Annotations\AnnotationException;
|
||||||
use Exception;
|
use Exception;
|
||||||
|
use PDO;
|
||||||
use ReflectionException;
|
use ReflectionException;
|
||||||
use Swoole\Coroutine;
|
use Swoole\Coroutine;
|
||||||
use Swoole\Database\PDOConfig;
|
use Swoole\Database\PDOConfig;
|
||||||
@@ -101,6 +102,7 @@ class WorkerStartEvent implements SwooleEvent
|
|||||||
->withCharset('utf8mb4')
|
->withCharset('utf8mb4')
|
||||||
->withUsername($sql["sql_username"])
|
->withUsername($sql["sql_username"])
|
||||||
->withPassword($sql["sql_password"])
|
->withPassword($sql["sql_password"])
|
||||||
|
->withOptions($sql["sql_options"] ?? [PDO::ATTR_STRINGIFY_FETCHES => false])
|
||||||
);
|
);
|
||||||
DB::initTableList();
|
DB::initTableList();
|
||||||
}
|
}
|
||||||
@@ -174,13 +176,8 @@ class WorkerStartEvent implements SwooleEvent
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
//加载composer类
|
//加载composer类
|
||||||
Console::info("加载composer资源中");
|
//remove stupid duplicate code
|
||||||
if (file_exists(DataProvider::getWorkingDir() . "/vendor/autoload.php")) {
|
|
||||||
require_once DataProvider::getWorkingDir() . "/vendor/autoload.php";
|
|
||||||
}
|
|
||||||
if (isPharMode()) require_once WORKING_DIR . "/vendor/autoload.php";
|
|
||||||
|
|
||||||
//加载各个模块的注解类,以及反射
|
//加载各个模块的注解类,以及反射
|
||||||
Console::info("检索Module中");
|
Console::info("检索Module中");
|
||||||
|
|||||||
@@ -184,7 +184,7 @@ class Response
|
|||||||
* @return mixed
|
* @return mixed
|
||||||
*/
|
*/
|
||||||
public function redirect($location, $http_code = null) {
|
public function redirect($location, $http_code = null) {
|
||||||
return $this->redirect($location, $http_code);
|
return $this->response->redirect($location, $http_code);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -15,6 +15,11 @@ use ZM\Http\Response;
|
|||||||
use Swoole\WebSocket\Frame;
|
use Swoole\WebSocket\Frame;
|
||||||
use Swoole\WebSocket\Server;
|
use Swoole\WebSocket\Server;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Class ModBase
|
||||||
|
* @package ZM
|
||||||
|
* @deprecated
|
||||||
|
*/
|
||||||
abstract class ModBase
|
abstract class ModBase
|
||||||
{
|
{
|
||||||
/** @var Server */
|
/** @var Server */
|
||||||
|
|||||||
@@ -4,6 +4,7 @@
|
|||||||
namespace ZM\Utils;
|
namespace ZM\Utils;
|
||||||
|
|
||||||
|
|
||||||
|
use Framework\Console;
|
||||||
use Swlib\Saber;
|
use Swlib\Saber;
|
||||||
use Swoole\Coroutine\Http\Client;
|
use Swoole\Coroutine\Http\Client;
|
||||||
|
|
||||||
@@ -11,20 +12,21 @@ class ZMRequest
|
|||||||
{
|
{
|
||||||
/**
|
/**
|
||||||
* 使用Swoole协程客户端发起HTTP GET请求
|
* 使用Swoole协程客户端发起HTTP GET请求
|
||||||
* @version 1.1
|
|
||||||
* 返回请求后的body
|
|
||||||
* 如果请求失败或返回状态不是200,则返回 false
|
|
||||||
* @param $url
|
* @param $url
|
||||||
* @param array $headers
|
* @param array $headers
|
||||||
* @param array $set
|
* @param array $set
|
||||||
* @param bool $return_body
|
* @param bool $return_body
|
||||||
* @return bool|string|Client
|
* @return bool|string|Client
|
||||||
|
* @version 1.1
|
||||||
|
* 返回请求后的body
|
||||||
|
* 如果请求失败或返回状态不是200,则返回 false
|
||||||
*/
|
*/
|
||||||
public static function get($url, $headers = [], $set = [], $return_body = true) {
|
public static function get($url, $headers = [], $set = [], $return_body = true) {
|
||||||
$parse = parse_url($url);
|
/** @var Client $cli */
|
||||||
$cli = new Client($parse["host"], ($parse["scheme"] == "https" ? 443 : (isset($parse["port"]) ? $parse["port"] : 80)), ($parse["scheme"] == "https" ? true : false));
|
list($cli, $parse) = self::getNewClient($url);
|
||||||
$cli->setHeaders($headers);
|
if($cli === null) return false;
|
||||||
$cli->set($set == [] ? ['timeout' => 15.0] : $set);
|
$cli->set($set == [] ? ['timeout' => 15.0] : $set);
|
||||||
|
$cli->setHeaders($headers);
|
||||||
$cli->get($parse["path"] . (isset($parse["query"]) ? "?" . $parse["query"] : ""));
|
$cli->get($parse["path"] . (isset($parse["query"]) ? "?" . $parse["query"] : ""));
|
||||||
if ($return_body) {
|
if ($return_body) {
|
||||||
if ($cli->errCode != 0 || $cli->statusCode != 200) return false;
|
if ($cli->errCode != 0 || $cli->statusCode != 200) return false;
|
||||||
@@ -49,8 +51,9 @@ class ZMRequest
|
|||||||
* @return bool|string|Client
|
* @return bool|string|Client
|
||||||
*/
|
*/
|
||||||
public static function post($url, array $header, $data, $set = [], $return_body = true) {
|
public static function post($url, array $header, $data, $set = [], $return_body = true) {
|
||||||
$parse = parse_url($url);
|
/** @var Client $cli */
|
||||||
$cli = new Client($parse["host"], ($parse["scheme"] == "https" ? 443 : (isset($parse["port"]) ? $parse["port"] : 80)), ($parse["scheme"] == "https" ? true : false));
|
list($cli, $parse) = self::getNewClient($url);
|
||||||
|
if($cli === null) return false;
|
||||||
$cli->set($set == [] ? ['timeout' => 15.0] : $set);
|
$cli->set($set == [] ? ['timeout' => 15.0] : $set);
|
||||||
$cli->setHeaders($header);
|
$cli->setHeaders($header);
|
||||||
$cli->post($parse["path"] . (isset($parse["query"]) ? ("?" . $parse["query"]) : ""), $data);
|
$cli->post($parse["path"] . (isset($parse["query"]) ? ("?" . $parse["query"]) : ""), $data);
|
||||||
@@ -65,6 +68,17 @@ class ZMRequest
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param $url
|
||||||
|
* @param array $set
|
||||||
|
* @param array $header
|
||||||
|
* @return ZMWebSocket
|
||||||
|
* @since 1.5
|
||||||
|
*/
|
||||||
|
public static function websocket($url, $set = ['websocket_mask' => true], $header = []) {
|
||||||
|
return new ZMWebSocket($url, $set, $header);
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @param $option
|
* @param $option
|
||||||
* @return Saber
|
* @return Saber
|
||||||
@@ -72,4 +86,68 @@ class ZMRequest
|
|||||||
public static function session($option) {
|
public static function session($option) {
|
||||||
return Saber::session($option);
|
return Saber::session($option);
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
/**
|
||||||
|
* @param $url
|
||||||
|
* @param array $attribute
|
||||||
|
* @param bool $return_body
|
||||||
|
* @return bool|string|Client
|
||||||
|
*/
|
||||||
|
public static function request($url, $attribute = [], $return_body = true) {
|
||||||
|
/** @var Client $cli */
|
||||||
|
list($cli, $parse) = self::getNewClient($url);
|
||||||
|
if($cli === null) return false;
|
||||||
|
$cli->set($attribute["set"] ?? ["timeout" => 15.0]);
|
||||||
|
$cli->setMethod($attribute["method"] ?? "GET");
|
||||||
|
$cli->setHeaders($attribute["headers"] ?? []);
|
||||||
|
if(isset($attribute["data"])) $cli->setData($attribute["data"]);
|
||||||
|
if(isset($attribute["file"])) {
|
||||||
|
foreach($attribute["file"] as $k => $v) {
|
||||||
|
$cli->addFile($v["path"], $v["name"], $v["mime_type"] ?? null, $v["filename"] ?? null, $v["offset"] ?? 0, $v["length"] ?? 0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
$cli->execute($parse["path"] . (isset($parse["query"]) ? "?" . $parse["query"] : ""));
|
||||||
|
if ($return_body) {
|
||||||
|
if ($cli->errCode != 0 || $cli->statusCode != 200) return false;
|
||||||
|
$a = $cli->body;
|
||||||
|
$cli->close();
|
||||||
|
return $a;
|
||||||
|
} else {
|
||||||
|
$cli->close();
|
||||||
|
return $cli;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param $url
|
||||||
|
* @param null|bool $dst
|
||||||
|
* @return bool
|
||||||
|
*/
|
||||||
|
public static function downloadFile($url, $dst = null) {
|
||||||
|
/** @var Client $cli */
|
||||||
|
list($cli, $parse) = self::getNewClient($url);
|
||||||
|
if($cli === null) return false;
|
||||||
|
$cli->set(["timeout" => 60.0]);
|
||||||
|
$save_path = $dst === null ? "/tmp/_zm_".mt_rand(1000000, 9999999) : $dst;
|
||||||
|
$result = $cli->download($parse["path"] . (isset($parse["query"]) ? "?" . $parse["query"] : ""), $save_path);
|
||||||
|
if($result === false) return false;
|
||||||
|
elseif ($dst === null) return $save_path;
|
||||||
|
else return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param $url
|
||||||
|
* @return bool|array
|
||||||
|
*/
|
||||||
|
private static function getNewClient($url) {
|
||||||
|
$parse = parse_url($url);
|
||||||
|
if (!isset($parse["host"])) {
|
||||||
|
Console::warning("ZMRequest: url must contains scheme such as \"http(s)://\"");
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if(!isset($parse["path"])) $parse["path"] = "/";
|
||||||
|
$port = $parse["port"] ?? (($parse["scheme"] ?? "http") == "https" ? 443 : 80);
|
||||||
|
$cli = new Client($parse["host"], $port, ($parse["scheme"] ?? "http") == "https");
|
||||||
|
return [$cli, $parse];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -24,7 +24,7 @@ class ZMUtil
|
|||||||
|
|
||||||
public static function stop($without_shutdown = false) {
|
public static function stop($without_shutdown = false) {
|
||||||
Console::info(Console::setColor("Stopping server...", "red"));
|
Console::info(Console::setColor("Stopping server...", "red"));
|
||||||
foreach (ZMBuf::$server->connections as $v) {
|
foreach ((ZMBuf::$server->connections ?? []) as $v) {
|
||||||
ZMBuf::$server->close($v);
|
ZMBuf::$server->close($v);
|
||||||
}
|
}
|
||||||
DataProvider::saveBuffer();
|
DataProvider::saveBuffer();
|
||||||
|
|||||||
106
src/ZM/Utils/ZMWebSocket.php
Normal file
106
src/ZM/Utils/ZMWebSocket.php
Normal file
@@ -0,0 +1,106 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
|
||||||
|
namespace ZM\Utils;
|
||||||
|
|
||||||
|
|
||||||
|
use Framework\Console;
|
||||||
|
use Swoole\Coroutine\Http\Client;
|
||||||
|
use Swoole\WebSocket\Frame;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Class ZMWebSocket
|
||||||
|
* @package ZM\Utils
|
||||||
|
* @since 1.5
|
||||||
|
*/
|
||||||
|
class ZMWebSocket
|
||||||
|
{
|
||||||
|
private $parse;
|
||||||
|
private $client;
|
||||||
|
|
||||||
|
public $is_available = false;
|
||||||
|
|
||||||
|
private $close_func;
|
||||||
|
private $message_func;
|
||||||
|
|
||||||
|
public function __construct($url, $set = ['websocket_mask' => true], $header = []) {
|
||||||
|
$this->parse = parse_url($url);
|
||||||
|
if (!isset($this->parse["host"])) {
|
||||||
|
Console::warning("ZMRequest: url must contains scheme such as \"ws(s)://\"");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!isset($this->parse["path"])) $this->parse["path"] = "/";
|
||||||
|
$port = $this->parse["port"] ?? (($this->parse["scheme"] ?? "ws") == "wss" ? 443 : 80);
|
||||||
|
$this->client = new Client($this->parse["host"], $port, (($this->parse["scheme"] ?? "ws") == "wss" ? true : false));
|
||||||
|
$this->client->set($set);
|
||||||
|
if ($header != []) $this->client->setHeaders($header);
|
||||||
|
$this->is_available = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return bool
|
||||||
|
*/
|
||||||
|
public function upgrade() {
|
||||||
|
if (!$this->is_available) return false;
|
||||||
|
$r = $this->client->upgrade($this->parse["path"] . (isset($this->parse["query"]) ? ("?" . $this->parse["query"]) : ""));
|
||||||
|
if ($r) {
|
||||||
|
go(function () {
|
||||||
|
while (true) {
|
||||||
|
$result = $this->client->recv(60);
|
||||||
|
if ($result === false) {
|
||||||
|
if ($this->client->connected === false) {
|
||||||
|
go(function () {
|
||||||
|
call_user_func($this->close_func, $this->client);
|
||||||
|
});
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
} elseif ($result instanceof Frame) {
|
||||||
|
go(function () use ($result) {
|
||||||
|
$this->is_available = false;
|
||||||
|
call_user_func($this->message_func, $result, $this->client);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param callable $callable
|
||||||
|
* @return $this
|
||||||
|
*/
|
||||||
|
public function onMessage(callable $callable) {
|
||||||
|
$this->message_func = $callable;
|
||||||
|
return $this;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param callable $callable
|
||||||
|
* @return $this
|
||||||
|
*/
|
||||||
|
public function onClose(callable $callable) {
|
||||||
|
$this->close_func = $callable;
|
||||||
|
return $this;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!debug_backtrace()) {
|
||||||
|
go(function () {
|
||||||
|
require_once __DIR__ . "/../../Framework/Console.php";
|
||||||
|
$cli = new ZMWebSocket("ws://127.0.0.1:20001/");
|
||||||
|
if (!$cli->is_available) die("Error!\n");
|
||||||
|
$cli->onMessage(function (Frame $frame) {
|
||||||
|
var_dump($frame);
|
||||||
|
});
|
||||||
|
$cli->onClose(function () {
|
||||||
|
echo "Connection closed.\n";
|
||||||
|
});
|
||||||
|
if ($cli->upgrade()) {
|
||||||
|
echo "成功连接!\n";
|
||||||
|
} else {
|
||||||
|
echo "连接失败!\n";
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user