zbzt-live-sdk 0.0.2

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 (80) hide show
  1. package/.babelrc +8 -0
  2. package/.editorconfig +13 -0
  3. package/.eslintrc.js +29 -0
  4. package/CHANGELOG.md +16 -0
  5. package/README.md +32 -0
  6. package/dist/zbzt-live-sdk.cjs.js +51 -0
  7. package/dist/zbzt-live-sdk.esm.js +51 -0
  8. package/dist/zbzt-live-sdk.umd.js +52 -0
  9. package/dist/zbzt-live-sdk.umd.js.map +1 -0
  10. package/example/app.js +133 -0
  11. package/example/bootstrap-3.4.1/css/bootstrap-theme.css +587 -0
  12. package/example/bootstrap-3.4.1/css/bootstrap-theme.css.map +1 -0
  13. package/example/bootstrap-3.4.1/css/bootstrap-theme.min.css +6 -0
  14. package/example/bootstrap-3.4.1/css/bootstrap-theme.min.css.map +1 -0
  15. package/example/bootstrap-3.4.1/css/bootstrap.css +6834 -0
  16. package/example/bootstrap-3.4.1/css/bootstrap.css.map +1 -0
  17. package/example/bootstrap-3.4.1/css/bootstrap.min.css +6 -0
  18. package/example/bootstrap-3.4.1/css/bootstrap.min.css.map +1 -0
  19. package/example/bootstrap-3.4.1/fonts/glyphicons-halflings-regular.eot +0 -0
  20. package/example/bootstrap-3.4.1/fonts/glyphicons-halflings-regular.svg +288 -0
  21. package/example/bootstrap-3.4.1/fonts/glyphicons-halflings-regular.ttf +0 -0
  22. package/example/bootstrap-3.4.1/fonts/glyphicons-halflings-regular.woff +0 -0
  23. package/example/bootstrap-3.4.1/fonts/glyphicons-halflings-regular.woff2 +0 -0
  24. package/example/bootstrap-3.4.1/js/bootstrap.js +2580 -0
  25. package/example/bootstrap-3.4.1/js/bootstrap.min.js +6 -0
  26. package/example/bootstrap-3.4.1/js/npm.js +13 -0
  27. package/example/css/style.css +18 -0
  28. package/example/index.html +59 -0
  29. package/example/js/jquery-3.7.1.min.js +2 -0
  30. package/example/js/utils.js +25 -0
  31. package/example/js/variables.js +14 -0
  32. package/example/js/zegoApi.js +229 -0
  33. package/example/style.css +25 -0
  34. package/example/test.html +100 -0
  35. package/package.json +60 -0
  36. package/release.js +33 -0
  37. package/rollup-plugin-http.js +49 -0
  38. package/src/channel/getSendMsgParams.js +66 -0
  39. package/src/channel/index.js +135 -0
  40. package/src/channel/pomelo/index.js +182 -0
  41. package/src/channel/pomelo/latestQueue.js +150 -0
  42. package/src/channel/pomelo/polemo.js +730 -0
  43. package/src/channel/pomelo/util.js +54 -0
  44. package/src/channel/sdk-cb.js +73 -0
  45. package/src/channel/stream-msg.js +97 -0
  46. package/src/channel/zbzt/index.js +74 -0
  47. package/src/channel/zbzt/interactWithChannel.js +4 -0
  48. package/src/channel/zbzt/interactWithChannelControl.js +1568 -0
  49. package/src/channel/zbzt/interactWithChannelEntry.js +318 -0
  50. package/src/config/config.js +226 -0
  51. package/src/default/base.js +71 -0
  52. package/src/default/extend.js +36 -0
  53. package/src/default/index.js +10 -0
  54. package/src/live/base.js +43 -0
  55. package/src/live/call-method.js +10 -0
  56. package/src/live/extend.js +53 -0
  57. package/src/live/index.js +10 -0
  58. package/src/network/api.js +56 -0
  59. package/src/network/commonFetch.js +66 -0
  60. package/src/network/dataReport.js +448 -0
  61. package/src/notice.js +418 -0
  62. package/src/tool/base.js +74 -0
  63. package/src/tool/call-method.js +10 -0
  64. package/src/tool/extend.js +42 -0
  65. package/src/tool/index.js +10 -0
  66. package/src/util/bridge.js +87 -0
  67. package/src/util/bridge1.js +46 -0
  68. package/src/util/dict.js +51 -0
  69. package/src/util/sessionStorage.js +29 -0
  70. package/src/util/sha256.js +483 -0
  71. package/src/util/util.js +329 -0
  72. package/src/zbzt-av-sdk/default-sdk.js +192 -0
  73. package/src/zbzt-av-sdk/device.js +86 -0
  74. package/src/zbzt-av-sdk/rtc-sdk.js +2854 -0
  75. package/src/zbzt-av-sdk/talrtc-sdk.js +2620 -0
  76. package/src/zbzt-av-sdk/trtc-sdk.js +1802 -0
  77. package/src/zbzt-av-sdk/zbzt-av-sdk.js +2121 -0
  78. package/src/zbzt-av-sdk/zego-sdk.js +1718 -0
  79. package/src/zbzt-av-sdk/zego-sdk.js.bak +3133 -0
  80. package/src/zbzt-live-sdk.js +1484 -0
