mm_os 4.2.6 → 4.2.8

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 (74) hide show
  1. package/README.md +1 -1
  2. package/README_EN.md +2 -2
  3. package/adapter/adapter.js +105 -52
  4. package/adapter/custom_persistence.js +32 -31
  5. package/adapter/mqtt.js +59 -79
  6. package/adapter/socket.js +188 -58
  7. package/adapter/web.js +92 -68
  8. package/adapter/websocket.js +43 -146
  9. package/com/api/drive.js +732 -708
  10. package/com/api/index.js +196 -198
  11. package/com/cmd/config.tpl.json +48 -122
  12. package/com/cmd/drive.js +176 -1548
  13. package/com/cmd/index.js +287 -1066
  14. package/com/cmd/job/config.json +66 -0
  15. package/com/cmd/job/index.js +241 -0
  16. package/com/cmd/job/test.js +188 -0
  17. package/com/cmd/script.tpl.js +12 -33
  18. package/com/db/drive.js +2206 -2019
  19. package/com/db/index.js +241 -242
  20. package/com/event/config.tpl.json +3 -1
  21. package/com/event/drive.js +3 -1
  22. package/com/event/index.js +73 -49
  23. package/com/event/script.tpl.js +1 -1
  24. package/com/mqtt/config.tpl.json +16 -8
  25. package/com/mqtt/drive.js +696 -676
  26. package/com/mqtt/index.js +1012 -822
  27. package/com/mqtt/index.test.js +503 -0
  28. package/com/mqtt/mm_mqtt.js +446 -420
  29. package/com/mqtt/script.tpl.js +3 -7
  30. package/com/nav/drive.js +7 -7
  31. package/com/nav/index.js +228 -231
  32. package/com/param/index.js +19 -17
  33. package/com/pendant/index.js +467 -441
  34. package/com/socket/drive.js +679 -616
  35. package/com/socket/index.js +94 -48
  36. package/com/sql/drive.js +1283 -1259
  37. package/com/sql/index.js +152 -150
  38. package/com/static/drive.js +1 -1
  39. package/com/static/index.js +232 -226
  40. package/com/task/drive.js +428 -405
  41. package/com/task/index.js +154 -148
  42. package/com/template/drive.js +1 -1
  43. package/com/template/index.js +141 -138
  44. package/com.js +87 -6
  45. package/common/middleware/web_after/index.js +4 -10
  46. package/common/middleware/web_base/index.js +1 -1
  47. package/common/middleware/web_cors/index.js +1 -1
  48. package/common/middleware/web_error/index.js +131 -119
  49. package/common/middleware/web_error/middleware.json +2 -1
  50. package/common/middleware/web_logger/index.js +1 -1
  51. package/common/middleware/web_main/index.js +2 -0
  52. package/common/middleware/web_static/index.js +2 -2
  53. package/common/middleware/web_waf/index.js +1 -1
  54. package/core/app/config.tpl.json +4 -4
  55. package/core/app/index.js +710 -534
  56. package/core/middleware/index.js +1 -9
  57. package/core/mod/config.tpl.json +1 -1
  58. package/core/model/config.tpl.json +1 -1
  59. package/core/plugin/config.tpl.json +15 -3
  60. package/core/plugin/index.js +31 -0
  61. package/core/pusher/index.js +158 -161
  62. package/core/scene/loop.js +1306 -1255
  63. package/core/store/index.js +1794 -1755
  64. package/core/store/sql.js +1488 -1464
  65. package/core/zone/bat/index.js +744 -728
  66. package/core/zone/config.tpl.json +3 -3
  67. package/core/zone/index.js +655 -616
  68. package/os.js +0 -4
  69. package/package.json +16 -16
  70. package/server.js +583 -427
  71. package/com/cmd/nlp.js +0 -525
  72. package/core/app/index copy.js +0 -611
  73. package/software.js +0 -194
  74. package/tcp.js +0 -279
