node-karin 0.12.0 → 0.12.2-5.pr.206.027f2f2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (254) hide show
  1. package/CHANGELOG.md +1029 -0
  2. package/default/comment/config.json +34 -0
  3. package/default/comment/friendDirect.json +10 -0
  4. package/default/comment/groupGuild.json +11 -0
  5. package/default/comment/server.json +17 -0
  6. package/default/config/adapter.json +28 -0
  7. package/default/config/config.json +47 -0
  8. package/default/config/groups.json +47 -0
  9. package/default/config/groups.yaml +70 -0
  10. package/default/config/pm2.json +16 -0
  11. package/default/config/privates.json +23 -0
  12. package/default/config/privates.yaml +31 -0
  13. package/default/config/redis.json +10 -0
  14. package/default/config/render.json +19 -0
  15. package/default/view/group.yaml +73 -0
  16. package/dist/index.d.ts +9869 -0
  17. package/dist/index.js +12643 -0
  18. package/dist/module/art-template.cjs +11 -0
  19. package/dist/module/art-template.d.ts +1 -0
  20. package/dist/module/axios.cjs +22 -0
  21. package/dist/module/axios.d.ts +2 -0
  22. package/dist/module/chalk.cjs +22 -0
  23. package/dist/module/chalk.d.ts +2 -0
  24. package/dist/module/chokidar.cjs +22 -0
  25. package/dist/module/chokidar.d.ts +2 -0
  26. package/dist/module/commander.cjs +35 -0
  27. package/dist/module/commander.d.ts +3 -0
  28. package/dist/module/commander.js +3 -0
  29. package/dist/module/dotenv.cjs +22 -0
  30. package/dist/module/dotenv.d.ts +2 -0
  31. package/dist/module/dotenv.js +2 -0
  32. package/dist/module/express.cjs +112 -0
  33. package/dist/module/express.d.ts +1 -0
  34. package/dist/module/express.js +1 -0
  35. package/dist/module/level.cjs +22 -0
  36. package/dist/module/level.d.ts +2 -0
  37. package/dist/module/lodash.cjs +11 -0
  38. package/dist/module/lodash.d.ts +1 -0
  39. package/dist/module/log4js.cjs +22 -0
  40. package/dist/module/log4js.d.ts +2 -0
  41. package/dist/module/moment.cjs +11 -0
  42. package/dist/module/moment.d.ts +1 -0
  43. package/dist/module/node-schedule.cjs +22 -0
  44. package/dist/module/node-schedule.d.ts +2 -0
  45. package/dist/module/redis.cjs +22 -0
  46. package/dist/module/redis.d.ts +2 -0
  47. package/dist/module/ws.cjs +28 -0
  48. package/dist/module/ws.d.ts +1 -0
  49. package/dist/module/ws.js +1 -0
  50. package/dist/module/yaml.cjs +22 -0
  51. package/dist/module/yaml.d.ts +2 -0
  52. package/dist/root.d.ts +40 -0
  53. package/dist/root.js +44 -0
  54. package/package.json +142 -128
  55. package/LICENSE +0 -674
  56. package/README.md +0 -56
  57. package/config/defSet/App.yaml +0 -42
  58. package/config/defSet/config.yaml +0 -65
  59. package/config/defSet/group.yaml +0 -56
  60. package/config/defSet/pm2.yaml +0 -21
  61. package/config/defSet/redis.yaml +0 -18
  62. package/config/defSet/server.yaml +0 -42
  63. package/config/view/group.yaml +0 -92
  64. package/lib/adapter/index.d.ts +0 -2
  65. package/lib/adapter/index.js +0 -2
  66. package/lib/adapter/input/index.d.ts +0 -78
  67. package/lib/adapter/input/index.js +0 -205
  68. package/lib/adapter/onebot/11/convert.d.ts +0 -12
  69. package/lib/adapter/onebot/11/convert.js +0 -167
  70. package/lib/adapter/onebot/11/event.d.ts +0 -25
  71. package/lib/adapter/onebot/11/event.js +0 -442
  72. package/lib/adapter/onebot/11/index.d.ts +0 -508
  73. package/lib/adapter/onebot/11/index.js +0 -1047
  74. package/lib/cli/index.d.ts +0 -92
  75. package/lib/cli/index.js +0 -307
  76. package/lib/cli/init.d.ts +0 -2
  77. package/lib/cli/init.js +0 -22
  78. package/lib/cli/karin.d.ts +0 -2
  79. package/lib/cli/karin.js +0 -16
  80. package/lib/cli/pkg.d.ts +0 -4
  81. package/lib/cli/pkg.js +0 -14
  82. package/lib/cli/start.d.ts +0 -1
  83. package/lib/cli/start.js +0 -8
  84. package/lib/core/index.d.ts +0 -10
  85. package/lib/core/index.js +0 -10
  86. package/lib/core/init/config.d.ts +0 -43
  87. package/lib/core/init/config.js +0 -201
  88. package/lib/core/init/dir.d.ts +0 -4
  89. package/lib/core/init/dir.js +0 -7
  90. package/lib/core/init/init.d.ts +0 -1
  91. package/lib/core/init/init.js +0 -47
  92. package/lib/core/karin/karin.d.ts +0 -198
  93. package/lib/core/karin/karin.js +0 -226
  94. package/lib/core/listener/listener.d.ts +0 -145
  95. package/lib/core/listener/listener.js +0 -235
  96. package/lib/core/plugin/base.d.ts +0 -156
  97. package/lib/core/plugin/base.js +0 -131
  98. package/lib/core/plugin/loader.d.ts +0 -141
  99. package/lib/core/plugin/loader.js +0 -618
  100. package/lib/core/process/process.d.ts +0 -18
  101. package/lib/core/process/process.js +0 -96
  102. package/lib/core/server/server.d.ts +0 -25
  103. package/lib/core/server/server.js +0 -295
  104. package/lib/db/index.d.ts +0 -2
  105. package/lib/db/index.js +0 -2
  106. package/lib/db/level/level.d.ts +0 -19
  107. package/lib/db/level/level.js +0 -36
  108. package/lib/db/redis/redis.d.ts +0 -2
  109. package/lib/db/redis/redis.js +0 -135
  110. package/lib/db/redis/redis_level.d.ts +0 -112
  111. package/lib/db/redis/redis_level.js +0 -281
  112. package/lib/event/handler/base.d.ts +0 -42
  113. package/lib/event/handler/base.js +0 -200
  114. package/lib/event/handler/message.d.ts +0 -29
  115. package/lib/event/handler/message.js +0 -307
  116. package/lib/event/handler/notice.d.ts +0 -18
  117. package/lib/event/handler/notice.js +0 -214
  118. package/lib/event/handler/request.d.ts +0 -18
  119. package/lib/event/handler/request.js +0 -115
  120. package/lib/event/handler/review.d.ts +0 -55
  121. package/lib/event/handler/review.js +0 -386
  122. package/lib/event/index.d.ts +0 -5
  123. package/lib/event/index.js +0 -5
  124. package/lib/index.d.ts +0 -8
  125. package/lib/index.js +0 -8
  126. package/lib/modules/art-template.d.ts +0 -1
  127. package/lib/modules/axios.d.ts +0 -2
  128. package/lib/modules/chalk.d.ts +0 -2
  129. package/lib/modules/chokidar.d.ts +0 -2
  130. package/lib/modules/commander.d.ts +0 -2
  131. package/lib/modules/commander.js +0 -2
  132. package/lib/modules/express.d.ts +0 -3
  133. package/lib/modules/express.js +0 -3
  134. package/lib/modules/level.d.ts +0 -2
  135. package/lib/modules/lodash.d.ts +0 -1
  136. package/lib/modules/log4js.d.ts +0 -2
  137. package/lib/modules/moment.d.ts +0 -1
  138. package/lib/modules/node-schedule.d.ts +0 -2
  139. package/lib/modules/redis.d.ts +0 -2
  140. package/lib/modules/ws.d.ts +0 -3
  141. package/lib/modules/ws.js +0 -3
  142. package/lib/modules/yaml.d.ts +0 -2
  143. package/lib/modules.d.ts +0 -15
  144. package/lib/modules.js +0 -15
  145. package/lib/render/app.d.ts +0 -56
  146. package/lib/render/app.js +0 -120
  147. package/lib/render/base.d.ts +0 -30
  148. package/lib/render/base.js +0 -69
  149. package/lib/render/client.d.ts +0 -41
  150. package/lib/render/client.js +0 -238
  151. package/lib/render/http.d.ts +0 -19
  152. package/lib/render/http.js +0 -50
  153. package/lib/render/index.d.ts +0 -6
  154. package/lib/render/index.js +0 -6
  155. package/lib/render/server.d.ts +0 -25
  156. package/lib/render/server.js +0 -101
  157. package/lib/render/wormhole.d.ts +0 -1
  158. package/lib/render/wormhole.js +0 -156
  159. package/lib/types/adapter/api.d.ts +0 -399
  160. package/lib/types/adapter/api.js +0 -1
  161. package/lib/types/adapter/base.d.ts +0 -560
  162. package/lib/types/adapter/base.js +0 -1
  163. package/lib/types/config/config.d.ts +0 -379
  164. package/lib/types/config/config.js +0 -1
  165. package/lib/types/element/element.d.ts +0 -565
  166. package/lib/types/element/element.js +0 -1
  167. package/lib/types/element/qqbot.d.ts +0 -123
  168. package/lib/types/element/qqbot.js +0 -1
  169. package/lib/types/event/contact.d.ts +0 -28
  170. package/lib/types/event/contact.js +0 -1
  171. package/lib/types/event/event.d.ts +0 -305
  172. package/lib/types/event/event.js +0 -1
  173. package/lib/types/event/index.d.ts +0 -12
  174. package/lib/types/event/index.js +0 -7
  175. package/lib/types/event/message.d.ts +0 -109
  176. package/lib/types/event/message.js +0 -74
  177. package/lib/types/event/notice.d.ts +0 -513
  178. package/lib/types/event/notice.js +0 -52
  179. package/lib/types/event/reply.d.ts +0 -50
  180. package/lib/types/event/reply.js +0 -1
  181. package/lib/types/event/request.d.ts +0 -126
  182. package/lib/types/event/request.js +0 -52
  183. package/lib/types/event/sender.d.ts +0 -44
  184. package/lib/types/event/sender.js +0 -1
  185. package/lib/types/index.d.ts +0 -13
  186. package/lib/types/index.js +0 -13
  187. package/lib/types/logger/logger.d.ts +0 -110
  188. package/lib/types/logger/logger.js +0 -1
  189. package/lib/types/onebot11/api.d.ts +0 -53
  190. package/lib/types/onebot11/api.js +0 -1
  191. package/lib/types/onebot11/event.d.ts +0 -619
  192. package/lib/types/onebot11/event.js +0 -2
  193. package/lib/types/onebot11/index.d.ts +0 -6
  194. package/lib/types/onebot11/index.js +0 -6
  195. package/lib/types/onebot11/params.d.ts +0 -609
  196. package/lib/types/onebot11/params.js +0 -1
  197. package/lib/types/onebot11/response.d.ts +0 -516
  198. package/lib/types/onebot11/response.js +0 -1
  199. package/lib/types/onebot11/segment.d.ts +0 -269
  200. package/lib/types/onebot11/segment.js +0 -1
  201. package/lib/types/onebot11/sender.d.ts +0 -59
  202. package/lib/types/onebot11/sender.js +0 -1
  203. package/lib/types/plugin/app.d.ts +0 -71
  204. package/lib/types/plugin/app.js +0 -1
  205. package/lib/types/plugin/plugin.d.ts +0 -473
  206. package/lib/types/plugin/plugin.js +0 -1
  207. package/lib/types/render/render.d.ts +0 -118
  208. package/lib/types/render/render.js +0 -1
  209. package/lib/types/type/global.d.ts +0 -25
  210. package/lib/types/type/global.js +0 -1
  211. package/lib/utils/common/common.d.ts +0 -236
  212. package/lib/utils/common/common.js +0 -708
  213. package/lib/utils/config/config.d.ts +0 -193
  214. package/lib/utils/config/config.js +0 -328
  215. package/lib/utils/config/updateVersion.d.ts +0 -33
  216. package/lib/utils/config/updateVersion.js +0 -145
  217. package/lib/utils/config/yamlEditor.d.ts +0 -101
  218. package/lib/utils/config/yamlEditor.js +0 -330
  219. package/lib/utils/core/handler.d.ts +0 -18
  220. package/lib/utils/core/handler.js +0 -46
  221. package/lib/utils/core/logger.d.ts +0 -3
  222. package/lib/utils/core/logger.js +0 -105
  223. package/lib/utils/core/segment.d.ts +0 -279
  224. package/lib/utils/core/segment.js +0 -451
  225. package/lib/utils/index.d.ts +0 -13
  226. package/lib/utils/index.js +0 -13
  227. package/lib/utils/tools/button.d.ts +0 -2
  228. package/lib/utils/tools/button.js +0 -27
  229. package/lib/utils/tools/exec.d.ts +0 -20
  230. package/lib/utils/tools/exec.js +0 -54
  231. package/lib/utils/tools/ffmpeg.d.ts +0 -12
  232. package/lib/utils/tools/ffmpeg.js +0 -25
  233. package/lib/utils/tools/restart.d.ts +0 -15
  234. package/lib/utils/tools/restart.js +0 -39
  235. package/lib/utils/tools/stop.d.ts +0 -7
  236. package/lib/utils/tools/stop.js +0 -13
  237. package/lib/utils/tools/update.d.ts +0 -67
  238. package/lib/utils/tools/update.js +0 -151
  239. /package/{config → default}/view/App.yaml +0 -0
  240. /package/{config → default}/view/config.yaml +0 -0
  241. /package/{config → default}/view/pm2.yaml +0 -0
  242. /package/{config → default}/view/redis.yaml +0 -0
  243. /package/{config → default}/view/server.yaml +0 -0
  244. /package/{lib/modules → dist/module}/art-template.js +0 -0
  245. /package/{lib/modules → dist/module}/axios.js +0 -0
  246. /package/{lib/modules → dist/module}/chalk.js +0 -0
  247. /package/{lib/modules → dist/module}/chokidar.js +0 -0
  248. /package/{lib/modules → dist/module}/level.js +0 -0
  249. /package/{lib/modules → dist/module}/lodash.js +0 -0
  250. /package/{lib/modules → dist/module}/log4js.js +0 -0
  251. /package/{lib/modules → dist/module}/moment.js +0 -0
  252. /package/{lib/modules → dist/module}/node-schedule.js +0 -0
  253. /package/{lib/modules → dist/module}/redis.js +0 -0
  254. /package/{lib/modules → dist/module}/yaml.js +0 -0