@@ -0,0 +1,730 @@
1
+ import Protocol from 'pomelo-protocol';
2
+ import Protobuf from 'pomelo-protobuf';
3
+ import LatestQueue from './latestQueue.js';
4
+ import util from './util';
5
+ import CHANNEL from '../index';
6
+ import defaultApi from '../../default/extend';
7
+ import dataReport from '../../network/dataReport';
8
+
9
+ var _protocol = Protocol;
10
+ var _protobuf = Protobuf;
11
+ var _package = Protocol.Package;
12
+ var _message = Protocol.Message;
13
+ var _JS_WS_CLIENT_TYPE = 'js-websocket';
14
+ var _JS_WS_CLIENT_VERSION = '1.0.0';
15
+ // 重连间隔时间
16
+ const reconnectInterval = 10 * 1000;
17
+
18
+
19
+ class PomeloClient {
20
+ constructor() {
21
+ this.handshakeBuffer = {
22
+ sys: {
23
+ type: _JS_WS_CLIENT_TYPE,
24
+ version: _JS_WS_CLIENT_VERSION
25
+ },
26
+ user: {}
27
+ };
28
+ this.pomeloData = {};
29
+ this.heartbeatInterval = 5000;
30
+ this.heartbeatTimeout = this.heartbeatInterval * 2;
31
+ this.nextHeartbeatTimeout = 0;
32
+ this.heartbeatId = null;
33
+ this.heartbeatTimeoutId = null;
34
+ this.handshakeCallback = null;
35
+ this.socket = null;
36
+ this.reqId = 0;
37
+ this.callBacks = {};
38
+ this.handlers = {};
39
+ this.routeMap = {};
40
+ this.initCallback = null;
41
+ //自定义
42
+ this.pomeloConfig = {};
43
+ // 初始化参数
44
+ this.indexChannelInfo = {};
45
+ // 最后一条接收消息的uuid,用于消息恢复
46
+ this.lastReceiveMsgUuid = '';
47
+ // 是否正在获取缓存消息列表
48
+ this.isGettingCacheMsgList = false;
49
+ // 重连定时器
50
+ this.reconnectTimer = null;
51
+ // 是否在重连
52
+ this.isReconnectting = false;
53
+ // 是否连接成功
54
+ this.isConnected = false;
55
+ //是否在教室
56
+ this.isInRoom = false;
57
+ // 是否链接成功过
58
+ this.hasConnected = false;
59
+
60
+ this.latestQueueObj = new LatestQueue();
61
+ this.deleteQueueTimer = setInterval(() => {
62
+ this.latestQueueObj.delete.call(
63
+ this.latestQueueObj,
64
+ 5000 * 4,
65
+ 1000
66
+ );
67
+ }, 1000);
68
+
69
+ this.failTimes = 0;
70
+ this.retryTimesWhenHeartBeatFailed = 100;
71
+
72
+ this.EventType = {
73
+ SOCKET_IO_ERROR: 'SOCKET_IO_ERROR'
74
+ };
75
+ }
76
+
77
+ //初始化pomelo
78
+ initPomelo(pomeloConfig, callBack) {
79
+ this.pomeloConfig = pomeloConfig;
80
+ let port = pomeloConfig.port ? `:${pomeloConfig.port}` : '';
81
+ var url = `wss://${pomeloConfig.host}${port}`;
82
+
83
+ this.handshakeBuffer.user = pomeloConfig.user;
84
+ this.initCallback = callBack;
85
+ // this.handshakeCallback = pomeloConfig.handshakeCallback;
86
+ defaultApi.writeLog(`channel_log : ${url} ${JSON.stringify(pomeloConfig)} initPomelo ......`);
87
+ //开始连接websocket
88
+ this.initWebSocket(url, pomeloConfig.serverType);
89
+ }
90
+
91
+ joinRoom(pomeloConfig, callBack) {
92
+ this.callback = callBack;
93
+ this.isInRoom = true;
94
+ pomeloConfig.port = '443';
95
+ this.indexChannelInfo = pomeloConfig;
96
+ defaultApi.writeLog(`channel_log :${JSON.stringify(pomeloConfig)} the first step to join pomelo ......`);
97
+ try {
98
+ dataReport.pomeloJoinRoom({pomeloConfig});
99
+ } catch(e) {
100
+ defaultApi.writeLog(`pomeloJoinRoom_error ${JSON.stringify(e)}`);
101
+ }
102
+ return this.connectGateServer(pomeloConfig);
103
+ }
104
+
105
+ initWebSocket(url, serverType) {
106
+ var _this = this;
107
+ defaultApi.writeLog(`channel_log : ${url} ${serverType} socket init......`);
108
+ try {
109
+ if (this.socket) {
110
+ defaultApi.writeLog('channel_log : socket is closed......');
111
+ this.socket.close();
112
+ }
113
+ } catch (e) {
114
+ defaultApi.writeLog('pomelo socket close error');
115
+ }
116
+
117
+ //initSocket
118
+ this.socket = new WebSocket(url);
119
+ try {
120
+ dataReport.pomeloInitWebSocket({url});
121
+ } catch(e) {
122
+ defaultApi.writeLog(`pomeloInitWebSocket_error ${JSON.stringify(e)}`);
123
+ }
124
+ defaultApi.writeLog('channel_log : new WebSocket......');
125
+ this.socket.binaryType = 'arraybuffer';
126
+
127
+ this.socket.onopen = evt => {
128
+ _this.onSocketOpen(evt);
129
+ defaultApi.writeLog(`channel_log : ${JSON.stringify(evt)} socket is onopen......`);
130
+ };
131
+
132
+ this.socket.onmessage = evt => {
133
+ _this.onSocketMessage(evt);
134
+ };
135
+
136
+ this.socket.onerror = evt => {
137
+ // new update start
138
+ this.socket.onerror = null;
139
+ this.socket.onclose = null;
140
+ // new update end
141
+ _this.onSocketError(evt);
142
+ defaultApi.writeLog(`channel_log : ${JSON.stringify(evt)} socket is onerror......`);
143
+ // 重连
144
+ this.reconnect();
145
+ };
146
+
147
+ this.socket.onclose = evt => {
148
+ // new update start
149
+ this.socket.onerror = null;
150
+ this.socket.onclose = null;
151
+ // new update end
152
+
153
+ defaultApi.writeLog(`channel_log : ${JSON.stringify(evt)} socket is onclose......`);
154
+ if (serverType == 'chat') {
155
+ // this.emit(SocketEventType.SOCKET_CLOSE, evt);
156
+ defaultApi.writeLog(`[webSocket-state]:onClose---ErrorInfo: ${JSON.stringify(evt)}`);
157
+ // 重连
158
+ this.reconnect();
159
+
160
+ if (this.heartbeatId) {
161
+ clearTimeout(this.heartbeatId);
162
+ this.heartbeatId = null;
163
+ }
164
+ if (this.heartbeatTimeoutId) {
165
+ clearTimeout(this.heartbeatTimeoutId);
166
+ this.heartbeatTimeoutId = null;
167
+ }
168
+ }
169
+ };
170
+ defaultApi.writeLog(`===start-init-websocket${url}===`);
171
+ }
172
+ //onSocketOpen
173
+ onSocketOpen(evt) {
174
+ if (this.socket.readyState == 1) {
175
+ var obj = _package.encode(
176
+ _package.TYPE_HANDSHAKE,
177
+ _protocol.strencode(JSON.stringify(this.handshakeBuffer))
178
+ );
179
+ this.send(obj);
180
+ }
181
+ }
182
+
183
+ //request
184
+ request(route, msg, cb) {
185
+ msg = msg || {};
186
+ route = route || msg.route;
187
+ if (!route) {
188
+ defaultApi.writeLog('fail to send request without route.');
189
+ return;
190
+ }
191
+ this.reqId++;
192
+ this.sendMessage(this.reqId, route, msg);
193
+ this.callBacks[this.reqId] = cb;
194
+ this.routeMap[this.reqId] = route;
195
+ }
196
+
197
+ notify(route, msg) {
198
+ msg = msg || {};
199
+ this.sendMessage(0, route, msg);
200
+ }
201
+
202
+ //sendMessage
203
+ sendMessage(reqId, route, msg) {
204
+ var type = reqId ? _message.TYPE_REQUEST : _message.TYPE_NOTIFY;
205
+ //compress message by protobuf
206
+ var protos = this.pomeloData.protos
207
+ ? this.pomeloData.protos.client
208
+ : {};
209
+ if (protos[route]) {
210
+ msg = _protobuf.encode(route, msg);
211
+ } else {
212
+ msg = _protocol.strencode(JSON.stringify(msg));
213
+ }
214
+
215
+ var compressRoute = 0;
216
+ msg = _message.encode(reqId, type, compressRoute, route, msg);
217
+ var packet = _package.encode(_package.TYPE_DATA, msg);
218
+ this.send(packet);
219
+ }
220
+
221
+ //onSocketMessage
222
+ onSocketMessage(evt) {
223
+ var msgData = _package.decode(evt.data);
224
+ switch (msgData.type) {
225
+ case _package.TYPE_HANDSHAKE:
226
+ this.handshake(msgData.body);
227
+ break;
228
+ case _package.TYPE_HEARTBEAT:
229
+ this.heartbeat(msgData.body);
230
+ break;
231
+ case _package.TYPE_DATA:
232
+ // defaultApi.writeLog(`channel_log : ${JSON.stringify(msgData)} _package TYPE_DATA ......`);
233
+ var msg = _message.decode(msgData.body);
234
+
235
+ if (msg.id > 0) {
236
+ msg.route = this.routeMap[msg.id];
237
+ delete this.routeMap[msg.id];
238
+ if (!msg.route) {
239
+ return;
240
+ }
241
+ }
242
+ msg.body = this.deCompose(msg);
243
+ this.processMessage(msg);
244
+ break;
245
+ case _package.TYPE_KICK:
246
+ defaultApi.writeLog('channel_log : _package TYPE_KICK ......');
247
+ // this.emit(SocketEventType.POMELO_MESSAGE_KICK);
248
+ break;
249
+ }
250
+ if (this.heartbeatTimeout) {
251
+ this.nextHeartbeatTimeout = Date.now() + this.heartbeatTimeout;
252
+ }
253
+ }
254
+ //onSocketError
255
+ onSocketError(evt) {
256
+ // this.emit(SocketEventType.SOCKET_IO_ERROR, evt);
257
+ defaultApi.writeLog(`[webSocket-state]:onError---ErrorInfo: ${JSON.stringify(evt)}`);
258
+ }
259
+ //onSocketClose
260
+ onSocketClose(evt) {
261
+ // this.emit(SocketEventType.SOCKET_CLOSE, evt);
262
+ defaultApi.writeLog(`[webSocket-state]:onClose---ErrorInfo: ${JSON.stringify(evt)}`);
263
+ }
264
+ //handshake
265
+ handshake(data) {
266
+ var _this = this;
267
+ data = JSON.parse(_protocol.strdecode(data));
268
+ defaultApi.writeLog(`[websocket-handshake-code:${data.code}]`);
269
+ // heartBeatConfig
270
+ if (data.sys && data.sys.heartbeat) {
271
+ this.heartbeatInterval = data.sys.heartbeat * 1000; // heartbeat interval
272
+ this.heartbeatTimeout = this.heartbeatInterval * 2; // max heartbeat timeout
273
+ } else {
274
+ this.heartbeatInterval = 0;
275
+ this.heartbeatTimeout = 0;
276
+ }
277
+
278
+ if (data.sys && data.sys['minHeartbeatInterval']) {
279
+ this.minHeartbeatInterval = data.sys['minHeartbeatInterval'] * 1000; // heartbeat interval
280
+ } else {
281
+ this.minHeartbeatInterval = 3000;
282
+ }
283
+
284
+ if (data.sys && data.sys['retryTimesWhenHeartBeatFailed']) {
285
+ this.retryTimesWhenHeartBeatFailed =
286
+ data.sys['retryTimesWhenHeartBeatFailed'];
287
+ }
288
+
289
+ this.initPomeloData(data);
290
+ // handshake-complete
291
+ this.send(_package.encode(_package.TYPE_HANDSHAKE_ACK));
292
+ if (this.initCallback) {
293
+ this.initCallback(this.socket);
294
+ this.initCallback = null;
295
+ }
296
+ }
297
+ //heartbeat
298
+ async heartbeat(data) {
299
+ var _this = this;
300
+ // defaultApi.writeLog('[websocket-heartbeat-state]:receive heartbeat...');
301
+ var obj = _package.encode(_package.TYPE_HEARTBEAT);
302
+
303
+ if (this.failTimes) {
304
+ this.failTimes = 0;
305
+ defaultApi.writeLog('重新连上了');
306
+ }
307
+
308
+ if (this.heartbeatTimeoutId) {
309
+ clearTimeout(this.heartbeatTimeoutId);
310
+ this.heartbeatTimeoutId = null;
311
+ }
312
+
313
+ if (this.heartbeatId) {
314
+ // already in a heartbeat interval
315
+ return;
316
+ }
317
+ this.heartbeatId = setTimeout(() => {
318
+ this.heartbeatId = null;
319
+ this.send(obj);
320
+ // defaultApi.writeLog('[pomeloclient.heartbeat]:send heartbeat...');
321
+ this.nextHeartbeatTimeout = Date.now() + this.heartbeatTimeout;
322
+ this.heartbeatTimeoutId = setTimeout(() => {
323
+ this.heartbeatTimeoutCb(this);
324
+ }, this.minHeartbeatInterval);
325
+ }, this.heartbeatInterval);
326
+ }
327
+ //heartbeatTimeoutCb
328
+ heartbeatTimeoutCb(that) {
329
+ var self = this;
330
+ defaultApi.writeLog('heartbeatTimeoutCb log !!!');
331
+ if (this.failTimes < this.retryTimesWhenHeartBeatFailed) {
332
+ var obj = _package.encode(_package.TYPE_HEARTBEAT);
333
+ self.send(obj);
334
+ this.failTimes += 1;
335
+ defaultApi.writeLog(`心跳重试第${this.failTimes}次`);
336
+ self.heartbeatTimeoutId = setTimeout(
337
+ this.heartbeatTimeoutCb.bind(self),
338
+ this.minHeartbeatInterval
339
+ );
340
+ } else {
341
+ // update start
342
+ // 超时前先断开监听事件
343
+ self.socket.onmessage = null;
344
+ self.socket.onerror = null;
345
+ self.socket.onclose = null;
346
+ // update end
347
+
348
+ defaultApi.writeLog('server heartbeat timeout');
349
+ // 重连
350
+ this.reconnect();
351
+ // update start
352
+ // this.disconnect(true);
353
+ // update end
354
+ }
355
+ }
356
+ //processMessage
357
+ processMessage(msg) {
358
+ var _this = this;
359
+ // eslint-disable-next-line no-extra-boolean-cast
360
+ if (!!msg.body.msgId) {
361
+ var replyRoute = 'connector.' + msg.route + '.ack';
362
+ var replyMsg = {
363
+ msgId: msg.body.msgId,
364
+ ack: 1
365
+ };
366
+
367
+ this.notify(replyRoute, replyMsg);
368
+ }
369
+ if (!msg || !msg.id) {
370
+ switch (msg.route) {
371
+ case 'onChat':
372
+ break;
373
+ case 'onServer':
374
+ try {
375
+ const onServerMsg = JSON.parse(msg.body.msg);
376
+ this.dealOnServerMsg(onServerMsg, msg.body.from);
377
+ } catch (error) {
378
+ }
379
+ break;
380
+ case 'onAdd':
381
+ break;
382
+ case 'onLeave':
383
+ break;
384
+ case 'onNotice':
385
+ break;
386
+ case 'onKick':
387
+ this.disconnect(true);
388
+ break;
389
+ default:
390
+ }
391
+
392
+ return;
393
+ }
394
+ var cb = this.callBacks[msg.id];
395
+ delete this.callBacks[msg.id];
396
+ if (typeof cb !== 'function') {
397
+ return;
398
+ }
399
+ cb(msg.body);
400
+ return;
401
+ }
402
+ //deCompose
403
+ deCompose(msg) {
404
+ var protos = this.pomeloData.protos
405
+ ? this.pomeloData.protos.server
406
+ : {};
407
+ var abbrs = this.pomeloData.abbrs;
408
+ var route = msg.route;
409
+ try {
410
+ //Decompose route from dict
411
+ if (msg.compressRoute) {
412
+ if (!abbrs[route]) {
413
+ defaultApi.writeLog('illegal msg!');
414
+ return {};
415
+ }
416
+ route = msg.route = abbrs[route];
417
+ }
418
+ if (protos[route]) {
419
+ return _protobuf.decode(route, msg.body);
420
+ }
421
+ return JSON.parse(_protocol.strdecode(msg.body));
422
+ } catch (ex) {
423
+ console.error('route, body = ' + route + ', ' + msg.body);
424
+ }
425
+ return msg;
426
+ }
427
+ //handshakeInit
428
+ initPomeloData(data) {
429
+ if (!data || !data.sys) {
430
+ return;
431
+ }
432
+ this.pomeloData = this.pomeloData || {};
433
+ var dict = data.sys.dict;
434
+ var protos = data.sys.protos;
435
+ //Init compress dict
436
+ if (dict) {
437
+ this.pomeloData.dict = dict;
438
+ this.pomeloData.abbrs = {};
439
+ for (var route in dict) {
440
+ this.pomeloData.abbrs[dict[route]] = route;
441
+ }
442
+ }
443
+ //Init protobuf protos
444
+ if (protos) {
445
+ this.pomeloData.protos = {
446
+ server: protos.server || {},
447
+ client: protos.client || {}
448
+ };
449
+ if (_protobuf) {
450
+ _protobuf.init({
451
+ encoderProtos: protos.client,
452
+ decoderProtos: protos.server
453
+ });
454
+ }
455
+ }
456
+ }
457
+ //disconnect
458
+ disconnect(isSelf) {
459
+ if (this.socket) {
460
+ this.socket.onmessage = null;
461
+ this.socket.onerror = null;
462
+ this.socket.onclose = null;
463
+ this.isGettingCacheMsgList = false;
464
+ this.isConnected = false;
465
+ if (!isSelf) {
466
+ this.hasConnected = false;
467
+ this.isInRoom = false;
468
+ if (this.reconnectTimer) {
469
+ clearInterval(this.reconnectTimer);
470
+ this.reconnectTimer = null;
471
+ }
472
+ }
473
+
474
+ if (this.socket.disconnect) {
475
+ this.socket.disconnect();
476
+ }
477
+ if (this.socket.close) {
478
+ this.socket.close();
479
+ }
480
+ defaultApi.writeLog('[webSocket-disconnect]');
481
+ }
482
+ if (this.heartbeatId) {
483
+ clearTimeout(this.heartbeatId);
484
+ this.heartbeatId = null;
485
+ }
486
+ if (this.heartbeatTimeoutId) {
487
+ clearTimeout(this.heartbeatTimeoutId);
488
+ this.heartbeatTimeoutId = null;
489
+ }
490
+ if (this.deleteQueueTimer) {
491
+ clearInterval(this.deleteQueueTimer);
492
+ this.deleteQueueTimer = null;
493
+ }
494
+ }
495
+ //send
496
+ send(packet) {
497
+ if (this.socket) {
498
+ if (this.socket.readyState == 2 || this.socket.readyState == 3) {
499
+ this.disconnect(true);
500
+ return;
501
+ }
502
+ this.socket.send(packet.buffer || packet, {
503
+ binary: true,
504
+ mask: true
505
+ });
506
+ }
507
+ }
508
+ //发送消息
509
+ sendChannelMessage(msgData, target = '*') {
510
+ return new Promise((resolve, reject) => {
511
+ this.request(
512
+ 'chat.chatHandler.send',
513
+ {
514
+ // rid: this.indexChannelInfo.channelID,
515
+ content: JSON.stringify(msgData),
516
+ from: this.indexChannelInfo.userID,
517
+ target: target || '*',
518
+ route: 'onServer'
519
+ },
520
+ data => {
521
+ if (data.error) {
522
+ reject({code: -1});
523
+ }
524
+ resolve({code: 200});
525
+ }
526
+ );
527
+ });
528
+ }
529
+ //连接gate服务器,获取chat连接地址
530
+ async connectGateServer(channelInfo) {
531
+ await new Promise((resolve, reject) => {
532
+ this.initPomelo({
533
+ serverType: 'gate',
534
+ host: channelInfo.host,
535
+ port: channelInfo.port,
536
+ log: true
537
+ }, () => {
538
+ resolve(true);
539
+ });
540
+ });
541
+ defaultApi.writeLog('channel_log : connectGateServer,the second step to join pomelo ......');
542
+
543
+ const queryData = {
544
+ uid: channelInfo.userId,
545
+ rtype: 4,
546
+ utype: 2,
547
+ retrytime: new Date().getTime(),
548
+ protocolVersion: '1.0',
549
+ // uniqId: channelInfo.guid
550
+ };
551
+
552
+ console.log('gate', queryData, channelInfo);
553
+ const _channelInfo = Object.assign({}, channelInfo);
554
+
555
+ await new Promise((resolve, reject) => {
556
+ this.request('gate.gateHandler.queryEntry', queryData, data => {
557
+ try {
558
+ this.socket.close();
559
+ defaultApi.writeLog('channel_log :gate socket close......');
560
+ } catch (error) {
561
+ //
562
+ }
563
+ this.socket = null;
564
+
565
+ if (data.code === 500) {
566
+ defaultApi.writeLog(`channel_log : ${data.code} request-gateServerFailed......`);
567
+ reject('gateServerFailed');
568
+ }
569
+
570
+ _channelInfo.host = data.host;
571
+ _channelInfo.port = data.port;
572
+ defaultApi.writeLog(`channel_log : ${data.code} request-gateServerSuccess ......`);
573
+ try {
574
+ dataReport.pomeloInitGate({gateRes:data});
575
+ } catch(e) {
576
+ console.log('pomeloInitGate_error',e);
577
+ }
578
+ resolve('gateServerSuccess');
579
+ });
580
+ });
581
+ return this.connectChatServer(_channelInfo);
582
+ }
583
+ // 重连chat服务器
584
+ reconnectChatServer(enterData) {
585
+ this.request('connector.entryHandler.enter', enterData, data => {
586
+ if (data.code === 500) {
587
+ this.reconnectChatServer(enterData);
588
+ return;
589
+ }
590
+ resolve(data);
591
+ });
592
+ }
593
+ // 连接chat服务器
594
+ async connectChatServer(channelInfo) {
595
+ defaultApi.writeLog('channel_log : connectChatServer,the third step to join pomelo ......');
596
+ await new Promise((resolve, reject) => {
597
+ this.initPomelo({
598
+ serverType: 'chat',
599
+ host: channelInfo.host,
600
+ port: channelInfo.port,
601
+ log: true
602
+ }, () => {
603
+ resolve(true);
604
+ });
605
+ });
606
+ const enterData = {
607
+ uid: channelInfo.userId,
608
+ rid: channelInfo.roomId,
609
+ rtype: 4,
610
+ username: channelInfo.userId,
611
+ uname: channelInfo.userName,
612
+ // ulevel: userInfo.level, //用户等级x
613
+ role: channelInfo.role,
614
+ classid: channelInfo.roomId,
615
+ protocolVersion: '1.0',
616
+ uniqId: channelInfo.guid
617
+ };
618
+
619
+ return new Promise(async (resolve, reject) => {
620
+ this.request(
621
+ 'connector.entryHandler.enter',
622
+ enterData,
623
+ async data => {
624
+ if (data.code === 500) {
625
+ reject(data);
626
+ defaultApi.writeLog(`channel_log : ${data.code} request-chatServerFailed......`);
627
+ return;
628
+ }
629
+ this.dealConnectSuccess();
630
+ try {
631
+ dataReport.pomeloInitChat({chatRes:data});
632
+ } catch(e) {
633
+ defaultApi.writeLog(`pomeloInitChat_error ${JSON.stringify(e)}`, null, 'error');
634
+ }
635
+ resolve(data);
636
+ defaultApi.writeLog(`channel_log : ${JSON.stringify(data)} request-chatServerSuccess......`);
637
+ }
638
+ );
639
+ });
640
+ }
641
+ // 处理连接成功
642
+ async dealConnectSuccess() {
643
+ // 获取历史列表
644
+ if (this.lastReceiveMsgUuid) {
645
+ try {
646
+ this.isGettingCacheMsgList = true;
647
+ defaultApi.writeLog('msgRecoverStream--start');
648
+ const res = JSON.parse(util.unzip(await this.msgRecoverStream()));
649
+ defaultApi.writeLog(`msgRecoverStream--end ${JSON.stringify(res)}`);
650
+ if (res.code === 200) {
651
+ const recoverMsgList = res.result.cacheList;
652
+ recoverMsgList.forEach(msg => {
653
+ const _msg = JSON.parse(msg);
654
+ this.dealOnServerMsg(_msg, _msg.from);
655
+ });
656
+ this.isGettingCacheMsgList = false;
657
+ }
658
+ } catch (error) {
659
+
660
+ }
661
+ }
662
+ if (this.hasConnected) {
663
+ // 处理公共重进逻辑
664
+ CHANNEL.reJoin();
665
+ }
666
+ this.hasConnected = true;
667
+ clearInterval(this.reconnectTimer);
668
+ this.reconnectTimer = null;
669
+ this.isReconnectting = false;
670
+ this.isConnected = true;
671
+ }
672
+ // 消息恢复
673
+ msgRecoverStream() {
674
+ return new Promise((resolve, reject) => {
675
+ const { userId, roomId } = this.indexChannelInfo;
676
+ this.request(
677
+ 'recover.recoverHandler.msgRecoverStream',
678
+ {
679
+ stuId: userId,
680
+ rid: roomId,
681
+ uuid: this.lastReceiveMsgUuid
682
+ },
683
+ data => {
684
+ if (data.code === 500) {
685
+ reject(data);
686
+ return;
687
+ }
688
+ resolve(data);
689
+ }
690
+ );
691
+ });
692
+ }
693
+ // 重连
694
+ reconnect() {
695
+ defaultApi.writeLog('pomelo reconnect...');
696
+ if (this.isReconnectting) {
697
+ return;
698
+ }
699
+ if (this.socket) {
700
+ // 创建实例前断开
701
+ this.disconnect(true);
702
+ this.socket = null;
703
+ }
704
+ this.isReconnectting = true;
705
+ if (!this.isConnected && this.isInRoom) {
706
+ this.connectGateServer(this.indexChannelInfo);
707
+ }
708
+ this.reconnectTimer = setInterval(() => {
709
+ if (!this.isConnected && this.isInRoom) {
710
+ this.connectGateServer(this.indexChannelInfo);
711
+ }
712
+ }, reconnectInterval);
713
+ }
714
+ // 处理onserver消息
715
+ dealOnServerMsg(onServerMsg, from) {
716
+ if (from === 'sdkset') {
717
+ this.callback(onServerMsg);
718
+ } else if (from !== this.indexChannelInfo.userId) {
719
+ if (this.latestQueueObj.isRepeat(onServerMsg.uuid)) {
720
+ return;
721
+ }
722
+ this.latestQueueObj.insert(onServerMsg.uuid, Date.now());
723
+ if (!this.isGettingCacheMsgList) {
724
+ this.lastReceiveMsgUuid = onServerMsg.uuid;
725
+ }
726
+ this.callback(onServerMsg);
727
+ }
728
+ }
729
+ }
730
+ export default new PomeloClient();