@@ -1,616 +1,679 @@
1
- const Item = require('mm_machine').Drive;
2
-
3
- // 提供一个全局方法容器
4
- if (!$.methods) {
5
- $.methods = {};
6
- }
7
-
8
- /**
9
- * websocket驱动类
10
- * @augments {Item}
11
- * @class
12
- */
13
- class Drive extends Item {
14
- static config = {
15
- // 同步消息循环发送的时间间隔
16
- 'interval': 1000
17
- };
18
- /**
19
- * 构造函数
20
- * @param {object} config 配置参数
21
- * @param {object} parent 父对象
22
- * @class
23
- */
24
- constructor(config, parent) {
25
- super({ ...Drive.config, ...config }, parent);
26
- }
27
- }
28
-
29
- /**
30
- * 获取驱动实例的全局存储键名
31
- * @returns {string} 存储键名
32
- * @private
33
- */
34
- Drive.prototype._getStorageKey = function () {
35
- return 'socket_drive_' + (this.config.name || 'default');
36
- };
37
-
38
- /**
39
- * 确保数据引用有效(热更新后调用)
40
- * @private
41
- */
42
- Drive.prototype._ensureRefs = function () {
43
- var storage_key = this._getStorageKey();
44
-
45
- // 检查全局存储是否存在
46
- if (!$.sockets || !$.sockets[storage_key]) {
47
- // 如果全局存储不存在,重新初始化
48
- this._preset();
49
- return;
50
- }
51
-
52
- // 确保数据引用正确
53
- this._storage = $.sockets[storage_key];
54
-
55
- // 重新建立数据引用
56
- if (!this.clients || this.clients !== this._storage.clients) {
57
- this.clients = this._storage.clients;
58
- }
59
-
60
- if (!this.list_msg || this.list_msg !== this._storage.list_msg) {
61
- this.list_msg = this._storage.list_msg;
62
- }
63
- };
64
-
65
- /**
66
- * 预设配置
67
- */
68
- Drive.prototype._preset = function () {
69
- // 开放给前端调用的函数
70
- this.methods = { ...$.methods };
71
-
72
- // 初始化全局存储结构
73
- var storage_key = this._getStorageKey();
74
- if (!$.sockets) {
75
- $.sockets = {};
76
- }
77
-
78
- if (!$.sockets[storage_key]) {
79
- $.sockets[storage_key] = {
80
- clients: {},
81
- list_msg: []
82
- };
83
- }
84
-
85
- // 使用全局存储的数据
86
- this._storage = $.sockets[storage_key];
87
-
88
- // 保持对全局数据的引用(为了向后兼容)
89
- this.clients = this._storage.clients;
90
- this.list_msg = this._storage.list_msg;
91
- };
92
-
93
- /**
94
- * 获取session ID
95
- * @param {object} ctx HTTP上下文
96
- * @returns {string} 返回用户的uuid
97
- */
98
- Drive.prototype.getToken = async function (ctx) {
99
- var hd = ctx.request.header;
100
- var uuid = await ctx.cookies.get('mm:uuid');
101
- if(!uuid) {
102
- uuid = hd[''];
103
- }
104
- if (!uuid) {
105
- var agent = hd['user-agent'];
106
- if (!agent) {
107
- agent = 'mm';
108
- }
109
- var start = agent.md5().substring(0, 32);
110
- var stamp = Date.parse(new Date()) / 1000;
111
- uuid = (ctx.ip + '_' + stamp).aesEncode(start);
112
- }
113
- return uuid;
114
- };
115
-
116
- /**
117
- * 收到消息时处理函数
118
- * @param {string} body_str 消息正文字符串
119
- * @param {object} ctx http上下文
120
- * @param {string} token 临时访问牌
121
- */
122
- Drive.prototype.onmessage = async function (body_str, ctx, token) {
123
- // 解析消息内容
124
- var msg = {};
125
- if (body_str && (body_str.indexOf('[') === 0 || body_str.indexOf('{') === 0)) {
126
- try {
127
- msg = JSON.parse(body_str);
128
- } catch (error) {
129
- console.error('Socket消息结构体不对:', error);
130
- }
131
- }
132
-
133
- // 处理回复消息(如果有ID字段)
134
- if (msg && msg.id) {
135
- // 调用驱动的消息回复处理
136
- this._handleResponse(msg);
137
- }
138
-
139
- var ret = await this.run(body_str, ctx, token);
140
- if (ret) {
141
- var ws = ctx.websocket;
142
- if (typeof (ret) === 'object') {
143
- ws.send(JSON.stringify(ret));
144
- } else {
145
- ws.send(ret);
146
- }
147
- }
148
- };
149
-
150
- /**
151
- * 状态变更通知
152
- * @param {string} type 通知类型
153
- * @param {string} body_str 消息正文字符串
154
- * @param {object} ctx http上下文
155
- * @param {string} token 临时访问牌
156
- * @returns {boolean} 返回true表示做状态修改, 例如关闭时为true, 会删除该客户端
157
- */
158
- Drive.prototype.noticy = async function (type, body_str, ctx, token) {
159
- // this.log('debug', '通知:', '关闭了');
160
- return true;
161
- };
162
-
163
- /**
164
- * 关闭连接时处理函数
165
- * @param {string} body_str 消息正文字符串
166
- * @param {object} ctx http上下文
167
- * @param {string} token 临时访问牌
168
- */
169
- Drive.prototype.onclose = async function (body_str, ctx, token) {
170
- var del = await this.noticy('close', ctx, token);
171
- if (del) {
172
- var lt = this.clients[token];
173
- var index = lt.indexOf(ctx);
174
- lt.splice(index, 1);
175
- }
176
- };
177
-
178
- /**
179
- * 设置websocket
180
- * @param {object} ctx http上下文
181
- * @param {string} token 临时访问牌
182
- */
183
- Drive.prototype.setSocket = function (ctx, token) {
184
- var ws = ctx.websocket;
185
-
186
- // 增加消息队列
187
- ws.list_msg = [];
188
-
189
- /**
190
- * 设置发送请求
191
- * @param {string} method 方法名称
192
- * @param {object} params 请求参数
193
- * @param {Function} func 回调函数
194
- */
195
- var _this = this;
196
- ws.req = async function (method, params, func) {
197
- var key = _this.config.name + '';
198
- var data = {
199
- id: key + new Date().getTime() + Math.random(),
200
- method: method,
201
- params: params
202
- };
203
- this.send(JSON.stringify(data));
204
-
205
- if (func) {
206
- data.func = func;
207
- this.list_msg.push(data);
208
- }
209
- };
210
-
211
- // 设置事件 —— 获取消息时和socket关闭时
212
- ws.on('message', async (body_str) => {
213
- _this.onmessage(body_str, ctx, token);
214
- });
215
-
216
- ws.on('close', async (body_str) => {
217
- _this.onclose(body_str, ctx, token);
218
- });
219
- };
220
-
221
-
222
- /**
223
- * 握手成功, 发送首条返回内容
224
- * @param {object} ctx http 上下文
225
- * @param {string} token 临时访问牌
226
- */
227
- Drive.prototype.success = function (ctx, token) {
228
- var ret = $.ret.bl(true, 'connection succeeded');
229
- // 首次响应加上身份牌
230
- ret.result.token = token;
231
- // ID为0表示连接成功
232
- ret.id = 0;
233
- ctx.websocket.send(JSON.stringify(ret));
234
- };
235
-
236
- /**
237
- * 添加客户端
238
- * @param {object} ctx 请求上下文
239
- */
240
- Drive.prototype.add = async function (ctx) {
241
- var token = await this.getToken(ctx);
242
- if (!this.clients[token]) {
243
- this.clients[token] = [];
244
- }
245
- this.setSocket(ctx, token);
246
- this.success(ctx, token);
247
- this.clients[token].push(ctx);
248
- };
249
-
250
- /**
251
- * 发送消息到指定客户端
252
- * @param {string} token 客户端token
253
- * @param {string} method 方法名称
254
- * @param {object} params 请求参数
255
- * @returns {boolean} 发送是否成功
256
- */
257
- Drive.prototype.send = function (token, method, params) {
258
- // 确保数据引用有效(热更新保护)
259
- this._ensureRefs();
260
-
261
- var list = this.clients[token];
262
- if (list && list.length > 0) {
263
- var data = {
264
- method: method,
265
- params: params
266
- };
267
-
268
- for (var i = 0; i < list.length; i++) {
269
- var ctx = list[i];
270
- var ws = ctx.websocket;
271
- if (ws && ws.readyState === 1) { // WebSocket.OPEN
272
- ws.send(JSON.stringify(data));
273
- }
274
- }
275
- return true;
276
- }
277
- return false;
278
- };
279
-
280
- /**
281
- * 发送消息到所有连接的客户端
282
- * @param {string} method 方法名称
283
- * @param {object} params 请求参数
284
- */
285
- Drive.prototype.sendAll = function (method, params) {
286
- // 确保数据引用有效(热更新保护)
287
- this._ensureRefs();
288
-
289
- var data = {
290
- method: method,
291
- params: params
292
- };
293
-
294
- for (var token in this.clients) {
295
- var list = this.clients[token];
296
- for (var i = 0; i < list.length; i++) {
297
- var ctx = list[i];
298
- var ws = ctx.websocket;
299
- if (ws && ws.readyState === 1) { // WebSocket.OPEN
300
- ws.send(JSON.stringify(data));
301
- }
302
- }
303
- }
304
- };
305
-
306
- /**
307
- * 发送请求到指定客户端
308
- * @param {string} token 客户端token
309
- * @param {string} method 方法名称
310
- * @param {object} params 请求参数
311
- * @param {Function} func 回调函数
312
- * @param {number} timeout 超时时间(毫秒)
313
- * @returns {boolean} 发送是否成功
314
- */
315
- Drive.prototype.req = function (token, method, params, func, timeout = 0) {
316
- // 确保数据引用有效(热更新保护)
317
- this._ensureRefs();
318
-
319
- var list = this.clients[token];
320
- if (list && list.length > 0) {
321
- var data = {
322
- id: this._genMsgId(),
323
- method: method,
324
- params: params
325
- };
326
-
327
- if (func) {
328
- data.func = func;
329
- data.timestamp = Date.now();
330
- data.timeout = timeout || 3000;
331
-
332
- // 将消息添加到驱动的消息队列
333
- this.list_msg.push(data);
334
-
335
- // 设置超时移除定时器
336
- var _this = this;
337
- data.timer = setTimeout(() => {
338
- _this._delMsgById(data.id);
339
- }, data.timeout);
340
- }
341
-
342
- for (var i = 0; i < list.length; i++) {
343
- var ctx = list[i];
344
- var ws = ctx.websocket;
345
- if (ws && ws.readyState === 1) { // WebSocket.OPEN
346
- ws.send(JSON.stringify(data));
347
- }
348
- }
349
- return true;
350
- }
351
- return false;
352
- };
353
-
354
- /**
355
- * 发送请求到所有连接的客户端
356
- * @param {string} method 方法名称
357
- * @param {object} params 请求参数
358
- * @param {Function} func 回调函数
359
- * @param {number} timeout 超时时间(毫秒)
360
- */
361
- Drive.prototype.reqAll = function (method, params, func, timeout = 0) {
362
- // 确保数据引用有效(热更新保护)
363
- this._ensureRefs();
364
-
365
- var data = {
366
- id: this._genMsgId(),
367
- method: method,
368
- params: params
369
- };
370
-
371
- if (func) {
372
- data.func = func;
373
- data.timestamp = Date.now();
374
- data.timeout = timeout || 3000;
375
-
376
- // 将消息添加到驱动的消息队列
377
- this.list_msg.push(data);
378
-
379
- // 设置超时移除定时器
380
- var _this = this;
381
- data.timer = setTimeout(() => {
382
- _this._delMsgById(data.id);
383
- }, data.timeout);
384
- }
385
-
386
- for (var token in this.clients) {
387
- var list = this.clients[token];
388
- for (var i = 0; i < list.length; i++) {
389
- var ctx = list[i];
390
- var ws = ctx.websocket;
391
- if (ws && ws.readyState === 1) { // WebSocket.OPEN
392
- ws.send(JSON.stringify(data));
393
- }
394
- }
395
- }
396
- };
397
-
398
- /**
399
- * 生成消息ID
400
- * @returns {string} 消息ID
401
- * @private
402
- */
403
- Drive.prototype._genMsgId = function () {
404
- return 'drive_' + Date.parse(new Date()) + '_' + Math.random().toString(36).substr(2, 9);
405
- };
406
-
407
- /**
408
- * 根据ID移除消息
409
- * @param {string} msg_id 消息ID
410
- * @private
411
- */
412
- Drive.prototype._delMsgById = function (msg_id) {
413
- // 确保数据引用有效(热更新保护)
414
- this._ensureRefs();
415
-
416
- for (var i = 0; i < this.list_msg.length; i++) {
417
- if (this.list_msg[i].id === msg_id) {
418
- // 清除定时器
419
- if (this.list_msg[i].timer) {
420
- clearTimeout(this.list_msg[i].timer);
421
- }
422
- this.list_msg.splice(i, 1);
423
- break;
424
- }
425
- }
426
- };
427
-
428
- /**
429
- * 处理消息回复
430
- * @param {object} msg 回复消息
431
- * @private
432
- */
433
- Drive.prototype._handleResponse = function (msg) {
434
- // 确保数据引用有效(热更新保护)
435
- this._ensureRefs();
436
-
437
- if (!msg || !msg.id) {
438
- return;
439
- }
440
-
441
- for (var i = 0; i < this.list_msg.length; i++) {
442
- let o = this.list_msg[i];
443
- if (o.id === msg.id && o.func) {
444
- try {
445
- // 执行回调函数
446
- o.func(msg);
447
- } catch (error) {
448
- console.error('Socket驱动回调函数执行错误:', error);
449
- }
450
-
451
- // 从列表中移除已处理的消息
452
- this._delMsgById(o.id);
453
- break;
454
- }
455
- }
456
- };
457
-
458
- /**
459
- * 执行
460
- * @param {string} body 正文字符串
461
- * @param {object} ctx 请求上下文
462
- * @param {string} token 临时访问牌
463
- * @returns {object} 返回执行结果
464
- */
465
- Drive.prototype.run = async function (body, ctx, token) {
466
- try {
467
- var by = body.toString();
468
- var ws = ctx.websocket;
469
- var json = by.toJson();
470
- var req = ctx.request;
471
- var request = { headers: req.headers, query: req.query, token: token };
472
- if (!json) {
473
- return await this.main(by, ws, request);
474
- }
475
- return await this._handleJson(json, ws, request);
476
- } catch (err) {
477
- this.log('error', 'webscoket 错误', err);
478
- return $.ret.error(10000, '代码错误!原因:' + err.toString());
479
- }
480
- };
481
-
482
- /**
483
- * 处理 JSON 请求
484
- * @param {object} json JSON 对象
485
- * @param {object} ws WebSocket
486
- * @param {object} request 请求对象
487
- * @returns {object} 返回处理结果
488
- * @private
489
- */
490
- Drive.prototype._handleJson = async function (json, ws, request) {
491
- var { id, method } = json;
492
- if (json.result && id) {
493
- return this._handleRet(json, ws);
494
- }
495
- if (method && this.methods[method]) {
496
- return await this._callMethod(json, ws, request);
497
- }
498
- return await this.main(json, ws, request);
499
- };
500
-
501
- /**
502
- * 处理结果回调
503
- * @param {object} json JSON 对象
504
- * @param {object} ws WebSocket
505
- * @private
506
- */
507
- Drive.prototype._handleRet = function (json, ws) {
508
- var id = json.id;
509
- var lt = ws.list_msg;
510
- var len = lt.length;
511
- for (var i = 0; i < len; i++) {
512
- var o = lt[i];
513
- if (id === o.id) {
514
- o.func(json.result);
515
- lt.splice(i, 1);
516
- return;
517
- }
518
- }
519
- };
520
-
521
- /**
522
- * 调用方法
523
- * @param {object} json JSON 对象
524
- * @param {object} ws WebSocket
525
- * @param {object} request 请求对象
526
- * @returns {object} 返回调用结果
527
- * @private
528
- */
529
- Drive.prototype._callMethod = async function (json, ws, request) {
530
- var { id, method } = json;
531
- var result = await this.methods[method](json.params, ws, request);
532
- if (!result) {
533
- return;
534
- }
535
- if (typeof (result) == 'object' && !Array.isArray(result)) {
536
- return { id, ...result };
537
- }
538
- var ret = { result };
539
- if (id) {
540
- ret.id = id;
541
- }
542
- return ret;
543
- };
544
-
545
- /**
546
- * 非定义函数时执行
547
- * @param {object} body 请求正文
548
- * @param {object} websocket Websocket服务
549
- * @param {object} request 请求协议头
550
- * @returns {object} 返回执行结果
551
- */
552
- Drive.prototype.main = async function (body, websocket, request) {
553
- return null;
554
- };
555
-
556
- /**
557
- * 初始化函数, 用于定义开放给前端的函数
558
- */
559
- Drive.prototype.init = async function () {
560
-
561
- };
562
-
563
- /**
564
- * 加载完成时
565
- */
566
- Drive.prototype.loadAfter = function () {
567
- var m = this.methods;
568
-
569
- /**
570
- * 获取所有方法
571
- * @param {object} params 参数
572
- * @param {object} ws Websocket服务
573
- * @param {object} request 请求协议头
574
- * @returns {object} 返回执行结果
575
- */
576
- m.getMethods = async function (params, ws, request) {
577
- return Object.keys(m);
578
- };
579
- };
580
-
581
- /**
582
- * 获取插件
583
- * @param {string} app 应用名称
584
- * @param {string} name 插件名称
585
- * @returns {object} 返回获取到的插件
586
- */
587
- Drive.prototype.plugin = function (app, name) {
588
- var l = $.slash;
589
- var app_name = app || this.config_file.between('app' + l, l);
590
- var plugin_name = name || this.config_file.between('plugin' + l, l);
591
- var plus;
592
- var plugins = $.pool.plugin[app_name];
593
- if (plugins) {
594
- plus = plugins.get(plugin_name);
595
- }
596
- return plus;
597
- };
598
-
599
- /**
600
- * 获取模型
601
- * @param {string} type 模型类型
602
- * @returns {object} 返回获取到的模型
603
- */
604
- Drive.prototype.getModel = function (type) {
605
- let model = { ...this.config };
606
- let dir = this.getDir();
607
- let l = $.slash;
608
- let app_name = dir.between('app' + l, l);
609
- let plugin_name = dir.between('plugin' + l, l);
610
- let name = dir.basename();
611
- model.app = app_name;
612
- model.plugin = plugin_name;
613
- model.name = model.name || name;
614
- return model;
615
- };
616
- module.exports = Drive;
1
+ const Item = require('mm_machine').Drive;
2
+
3
+ // 提供一个全局方法容器
4
+ if (!$.methods) {
5
+ $.methods = {};
6
+ }
7
+
8
+ /**
9
+ * websocket驱动类
10
+ * @augments {Item}
11
+ * @class
12
+ */
13
+ class Drive extends Item {
14
+ static config = {
15
+ // webscoket请求路由地址
16
+ path: '',
17
+ // 名称
18
+ name: '',
19
+ // websocket标题
20
+ title: '',
21
+ // 描述,用来介绍该websocket程序是做什么用的
22
+ description: '',
23
+ // 同步消息循环发送的时间间隔
24
+ interval: 1000,
25
+ // 心跳间隔时间, 单位: ms, 默认30秒
26
+ ping_interval: 30000,
27
+ // 心跳超时时间, 单位: ms, 默认10秒
28
+ ping_timeout: 10000,
29
+ };
30
+ /**
31
+ * 构造函数
32
+ * @param {object} config 配置参数
33
+ * @param {object} parent 父对象
34
+ * @class
35
+ */
36
+ constructor(config, parent) {
37
+ super({ ...Drive.config, ...config }, parent);
38
+ }
39
+ }
40
+
41
+ /**
42
+ * 获取驱动实例的全局存储键名
43
+ * @returns {string} 存储键名
44
+ * @private
45
+ */
46
+ Drive.prototype._getStorageKey = function () {
47
+ return 'socket_drive_' + (this.config.name || 'default');
48
+ };
49
+
50
+ /**
51
+ * 确保数据引用有效(热更新后调用)
52
+ * @private
53
+ */
54
+ Drive.prototype._ensureRefs = function () {
55
+ var storage_key = this._getStorageKey();
56
+
57
+ // 检查全局存储是否存在
58
+ if (!$.sockets || !$.sockets[storage_key]) {
59
+ // 如果全局存储不存在,重新初始化
60
+ this._preset();
61
+ return;
62
+ }
63
+
64
+ // 确保数据引用正确
65
+ this._storage = $.sockets[storage_key];
66
+
67
+ // 重新建立数据引用
68
+ if (!this.clients || this.clients !== this._storage.clients) {
69
+ this.clients = this._storage.clients;
70
+ }
71
+
72
+ if (!this.list_msg || this.list_msg !== this._storage.list_msg) {
73
+ this.list_msg = this._storage.list_msg;
74
+ }
75
+
76
+ if (!this.dict_msg || this.dict_msg !== this._storage.dict_msg) {
77
+ this.dict_msg = this._storage.dict_msg;
78
+ }
79
+ };
80
+
81
+ /**
82
+ * 预设配置
83
+ */
84
+ Drive.prototype._preset = function () {
85
+ // 开放给前端调用的函数
86
+ this.methods = { ...$.methods };
87
+
88
+ // 初始化全局存储结构
89
+ var storage_key = this._getStorageKey();
90
+ if (!$.sockets) {
91
+ $.sockets = {};
92
+ }
93
+
94
+ if (!$.sockets[storage_key]) {
95
+ $.sockets[storage_key] = {
96
+ clients: {},
97
+ list_msg: [],
98
+ dict_msg: {},
99
+ };
100
+ }
101
+
102
+ // 使用全局存储的数据
103
+ this._storage = $.sockets[storage_key];
104
+
105
+ // 保持对全局数据的引用(为了向后兼容)
106
+ this.clients = this._storage.clients;
107
+ this.list_msg = this._storage.list_msg;
108
+ this.dict_msg = this._storage.dict_msg;
109
+ };
110
+
111
+ /**
112
+ * 获取session ID
113
+ * @param {object} ctx HTTP上下文
114
+ * @returns {string} 返回用户的uuid
115
+ */
116
+ Drive.prototype.getToken = async function (ctx) {
117
+ var hd = ctx.request.header;
118
+ var uuid = await ctx.cookies.get('mm:uuid');
119
+ if (!uuid) {
120
+ uuid = hd[''];
121
+ }
122
+ if (!uuid) {
123
+ var agent = hd['user-agent'];
124
+ if (!agent) {
125
+ agent = 'mm';
126
+ }
127
+ var start = agent.md5().substring(0, 32);
128
+ var stamp = Date.parse(new Date()) / 1000;
129
+ uuid = (ctx.ip + '_' + stamp).aesEncode(start);
130
+ }
131
+ return uuid;
132
+ };
133
+
134
+ /**
135
+ * 收到消息时处理函数
136
+ * @param {string} body_str 消息正文字符串
137
+ * @param {object} ctx http上下文
138
+ * @param {string} token 临时访问牌
139
+ */
140
+ Drive.prototype.onMessage = async function (body_str, ctx, token) {
141
+ // 解析消息内容
142
+ var msg = {};
143
+ if (
144
+ body_str &&
145
+ (body_str.indexOf('[') === 0 || body_str.indexOf('{') === 0)
146
+ ) {
147
+ try {
148
+ msg = JSON.parse(body_str);
149
+ } catch (error) {
150
+ console.error('Socket消息结构体不对:', error);
151
+ }
152
+ }
153
+
154
+ // 处理回复消息(如果有ID字段)
155
+ if (msg && msg.id) {
156
+ // 调用驱动的消息回复处理
157
+ this._handleResponse(msg);
158
+ }
159
+
160
+ var ret = await this.run(body_str, ctx, token);
161
+ if (ret) {
162
+ var ws = ctx.websocket;
163
+ if (typeof ret === 'object') {
164
+ ws.send(JSON.stringify(ret));
165
+ } else {
166
+ ws.send(ret);
167
+ }
168
+ }
169
+ };
170
+
171
+ /**
172
+ * 状态变更通知
173
+ * @param {string} type 通知类型
174
+ * @param {string} body_str 消息正文字符串
175
+ * @param {object} ctx http上下文
176
+ * @param {string} token 临时访问牌
177
+ * @returns {boolean} 返回true表示做状态修改, 例如关闭时为true, 会删除该客户端
178
+ */
179
+ Drive.prototype.noticy = async function (type, body_str, ctx, token) {
180
+ // this.log('debug', '通知:', '关闭了');
181
+ return true;
182
+ };
183
+
184
+ /**
185
+ * 关闭连接时处理函数
186
+ * @param {string} body_str 消息正文字符串
187
+ * @param {object} ctx http上下文
188
+ * @param {string} token 临时访问牌
189
+ */
190
+ Drive.prototype.onClose = async function (body_str, ctx, token) {
191
+ var del = await this.noticy('close', ctx, token);
192
+ if (del) {
193
+ var lt = this.clients[token];
194
+ if (lt) {
195
+ var index = lt.indexOf(ctx);
196
+ if (index !== -1) {
197
+ lt.splice(index, 1);
198
+ }
199
+ // 当该 token 下没有连接时,清理空数组
200
+ if (lt.length === 0) {
201
+ delete this.clients[token];
202
+ }
203
+ }
204
+ // 关闭WebSocket连接并清理事件监听器
205
+ if (ctx.websocket) {
206
+ try {
207
+ ctx.websocket.removeAllListeners();
208
+ ctx.websocket.close();
209
+ } catch (e) {
210
+ // 忽略关闭错误
211
+ }
212
+ }
213
+ }
214
+ };
215
+
216
+ /**
217
+ * 设置websocket
218
+ * @param {object} ctx http上下文
219
+ * @param {string} token 临时访问牌
220
+ */
221
+ Drive.prototype.setSocket = function (ctx, token) {
222
+ var ws = ctx.websocket;
223
+
224
+ // 增加消息队列和索引
225
+ ws.list_msg = [];
226
+ ws.dict_msg = {};
227
+
228
+ /**
229
+ * 设置发送请求
230
+ * @param {string} method 方法名称
231
+ * @param {object} params 请求参数
232
+ * @param {Function} func 回调函数
233
+ */
234
+ var _this = this;
235
+ ws.req = async function (method, params, func) {
236
+ var key = _this.config.name + '';
237
+ var data = {
238
+ id: key + new Date().getTime() + Math.random(),
239
+ method: method,
240
+ params: params,
241
+ };
242
+ this.send(JSON.stringify(data));
243
+
244
+ if (func) {
245
+ data.func = func;
246
+ this.list_msg.push(data);
247
+ this.dict_msg[data.id] = data;
248
+ }
249
+ };
250
+
251
+ // 设置事件 —— 获取消息时和socket关闭时
252
+ ws.on('message', async (body_str) => {
253
+ await _this.onMessage(body_str, ctx, token);
254
+ });
255
+
256
+ ws.on('close', async (body_str) => {
257
+ await _this.onClose(body_str, ctx, token);
258
+ });
259
+
260
+ // 设置心跳检测, 防止死连接
261
+ if (this.config.ping_interval > 0) {
262
+ ws._ping_timer = setInterval(() => {
263
+ if (ws.readyState !== 1) {
264
+ clearInterval(ws._ping_timer);
265
+ return;
266
+ }
267
+ ws.ping();
268
+ ws._pong_timeout = setTimeout(() => {
269
+ clearInterval(ws._ping_timer);
270
+ ws.terminate();
271
+ }, this.config.ping_timeout);
272
+ }, this.config.ping_interval);
273
+
274
+ ws.on('pong', () => {
275
+ if (ws._pong_timeout) {
276
+ clearTimeout(ws._pong_timeout);
277
+ ws._pong_timeout = null;
278
+ }
279
+ });
280
+ }
281
+ };
282
+
283
+ /**
284
+ * 握手成功, 发送首条返回内容
285
+ * @param {object} ctx http 上下文
286
+ * @param {string} token 临时访问牌
287
+ */
288
+ Drive.prototype.success = function (ctx, token) {
289
+ var ret = $.ret.bl(true, 'connection succeeded');
290
+ // 首次响应加上身份牌
291
+ ret.result.token = token;
292
+ // ID为0表示连接成功
293
+ ret.id = 0;
294
+ ctx.websocket.send(JSON.stringify(ret));
295
+ };
296
+
297
+ /**
298
+ * 添加客户端
299
+ * @param {object} ctx 请求上下文
300
+ */
301
+ Drive.prototype.add = async function (ctx) {
302
+ var token = await this.getToken(ctx);
303
+ if (!this.clients[token]) {
304
+ this.clients[token] = [];
305
+ }
306
+ this.setSocket(ctx, token);
307
+ this.success(ctx, token);
308
+ this.clients[token].push(ctx);
309
+ };
310
+
311
+ /**
312
+ * 发送消息到指定客户端
313
+ * @param {string} token 客户端token
314
+ * @param {string} method 方法名称
315
+ * @param {object} params 请求参数
316
+ * @returns {boolean} 发送是否成功
317
+ */
318
+ Drive.prototype.send = function (token, method, params) {
319
+ // 确保数据引用有效(热更新保护)
320
+ this._ensureRefs();
321
+
322
+ var list = this.clients[token];
323
+ if (list && list.length > 0) {
324
+ var data = {
325
+ method: method,
326
+ params: params,
327
+ };
328
+
329
+ for (var i = 0; i < list.length; i++) {
330
+ var ctx = list[i];
331
+ var ws = ctx.websocket;
332
+ if (ws && ws.readyState === 1) {
333
+ // WebSocket.OPEN
334
+ ws.send(JSON.stringify(data));
335
+ }
336
+ }
337
+ return true;
338
+ }
339
+ return false;
340
+ };
341
+
342
+ /**
343
+ * 发送消息到所有连接的客户端
344
+ * @param {string} method 方法名称
345
+ * @param {object} params 请求参数
346
+ */
347
+ Drive.prototype.sendAll = function (method, params) {
348
+ // 确保数据引用有效(热更新保护)
349
+ this._ensureRefs();
350
+
351
+ var data = {
352
+ method: method,
353
+ params: params,
354
+ };
355
+
356
+ for (var token in this.clients) {
357
+ var list = this.clients[token];
358
+ for (var i = 0; i < list.length; i++) {
359
+ var ctx = list[i];
360
+ var ws = ctx.websocket;
361
+ if (ws && ws.readyState === 1) {
362
+ // WebSocket.OPEN
363
+ ws.send(JSON.stringify(data));
364
+ }
365
+ }
366
+ }
367
+ };
368
+
369
+ /**
370
+ * 发送请求到指定客户端
371
+ * @param {string} token 客户端token
372
+ * @param {string} method 方法名称
373
+ * @param {object} params 请求参数
374
+ * @param {Function} func 回调函数
375
+ * @param {number} timeout 超时时间(毫秒)
376
+ * @returns {boolean} 发送是否成功
377
+ */
378
+ Drive.prototype.req = function (token, method, params, func, timeout = 0) {
379
+ // 确保数据引用有效(热更新保护)
380
+ this._ensureRefs();
381
+
382
+ var list = this.clients[token];
383
+ if (list && list.length > 0) {
384
+ var data = {
385
+ id: this._genMsgId(),
386
+ method: method,
387
+ params: params,
388
+ };
389
+
390
+ if (func) {
391
+ data.func = func;
392
+ data.timestamp = Date.now();
393
+ data.timeout = timeout || 3000;
394
+
395
+ // 将消息添加到驱动的消息队列
396
+ this.list_msg.push(data);
397
+ this.dict_msg[data.id] = data;
398
+
399
+ // 设置超时移除定时器
400
+ var _this = this;
401
+ data.timer = setTimeout(() => {
402
+ _this._delMsgById(data.id);
403
+ }, data.timeout);
404
+ }
405
+
406
+ for (var i = 0; i < list.length; i++) {
407
+ var ctx = list[i];
408
+ var ws = ctx.websocket;
409
+ if (ws && ws.readyState === 1) {
410
+ // WebSocket.OPEN
411
+ ws.send(JSON.stringify(data));
412
+ }
413
+ }
414
+ return true;
415
+ }
416
+ return false;
417
+ };
418
+
419
+ /**
420
+ * 发送请求到所有连接的客户端
421
+ * @param {string} method 方法名称
422
+ * @param {object} params 请求参数
423
+ * @param {Function} func 回调函数
424
+ * @param {number} timeout 超时时间(毫秒)
425
+ */
426
+ Drive.prototype.reqAll = function (method, params, func, timeout = 0) {
427
+ // 确保数据引用有效(热更新保护)
428
+ this._ensureRefs();
429
+
430
+ var data = {
431
+ id: this._genMsgId(),
432
+ method: method,
433
+ params: params,
434
+ };
435
+
436
+ if (func) {
437
+ data.func = func;
438
+ data.timestamp = Date.now();
439
+ data.timeout = timeout || 3000;
440
+
441
+ // 将消息添加到驱动的消息队列
442
+ this.list_msg.push(data);
443
+ this.dict_msg[data.id] = data;
444
+
445
+ // 设置超时移除定时器
446
+ var _this = this;
447
+ data.timer = setTimeout(() => {
448
+ _this._delMsgById(data.id);
449
+ }, data.timeout);
450
+ }
451
+
452
+ for (var token in this.clients) {
453
+ var list = this.clients[token];
454
+ for (var i = 0; i < list.length; i++) {
455
+ var ctx = list[i];
456
+ var ws = ctx.websocket;
457
+ if (ws && ws.readyState === 1) {
458
+ // WebSocket.OPEN
459
+ ws.send(JSON.stringify(data));
460
+ }
461
+ }
462
+ }
463
+ };
464
+
465
+ /**
466
+ * 生成消息ID
467
+ * @returns {string} 消息ID
468
+ * @private
469
+ */
470
+ Drive.prototype._genMsgId = function () {
471
+ return (
472
+ 'drive_' +
473
+ Date.parse(new Date()) +
474
+ '_' +
475
+ Math.random().toString(36).substr(2, 9)
476
+ );
477
+ };
478
+
479
+ /**
480
+ * 根据ID移除消息
481
+ * @param {string} msg_id 消息ID
482
+ * @private
483
+ */
484
+ Drive.prototype._delMsgById = function (msg_id) {
485
+ // 确保数据引用有效(热更新保护)
486
+ this._ensureRefs();
487
+
488
+ var o = this.dict_msg[msg_id];
489
+ if (!o) {
490
+ return;
491
+ }
492
+ // 清除定时器
493
+ if (o.timer) {
494
+ clearTimeout(o.timer);
495
+ }
496
+ delete this.dict_msg[msg_id];
497
+
498
+ // 从数组中移除 (保持list_msg与dict_msg同步)
499
+ for (var i = 0; i < this.list_msg.length; i++) {
500
+ if (this.list_msg[i].id === msg_id) {
501
+ this.list_msg.splice(i, 1);
502
+ break;
503
+ }
504
+ }
505
+ };
506
+
507
+ /**
508
+ * 处理消息回复
509
+ * @param {object} msg 回复消息
510
+ * @private
511
+ */
512
+ Drive.prototype._handleResponse = function (msg) {
513
+ // 确保数据引用有效(热更新保护)
514
+ this._ensureRefs();
515
+
516
+ if (!msg || !msg.id) {
517
+ return;
518
+ }
519
+
520
+ var o = this.dict_msg[msg.id];
521
+ if (o && o.func) {
522
+ try {
523
+ // 执行回调函数
524
+ o.func(msg);
525
+ } catch (error) {
526
+ console.error('Socket驱动回调函数执行错误:', error);
527
+ }
528
+
529
+ // 从列表中移除已处理的消息
530
+ this._delMsgById(o.id);
531
+ }
532
+ };
533
+
534
+ /**
535
+ * 执行
536
+ * @param {string} body 正文字符串
537
+ * @param {object} ctx 请求上下文
538
+ * @param {string} token 临时访问牌
539
+ * @returns {object} 返回执行结果
540
+ */
541
+ Drive.prototype.run = async function (body, ctx, token) {
542
+ try {
543
+ var by = body.toString();
544
+ var ws = ctx.websocket;
545
+ var json = by.toJson();
546
+ var req = ctx.request;
547
+ var request = { headers: req.headers, query: req.query, token: token };
548
+ if (!json) {
549
+ return await this.main(by, ws, request);
550
+ }
551
+ return await this._handleJson(json, ws, request);
552
+ } catch (err) {
553
+ this.log('error', 'webscoket 错误', err);
554
+ return $.ret.error(10000, '代码错误!原因:' + err.toString());
555
+ }
556
+ };
557
+
558
+ /**
559
+ * 处理 JSON 请求
560
+ * @param {object} json JSON 对象
561
+ * @param {object} ws WebSocket
562
+ * @param {object} request 请求对象
563
+ * @returns {object} 返回处理结果
564
+ * @private
565
+ */
566
+ Drive.prototype._handleJson = async function (json, ws, request) {
567
+ var { id, method } = json;
568
+ if (json.result && id) {
569
+ return await this._handleRet(json, ws);
570
+ }
571
+ if (method && this.methods[method]) {
572
+ return await this._callMethod(json, ws, request);
573
+ }
574
+ return await this.main(json, ws, request);
575
+ };
576
+
577
+ /**
578
+ * 处理结果回调
579
+ * @param {object} json JSON 对象
580
+ * @param {object} ws WebSocket
581
+ * @private
582
+ */
583
+ /* eslint-disable no-param-reassign */
584
+ Drive.prototype._handleRet = async function (json, ws) {
585
+ var id = json.id;
586
+ var o = ws.dict_msg[id];
587
+ if (o) {
588
+ await o.func(json.result);
589
+ delete ws.dict_msg[id];
590
+ var lt = ws.list_msg;
591
+ for (var i = 0; i < lt.length; i++) {
592
+ if (id === lt[i].id) {
593
+ lt.splice(i, 1);
594
+ return;
595
+ }
596
+ }
597
+ }
598
+ };
599
+ /* eslint-enable no-param-reassign */
600
+
601
+ /**
602
+ * 调用方法
603
+ * @param {object} json JSON 对象
604
+ * @param {object} ws WebSocket
605
+ * @param {object} request 请求对象
606
+ * @returns {object} 返回调用结果
607
+ * @private
608
+ */
609
+ Drive.prototype._callMethod = async function (json, ws, request) {
610
+ var { id, method } = json;
611
+ var result = await this.methods[method](json.params, ws, request);
612
+ if (!result) {
613
+ return;
614
+ }
615
+ if (typeof result == 'object' && !Array.isArray(result)) {
616
+ return { id, ...result };
617
+ }
618
+ var ret = { result };
619
+ if (id) {
620
+ ret.id = id;
621
+ }
622
+ return ret;
623
+ };
624
+
625
+ /**
626
+ * 加载完成时
627
+ */
628
+ Drive.prototype.loadAfter = function () {
629
+ var m = this.methods;
630
+
631
+ /**
632
+ * 获取所有方法
633
+ * @param {object} params 参数
634
+ * @param {object} ws Websocket服务
635
+ * @param {object} request 请求协议头
636
+ * @returns {object} 返回执行结果
637
+ */
638
+ m.getMethods = async function (params, ws, request) {
639
+ return Object.keys(m);
640
+ };
641
+ };
642
+
643
+ /**
644
+ * 获取插件
645
+ * @param {string} app 应用名称
646
+ * @param {string} name 插件名称
647
+ * @returns {object} 返回获取到的插件
648
+ */
649
+ Drive.prototype.plugin = function (app, name) {
650
+ var l = $.slash;
651
+ var app_name = app || this.config_file.between('app' + l, l);
652
+ var plugin_name = name || this.config_file.between('plugin' + l, l);
653
+ var plus;
654
+ var plugins = $.pool.plugin[app_name];
655
+ if (plugins) {
656
+ plus = plugins.get(plugin_name);
657
+ }
658
+ return plus;
659
+ };
660
+
661
+ /**
662
+ * 获取模型
663
+ * @param {string} type 模型类型
664
+ * @returns {object} 返回获取到的模型
665
+ */
666
+ Drive.prototype.getModel = function (type) {
667
+ let model = { ...this.config };
668
+ let dir = this.getDir();
669
+ let l = $.slash;
670
+ let app_name = dir.between('app' + l, l);
671
+ let plugin_name = dir.between('plugin' + l, l);
672
+ let name = dir.basename();
673
+ model.app = app_name;
674
+ model.plugin = plugin_name;
675
+ model.name = model.name || name;
676
+ return model;
677
+ };
678
+
679
+ module.exports = Drive;