@@ -1,96 +0,0 @@
1
- import { karin } from '../karin/karin.js';
2
- import { logger, common, config } from '../../utils/index.js';
3
- /**
4
- * 处理基本事件
5
- */
6
- export default class Process {
7
- /**
8
- * 进程初始化
9
- */
10
- static async process() {
11
- /**
12
- * 监听挂起信号 在终端关闭时触发
13
- */
14
- process.once('SIGHUP', async (code) => await this.exit(code));
15
- /**
16
- * 监听中断信号 用户按下 Ctrl + C 时触发
17
- */
18
- process.once('SIGINT', async (code) => await this.exit(code));
19
- /**
20
- * 监听终止信号 程序正常退出时触发
21
- */
22
- process.once('SIGTERM', async (code) => await this.exit(code));
23
- /**
24
- * 监听退出信号 windows下程序正常退出时触发
25
- */
26
- process.once('SIGBREAK', async (code) => await this.exit(code));
27
- /**
28
- * 监听退出信号 与 SIGINT 类似,但会生成核心转储
29
- */
30
- process.once('SIGQUIT', async (code) => await this.exit(code));
31
- /**
32
- * 监听退出信号 Node.js进程退出时触发
33
- */
34
- process.once('exit', async (code) => await this.exit(code));
35
- /**
36
- * 捕获警告
37
- */
38
- process.on('warning', warning => karin.emit('warn', warning));
39
- /**
40
- * 捕获错误
41
- */
42
- process.on('uncaughtException', error => karin.emit('error', error));
43
- /**
44
- * 捕获未处理的Promise错误
45
- */
46
- process.on('unhandledRejection', error => karin.emit('error', error));
47
- return this;
48
- }
49
- /**
50
- * 检查后台进程
51
- */
52
- static async check() {
53
- const host = `http://127.0.0.1:${config.Server.http.port}/api`;
54
- /**
55
- * 使用api来检查后台
56
- */
57
- const res = await common.axios(host + '/ping', 'get', { timeout: 2000 });
58
- if (!res)
59
- return this;
60
- logger.mark(logger.red('检测到后台进程 正在关闭'));
61
- /** 发退出信号 */
62
- await common.axios(host + '/exit', 'get', { timeout: 10 });
63
- for (let i = 0; i < 50; i++) {
64
- const res = await common.axios(host + '/ping', 'get', { timeout: 100 });
65
- /** 请求成功继续循环 */
66
- if (res)
67
- continue;
68
- /** 请求异常即代表后台进程已关闭 */
69
- logger.mark(logger.green('后台进程已关闭'));
70
- return this;
71
- }
72
- /**
73
- * 走到这里说明后台关闭失败
74
- * 根据配置文件判断是否继续
75
- */
76
- logger.error(logger.red(`后台进程关闭失败,请检查是否有进程正在占用端口${config.Server.http.port}`));
77
- await this.exit();
78
- return this;
79
- }
80
- /**
81
- * 退出Karin
82
- * @param code 退出码
83
- */
84
- static async exit(code = 0) {
85
- try {
86
- const { redis } = await import('../../db/index.js');
87
- if (redis && redis.save)
88
- await redis.save();
89
- logger.mark(`Karin 已停止运行 运行时间:${common.uptime()} 退出码:${code || '未知'}`);
90
- }
91
- finally {
92
- process.exit();
93
- }
94
- }
95
- }
96
- Process.process();
@@ -1,25 +0,0 @@
1
- import { WebSocketServer } from 'ws';
2
- import { Express } from 'express';
3
- import { Server as ServerType, ServerResponse, IncomingMessage } from 'http';
4
- export declare const server: {
5
- reg: RegExp;
6
- list: string[];
7
- app: Express;
8
- server: ServerType<typeof IncomingMessage, typeof ServerResponse>;
9
- WebSocketServer: WebSocketServer;
10
- RegExp: RegExp;
11
- /**
12
- * 监听WebSocket连接并初始化http服务器
13
- */
14
- init(): Promise<false | any>;
15
- /**
16
- * HTTP渲染器
17
- */
18
- static(): void;
19
- /**
20
- * 构建静态资源路径
21
- */
22
- staticPath(): Promise<void>;
23
- /** 重启当前HTTP服务器 */
24
- "__#15@#restartServer"(): Promise<void>;
25
- };
@@ -1,295 +0,0 @@
1
- import fs from 'fs';
2
- import { level } from '../../db/index.js';
3
- import { WebSocketServer } from 'ws';
4
- import { createServer } from 'http';
5
- import { karin } from '../karin/karin.js';
6
- import Process from '../process/process.js';
7
- import express from 'express';
8
- import { exec, config, logger, common } from '../../utils/index.js';
9
- import { AdapterOneBot11 } from '../../adapter/onebot/11/index.js';
10
- import { render, HttpRenderer, Wormhole, RenderClient } from '../../render/index.js';
11
- export const server = new (class Server {
12
- reg;
13
- list;
14
- app;
15
- server;
16
- WebSocketServer;
17
- RegExp;
18
- constructor() {
19
- this.reg = /(?:)/;
20
- this.list = [];
21
- this.app = express();
22
- this.server = createServer(this.app);
23
- this.WebSocketServer = new WebSocketServer({ server: this.server });
24
- this.RegExp = new RegExp(`(${process.cwd()}|${process.cwd().replace(/\\/g, '/')})`, 'g');
25
- }
26
- /**
27
- * 监听WebSocket连接并初始化http服务器
28
- */
29
- async init() {
30
- try {
31
- /** 防止多进程端口冲突 启动失败 */
32
- await Process.check();
33
- level.open();
34
- this.WebSocketServer.on('connection', (socket, request) => {
35
- const path = request.url;
36
- const headers = request.headers;
37
- logger.debug('[反向WS]', path, JSON.stringify(headers, null, 2));
38
- try {
39
- const Adapter = karin.getAdapter(path);
40
- if (!Adapter) {
41
- logger.error(`[反向WS] 适配器不存在:${path}`);
42
- return socket.close();
43
- }
44
- const KarinAdapter = new Adapter();
45
- if (typeof KarinAdapter?.server === 'function') {
46
- KarinAdapter.server(socket, request);
47
- }
48
- }
49
- catch (error) {
50
- logger.error(`[反向WS] 注册适配器发生错误:${path}`, error.stack || error.message || error);
51
- socket.close();
52
- }
53
- });
54
- /** GET接口 - 获取当前启动信息 */
55
- this.app.get('/api/ping', (req, res) => {
56
- /** 只允许本机ip访问 */
57
- if (req.hostname === 'localhost' || req.hostname === '127.0.0.1') {
58
- const data = {
59
- pm2_id: process.env.pm_id || '',
60
- uptime: process.uptime(),
61
- karin_app_mode: process.env.karin_app_mode,
62
- karin_app_lang: process.env.karin_app_lang,
63
- karin_app_runner: process.env.karin_app_runner,
64
- karin_app_start_count: process.env.karin_app_start_count,
65
- };
66
- res.json(data);
67
- }
68
- else {
69
- res.status(403).json({ error: '禁止访问', message: '无效的请求' });
70
- }
71
- });
72
- /** GET接口 - 退出当前进程 */
73
- this.app.get('/api/exit', async (req) => {
74
- /** 只允许本机ip访问 */
75
- if (req.hostname === 'localhost' || req.hostname === '127.0.0.1') {
76
- logger.mark('[服务器][HTTP] 收到退出请求,即将退出');
77
- /** 关闭服务器 */
78
- karin.emit('exit.grpc');
79
- this.server.close();
80
- try {
81
- await level.close();
82
- const redis = (await import('../../db/index.js')).redis;
83
- if (redis && redis.id === 'RedisLevel')
84
- await redis.level.close();
85
- }
86
- catch (error) {
87
- logger.error('[服务器][HTTP] 关闭数据库失败');
88
- logger.error(error);
89
- }
90
- /** 如果是pm2 获取当前pm2ID 使用 */
91
- if (process.env.pm_id)
92
- await exec(`pm2 delete ${process.env.pm_id}`);
93
- /** 正常启动的进程 */
94
- process.exit();
95
- }
96
- });
97
- /** 控制台适配器 */
98
- this.app.get('/api/input', (req, res) => {
99
- const name = req.query.name;
100
- const token = req.query.token;
101
- if (!name || !token) {
102
- logger.error('[HTTP][input] 缺少参数', req.query);
103
- return res.status(403).json({ error: '禁止访问', message: '缺少参数' });
104
- }
105
- // 禁止键入向上级目录
106
- if (name.includes('/')) {
107
- logger.error('[HTTP][input] 无效的文件名', name);
108
- return res.status(403).json({ error: '禁止访问', message: '无效的文件名' });
109
- }
110
- const CfgToken = config.Config.AdapterInput.token;
111
- if (CfgToken === 'AdapterInput' || CfgToken !== token) {
112
- logger.error('[HTTP][input] 无效的令牌', token);
113
- return res.status(403).json({ error: '禁止访问', message: '无效的令牌' });
114
- }
115
- const file = process.cwd() + `/temp/input/${name}`;
116
- if (!fs.existsSync(file)) {
117
- logger.error('[HTTP][input] 文件不存在', file);
118
- return res.status(404).json({ error: '文件不存在', message: '找不到指定文件' });
119
- }
120
- logger.info(`${logger.yellow('[HTTP][input]')} ${logger.green(token)} file:${file}`);
121
- res.sendFile(file);
122
- });
123
- /** 监听端口 */
124
- const { host, port } = config.Server.http;
125
- this.server.listen(port, host, () => {
126
- logger.mark('[服务器][启动成功][HTTP]: ' + logger.green(`http://${host}:${port}`));
127
- });
128
- karin.once('restart.http', () => {
129
- logger.mark('[服务器][重启][HTTP] 正在重启HTTP服务器...');
130
- this.#restartServer();
131
- });
132
- const renderCfg = config.Server.websocket.render;
133
- if (Array.isArray(renderCfg) && renderCfg.length) {
134
- for (const url of renderCfg) {
135
- new RenderClient(url).start();
136
- }
137
- }
138
- const Onebot11 = config.Server.websocket.OneBot11Host;
139
- if (Array.isArray(Onebot11) && Onebot11.length) {
140
- for (const connect of Onebot11) {
141
- new AdapterOneBot11().client(connect);
142
- }
143
- }
144
- const { enable, WormholeClient } = config.Server.HttpRender;
145
- if (enable) {
146
- this.static();
147
- if (WormholeClient) {
148
- Wormhole();
149
- return this;
150
- }
151
- const { host, post, token } = config.Server.HttpRender;
152
- /** 注册渲染器 */
153
- const rd = new HttpRenderer(host, post, token);
154
- render.app({ id: 'puppeteer', type: 'image', render: rd.render.bind(rd) });
155
- }
156
- return this;
157
- }
158
- catch (error) {
159
- logger.error('初始化HTTP服务器失败: ', error);
160
- return false;
161
- }
162
- }
163
- /**
164
- * HTTP渲染器
165
- */
166
- static() {
167
- this.staticPath();
168
- /** GET接口 - 渲染 */
169
- this.app.get('/api/renderHtml', (req, res) => {
170
- try {
171
- let { html } = req.query;
172
- if (!html)
173
- return res.status(404).send(JSON.stringify({ code: 404, msg: 'Not Found' }));
174
- html = decodeURIComponent(html)
175
- .replace(/\\/g, '/')
176
- .replace(/^\.\//, '');
177
- /** 判断是否为html文件且路径存在 */
178
- if (!html.endsWith('.html') || !fs.existsSync(html)) {
179
- const not_found = config.Server.HttpRender.not_found;
180
- if (not_found.startsWith('http')) {
181
- return res.redirect(not_found);
182
- }
183
- else {
184
- return res.status(404).send(JSON.stringify({ code: 404, msg: not_found || '?' }));
185
- }
186
- }
187
- let content = fs.readFileSync(html, 'utf-8');
188
- /** 处理所有绝对路径、相对路径 */
189
- content = content.replace(this.RegExp, '');
190
- res.send(content);
191
- }
192
- catch (e) {
193
- logger.error('[服务器][GET接口 - 渲染]', e);
194
- res.status(500).send(JSON.stringify({ code: 500, msg: 'Internal Server Error' }));
195
- }
196
- });
197
- /** 拦截静态资源 防止恶意访问 */
198
- this.app.use((req, res, next) => {
199
- logger.debug(`[静态资源][${req.headers.host}] ${req.url}`);
200
- /** 解码 */
201
- req.url = decodeURIComponent(req.url);
202
- req.url = req.url
203
- .replace(/\\/g, '/')
204
- .replace(/^\.\//, '')
205
- .replace(/^(\.\.\/)+/, '');
206
- /** 拦截非资源文件 */
207
- this.reg.lastIndex = 0;
208
- if (!this.reg.test(req.url)) {
209
- logger.mark(`[${req.ip}][拦截非资源文件]`, req.url);
210
- res.status(404).send(JSON.stringify({ code: 404, msg: 'Not Found' }));
211
- return;
212
- }
213
- next();
214
- });
215
- /** 设置静态文件目录 */
216
- this.app.use(express.static(process.cwd()));
217
- }
218
- /**
219
- * 构建静态资源路径
220
- */
221
- async staticPath() {
222
- this.list = [];
223
- /** 读取./resources文件夹 */
224
- const resDir = './resources';
225
- const resdirs = fs.readdirSync(resDir);
226
- for (const dir of resdirs) {
227
- const file = `${resDir}/${dir}`;
228
- if (common.isDir(file))
229
- this.list.push(file.replace('.', ''));
230
- }
231
- /** 读取./temp/html下所有文件夹 */
232
- const htmlDir = './temp/html';
233
- const dirs = fs.readdirSync(htmlDir);
234
- for (const dir of dirs) {
235
- const file = `${htmlDir}/${dir}`;
236
- if (common.isDir(file))
237
- this.list.push(file.replace('.', ''));
238
- }
239
- /** 读取./plugins/xxx/resources下所有文件夹 */
240
- const pluginsDir = './plugins';
241
- const plugins = fs.readdirSync(pluginsDir);
242
- for (const dir of plugins) {
243
- /** 忽略不是karin-plugin-开头 */
244
- if (!dir.startsWith('karin-plugin-'))
245
- continue;
246
- const file = `${pluginsDir}/${dir}`;
247
- const resFile = `${file}/resources`;
248
- /** 包含resources文件夹 */
249
- if (common.isDir(file) && common.isDir(resFile))
250
- this.list.push(resFile.replace('.', ''));
251
- const componentsFile = `${file}/lib/components`;
252
- /** 包含lib/components文件夹 兼容mys */
253
- if (common.isDir(file) && common.isDir(componentsFile))
254
- this.list.push(componentsFile.replace('.', ''));
255
- /** 读取package.json 查找是否存在自定义资源文件入口 */
256
- const pkgFile = `${file}/package.json`;
257
- if (!common.exists(pkgFile))
258
- continue;
259
- const pkg = common.readJson(pkgFile);
260
- if (!pkg?.karin?.static || !Array.isArray(pkg.karin.static))
261
- continue;
262
- /** 标准格式为 lib/test/xxxx */
263
- for (let staticFile of pkg.karin.static) {
264
- /** 不允许向上级目录 ../开头等 */
265
- if (staticFile.startsWith('../'))
266
- continue;
267
- /** ./开头去掉./ */
268
- if (staticFile.startsWith('./'))
269
- staticFile = staticFile.slice(2);
270
- this.list.push(`${file}/${staticFile}`);
271
- }
272
- }
273
- this.reg = new RegExp(`(${this.list.join('|')})`, 'g');
274
- }
275
- /** 重启当前HTTP服务器 */
276
- async #restartServer() {
277
- try {
278
- /** 断开所有 WebSocket 连接 */
279
- for (const ws of this.WebSocketServer.clients)
280
- ws.terminate();
281
- /** 关闭当前HTTP服务器 */
282
- this.server.close();
283
- /** 延迟1秒 */
284
- await common.sleep(1000);
285
- /** 创建一个新的服务器实例 */
286
- this.server = createServer(this.app);
287
- this.WebSocketServer = new WebSocketServer({ server: this.server });
288
- this.init();
289
- this.static();
290
- }
291
- catch (err) {
292
- logger.error('[服务器][重启失败]', err);
293
- }
294
- }
295
- })();
package/lib/db/index.d.ts DELETED
@@ -1,2 +0,0 @@
1
- export * from './level/level.js';
2
- export * from './redis/redis.js';
package/lib/db/index.js DELETED
@@ -1,2 +0,0 @@
1
- export * from './level/level.js';
2
- export * from './redis/redis.js';
@@ -1,19 +0,0 @@
1
- import { Level } from 'level';
2
- /**
3
- * @type {Level}
4
- */
5
- export default class LevelDB extends Level {
6
- id: string;
7
- constructor();
8
- /**
9
- * 对get方法进行重写 找不到数据时返回null
10
- */
11
- get(key: string): Promise<string>;
12
- /**
13
- * 增加set方法
14
- * @param {string} key 键
15
- * @param {object|string} value 值
16
- */
17
- set(key: string, value: string | object): Promise<void>;
18
- }
19
- export declare const level: LevelDB;
@@ -1,36 +0,0 @@
1
- import { Level } from 'level';
2
- const path = process.cwd() + '/data/db/Level';
3
- /**
4
- * @type {Level}
5
- */
6
- export default class LevelDB extends Level {
7
- id;
8
- constructor() {
9
- super(path, { valueEncoding: 'json' });
10
- /**
11
- * @type {'Level'} 唯一标识符 用于区分不同的数据库
12
- */
13
- this.id = 'Level';
14
- }
15
- /**
16
- * 对get方法进行重写 找不到数据时返回null
17
- */
18
- async get(key) {
19
- try {
20
- const res = await super.get(key);
21
- return res;
22
- }
23
- catch {
24
- return '';
25
- }
26
- }
27
- /**
28
- * 增加set方法
29
- * @param {string} key 键
30
- * @param {object|string} value 值
31
- */
32
- async set(key, value) {
33
- return await super.put(key, value);
34
- }
35
- }
36
- export const level = new LevelDB();
@@ -1,2 +0,0 @@
1
- import { RedisClientType } from 'redis';
2
- export declare const redis: RedisClientType;
@@ -1,135 +0,0 @@
1
- import { exec } from 'child_process';
2
- import RedisLevel from './redis_level.js';
3
- import { logger, config } from '../../utils/index.js';
4
- import { createClient, createCluster } from 'redis';
5
- class Redis {
6
- id;
7
- RunCmd;
8
- constructor() {
9
- this.id = 'redis';
10
- this.RunCmd = '';
11
- }
12
- /**
13
- * redis实例化
14
- */
15
- async start() {
16
- const { host, port, username, password, db: database, cluster } = config.redis;
17
- /** 集群模式 */
18
- if (cluster && cluster.enable) {
19
- const rootNodes = cluster.rootNodes.map((node) => ({ url: node }));
20
- logger.debug('正在连接 Redis 集群...');
21
- const { status, data } = await this.connectCluster(rootNodes);
22
- if (status === 'ok') {
23
- logger.info('Redis 集群连接成功');
24
- return data;
25
- }
26
- logger.error(`Redis 集群建立连接失败:${logger.red(data)}`);
27
- return false;
28
- }
29
- logger.debug(`正在连接 ${logger.green(`Redis://${host}:${port}/${database}`)}`);
30
- const options = { socket: { host, port }, username, password, database };
31
- /** 第一次连接 */
32
- const { status, data } = await this.connect(options);
33
- if (status === 'ok') {
34
- logger.info('Redis 连接成功');
35
- return data;
36
- }
37
- /** 第一次连接失败尝试拉起 windows直接降级 */
38
- if (process.platform === 'win32') {
39
- // logger.info(`Redis 建立连接失败:${data}`)
40
- return await this.LevelDB();
41
- }
42
- this.RunCmd = 'redis-server --save 900 1 --save 300 10 --daemonize yes' + (await this.aarch64());
43
- logger.info('正在尝试启动 Redis...');
44
- try {
45
- await this.execSync(this.RunCmd);
46
- /** 启动成功再次重试 */
47
- const { status, data } = await this.connect(options);
48
- if (status === 'ok') {
49
- logger.info('Redis 连接成功');
50
- return data;
51
- }
52
- logger.debug(`Redis 二次建立连接失败:${logger.red(data)}`);
53
- return false;
54
- }
55
- catch (error) {
56
- logger.debug(`Redis 启动失败:${logger.red(data)}`);
57
- return await this.LevelDB();
58
- }
59
- }
60
- /**
61
- * 降级为 LevelDB
62
- */
63
- async LevelDB() {
64
- try {
65
- logger.debug('使用LevelDB代替Redis实现基础Api');
66
- const redis = new RedisLevel();
67
- return redis;
68
- }
69
- catch (error) {
70
- logger.error('降级为 LevelDB 失败');
71
- logger.error(error);
72
- return false;
73
- }
74
- }
75
- /**
76
- * 连接 Redis 单例
77
- */
78
- async connect(options) {
79
- const client = createClient(options);
80
- try {
81
- await client.connect();
82
- return { status: 'ok', data: client };
83
- }
84
- catch (error) {
85
- return { status: 'error', data: error };
86
- }
87
- }
88
- /**
89
- * 连接 Redis 集群
90
- */
91
- async connectCluster(rootNodes) {
92
- const client = createCluster({ rootNodes });
93
- try {
94
- await client.connect();
95
- return { status: 'ok', data: client };
96
- }
97
- catch (error) {
98
- return { status: 'error', data: error };
99
- }
100
- }
101
- /**
102
- * 判断是否为 ARM64 并返回参数
103
- */
104
- async aarch64() {
105
- try {
106
- /** 判断arch */
107
- const arch = await this.execSync('uname -m');
108
- if (arch && arch.includes('aarch64')) {
109
- /** 提取 Redis 版本 */
110
- const version = await this.execSync('redis-server -v');
111
- if (version) {
112
- /** 提取版本号 */
113
- const RedisVersion = version.match(/v=(\d)./);
114
- /** 如果>=6版本则忽略警告 */
115
- if (RedisVersion && Number(RedisVersion[1]) >= 6)
116
- return ' --ignore-warnings ARM64-COW-BUG';
117
- }
118
- }
119
- return '';
120
- }
121
- catch {
122
- return '';
123
- }
124
- }
125
- execSync(cmd) {
126
- return new Promise((resolve, reject) => {
127
- exec(cmd, (error, stdout) => {
128
- if (error)
129
- return reject(error);
130
- resolve(stdout);
131
- });
132
- });
133
- }
134
- }
135
- export const redis = await new Redis().start();