@realsee/live 0.4.0-beta.7 → 0.5.0-alpha.10

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 (34) hide show
  1. package/dist/live/controller.d.ts +81 -38
  2. package/dist/live/createLive.d.ts +5 -3
  3. package/dist/live/createLiveReact.d.ts +49 -3
  4. package/dist/live/live.d.ts +170 -0
  5. package/dist/realsee-live.cjs.development.js +1654 -1445
  6. package/dist/realsee-live.cjs.development.js.map +1 -1
  7. package/dist/realsee-live.cjs.production.js +1 -1
  8. package/dist/realsee-live.cjs.production.js.map +1 -1
  9. package/dist/realsee-live.esm.js +1656 -1447
  10. package/dist/realsee-live.esm.js.map +1 -1
  11. package/dist/realsee-live.umd.development.js +51517 -51302
  12. package/dist/realsee-live.umd.development.js.map +1 -1
  13. package/dist/realsee-live.umd.production.js +1 -1
  14. package/dist/realsee-live.umd.production.js.map +1 -1
  15. package/dist/typings/live/EventType.d.ts +17 -33
  16. package/dist/typings/live/LiveConnectOptions.d.ts +7 -0
  17. package/dist/typings/live/LiveErrorType.d.ts +9 -0
  18. package/dist/typings/live/LiveOptions.d.ts +5 -12
  19. package/dist/typings/live/LiveState.d.ts +15 -0
  20. package/dist/typings/live/index.d.ts +2 -1
  21. package/dist/typings/react/index.d.ts +0 -1
  22. package/dist/utils/RobustWebSocket.d.ts +153 -0
  23. package/dist/utils/logger.d.ts +16 -0
  24. package/docs/assets/search.js +1 -1
  25. package/docs/classes/VRWebViewRTC.html +5 -5
  26. package/docs/enums/LiveState.html +7 -0
  27. package/docs/index.html +1 -1
  28. package/docs/interfaces/LiveOptions.html +16 -19
  29. package/docs/modules.html +40 -40
  30. package/package.json +2 -2
  31. package/dist/typings/live/Live.d.ts +0 -128
  32. package/dist/typings/react/LiveReact.d.ts +0 -164
  33. package/docs/interfaces/Live.html +0 -116
  34. package/docs/interfaces/LiveReact.html +0 -52
@@ -3,8 +3,8 @@
3
3
  Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
5
  var JSBridge = require('@realsee/jsbridge-x');
6
- var amazonChimeSdkJs = require('amazon-chime-sdk-js');
7
6
  var TRTC = require('trtc-js-sdk');
7
+ var amazonChimeSdkJs = require('amazon-chime-sdk-js');
8
8
  var React = require('react');
9
9
 
10
10
  function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
@@ -13,97 +13,7 @@ var JSBridge__default = /*#__PURE__*/_interopDefaultLegacy(JSBridge);
13
13
  var TRTC__default = /*#__PURE__*/_interopDefaultLegacy(TRTC);
14
14
  var React__default = /*#__PURE__*/_interopDefaultLegacy(React);
15
15
 
16
- /******************************************************************************
17
- Copyright (c) Microsoft Corporation.
18
-
19
- Permission to use, copy, modify, and/or distribute this software for any
20
- purpose with or without fee is hereby granted.
21
-
22
- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
23
- REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
24
- AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
25
- INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
26
- LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
27
- OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
28
- PERFORMANCE OF THIS SOFTWARE.
29
- ***************************************************************************** */
30
- /* global Reflect, Promise */
31
-
32
- var extendStatics = function(d, b) {
33
- extendStatics = Object.setPrototypeOf ||
34
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
35
- function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
36
- return extendStatics(d, b);
37
- };
38
-
39
- function __extends(d, b) {
40
- if (typeof b !== "function" && b !== null)
41
- throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
42
- extendStatics(d, b);
43
- function __() { this.constructor = d; }
44
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
45
- }
46
-
47
- var __assign = function() {
48
- __assign = Object.assign || function __assign(t) {
49
- for (var s, i = 1, n = arguments.length; i < n; i++) {
50
- s = arguments[i];
51
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
52
- }
53
- return t;
54
- };
55
- return __assign.apply(this, arguments);
56
- };
57
-
58
- function __awaiter(thisArg, _arguments, P, generator) {
59
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
60
- return new (P || (P = Promise))(function (resolve, reject) {
61
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
62
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
63
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
64
- step((generator = generator.apply(thisArg, _arguments || [])).next());
65
- });
66
- }
67
-
68
- function __generator(thisArg, body) {
69
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
70
- return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
71
- function verb(n) { return function (v) { return step([n, v]); }; }
72
- function step(op) {
73
- if (f) throw new TypeError("Generator is already executing.");
74
- while (_) try {
75
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
76
- if (y = 0, t) op = [op[0] & 2, t.value];
77
- switch (op[0]) {
78
- case 0: case 1: t = op; break;
79
- case 4: _.label++; return { value: op[1], done: false };
80
- case 5: _.label++; y = op[1]; op = [0]; continue;
81
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
82
- default:
83
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
84
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
85
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
86
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
87
- if (t[2]) _.ops.pop();
88
- _.trys.pop(); continue;
89
- }
90
- op = body.call(thisArg, _);
91
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
92
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
93
- }
94
- }
95
-
96
- function __spreadArray(to, from, pack) {
97
- if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
98
- if (ar || !(i in from)) {
99
- if (!ar) ar = Array.prototype.slice.call(from, 0, i);
100
- ar[i] = from[i];
101
- }
102
- }
103
- return to.concat(ar || Array.prototype.slice.call(from));
104
- }
105
-
106
- var EVENT_SYMBOL = Symbol('$$REALSEE_LIVE_EVENT$$');
16
+ const EVENT_SYMBOL = Symbol('$$REALSEE_LIVE_EVENT$$');
107
17
  function __generateEventIfNotExisted(instance) {
108
18
  if (!instance[EVENT_SYMBOL]) {
109
19
  instance[EVENT_SYMBOL] = {};
@@ -126,17 +36,15 @@ function __removeEventIfNotExisted(instance) {
126
36
  * }>()
127
37
  * ```
128
38
  */
129
- var Subscribe = /** @class */ (function () {
130
- function Subscribe() {
131
- }
39
+ class Subscribe {
132
40
  /**
133
41
  * 判断是否注册了事件
134
42
  * @param name 事件类型
135
43
  */
136
- Subscribe.prototype.hasListener = function (name) {
137
- var events = __generateEventIfNotExisted(this);
44
+ hasListener(name) {
45
+ const events = __generateEventIfNotExisted(this);
138
46
  return events && events[name] && events[name].length > 0;
139
- };
47
+ }
140
48
  /**
141
49
  * 注册事件
142
50
  * @param name 事件类型
@@ -146,14 +54,13 @@ var Subscribe = /** @class */ (function () {
146
54
  * @template K 预设的监听事件名称
147
55
  * @template C 回调函数函数上下文
148
56
  */
149
- Subscribe.prototype.on = function (name, callback, once) {
150
- var _this = this;
151
- var events = __generateEventIfNotExisted(this);
57
+ on(name, callback, once) {
58
+ const events = __generateEventIfNotExisted(this);
152
59
  if (!events[name])
153
60
  events[name] = [];
154
61
  events[name].push([callback, once || false]);
155
- return function () { return _this.off(name, callback); };
156
- };
62
+ return () => this.off(name, callback);
63
+ }
157
64
  /**
158
65
  * 注册事件(是否只执行一次)
159
66
  * @param name 事件类型
@@ -162,9 +69,9 @@ var Subscribe = /** @class */ (function () {
162
69
  * @template K 预设的监听事件名称
163
70
  * @template C 回调函数函数上下文
164
71
  */
165
- Subscribe.prototype.once = function (name, callback) {
72
+ once(name, callback) {
166
73
  return this.on(name, callback, true);
167
- };
74
+ }
168
75
  /**
169
76
  * 解除事件
170
77
  *
@@ -174,19 +81,19 @@ var Subscribe = /** @class */ (function () {
174
81
  * @param callback 事件回调函数
175
82
  * @template K 预设的监听事件名称
176
83
  */
177
- Subscribe.prototype.off = function (name, callback) {
84
+ off(name, callback) {
178
85
  if (name === undefined) {
179
86
  __removeEventIfNotExisted(this);
180
87
  return;
181
88
  }
182
- var events = __generateEventIfNotExisted(this);
89
+ const events = __generateEventIfNotExisted(this);
183
90
  if (!events[name])
184
91
  events[name] = [];
185
92
  if (callback === undefined) {
186
93
  events[name].length = 0;
187
94
  return;
188
95
  }
189
- var index = 0;
96
+ let index = 0;
190
97
  for (; index < events[name].length; index++) {
191
98
  if (events[name][index][0] === callback)
192
99
  break;
@@ -194,7 +101,7 @@ var Subscribe = /** @class */ (function () {
194
101
  if (index < events[name].length) {
195
102
  events[name].splice(index, 1);
196
103
  }
197
- };
104
+ }
198
105
  /**
199
106
  * 触发事件
200
107
  * @param name 事件类型
@@ -202,38 +109,52 @@ var Subscribe = /** @class */ (function () {
202
109
  * @returns canceled 是否被触发取消
203
110
  * @template K 预设的监听事件名称
204
111
  */
205
- Subscribe.prototype.emit = function (name) {
206
- var data = [];
207
- for (var _i = 1; _i < arguments.length; _i++) {
208
- data[_i - 1] = arguments[_i];
209
- }
210
- var canceled = false;
211
- var events = __generateEventIfNotExisted(this);
212
- var event = events[name] || [];
213
- for (var _a = 0, _b = event.slice(); _a < _b.length; _a++) {
214
- var one = _b[_a];
215
- var callback = one[0], _c = one[1], once = _c === void 0 ? false : _c;
216
- var result = callback.apply(void 0, data);
112
+ emit(name, ...data) {
113
+ let canceled = false;
114
+ const events = __generateEventIfNotExisted(this);
115
+ const event = events[name] || [];
116
+ for (let one of event.slice()) {
117
+ const [callback, once = false] = one;
118
+ const result = callback(...data);
217
119
  if (once)
218
120
  this.off(name, callback);
219
121
  if (result === false)
220
122
  canceled = true;
221
123
  }
222
124
  return canceled;
223
- };
224
- return Subscribe;
225
- }());
125
+ }
126
+ }
226
127
 
227
128
  /**
228
129
  * rtc 基础抽象类
229
130
  */
230
- var CoreRTC = /** @class */ (function (_super) {
231
- __extends(CoreRTC, _super);
232
- function CoreRTC() {
233
- return _super !== null && _super.apply(this, arguments) || this;
234
- }
235
- return CoreRTC;
236
- }(Subscribe));
131
+ class CoreRTC extends Subscribe {
132
+ }
133
+
134
+ /******************************************************************************
135
+ Copyright (c) Microsoft Corporation.
136
+
137
+ Permission to use, copy, modify, and/or distribute this software for any
138
+ purpose with or without fee is hereby granted.
139
+
140
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
141
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
142
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
143
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
144
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
145
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
146
+ PERFORMANCE OF THIS SOFTWARE.
147
+ ***************************************************************************** */
148
+
149
+ function __awaiter(thisArg, _arguments, P, generator) {
150
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
151
+ return new (P || (P = Promise))(function (resolve, reject) {
152
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
153
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
154
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
155
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
156
+ });
157
+ }
237
158
 
238
159
  /**
239
160
  * rtc 类型
@@ -273,231 +194,199 @@ function uuid() {
273
194
  S4()).toLowerCase();
274
195
  }
275
196
 
276
- var BrowserRTC = /** @class */ (function (_super) {
277
- __extends(BrowserRTC, _super);
278
- function BrowserRTC(options) {
279
- var _this = _super.call(this) || this;
280
- _this.type = exports.RTCType.RealseeBrowserRTC;
281
- _this.joined = false;
282
- _this.micro = false;
283
- _this.voiceId = '';
284
- _this._getVoiceSign = function () {
197
+ class BrowserRTC extends CoreRTC {
198
+ constructor(options) {
199
+ super();
200
+ this.type = exports.RTCType.RealseeBrowserRTC;
201
+ this.joined = false;
202
+ this.micro = false;
203
+ this.voiceId = '';
204
+ this._getVoiceSign = () => {
285
205
  throw new Error('方法 getVoiceSign 未实现');
286
206
  };
287
- _this.$dom = document.createElement('div');
288
- _this._trtc = {
207
+ this.$dom = document.createElement('div');
208
+ this._trtc = {
289
209
  client: null,
290
210
  stream: null,
291
211
  };
292
- _this.join = function (options) { return __awaiter(_this, void 0, void 0, function () {
293
- var createClientOptions, result;
294
- var _this = this;
212
+ this.join = (options) => __awaiter(this, void 0, void 0, function* () {
295
213
  var _a;
296
- return __generator(this, function (_b) {
297
- switch (_b.label) {
298
- case 0:
299
- this.emit('joinWillStart');
300
- return [4 /*yield*/, this._getVoiceSign({
301
- voiceId: options.voiceId,
302
- roomId: options.roomId,
303
- userId: options.userId,
304
- })];
305
- case 1:
306
- createClientOptions = _b.sent();
307
- // 1. 创建client
308
- this._trtc.client = TRTC__default["default"].createClient(__assign({ mode: 'rtc' }, createClientOptions));
309
- (_a = this._trtc.client) === null || _a === void 0 ? void 0 : _a.enableAudioVolumeEvaluation();
310
- // 2. 订阅事件
311
- this._registerRtcEvent();
312
- return [4 /*yield*/, new Promise(function (resolve) {
313
- var _a;
314
- (_a = _this._trtc.client) === null || _a === void 0 ? void 0 : _a.join({ roomId: Number(options.voiceId) }).then(function () { return resolve(true); }).catch(function () { return resolve(false); });
315
- })];
316
- case 2:
317
- result = _b.sent();
318
- this.joined = result;
319
- if (!result)
320
- return [2 /*return*/, false]; // 进房失败
321
- // 4. 创建本地流
322
- this._trtc.stream = TRTC__default["default"].createStream({
323
- userId: createClientOptions.userId,
324
- audio: true,
325
- video: false,
326
- });
327
- return [4 /*yield*/, new Promise(function (resolve) {
328
- var _a;
329
- (_a = _this._trtc.stream) === null || _a === void 0 ? void 0 : _a.initialize().then(function () { return resolve(true); }).catch(function () { return resolve(false); });
330
- })];
331
- case 3:
332
- // 5. 初始化本地流
333
- result = _b.sent();
334
- return [4 /*yield*/, new Promise(function (resolve) {
335
- var _a;
336
- (_a = _this._trtc.client) === null || _a === void 0 ? void 0 : _a.publish(_this._trtc.stream).then(function () { return resolve(true); }).catch(function () { return resolve(false); });
337
- })];
338
- case 4:
339
- // 6. 发布本地流
340
- result = _b.sent();
341
- this.joined = result;
342
- if (this.joined)
343
- this.emit('joined');
344
- return [2 /*return*/, result];
345
- }
214
+ this.emit('joinWillStart');
215
+ const createClientOptions = yield this._getVoiceSign({
216
+ voiceId: options.voiceId,
217
+ roomId: options.roomId,
218
+ userId: options.userId,
219
+ });
220
+ // 1. 创建client
221
+ this._trtc.client = TRTC__default["default"].createClient(Object.assign({ mode: 'rtc' }, createClientOptions));
222
+ (_a = this._trtc.client) === null || _a === void 0 ? void 0 : _a.enableAudioVolumeEvaluation();
223
+ // 2. 订阅事件
224
+ this._registerRtcEvent();
225
+ // 3. 加入语音房间
226
+ let result = yield new Promise((resolve) => {
227
+ var _a;
228
+ (_a = this._trtc.client) === null || _a === void 0 ? void 0 : _a.join({ roomId: Number(options.voiceId) }).then(() => resolve(true)).catch(() => resolve(false));
346
229
  });
347
- }); };
348
- _this._handleStreamAdded = function (event) {
230
+ this.joined = result;
231
+ if (!result)
232
+ return false; // 进房失败
233
+ // 4. 创建本地流
234
+ this._trtc.stream = TRTC__default["default"].createStream({
235
+ userId: createClientOptions.userId,
236
+ audio: true,
237
+ video: false,
238
+ });
239
+ // 5. 初始化本地流
240
+ result = yield new Promise((resolve) => {
241
+ var _a;
242
+ (_a = this._trtc.stream) === null || _a === void 0 ? void 0 : _a.initialize().then(() => resolve(true)).catch(() => resolve(false));
243
+ });
244
+ // 6. 发布本地流
245
+ result = yield new Promise((resolve) => {
246
+ var _a;
247
+ (_a = this._trtc.client) === null || _a === void 0 ? void 0 : _a.publish(this._trtc.stream).then(() => resolve(true)).catch(() => resolve(false));
248
+ });
249
+ this.joined = result;
250
+ if (this.joined)
251
+ this.emit('joined');
252
+ return result;
253
+ });
254
+ this._handleStreamAdded = (event) => {
349
255
  var _a;
350
- var remoteStream = event.stream;
256
+ const remoteStream = event.stream;
351
257
  console.log('远端流增加: ' + remoteStream.getId());
352
258
  //订阅远端流
353
- (_a = _this._trtc.client) === null || _a === void 0 ? void 0 : _a.subscribe(remoteStream);
259
+ (_a = this._trtc.client) === null || _a === void 0 ? void 0 : _a.subscribe(remoteStream);
354
260
  };
355
- _this._handleStreamSubscribed = function (event) {
356
- var remoteStream = event.stream;
261
+ this._handleStreamSubscribed = (event) => {
262
+ const remoteStream = event.stream;
357
263
  console.log('远端流订阅成功:' + remoteStream.getId());
358
- var playId = remoteStream.getId();
359
- var domId = "rs-rtc-remote_stream-".concat(playId);
360
- var dom = document.createElement('div');
264
+ const playId = remoteStream.getId();
265
+ const domId = `rs-rtc-remote_stream-${playId}`;
266
+ const dom = document.createElement('div');
361
267
  dom.id = domId;
362
- _this.$dom.appendChild(dom);
268
+ this.$dom.appendChild(dom);
363
269
  // 播放远端流
364
270
  remoteStream.play(domId);
365
271
  };
366
- _this._getVoiceSign = options.getVoiceSign;
367
- _this._initParentDom();
368
- return _this;
272
+ this._getVoiceSign = options.getVoiceSign;
273
+ this._initParentDom();
369
274
  }
370
- BrowserRTC.prototype._initParentDom = function () {
371
- this.$dom.id = "rs-rtc-".concat(uuid());
275
+ _initParentDom() {
276
+ this.$dom.id = `rs-rtc-${uuid()}`;
372
277
  this.$dom.style.display = 'none';
373
278
  document.body.appendChild(this.$dom);
374
- };
375
- BrowserRTC.prototype.quit = function () {
376
- var _this = this;
377
- return new Promise(function (resolve) { return __awaiter(_this, void 0, void 0, function () {
378
- var _this = this;
279
+ }
280
+ quit() {
281
+ return new Promise((resolve) => __awaiter(this, void 0, void 0, function* () {
379
282
  var _a, _b;
380
- return __generator(this, function (_c) {
381
- switch (_c.label) {
382
- case 0:
383
- this.joined = false;
384
- if (!this._trtc.stream) return [3 /*break*/, 2];
385
- return [4 /*yield*/, ((_a = this._trtc.client) === null || _a === void 0 ? void 0 : _a.unpublish(this._trtc.stream))];
386
- case 1:
387
- _c.sent();
388
- this._trtc.stream.stop();
389
- this._trtc.stream.close();
390
- this._trtc.stream = null;
391
- _c.label = 2;
392
- case 2:
393
- (_b = this._trtc.client) === null || _b === void 0 ? void 0 : _b.leave().then(function () { return (_this._trtc.client = null); }).then(function () { return resolve(true); }).catch(function () { return resolve(false); });
394
- return [2 /*return*/];
395
- }
396
- });
397
- }); });
398
- };
399
- BrowserRTC.prototype.detectMicro = function () {
400
- return new Promise(function (resolve) {
401
- var rule = { audio: true, video: false };
283
+ this.joined = false;
284
+ if (this._trtc.stream) {
285
+ yield ((_a = this._trtc.client) === null || _a === void 0 ? void 0 : _a.unpublish(this._trtc.stream));
286
+ this._trtc.stream.stop();
287
+ this._trtc.stream.close();
288
+ this._trtc.stream = null;
289
+ }
290
+ (_b = this._trtc.client) === null || _b === void 0 ? void 0 : _b.leave().then(() => (this._trtc.client = null)).then(() => resolve(true)).catch(() => resolve(false));
291
+ }));
292
+ }
293
+ detectMicro() {
294
+ return new Promise((resolve) => {
295
+ const rule = { audio: true, video: false };
402
296
  try {
403
297
  navigator.mediaDevices
404
298
  .getUserMedia(rule)
405
- .then(function () { return resolve(true); })
406
- .catch(function () { return resolve(false); });
299
+ .then(() => resolve(true))
300
+ .catch(() => resolve(false));
407
301
  }
408
302
  catch (e) {
409
303
  console.error(e);
410
304
  resolve(false);
411
305
  }
412
306
  });
413
- };
414
- BrowserRTC.prototype.toggleMicro = function (flag) {
307
+ }
308
+ toggleMicro(flag) {
415
309
  var _a, _b, _c, _d;
416
310
  return Promise.resolve((flag
417
311
  ? (_b = (_a = this._trtc) === null || _a === void 0 ? void 0 : _a.stream) === null || _b === void 0 ? void 0 : _b.unmuteAudio()
418
312
  : (_d = (_c = this._trtc) === null || _c === void 0 ? void 0 : _c.stream) === null || _d === void 0 ? void 0 : _d.muteAudio()) || false);
419
- };
420
- BrowserRTC.prototype.shock = function () {
313
+ }
314
+ shock() {
421
315
  throw new Error('Method not implemented.');
422
- };
423
- BrowserRTC.prototype._registerRtcEvent = function () {
424
- var _this = this;
316
+ }
317
+ _registerRtcEvent() {
425
318
  var _a, _b, _c, _d;
426
319
  (_a = this._trtc.client) === null || _a === void 0 ? void 0 : _a.on('stream-added', this._handleStreamAdded);
427
320
  (_b = this._trtc.client) === null || _b === void 0 ? void 0 : _b.on('stream-subscribed', this._handleStreamSubscribed);
428
- (_c = this._trtc.client) === null || _c === void 0 ? void 0 : _c.on('audio-volume', function (event) {
429
- return _this.emit('userVolumes', [
430
- { userId: event.userId, audioVolume: event.audioVolume },
431
- ]);
432
- });
433
- (_d = this._trtc.client) === null || _d === void 0 ? void 0 : _d.on('error', function (event) { return _this.emit('error', event); });
434
- };
435
- return BrowserRTC;
436
- }(CoreRTC));
321
+ (_c = this._trtc.client) === null || _c === void 0 ? void 0 : _c.on('audio-volume', (event) => this.emit('userVolumes', [
322
+ { userId: event.userId, audioVolume: event.audioVolume },
323
+ ]));
324
+ (_d = this._trtc.client) === null || _d === void 0 ? void 0 : _d.on('error', (event) => this.emit('error', event));
325
+ }
326
+ }
437
327
 
438
328
  /**
439
329
  * amazon-chime-sdk-js 适配的rtc实现
440
330
  */
441
- var BrowserRTC4Chime = /** @class */ (function (_super) {
442
- __extends(BrowserRTC4Chime, _super);
443
- function BrowserRTC4Chime(options) {
444
- var _this = _super.call(this) || this;
445
- _this.type = exports.RTCType.RealseeBrowserChimeRTC;
446
- _this.joined = false;
447
- _this.micro = false;
448
- _this.voiceId = '';
449
- _this.userId = '';
450
- _this.deviceChangeObserver = {};
451
- _this.audioVideoObserver = {};
452
- _this._getVoiceSign = function () {
331
+ class BrowserRTC4Chime extends CoreRTC {
332
+ constructor(options) {
333
+ super();
334
+ this.type = exports.RTCType.RealseeBrowserChimeRTC;
335
+ this.joined = false;
336
+ this.micro = false;
337
+ this.voiceId = '';
338
+ this.userId = '';
339
+ this.deviceChangeObserver = {};
340
+ this.audioVideoObserver = {};
341
+ this._getVoiceSign = () => {
453
342
  throw new Error('方法 getVoiceSign 未实现');
454
343
  };
455
- _this.$dom = document.createElement('div');
456
- _this.$audio = document.createElement('audio');
344
+ this.$dom = document.createElement('div');
345
+ this.$audio = document.createElement('audio');
457
346
  /**
458
347
  * 对audio标签初始化
459
348
  */
460
- _this._initDom = function () {
461
- _this.$audio.id = "rs-rtc-".concat(uuid());
462
- _this.$dom.id = "rs-rtc-".concat(uuid());
463
- _this.$dom.appendChild(_this.$audio);
464
- document.body.appendChild(_this.$dom);
349
+ this._initDom = () => {
350
+ this.$audio.id = `rs-rtc-${uuid()}`;
351
+ this.$dom.id = `rs-rtc-${uuid()}`;
352
+ this.$dom.appendChild(this.$audio);
353
+ document.body.appendChild(this.$dom);
465
354
  };
466
355
  /**
467
356
  * 初始化事件监听器
468
357
  */
469
- _this.initObservers = function () {
358
+ this.initObservers = () => {
470
359
  // 输入输出设备变化的监听器
471
- _this.deviceChangeObserver = {
472
- audioInputsChanged: function (freshAudioInputDeviceList) {
360
+ this.deviceChangeObserver = {
361
+ audioInputsChanged: (freshAudioInputDeviceList) => {
473
362
  // An array of MediaDeviceInfo objects
474
- freshAudioInputDeviceList === null || freshAudioInputDeviceList === void 0 ? void 0 : freshAudioInputDeviceList.forEach(function (mediaDeviceInfo) {
475
- _this.logger.info("Device ID: ".concat(mediaDeviceInfo.deviceId, " Microphone: ").concat(mediaDeviceInfo.label));
363
+ freshAudioInputDeviceList === null || freshAudioInputDeviceList === void 0 ? void 0 : freshAudioInputDeviceList.forEach((mediaDeviceInfo) => {
364
+ this.logger.info(`Device ID: ${mediaDeviceInfo.deviceId} Microphone: ${mediaDeviceInfo.label}`);
476
365
  });
477
366
  },
478
- audioOutputsChanged: function (freshAudioOutputDeviceList) {
479
- _this.logger.info("Audio outputs updated: ".concat(freshAudioOutputDeviceList));
367
+ audioOutputsChanged: (freshAudioOutputDeviceList) => {
368
+ this.logger.info(`Audio outputs updated: ${freshAudioOutputDeviceList}`);
480
369
  },
481
- videoInputsChanged: function (freshVideoInputDeviceList) {
482
- _this.logger.info("Video inputs updated: ".concat(freshVideoInputDeviceList));
370
+ videoInputsChanged: (freshVideoInputDeviceList) => {
371
+ this.logger.info(`Video inputs updated: ${freshVideoInputDeviceList}`);
483
372
  },
484
- audioInputMuteStateChanged: function (device, muted) {
485
- _this.logger.info("Device ".concat(device.toString(), " ").concat(muted ? 'is muted in hardware' : 'is not muted'));
373
+ audioInputMuteStateChanged: (device, muted) => {
374
+ this.logger.info(`Device ${device.toString()} ${muted ? 'is muted in hardware' : 'is not muted'}`);
486
375
  },
487
376
  };
488
377
  // 流变化监听器
489
- _this.audioVideoObserver = {
490
- audioVideoDidStart: function () {
491
- _this.logger.info('Started');
378
+ this.audioVideoObserver = {
379
+ audioVideoDidStart: () => {
380
+ this.logger.info('Started');
492
381
  },
493
- audioVideoDidStop: function (sessionStatus) {
382
+ audioVideoDidStop: (sessionStatus) => {
494
383
  // See the "Stopping a session" section for details.
495
- _this.logger.info("Stopped with a session status code: ".concat(sessionStatus.statusCode()));
384
+ this.logger.info(`Stopped with a session status code: ${sessionStatus.statusCode()}`);
496
385
  },
497
- audioVideoDidStartConnecting: function (reconnecting) {
386
+ audioVideoDidStartConnecting: (reconnecting) => {
498
387
  if (reconnecting) {
499
388
  // e.g. the WiFi connection is dropped.
500
- _this.logger.info('Attempting to reconnect');
389
+ this.logger.info('Attempting to reconnect');
501
390
  }
502
391
  },
503
392
  };
@@ -505,15 +394,15 @@ var BrowserRTC4Chime = /** @class */ (function (_super) {
505
394
  /**
506
395
  * 注册rtc事件
507
396
  */
508
- _this._registerRtcEvent = function () {
397
+ this._registerRtcEvent = () => {
509
398
  var _a, _b, _c, _d, _e, _f;
510
- var presentAttendeeId = ((_c = (_b = (_a = _this.meetingSession) === null || _a === void 0 ? void 0 : _a.configuration) === null || _b === void 0 ? void 0 : _b.credentials) === null || _c === void 0 ? void 0 : _c.attendeeId) || '';
399
+ const presentAttendeeId = ((_c = (_b = (_a = this.meetingSession) === null || _a === void 0 ? void 0 : _a.configuration) === null || _b === void 0 ? void 0 : _b.credentials) === null || _c === void 0 ? void 0 : _c.attendeeId) || '';
511
400
  if (presentAttendeeId) {
512
401
  // 处理音量变化
513
- var roster_1 = new Map();
514
- var getUserVolumes_1 = function () {
515
- var result = [];
516
- roster_1.forEach(function (v, k) {
402
+ const roster = new Map();
403
+ const getUserVolumes = () => {
404
+ const result = [];
405
+ roster.forEach((v, k) => {
517
406
  result.push({
518
407
  userId: v.userId,
519
408
  volume: v.muted || v.signalStrength === 0 || !Boolean(v.volume)
@@ -523,208 +412,180 @@ var BrowserRTC4Chime = /** @class */ (function (_super) {
523
412
  });
524
413
  return result;
525
414
  };
526
- (_d = _this.meetingSession) === null || _d === void 0 ? void 0 : _d.audioVideo.realtimeSubscribeToAttendeeIdPresence(function (presentAttendeeId, present, externalUserId) {
415
+ (_d = this.meetingSession) === null || _d === void 0 ? void 0 : _d.audioVideo.realtimeSubscribeToAttendeeIdPresence((presentAttendeeId, present, externalUserId) => {
527
416
  var _a;
528
417
  if (!present) {
529
- roster_1.delete(presentAttendeeId);
530
- _this.emit('userVolumes', getUserVolumes_1());
418
+ roster.delete(presentAttendeeId);
419
+ this.emit('userVolumes', getUserVolumes());
531
420
  return;
532
421
  }
533
- (_a = _this.meetingSession) === null || _a === void 0 ? void 0 : _a.audioVideo.realtimeSubscribeToVolumeIndicator(presentAttendeeId, function (attendeeId, volume, muted, signalStrength) {
534
- var baseAttendeeId = new amazonChimeSdkJs.DefaultModality(attendeeId).base();
422
+ (_a = this.meetingSession) === null || _a === void 0 ? void 0 : _a.audioVideo.realtimeSubscribeToVolumeIndicator(presentAttendeeId, (attendeeId, volume, muted, signalStrength) => {
423
+ const baseAttendeeId = new amazonChimeSdkJs.DefaultModality(attendeeId).base();
535
424
  if (baseAttendeeId !== attendeeId) {
536
425
  // Optional: Do not include the content attendee (attendee-id#content) in the roster.
537
426
  // See the "Screen and content share" section for details.
538
427
  return;
539
428
  }
540
- roster_1.set(attendeeId, {
429
+ roster.set(attendeeId, {
541
430
  userId: externalUserId || attendeeId,
542
- volume: volume,
543
- muted: muted,
544
- signalStrength: signalStrength,
431
+ volume,
432
+ muted,
433
+ signalStrength,
545
434
  });
546
- _this.emit('userVolumes', getUserVolumes_1());
435
+ this.emit('userVolumes', getUserVolumes());
547
436
  });
548
437
  });
549
438
  // 弱网
550
- (_e = _this.meetingSession) === null || _e === void 0 ? void 0 : _e.audioVideo.realtimeSubscribeToVolumeIndicator(presentAttendeeId, function (attendeeId, volume, muted, signalStrength) {
551
- var baseAttendeeId = new amazonChimeSdkJs.DefaultModality(attendeeId).base();
439
+ (_e = this.meetingSession) === null || _e === void 0 ? void 0 : _e.audioVideo.realtimeSubscribeToVolumeIndicator(presentAttendeeId, (attendeeId, volume, muted, signalStrength) => {
440
+ const baseAttendeeId = new amazonChimeSdkJs.DefaultModality(attendeeId).base();
552
441
  if (baseAttendeeId === attendeeId) {
553
442
  if (signalStrength !== null && signalStrength !== 1) {
554
- _this.emit('weakNetwork');
443
+ this.emit('weakNetwork');
555
444
  }
556
445
  }
557
446
  });
558
447
  // 报错
559
- (_f = _this.meetingSession) === null || _f === void 0 ? void 0 : _f.audioVideo.realtimeSubscribeToFatalError(function (error) { return _this.emit('error', error); });
448
+ (_f = this.meetingSession) === null || _f === void 0 ? void 0 : _f.audioVideo.realtimeSubscribeToFatalError((error) => this.emit('error', error));
560
449
  }
561
450
  };
562
451
  // 挂载签名钩子
563
- _this._getVoiceSign = options.getVoiceSign;
564
- _this._initDom();
565
- _this.logger = new amazonChimeSdkJs.ConsoleLogger('WebRTCLogger', options.logLevel || amazonChimeSdkJs.LogLevel.OFF);
566
- _this.deviceController = new amazonChimeSdkJs.DefaultDeviceController(_this.logger);
567
- _this.initObservers();
568
- return _this;
452
+ this._getVoiceSign = options.getVoiceSign;
453
+ this._initDom();
454
+ this.logger = new amazonChimeSdkJs.ConsoleLogger('WebRTCLogger', options.logLevel || amazonChimeSdkJs.LogLevel.OFF);
455
+ this.deviceController = new amazonChimeSdkJs.DefaultDeviceController(this.logger);
456
+ this.initObservers();
569
457
  }
570
458
  /**
571
459
  * 加入语音会议
572
460
  * @param options
573
461
  * @returns
574
462
  */
575
- BrowserRTC4Chime.prototype.join = function (options) {
576
- return __awaiter(this, void 0, void 0, function () {
577
- var _this = this;
578
- return __generator(this, function (_a) {
579
- return [2 /*return*/, new Promise(function (success, fail) { return __awaiter(_this, void 0, void 0, function () {
580
- var _a, userId, userSig, _b, attendence, vendor_wrapper, configuration, observer, audioInputDevices, defaultAudioInput, otherAudioInput, e_1;
581
- var _this = this;
582
- var _c;
583
- return __generator(this, function (_d) {
584
- switch (_d.label) {
585
- case 0:
586
- this.emit('joinWillStart');
587
- _d.label = 1;
588
- case 1:
589
- _d.trys.push([1, 6, , 7]);
590
- return [4 /*yield*/, this._getVoiceSign(__assign(__assign({}, options), { roomId: options.roomId || 0 }))];
591
- case 2:
592
- _a = _d.sent(), userId = _a.userId, userSig = _a.userSig;
593
- this.userId = userId;
594
- _b = JSON.parse(decodeURIComponent(userSig)), attendence = _b.attendence, vendor_wrapper = _b.vendor_wrapper;
595
- configuration = new amazonChimeSdkJs.MeetingSessionConfiguration({
596
- Meeting: vendor_wrapper,
597
- }, {
598
- Attendee: {
599
- ExternalUserId: attendence.external_user_id,
600
- AttendeeId: attendence.attendee_id,
601
- JoinToken: attendence.join_token,
602
- },
603
- });
604
- // 初始化会议会话
605
- this.meetingSession = new amazonChimeSdkJs.DefaultMeetingSession(configuration, this.logger, this.deviceController);
606
- // 注册事件
607
- this._registerRtcEvent();
608
- // 绑定监听器
609
- this.meetingSession.audioVideo.addDeviceChangeObserver(this.deviceChangeObserver);
610
- this.meetingSession.audioVideo.addObserver(this.audioVideoObserver);
611
- // 绑定播放器
612
- this.meetingSession.audioVideo.bindAudioElement(this.$audio);
613
- observer = {
614
- audioVideoDidStart: function () {
615
- var _a;
616
- (_a = _this.meetingSession) === null || _a === void 0 ? void 0 : _a.audioVideo.realtimeMuteLocalAudio();
617
- _this.joined = true;
618
- _this.emit('joined');
619
- success(true);
620
- },
621
- audioVideoDidStop: function () {
622
- _this.joined = false;
623
- success(false);
624
- },
625
- };
626
- this.meetingSession.audioVideo.addObserver(observer);
627
- return [4 /*yield*/, this.deviceController.listAudioInputDevices(true)];
628
- case 3:
629
- audioInputDevices = _d.sent();
630
- defaultAudioInput = audioInputDevices.find(function (device) { return device.deviceId === 'default'; });
631
- otherAudioInput = audioInputDevices.find(function (device) { return device.deviceId !== ''; });
632
- this.audioInput = defaultAudioInput || otherAudioInput;
633
- return [4 /*yield*/, this.meetingSession.audioVideo.chooseVideoInputDevice(null)];
634
- case 4:
635
- _d.sent();
636
- return [4 /*yield*/, this.meetingSession.audioVideo.chooseAudioInputDevice(((_c = this.audioInput) === null || _c === void 0 ? void 0 : _c.deviceId) || 'default')];
637
- case 5:
638
- _d.sent();
639
- this.meetingSession.audioVideo.start();
640
- return [3 /*break*/, 7];
641
- case 6:
642
- e_1 = _d.sent();
643
- this.emit('error', e_1);
644
- this.logger.error(e_1.message);
645
- success(false);
646
- return [3 /*break*/, 7];
647
- case 7: return [2 /*return*/];
648
- }
649
- });
650
- }); })];
651
- });
463
+ join(options) {
464
+ return __awaiter(this, void 0, void 0, function* () {
465
+ return new Promise((success, fail) => __awaiter(this, void 0, void 0, function* () {
466
+ var _a;
467
+ this.emit('joinWillStart');
468
+ try {
469
+ // 取签名
470
+ const { sdkAppId, userId, roomId, userSig } = yield this._getVoiceSign(Object.assign(Object.assign({}, options), { roomId: options.roomId || 0 }));
471
+ this.userId = userId;
472
+ const { attendence, vendor_wrapper, } = JSON.parse(decodeURIComponent(userSig));
473
+ // 初始化配置
474
+ const configuration = new amazonChimeSdkJs.MeetingSessionConfiguration({
475
+ Meeting: vendor_wrapper,
476
+ }, {
477
+ Attendee: {
478
+ ExternalUserId: attendence.external_user_id,
479
+ AttendeeId: attendence.attendee_id,
480
+ JoinToken: attendence.join_token,
481
+ },
482
+ });
483
+ // 初始化会议会话
484
+ this.meetingSession = new amazonChimeSdkJs.DefaultMeetingSession(configuration, this.logger, this.deviceController);
485
+ // 注册事件
486
+ this._registerRtcEvent();
487
+ // 绑定监听器
488
+ this.meetingSession.audioVideo.addDeviceChangeObserver(this.deviceChangeObserver);
489
+ this.meetingSession.audioVideo.addObserver(this.audioVideoObserver);
490
+ // 绑定播放器
491
+ this.meetingSession.audioVideo.bindAudioElement(this.$audio);
492
+ const observer = {
493
+ audioVideoDidStart: () => {
494
+ var _a;
495
+ (_a = this.meetingSession) === null || _a === void 0 ? void 0 : _a.audioVideo.realtimeMuteLocalAudio();
496
+ this.joined = true;
497
+ this.emit('joined');
498
+ success(true);
499
+ },
500
+ audioVideoDidStop: () => {
501
+ this.joined = false;
502
+ success(false);
503
+ },
504
+ };
505
+ this.meetingSession.audioVideo.addObserver(observer);
506
+ // 选择语音输入设备
507
+ const audioInputDevices = yield this.deviceController.listAudioInputDevices(true);
508
+ const defaultAudioInput = audioInputDevices.find((device) => device.deviceId === 'default');
509
+ const otherAudioInput = audioInputDevices.find((device) => device.deviceId !== '');
510
+ this.audioInput = defaultAudioInput || otherAudioInput;
511
+ yield this.meetingSession.audioVideo.chooseVideoInputDevice(null);
512
+ yield this.meetingSession.audioVideo.chooseAudioInputDevice(((_a = this.audioInput) === null || _a === void 0 ? void 0 : _a.deviceId) || 'default');
513
+ this.meetingSession.audioVideo.start();
514
+ }
515
+ catch (e) {
516
+ this.emit('error', e);
517
+ this.logger.error(e.message);
518
+ success(false);
519
+ }
520
+ }));
652
521
  });
653
- };
654
- BrowserRTC4Chime.prototype.quit = function () {
655
- var _this = this;
522
+ }
523
+ quit() {
656
524
  if (!this.joined)
657
525
  return Promise.resolve(true);
658
- return new Promise(function (success, fail) {
526
+ return new Promise((success, fail) => {
659
527
  var _a, _b;
660
- _this.joined = false;
661
- var observer = {
662
- audioVideoDidStop: function (sessionStatus) {
663
- var sessionStatusCode = sessionStatus.statusCode();
528
+ this.joined = false;
529
+ const observer = {
530
+ audioVideoDidStop: (sessionStatus) => {
531
+ const sessionStatusCode = sessionStatus.statusCode();
664
532
  if (sessionStatusCode === amazonChimeSdkJs.MeetingSessionStatusCode.Left) {
665
533
  /*
666
534
  - You called meetingSession.audioVideo.stop().
667
535
  - When closing a browser window or page, Chime SDK attempts to leave the session.
668
536
  */
669
- _this.logger.info('You left the session');
537
+ this.logger.info('You left the session');
670
538
  success(true);
671
539
  }
672
540
  else {
673
- _this.logger.info("Stopped with a session status code: ".concat(sessionStatusCode));
541
+ this.logger.info(`Stopped with a session status code: ${sessionStatusCode}`);
674
542
  success(true);
675
543
  }
676
544
  },
677
545
  };
678
- (_a = _this.meetingSession) === null || _a === void 0 ? void 0 : _a.audioVideo.addObserver(observer);
679
- (_b = _this.meetingSession) === null || _b === void 0 ? void 0 : _b.audioVideo.stop();
680
- });
681
- };
682
- BrowserRTC4Chime.prototype.detectMicro = function () {
683
- return __awaiter(this, void 0, void 0, function () {
684
- var _this = this;
685
- return __generator(this, function (_a) {
686
- return [2 /*return*/, new Promise(function (resolve) {
687
- var rule = { audio: true, video: false };
688
- try {
689
- navigator.mediaDevices
690
- .getUserMedia(rule)
691
- .then(function () { return resolve(true); })
692
- .catch(function () { return resolve(false); });
693
- }
694
- catch (e) {
695
- _this.logger.error(e.message);
696
- resolve(false);
697
- }
698
- })];
699
- });
546
+ (_a = this.meetingSession) === null || _a === void 0 ? void 0 : _a.audioVideo.addObserver(observer);
547
+ (_b = this.meetingSession) === null || _b === void 0 ? void 0 : _b.audioVideo.stop();
700
548
  });
701
- };
702
- BrowserRTC4Chime.prototype.toggleMicro = function (flag) {
703
- var _a, _b, _c;
704
- return __awaiter(this, void 0, void 0, function () {
705
- var muted;
706
- return __generator(this, function (_d) {
707
- if (flag) {
708
- (_a = this.meetingSession) === null || _a === void 0 ? void 0 : _a.audioVideo.realtimeUnmuteLocalAudio();
709
- }
710
- else {
711
- (_b = this.meetingSession) === null || _b === void 0 ? void 0 : _b.audioVideo.realtimeMuteLocalAudio();
712
- }
713
- muted = (_c = this.meetingSession) === null || _c === void 0 ? void 0 : _c.audioVideo.realtimeIsLocalAudioMuted();
714
- if (muted !== undefined) {
715
- return [2 /*return*/, flag !== muted];
549
+ }
550
+ detectMicro() {
551
+ return __awaiter(this, void 0, void 0, function* () {
552
+ return new Promise((resolve) => {
553
+ const rule = { audio: true, video: false };
554
+ try {
555
+ navigator.mediaDevices
556
+ .getUserMedia(rule)
557
+ .then(() => resolve(true))
558
+ .catch(() => resolve(false));
716
559
  }
717
- else {
718
- return [2 /*return*/, false];
560
+ catch (e) {
561
+ this.logger.error(e.message);
562
+ resolve(false);
719
563
  }
720
564
  });
721
565
  });
722
- };
723
- BrowserRTC4Chime.prototype.shock = function () {
566
+ }
567
+ toggleMicro(flag) {
568
+ var _a, _b, _c;
569
+ return __awaiter(this, void 0, void 0, function* () {
570
+ if (flag) {
571
+ (_a = this.meetingSession) === null || _a === void 0 ? void 0 : _a.audioVideo.realtimeUnmuteLocalAudio();
572
+ }
573
+ else {
574
+ (_b = this.meetingSession) === null || _b === void 0 ? void 0 : _b.audioVideo.realtimeMuteLocalAudio();
575
+ }
576
+ const muted = (_c = this.meetingSession) === null || _c === void 0 ? void 0 : _c.audioVideo.realtimeIsLocalAudioMuted();
577
+ if (muted !== undefined) {
578
+ return flag !== muted;
579
+ }
580
+ else {
581
+ return false;
582
+ }
583
+ });
584
+ }
585
+ shock() {
724
586
  throw new Error('Method not implemented.');
725
- };
726
- return BrowserRTC4Chime;
727
- }(CoreRTC));
587
+ }
588
+ }
728
589
 
729
590
  /**
730
591
  * rtc加入返回值code枚举
@@ -749,122 +610,98 @@ exports.RTCJoinedInfoCodeEnum = void 0;
749
610
  RTCJoinedInfoCodeEnum[RTCJoinedInfoCodeEnum["NoMicroPermission"] = 3] = "NoMicroPermission";
750
611
  })(exports.RTCJoinedInfoCodeEnum || (exports.RTCJoinedInfoCodeEnum = {}));
751
612
 
752
- var VRWebViewRTC = /** @class */ (function (_super) {
753
- __extends(VRWebViewRTC, _super);
754
- function VRWebViewRTC(_a) {
755
- var jsBridge = _a.jsBridge, getVoiceSign = _a.getVoiceSign;
756
- var _this = _super.call(this) || this;
757
- _this.type = exports.RTCType.RealseeVRWebViewRTC;
758
- _this.joined = false;
759
- _this.micro = false;
760
- _this.voiceId = '';
761
- _this.options = { jsBridge: jsBridge, getVoiceSign: getVoiceSign };
762
- _this.jsBridge.callAndListen('live/userVolumes', function (userVolumes) {
763
- _this.emit('userVolumes', userVolumes);
764
- });
765
- _this.jsBridge.callAndListen('live/weakNetwork', function (weakNetwork) {
613
+ class VRWebViewRTC extends CoreRTC {
614
+ constructor({ jsBridge, getVoiceSign }) {
615
+ super();
616
+ this.type = exports.RTCType.RealseeVRWebViewRTC;
617
+ this.joined = false;
618
+ this.micro = false;
619
+ this.voiceId = '';
620
+ this.options = { jsBridge, getVoiceSign };
621
+ // TO-DO: 在微信小程序下有个音量上报的BUG会导致消息体过大从而jsbridge异常断开
622
+ if (this.jsBridge.webViewType !== 'WxMiniProgramWebView') {
623
+ this.jsBridge.callAndListen('live/userVolumes', (userVolumes) => {
624
+ this.emit('userVolumes', userVolumes);
625
+ });
626
+ }
627
+ this.jsBridge.callAndListen('live/weakNetwork', (weakNetwork) => {
766
628
  if (weakNetwork)
767
- _this.emit('weakNetwork');
629
+ this.emit('weakNetwork');
768
630
  });
769
- return _this;
770
- }
771
- Object.defineProperty(VRWebViewRTC.prototype, "jsBridge", {
772
- get: function () {
773
- return this.options.jsBridge;
774
- },
775
- enumerable: false,
776
- configurable: true
777
- });
778
- VRWebViewRTC.prototype.join = function (options) {
779
- return __awaiter(this, void 0, void 0, function () {
780
- var _a, sdkAppId, userId, userSig, _b, res, error;
781
- return __generator(this, function (_c) {
782
- switch (_c.label) {
783
- case 0:
784
- this.emit('joinWillStart');
785
- return [4 /*yield*/, this.options.getVoiceSign(options)];
786
- case 1:
787
- _a = _c.sent(), sdkAppId = _a.sdkAppId, userId = _a.userId, userSig = _a.userSig;
788
- this.type = options.type;
789
- return [4 /*yield*/, this.jsBridge.callAndBackfeed("live/join?sdkAppID=".concat(sdkAppId, "&userID=").concat(userId, "&roomID=").concat(Number(options.voiceId), "&userSig=").concat(userSig))];
790
- case 2:
791
- _b = _c.sent(), res = _b[0], error = _b[1];
792
- if (!res) {
793
- this.emit('error', error ? error : new Error('加入房间失败:未知异常。'));
794
- this.joined = false;
795
- }
796
- else {
797
- if (res.code === exports.RTCJoinedInfoCodeEnum.Success) {
798
- this.emit('joined');
799
- this.joined = true;
800
- }
801
- else {
802
- this.emit('error', res);
803
- this.joined = false;
804
- }
805
- }
806
- return [2 /*return*/, this.joined];
631
+ }
632
+ get jsBridge() {
633
+ return this.options.jsBridge;
634
+ }
635
+ join(options) {
636
+ return __awaiter(this, void 0, void 0, function* () {
637
+ try {
638
+ this.emit('joinWillStart');
639
+ const { sdkAppId, userId, userSig } = yield this.options.getVoiceSign(options);
640
+ if (!(Boolean(sdkAppId) && Boolean(userId) && Boolean(userSig))) {
641
+ this.emit('error', new Error('加入房间失败:rtc 签名请求异常'));
642
+ this.joined = false;
643
+ return this.joined;
807
644
  }
808
- });
809
- });
810
- };
811
- VRWebViewRTC.prototype.quit = function () {
812
- return __awaiter(this, void 0, void 0, function () {
813
- var _a, res, error;
814
- return __generator(this, function (_b) {
815
- switch (_b.label) {
816
- case 0: return [4 /*yield*/, this.jsBridge.callAndBackfeed('live/quit')];
817
- case 1:
818
- _a = _b.sent(), res = _a[0], error = _a[1];
819
- if (res === null) {
820
- this.emit('error', error ? error : new Error('退出房间失败:未知异常。'));
821
- }
645
+ this.type = options.type;
646
+ const [res, error] = yield this.jsBridge.callAndBackfeed(`live/join?sdkAppID=${sdkAppId}&userID=${userId}&roomID=${Number(options.voiceId)}&userSig=${userSig}`);
647
+ if (!res) {
648
+ this.emit('error', error ? error : new Error('加入房间失败:未知异常。'));
649
+ this.joined = false;
650
+ }
651
+ else {
652
+ if (res.code === exports.RTCJoinedInfoCodeEnum.Success) {
653
+ this.emit('joined');
654
+ this.joined = true;
655
+ }
656
+ else {
657
+ this.emit('error', res);
822
658
  this.joined = false;
823
- return [2 /*return*/, !!res];
659
+ }
824
660
  }
825
- });
661
+ return this.joined;
662
+ }
663
+ catch (e) {
664
+ this.emit('error', new Error('加入房间失败:' + e.message));
665
+ this.joined = false;
666
+ return this.joined;
667
+ }
826
668
  });
827
- };
828
- VRWebViewRTC.prototype.detectMicro = function () {
829
- return __awaiter(this, void 0, void 0, function () {
830
- var _a, res, error;
831
- return __generator(this, function (_b) {
832
- switch (_b.label) {
833
- case 0: return [4 /*yield*/, this.jsBridge.detectMicro()];
834
- case 1:
835
- _a = _b.sent(), res = _a[0], error = _a[1];
836
- if (res === null) {
837
- this.emit('error', error ? error : new Error('麦克风监测异常!'));
838
- return [2 /*return*/, false];
839
- }
840
- return [2 /*return*/, res];
841
- }
842
- });
669
+ }
670
+ quit() {
671
+ return __awaiter(this, void 0, void 0, function* () {
672
+ const [res, error] = yield this.jsBridge.callAndBackfeed('live/quit');
673
+ if (res === null) {
674
+ this.emit('error', error ? error : new Error('退出房间失败:未知异常。'));
675
+ }
676
+ this.joined = false;
677
+ return !!res;
843
678
  });
844
- };
845
- VRWebViewRTC.prototype.toggleMicro = function (flag) {
846
- return __awaiter(this, void 0, void 0, function () {
847
- var _a, res, error;
848
- return __generator(this, function (_b) {
849
- switch (_b.label) {
850
- case 0: return [4 /*yield*/, this.jsBridge.callAndBackfeed("live/toggleMicro?flag=".concat(!!flag ? 1 : 0))];
851
- case 1:
852
- _a = _b.sent(), res = _a[0], error = _a[1];
853
- if (res === null) {
854
- this.emit('error', error ? error : new Error('麦克风监测异常!'));
855
- return [2 /*return*/, false];
856
- }
857
- this.micro = res;
858
- return [2 /*return*/, res];
859
- }
860
- });
679
+ }
680
+ detectMicro() {
681
+ return __awaiter(this, void 0, void 0, function* () {
682
+ const [res, error] = yield this.jsBridge.detectMicro();
683
+ if (res === null) {
684
+ this.emit('error', error ? error : new Error('麦克风监测异常!'));
685
+ return false;
686
+ }
687
+ return res;
861
688
  });
862
- };
863
- VRWebViewRTC.prototype.shock = function () {
689
+ }
690
+ toggleMicro(flag) {
691
+ return __awaiter(this, void 0, void 0, function* () {
692
+ const [res, error] = yield this.jsBridge.callAndBackfeed(`live/toggleMicro?flag=${!!flag ? 1 : 0}`);
693
+ if (res === null) {
694
+ this.emit('error', error ? error : new Error('麦克风监测异常!'));
695
+ return false;
696
+ }
697
+ this.micro = res;
698
+ return res;
699
+ });
700
+ }
701
+ shock() {
864
702
  this.jsBridge.shock(1);
865
- };
866
- return VRWebViewRTC;
867
- }(CoreRTC));
703
+ }
704
+ }
868
705
 
869
706
  /**
870
707
  * WebSocket 通信指令
@@ -949,8 +786,8 @@ exports.MicroStatus = void 0;
949
786
  */
950
787
  function parseLiveMsg(jsonTxt) {
951
788
  try {
952
- var msg = JSON.parse(jsonTxt);
953
- var resMsg_1 = {
789
+ const msg = JSON.parse(jsonTxt);
790
+ const resMsg = {
954
791
  code: msg.code,
955
792
  message: msg.message,
956
793
  command: msg.command,
@@ -961,11 +798,11 @@ function parseLiveMsg(jsonTxt) {
961
798
  triggerUserID: msg.trigger_user_id,
962
799
  data: msg.data || {},
963
800
  };
964
- var undefinedKeys = Object.keys(resMsg_1).filter(function (key) { return resMsg_1[key] === undefined; });
801
+ const undefinedKeys = Object.keys(resMsg).filter((key) => resMsg[key] === undefined);
965
802
  if (undefinedKeys.length > 0) {
966
- console.warn("\u63A8\u9001\u6570\u636E\u683C\u5F0F\u5F02\u5E38\uFF1A".concat(undefinedKeys.join(" "), " \u503C\u4E0D\u5B58\u5728\uFF01"));
803
+ console.warn(`推送数据格式异常:${undefinedKeys.join(" ")} 值不存在!`);
967
804
  }
968
- return resMsg_1;
805
+ return resMsg;
969
806
  }
970
807
  catch (error) {
971
808
  // notcare? 过滤掉所有不符合规范的数据
@@ -973,6 +810,23 @@ function parseLiveMsg(jsonTxt) {
973
810
  }
974
811
  }
975
812
 
813
+ exports.LiveState = void 0;
814
+ (function (LiveState) {
815
+ LiveState[LiveState["NOTINITIALIZED"] = -1] = "NOTINITIALIZED";
816
+ /**
817
+ * 正在链接中
818
+ */
819
+ LiveState[LiveState["CONNECTING"] = 0] = "CONNECTING";
820
+ /**
821
+ * 已经链接并且可以通讯
822
+ */
823
+ LiveState[LiveState["OPEN"] = 1] = "OPEN";
824
+ /**
825
+ * 连接已关闭或者链接失败
826
+ */
827
+ LiveState[LiveState["CLOSED"] = 3] = "CLOSED";
828
+ })(exports.LiveState || (exports.LiveState = {}));
829
+
976
830
  /**
977
831
  * 用户当前状态枚举。
978
832
  */
@@ -1102,20 +956,45 @@ function parseWSClsErr(code) {
1102
956
  return exports.WebSocketCloseError.Err_unknown;
1103
957
  }
1104
958
 
959
+ function getDefaultExportFromCjs (x) {
960
+ return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
961
+ }
962
+
963
+ function createCommonjsModule(fn) {
964
+ var module = { exports: {} };
965
+ return fn(module, module.exports), module.exports;
966
+ }
967
+
968
+ var LogLevel_1 = createCommonjsModule(function (module, exports) {
969
+ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
970
+ // SPDX-License-Identifier: Apache-2.0
971
+ Object.defineProperty(exports, "__esModule", { value: true });
972
+ exports.LogLevel = void 0;
973
+ var LogLevel;
974
+ (function (LogLevel) {
975
+ LogLevel[LogLevel["DEBUG"] = 0] = "DEBUG";
976
+ LogLevel[LogLevel["INFO"] = 1] = "INFO";
977
+ LogLevel[LogLevel["WARN"] = 2] = "WARN";
978
+ LogLevel[LogLevel["ERROR"] = 3] = "ERROR";
979
+ LogLevel[LogLevel["OFF"] = 4] = "OFF";
980
+ })(LogLevel = exports.LogLevel || (exports.LogLevel = {}));
981
+ exports.default = LogLevel;
982
+
983
+ });
984
+
985
+ var LogLevel = /*@__PURE__*/getDefaultExportFromCjs(LogLevel_1);
986
+
1105
987
  function appendUri(uri, query) {
1106
- if (query === void 0) { query = {}; }
1107
- var hasQuery = uri.indexOf('?') !== -1;
1108
- var newQuery = Object.keys(query).reduce(function (accu, curr, idx) {
1109
- return "".concat(accu).concat((idx === 0 && !hasQuery) ? '?' : '&').concat(curr, "=").concat(query[curr]);
1110
- }, '');
988
+ const hasQuery = uri.indexOf('?') !== -1;
989
+ const newQuery = Object.keys(query).reduce((accu, curr, idx) => `${accu}${(idx === 0 && !hasQuery) ? '?' : '&'}${curr}=${query[curr]}`, '');
1111
990
  return uri + newQuery;
1112
991
  }
1113
992
 
1114
- var userAgent = globalThis.navigator.userAgent;
1115
- var isAndroid = /android/gi.test(userAgent);
1116
- var isIOS = /iPhone|iPad\s+OS/gi.test(userAgent);
1117
- var isWxMiniProgram = /MicroMessenger/gi.test(userAgent) && /miniProgram/gi.test(userAgent);
1118
- var isRealseeVRWebview = /realsee/gi.test(userAgent);
993
+ const userAgent = globalThis.navigator.userAgent;
994
+ const isAndroid = /android/gi.test(userAgent);
995
+ const isIOS = /iPhone|iPad\s+OS/gi.test(userAgent);
996
+ const isWxMiniProgram = /MicroMessenger/gi.test(userAgent) && /miniProgram/gi.test(userAgent);
997
+ const isRealseeVRWebview = /realsee/gi.test(userAgent);
1119
998
 
1120
999
  /**
1121
1000
  * 判断是否是真实的对象类型
@@ -1147,12 +1026,12 @@ function baseIsEqual(value, other) {
1147
1026
  * @returns
1148
1027
  */
1149
1028
  function objEqualShallow(value, other) {
1150
- var valueProps = Object.getOwnPropertyNames(value);
1151
- var otherProps = Object.getOwnPropertyNames(other);
1029
+ const valueProps = Object.getOwnPropertyNames(value);
1030
+ const otherProps = Object.getOwnPropertyNames(other);
1152
1031
  if (valueProps.length !== otherProps.length)
1153
1032
  return false;
1154
- for (var i = 0, len = valueProps.length; i < len; i++) {
1155
- var propName = valueProps[i];
1033
+ for (let i = 0, len = valueProps.length; i < len; i++) {
1034
+ const propName = valueProps[i];
1156
1035
  if (!baseIsEqual(value[propName], other[propName]))
1157
1036
  return false;
1158
1037
  }
@@ -1167,7 +1046,7 @@ function objEqualShallow(value, other) {
1167
1046
  function arrayEqualShallow(value, other) {
1168
1047
  if (value.length !== other.length)
1169
1048
  return false;
1170
- for (var i = 0, len = value.length; i < len; i++) {
1049
+ for (let i = 0, len = value.length; i < len; i++) {
1171
1050
  if (!baseIsEqual(value[i], other[i]))
1172
1051
  return false;
1173
1052
  }
@@ -1212,7 +1091,7 @@ function isDeepEqual(value, other) {
1212
1091
  function arrayEqualDeep(value, other) {
1213
1092
  if (value.length !== other.length)
1214
1093
  return false;
1215
- for (var i = 0, len = value.length; i < len; i++) {
1094
+ for (let i = 0, len = value.length; i < len; i++) {
1216
1095
  if (!isDeepEqual(value[i], other[i]))
1217
1096
  return false;
1218
1097
  }
@@ -1225,12 +1104,12 @@ function arrayEqualDeep(value, other) {
1225
1104
  * @returns
1226
1105
  */
1227
1106
  function objEqualDeep(value, other) {
1228
- var valueProps = Object.getOwnPropertyNames(value);
1229
- var otherProps = Object.getOwnPropertyNames(other);
1107
+ const valueProps = Object.getOwnPropertyNames(value);
1108
+ const otherProps = Object.getOwnPropertyNames(other);
1230
1109
  if (valueProps.length !== otherProps.length)
1231
1110
  return false;
1232
- for (var i = 0, len = valueProps.length; i < len; i++) {
1233
- var propName = valueProps[i];
1111
+ for (let i = 0, len = valueProps.length; i < len; i++) {
1112
+ const propName = valueProps[i];
1234
1113
  if (!isDeepEqual(value[propName], other[propName]))
1235
1114
  return false;
1236
1115
  }
@@ -1244,993 +1123,1323 @@ function objEqualDeep(value, other) {
1244
1123
  * @returns {boolean} 是否相等。
1245
1124
  */
1246
1125
  function equal(value, other, opt) {
1247
- if (opt === void 0) { opt = { deep: false }; }
1248
1126
  if (!opt.deep)
1249
1127
  return isShallowEqual(value, other);
1250
1128
  return isDeepEqual(value, other);
1251
1129
  }
1252
1130
 
1253
- var LiveController = /** @class */ (function () {
1254
- function LiveController(options) {
1255
- var _this = this;
1256
- this.readyState = exports.WebSocketState.NOTINITIALIZED;
1257
- this.canSync = true;
1258
- this.connecting = false;
1259
- this.keyframes = {};
1131
+ /**
1132
+ * 输出格式化日志
1133
+ */
1134
+ // 获取当前时间
1135
+ const getTime = () => {
1136
+ const date = new Date();
1137
+ const year = date.getFullYear();
1138
+ const month = (date.getMonth() + 1).toString().padStart(2, '0'); //月份是从0开始的
1139
+ const day = date.getDate().toString().padStart(2, '0');
1140
+ const hour = date.getHours().toString().padStart(2, '0');
1141
+ const min = date.getMinutes().toString().padStart(2, '0');
1142
+ const sec = date.getSeconds().toString().padStart(2, '0');
1143
+ const ms = date.getMilliseconds();
1144
+ return `[${year}-${month}-${day} ${hour}:${min}:${sec}.${ms}]`;
1145
+ };
1146
+ var LOG_LEVEL;
1147
+ (function (LOG_LEVEL) {
1148
+ LOG_LEVEL["info"] = "INFO";
1149
+ LOG_LEVEL["log"] = "LOG";
1150
+ LOG_LEVEL["error"] = "ERROR";
1151
+ LOG_LEVEL["warn"] = "WARN";
1152
+ })(LOG_LEVEL || (LOG_LEVEL = {}));
1153
+ // 输出日志
1154
+ const echo = (logLevel, args = []) => {
1155
+ args.unshift(`Realsee Live ${getTime()} <${logLevel}> `);
1156
+ switch (logLevel) {
1157
+ case LOG_LEVEL.info:
1158
+ return console.info(...args);
1159
+ case LOG_LEVEL.error:
1160
+ return console.error(...args);
1161
+ case LOG_LEVEL.warn:
1162
+ return console.warn(...args);
1163
+ default:
1164
+ return console.log(...args);
1165
+ }
1166
+ };
1167
+ const log = (...args) => echo(LOG_LEVEL.log, args);
1168
+ const info = (...args) => echo(LOG_LEVEL.info, args);
1169
+ const error = (...args) => echo(LOG_LEVEL.error, args);
1170
+ const warn = (...args) => echo(LOG_LEVEL.warn, args);
1171
+ const logger = {
1172
+ log,
1173
+ info,
1174
+ error,
1175
+ warn,
1176
+ };
1177
+ var logger$1 = logger;
1178
+
1179
+ /**
1180
+ * 具有鲁棒性的WebSocket封装
1181
+ * 1、自动重连
1182
+ * 2、可根据网络情况进行重连
1183
+ */
1184
+ class RobustWebSocket extends Subscribe {
1185
+ constructor(options) {
1186
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-call
1187
+ super();
1188
+ this._readyState = exports.WebSocketState.NOTINITIALIZED;
1189
+ this._options = {
1190
+ timeout: 10000,
1191
+ shouldReconnect: (event, ws) => {
1192
+ if (event.code === 1008 || event.code === 1011)
1193
+ return;
1194
+ return [0, 3000, 10000][ws.attempts];
1195
+ },
1196
+ should1000Reconnect: false,
1197
+ ignoreConnectivityEvents: false,
1198
+ automaticOpen: false,
1199
+ };
1200
+ this._attempts = 0;
1201
+ this._reconnects = -1;
1202
+ this._reconnectWhenOnlineAgain = false;
1203
+ this._explicitlyClosed = false;
1204
+ this._connectivityEventsAttached = false;
1260
1205
  /**
1261
- * 检测 WebSocket.readyState 状态
1206
+ * 做一个健康检查
1262
1207
  */
1263
- this.checkReadyState = function (live) {
1264
- do {
1265
- if (!_this.webSocket) {
1266
- if (_this.readyState !== exports.WebSocketState.NOTINITIALIZED) {
1267
- _this.readyState = exports.WebSocketState.NOTINITIALIZED;
1268
- live.emit('ws.readyStateUpdate', _this.readyState);
1269
- }
1270
- break;
1208
+ this._healthCheck = () => __awaiter(this, void 0, void 0, function* () {
1209
+ if (this._realWebSocket &&
1210
+ this._realWebSocket.readyState !== this._readyState) {
1211
+ this._readyState = this._realWebSocket.readyState;
1212
+ // 太惨了,断网的时候,ws不会直接closed,而是处于closing的状态
1213
+ if (this._readyState === exports.WebSocketState.CLOSING) {
1214
+ this.emit('closing');
1271
1215
  }
1272
- var readyState = _this.webSocket.readyState;
1273
- if (readyState !== _this.readyState) {
1274
- _this.readyState = readyState;
1275
- live.emit('ws.readyStateUpdate', _this.readyState);
1276
- }
1277
- } while (false);
1278
- return _this.readyState;
1216
+ }
1217
+ yield new Promise((resolve) => setTimeout(resolve, 2000));
1218
+ this._heathCheckTimer = requestAnimationFrame(this._healthCheck);
1219
+ });
1220
+ /**
1221
+ * 清理健康检查
1222
+ */
1223
+ this._clearHeathCheckIfNeed = () => {
1224
+ if (this._heathCheckTimer) {
1225
+ cancelAnimationFrame(this._heathCheckTimer);
1226
+ this._heathCheckTimer = undefined;
1227
+ }
1228
+ };
1229
+ /**
1230
+ * 开启健康检查
1231
+ */
1232
+ this._startHealthCheck = () => {
1233
+ this._clearHeathCheckIfNeed();
1234
+ this._heathCheckTimer = requestAnimationFrame(this._healthCheck);
1235
+ };
1236
+ /**
1237
+ * 停止健康检查
1238
+ */
1239
+ this._stopHealthCheck = () => {
1240
+ this._clearHeathCheckIfNeed();
1279
1241
  };
1280
- this.dispose = function () {
1281
- _this.disposeWebSocket();
1282
- _this.connecting = false;
1283
- if (_this.healthCheckId) {
1284
- clearInterval(_this.healthCheckId);
1285
- _this.healthCheckId = undefined;
1242
+ /**
1243
+ * 清理连接中的请求
1244
+ */
1245
+ this._clearPendingReconnectIfNeeded = () => {
1246
+ if (this._pendingReconnect) {
1247
+ clearTimeout(this._pendingReconnect);
1248
+ this._pendingReconnect = undefined;
1286
1249
  }
1287
- return true;
1288
1250
  };
1289
1251
  /**
1290
- * 销毁WebSocket相关依赖。
1252
+ * 当网页连接上网络进行重连
1253
+ * @param event
1291
1254
  */
1292
- this.disposeWebSocket = function () {
1293
- if (!_this.webSocket)
1294
- return;
1295
- if (_this.onEvtOpnListener) {
1296
- _this.webSocket.removeEventListener('open', _this.onEvtOpnListener);
1297
- _this.onEvtOpnListener = undefined;
1255
+ this._online = (event) => {
1256
+ if (this._reconnectWhenOnlineAgain) {
1257
+ this._clearPendingReconnectIfNeeded();
1258
+ this._reconnect(event);
1298
1259
  }
1299
- if (_this.onEvtMsgListener) {
1300
- _this.webSocket.removeEventListener('message', _this.onEvtMsgListener);
1301
- _this.onEvtMsgListener = undefined;
1260
+ };
1261
+ /**
1262
+ * 当网页断开网络进行关闭
1263
+ */
1264
+ this._offline = () => {
1265
+ var _a;
1266
+ this._reconnectWhenOnlineAgain = true;
1267
+ (_a = this._realWebSocket) === null || _a === void 0 ? void 0 : _a.close(1000, 'offline');
1268
+ };
1269
+ /**
1270
+ * 解除网络监听事件
1271
+ */
1272
+ this._detachConnectivityEvents = () => {
1273
+ if (this._connectivityEventsAttached) {
1274
+ globalThis === null || globalThis === void 0 ? void 0 : globalThis.removeEventListener('online', this._online);
1275
+ globalThis === null || globalThis === void 0 ? void 0 : globalThis.removeEventListener('offline', this._offline);
1276
+ this._connectivityEventsAttached = false;
1302
1277
  }
1303
- if (_this.onEvtErrListener) {
1304
- _this.webSocket.removeEventListener('error', _this.onEvtErrListener);
1305
- _this.onEvtErrListener = undefined;
1278
+ };
1279
+ /**
1280
+ * 注册网络监听事件
1281
+ */
1282
+ this._attachConnectivityEvents = () => {
1283
+ if (!this._connectivityEventsAttached) {
1284
+ globalThis === null || globalThis === void 0 ? void 0 : globalThis.addEventListener('online', this._online);
1285
+ globalThis === null || globalThis === void 0 ? void 0 : globalThis.addEventListener('offline', this._offline);
1286
+ this._connectivityEventsAttached = true;
1306
1287
  }
1307
- if (_this.onEvtCLEListener) {
1308
- _this.webSocket.removeEventListener('close', _this.onEvtCLEListener);
1309
- _this.onEvtCLEListener = undefined;
1288
+ };
1289
+ /**
1290
+ * 发送消息
1291
+ * @param data
1292
+ * @returns
1293
+ */
1294
+ this.send = (data) => {
1295
+ var _a, _b, _c;
1296
+ if (((_a = this._realWebSocket) === null || _a === void 0 ? void 0 : _a.readyState) === ((_b = this._realWebSocket) === null || _b === void 0 ? void 0 : _b.OPEN)) {
1297
+ (_c = this._realWebSocket) === null || _c === void 0 ? void 0 : _c.send(data);
1310
1298
  }
1311
- _this.webSocket.close();
1312
- _this.webSocket = undefined;
1313
- return true;
1314
1299
  };
1315
- this.options = Object.assign({ autoConnect: true, healthCheck: 3000 }, options);
1316
- }
1317
- /**
1318
- * 解析数据
1319
- * @param liveMsg
1320
- * @param live
1321
- */
1322
- LiveController.prototype.handleMessage = function (liveMsg, live) {
1323
- var _this = this;
1324
- var _a, _b, _c;
1325
- var command = liveMsg.command, data = liveMsg.data, frontRequestId = liveMsg.frontRequestId, code = liveMsg.code;
1326
- if (code === 'SUCCESS') {
1327
- switch (command) {
1328
- /**
1329
- * 自己的状态变化
1330
- */
1331
- case exports.Command.SelfUserInfo: {
1332
- var selfInfo = data;
1333
- if (equal(this.selfUserInfo, selfInfo, { deep: true }))
1334
- return;
1335
- this.selfUserInfo = selfInfo;
1336
- live.emit('selfInfoUpdate', this.selfUserInfo, frontRequestId);
1337
- break;
1338
- }
1339
- /**
1340
- * 房间信息变化
1341
- */
1342
- case exports.Command.RoomInfo: {
1343
- var roomInfo = data;
1344
- this.roomInfo = Object.assign({}, roomInfo);
1345
- live.emit('readyKeyframeSync', (roomInfo.last_frame || {}));
1346
- break;
1347
- }
1348
- /**
1349
- * 语音信息变化
1350
- */
1351
- case exports.Command.RTCInfo: {
1352
- var _d = data, voiceId = _d.voice_id, type = _d.type;
1353
- /* 如果已经进入语音房间,则不重复进入 --> "RTCInfo" 指令可能会下发多次 */
1354
- if (live.$RTC.joined) {
1355
- break;
1356
- }
1357
- live.$RTC.join({
1358
- voiceId: voiceId,
1359
- userId: ((_a = this.selfUserInfo) === null || _a === void 0 ? void 0 : _a.id) || '',
1360
- roomId: (_b = this.roomInfo) === null || _b === void 0 ? void 0 : _b.info.room_code,
1361
- type: type,
1362
- });
1363
- // 加入房间后 麦克风默认就开启了:需要发个指令。
1364
- live.updateStatus(exports.BuiltinEventType.UserChange, exports.BuiltinActionType.UserMicroStatus, {
1365
- status: exports.MicroStatus.OPEN,
1366
- });
1367
- break;
1368
- }
1369
- /**
1370
- * 房间用户列表变化
1371
- */
1372
- case exports.Command.UserList: {
1373
- var userList = data;
1374
- this.userList = userList;
1375
- live.emit('userListUpdate', this.userList, frontRequestId);
1376
- break;
1377
- }
1378
- /**
1379
- * 自定义事件广播
1380
- */
1381
- case exports.Command.CustomEvent: {
1382
- var evtMsg = data;
1383
- live.emit('broadcast', evtMsg, frontRequestId);
1384
- break;
1385
- }
1386
- /**
1387
- * 帧数据同步
1388
- */
1389
- case exports.Command.KeyframeSync: {
1390
- var remoteKeyframes_1 = data;
1391
- // 此处做一层 diff,仅跟本地数据不一致的情况下才广播数据。
1392
- var keyframes = Object.keys(remoteKeyframes_1).reduce(function (accu, curr) {
1393
- var _a;
1394
- if (equal(remoteKeyframes_1[curr], _this.keyframes[curr], { deep: true })) {
1395
- return accu;
1396
- }
1397
- var params = [
1398
- remoteKeyframes_1[curr],
1399
- _this.keyframes[curr],
1400
- frontRequestId,
1401
- ];
1402
- var evtName = curr;
1403
- (_a = live.keyframes).emit.apply(_a, __spreadArray([evtName], params, false));
1404
- _this.keyframes[curr] = remoteKeyframes_1[curr];
1405
- accu[curr] = remoteKeyframes_1[curr];
1406
- return accu;
1407
- }, {});
1408
- live.emit('keyframes', keyframes, frontRequestId);
1409
- break;
1410
- }
1411
- /**
1412
- * 内置消息
1413
- */
1414
- case exports.Command.BuiltinMsg: {
1415
- var builtinMsg = data;
1416
- live.emit('builtinEvent', builtinMsg);
1417
- if (builtinMsg.event_type === exports.BuiltinEventType.UserChange) {
1418
- live.emit('userChange', builtinMsg);
1419
- }
1420
- if (builtinMsg.event_type === exports.BuiltinEventType.RoomChange) {
1421
- live.emit('roomChange', builtinMsg);
1422
- }
1423
- /**
1424
- * 下发指令自己操作麦克风
1425
- */
1426
- if (builtinMsg.event_type === exports.BuiltinEventType.UserChange &&
1427
- builtinMsg.action === exports.BuiltinActionType.UserMicroStatus) {
1428
- live.toggleMicro(builtinMsg.data.status === exports.MicroStatus.OPEN);
1429
- }
1430
- /**
1431
- * 如果下发指令退出房间,则 关闭麦克风 及 销毁 WebSocket
1432
- */
1433
- if (builtinMsg.event_type === exports.BuiltinEventType.RoomChange &&
1434
- builtinMsg.action === exports.BuiltinActionType.RoomClose) {
1435
- (_c = this.options.rtc) === null || _c === void 0 ? void 0 : _c.quit();
1436
- this.disposeWebSocket();
1437
- }
1438
- break;
1439
- }
1440
- /**
1441
- * 被踢出房间
1442
- */
1443
- case exports.Command.UserKickOut: {
1444
- live.emit('kickOut');
1445
- break;
1446
- }
1447
- /**
1448
- * 其它未知广播
1449
- */
1450
- default: {
1451
- console.warn('unknown command: ', command);
1452
- }
1300
+ /**
1301
+ * 关闭连接
1302
+ * @param code 代码
1303
+ * @param reason 原因
1304
+ * @returns
1305
+ */
1306
+ this.close = (code, reason) => {
1307
+ var _a;
1308
+ if (typeof code !== 'number') {
1309
+ reason = code;
1310
+ code = 1000;
1311
+ }
1312
+ this._clearPendingReconnectIfNeeded();
1313
+ this._reconnectWhenOnlineAgain = false;
1314
+ this._explicitlyClosed = true;
1315
+ this._detachConnectivityEvents();
1316
+ return (_a = this._realWebSocket) === null || _a === void 0 ? void 0 : _a.close(code, reason);
1317
+ };
1318
+ /**
1319
+ * 进行ws连接
1320
+ */
1321
+ this.open = (url) => {
1322
+ var _a, _b;
1323
+ if (url) {
1324
+ this._url = url;
1325
+ }
1326
+ if (((_a = this._realWebSocket) === null || _a === void 0 ? void 0 : _a.readyState) !== WebSocket.OPEN &&
1327
+ ((_b = this._realWebSocket) === null || _b === void 0 ? void 0 : _b.readyState) !== WebSocket.CONNECTING) {
1328
+ this._clearPendingReconnectIfNeeded();
1329
+ this._reconnectWhenOnlineAgain = false;
1330
+ this._explicitlyClosed = false;
1331
+ this._createWebSocket();
1453
1332
  }
1333
+ };
1334
+ /**
1335
+ * 创建ws连接
1336
+ */
1337
+ this._createWebSocket = () => {
1338
+ var _a, _b, _c;
1339
+ const newUrl = typeof this._url === 'string' ? this._url : (_a = this._url) === null || _a === void 0 ? void 0 : _a.call(this, this);
1340
+ if (!newUrl)
1341
+ return;
1342
+ this._pendingReconnect = undefined;
1343
+ this._removeWebSocketEvent();
1344
+ this._realWebSocket = new WebSocket(newUrl, this._protocols || undefined);
1345
+ this._attempts = this._attempts + 1;
1346
+ this.emit('connecting', new CustomEvent('connecting', {
1347
+ detail: { attempts: this._attempts, reconnects: this._reconnects },
1348
+ }));
1349
+ const timeoutCallback = () => {
1350
+ this._connectTimeout = undefined;
1351
+ this._detachConnectivityEvents();
1352
+ this.emit('timeout', new CustomEvent('connecting', {
1353
+ detail: {
1354
+ attempts: this._attempts,
1355
+ reconnects: this._reconnects,
1356
+ },
1357
+ }));
1358
+ };
1359
+ this._connectTimeout = setTimeout(timeoutCallback, (_b = this._options) === null || _b === void 0 ? void 0 : _b.timeout);
1360
+ this._dispatchWebSocketEvent();
1361
+ if (!((_c = this._options) === null || _c === void 0 ? void 0 : _c.ignoreConnectivityEvents)) {
1362
+ this._attachConnectivityEvents();
1363
+ }
1364
+ };
1365
+ /**
1366
+ * 断开ws事件
1367
+ */
1368
+ this._removeWebSocketEvent = () => {
1369
+ var _a, _b, _c, _d;
1370
+ (_a = this._realWebSocket) === null || _a === void 0 ? void 0 : _a.removeEventListener('open', this._webSocketOpenHandler);
1371
+ (_b = this._realWebSocket) === null || _b === void 0 ? void 0 : _b.removeEventListener('close', this._webSocketCloseHandler);
1372
+ (_c = this._realWebSocket) === null || _c === void 0 ? void 0 : _c.removeEventListener('error', this._webSocketErrorHandler);
1373
+ (_d = this._realWebSocket) === null || _d === void 0 ? void 0 : _d.removeEventListener('message', this._webSocketMessageHandler);
1374
+ };
1375
+ /**
1376
+ * 分发ws事件
1377
+ */
1378
+ this._dispatchWebSocketEvent = () => {
1379
+ var _a, _b, _c, _d;
1380
+ (_a = this._realWebSocket) === null || _a === void 0 ? void 0 : _a.addEventListener('open', this._webSocketOpenHandler);
1381
+ (_b = this._realWebSocket) === null || _b === void 0 ? void 0 : _b.addEventListener('close', this._webSocketCloseHandler);
1382
+ (_c = this._realWebSocket) === null || _c === void 0 ? void 0 : _c.addEventListener('error', this._webSocketErrorHandler);
1383
+ (_d = this._realWebSocket) === null || _d === void 0 ? void 0 : _d.addEventListener('message', this._webSocketMessageHandler);
1384
+ };
1385
+ /**
1386
+ * ws连接事件
1387
+ * @returns
1388
+ */
1389
+ this._webSocketOpenHandler = (event) => {
1390
+ if (this._connectTimeout) {
1391
+ clearTimeout(this._connectTimeout);
1392
+ this._connectTimeout = undefined;
1393
+ }
1394
+ const reconnects = ++this._reconnects;
1395
+ const attempts = this._attempts;
1396
+ this._attempts = 0;
1397
+ this._reconnectWhenOnlineAgain = false;
1398
+ this._startHealthCheck();
1399
+ return this.emit('open', Object.assign(event, { detail: { reconnects, attempts } }));
1400
+ };
1401
+ /**
1402
+ * ws 关闭事件
1403
+ * @param event
1404
+ * @returns
1405
+ */
1406
+ this._webSocketCloseHandler = (event) => {
1407
+ this._reconnect(event);
1408
+ this._stopHealthCheck();
1409
+ return this.emit('close', event);
1410
+ };
1411
+ /**
1412
+ * ws 异常
1413
+ * @param event
1414
+ * @returns
1415
+ */
1416
+ this._webSocketErrorHandler = (event) => {
1417
+ return this.emit('error', new CustomEvent('error', { detail: { error: event } }));
1418
+ };
1419
+ /**
1420
+ * ws消息
1421
+ * @param event
1422
+ * @returns
1423
+ */
1424
+ this._webSocketMessageHandler = (event) => {
1425
+ return this.emit('message', event);
1426
+ };
1427
+ if (options) {
1428
+ this.setOptions(options);
1454
1429
  }
1455
- else {
1456
- live.emit('error', liveMsg);
1430
+ this._startHealthCheck();
1431
+ }
1432
+ get attempts() {
1433
+ return this._attempts;
1434
+ }
1435
+ setOptions(options) {
1436
+ if (!options)
1437
+ return;
1438
+ this._url = options.url;
1439
+ this._protocols = options.protocols;
1440
+ const opts = Object.assign(this._options, options.robustOptions || {});
1441
+ if (typeof (opts === null || opts === void 0 ? void 0 : opts.timeout) !== 'number') {
1442
+ throw new Error('timeout must be the number of milliseconds to timeout a connection attempt');
1457
1443
  }
1458
- };
1444
+ if (typeof (opts === null || opts === void 0 ? void 0 : opts.shouldReconnect) !== 'function') {
1445
+ throw new Error('shouldReconnect must be a function that returns the number of milliseconds to wait for a reconnect attempt, or null or undefined to not reconnect.');
1446
+ }
1447
+ this._options = opts;
1448
+ if (this._options.automaticOpen) {
1449
+ this._createWebSocket();
1450
+ }
1451
+ }
1452
+ /**
1453
+ * 进行重连
1454
+ * @param event
1455
+ * @returns
1456
+ */
1457
+ _reconnect(event) {
1458
+ var _a, _b, _c, _d;
1459
+ if ((!((_a = this._options) === null || _a === void 0 ? void 0 : _a.should1000Reconnect) && event.code === 1000) ||
1460
+ this._explicitlyClosed) {
1461
+ this._attempts = 0;
1462
+ return;
1463
+ }
1464
+ if (((_b = globalThis === null || globalThis === void 0 ? void 0 : globalThis.navigator) === null || _b === void 0 ? void 0 : _b.onLine) === false) {
1465
+ this._reconnectWhenOnlineAgain = true;
1466
+ return;
1467
+ }
1468
+ const delay = (_d = (_c = this._options) === null || _c === void 0 ? void 0 : _c.shouldReconnect) === null || _d === void 0 ? void 0 : _d.call(_c, event, this);
1469
+ if (typeof delay === 'number') {
1470
+ this._pendingReconnect = setTimeout(this._createWebSocket, delay);
1471
+ }
1472
+ }
1473
+ }
1474
+
1475
+ class LiveController extends Subscribe {
1476
+ constructor() {
1477
+ super();
1478
+ /**
1479
+ * ws代理器
1480
+ */
1481
+ this._ws = new RobustWebSocket({
1482
+ url: '',
1483
+ robustOptions: { timeout: 180000 },
1484
+ });
1485
+ /**
1486
+ * 带看连接状态
1487
+ */
1488
+ this._state = exports.LiveState.NOTINITIALIZED;
1489
+ /**
1490
+ * 添加事件监听
1491
+ */
1492
+ this._addWebSocketEventListeners = () => {
1493
+ this._ws.on('close', this._handleCloseEvent);
1494
+ this._ws.on('closing', this._handleClosingEvent);
1495
+ this._ws.on('connecting', this._handleConnectingEvent);
1496
+ this._ws.on('error', this._handleErrorEvent);
1497
+ this._ws.on('message', this._handleMessageEvent);
1498
+ this._ws.on('open', this._handleOpenEvent);
1499
+ this._ws.on('timeout', this._handleTimeoutEvent);
1500
+ };
1501
+ /**
1502
+ * 移除事件监听
1503
+ */
1504
+ this._removeWebSocketEventListeners = () => {
1505
+ this._ws.off('close', this._handleCloseEvent);
1506
+ this._ws.off('closing', this._handleClosingEvent);
1507
+ this._ws.off('connecting', this._handleConnectingEvent);
1508
+ this._ws.off('error', this._handleErrorEvent);
1509
+ this._ws.off('message', this._handleMessageEvent);
1510
+ this._ws.off('open', this._handleOpenEvent);
1511
+ this._ws.off('timeout', this._handleTimeoutEvent);
1512
+ };
1513
+ /**
1514
+ * 处理房间关闭事件
1515
+ * @param event
1516
+ */
1517
+ this._handleCloseEvent = (event) => {
1518
+ logger$1.info(`live room closed bacause of ${event.code}-${event.reason || parseWSClsErr(event.code)}`);
1519
+ this.state = exports.LiveState.CLOSED;
1520
+ };
1521
+ /**
1522
+ * 处理房间正在关闭事件(这个时候可能是断网了)
1523
+ */
1524
+ this._handleClosingEvent = () => {
1525
+ var _a;
1526
+ logger$1.info(`live room is closing, onLine:`, (_a = globalThis === null || globalThis === void 0 ? void 0 : globalThis.navigator) === null || _a === void 0 ? void 0 : _a.onLine);
1527
+ this.state = exports.LiveState.CLOSED;
1528
+ };
1529
+ /**
1530
+ * 连接中
1531
+ * @param event
1532
+ */
1533
+ this._handleConnectingEvent = () => {
1534
+ logger$1.info(`live room is connecting`);
1535
+ this.state = exports.LiveState.CONNECTING;
1536
+ };
1537
+ /**
1538
+ * 连接发送异常
1539
+ * @param event
1540
+ */
1541
+ this._handleErrorEvent = (event) => {
1542
+ logger$1.error(`live room error`, event);
1543
+ this.state = exports.LiveState.CLOSED;
1544
+ };
1545
+ /**
1546
+ * 接收到消息
1547
+ * @param event
1548
+ */
1549
+ this._handleMessageEvent = (event) => {
1550
+ // logger.info('live room received message ', event.data);
1551
+ let message = (() => {
1552
+ try {
1553
+ return JSON.parse(event.data);
1554
+ }
1555
+ catch (e) {
1556
+ return event.data;
1557
+ }
1558
+ })();
1559
+ this.emit('message', message);
1560
+ };
1561
+ /**
1562
+ * 连接建立成功
1563
+ * @param event
1564
+ */
1565
+ this._handleOpenEvent = (event) => {
1566
+ logger$1.info('live room open', event.detail);
1567
+ this.state = exports.LiveState.OPEN;
1568
+ if (event.detail.reconnects > 0) {
1569
+ this.emit('reconnected', event.detail);
1570
+ }
1571
+ };
1572
+ /**
1573
+ * 处理超时
1574
+ * @param event
1575
+ */
1576
+ this._handleTimeoutEvent = (event) => {
1577
+ logger$1.error('live room connect timeout!', event.detail);
1578
+ this.state = exports.LiveState.CLOSED;
1579
+ };
1580
+ /**
1581
+ * 释放资源,释放之后需要重新实例化
1582
+ * @returns
1583
+ */
1584
+ this.dispose = () => __awaiter(this, void 0, void 0, function* () {
1585
+ this._removeWebSocketEventListeners();
1586
+ return yield this.close('live room close by controller disposed!');
1587
+ });
1588
+ /**
1589
+ * 开启房间链接
1590
+ * @param url 房间链接
1591
+ * @returns
1592
+ */
1593
+ this.open = (url) => this._ws.open(url);
1594
+ /**
1595
+ * 关闭房间
1596
+ * @param code
1597
+ * @param reason
1598
+ */
1599
+ this.close = (code, reason) => new Promise((resolve) => {
1600
+ this._ws.once('close', () => resolve(true));
1601
+ this._ws.close(code, reason);
1602
+ });
1603
+ this._addWebSocketEventListeners();
1604
+ }
1605
+ set state(state) {
1606
+ const prevState = JSON.parse(JSON.stringify(this._state));
1607
+ this._state = state;
1608
+ this.emit('stateChange', this.state, prevState);
1609
+ }
1610
+ get state() {
1611
+ return this._state;
1612
+ }
1459
1613
  /**
1460
1614
  * 发送数据
1461
1615
  * @param data
1462
1616
  */
1463
- LiveController.prototype.sendMessage = function (data) {
1464
- if (!this.webSocket)
1465
- return console.warn('WebSocket has not yet been initialized!');
1466
- if (!data)
1467
- return console.warn('WebSocket messages is empty!');
1468
- this.webSocket.send(JSON.stringify(data));
1469
- };
1470
- return LiveController;
1471
- }());
1617
+ sendMessage(data = '') {
1618
+ if (data === undefined || data === null || data === '') {
1619
+ throw new Error('live message is empty!');
1620
+ }
1621
+ if (this.state === exports.LiveState.OPEN) {
1622
+ return this._ws.send(JSON.stringify(data));
1623
+ }
1624
+ else {
1625
+ throw new Error('live has not yet been initialized!');
1626
+ }
1627
+ }
1628
+ }
1472
1629
 
1473
- var unimplementedGetVoiceSign = function (params) {
1474
- return Promise.reject('unimplemented method GetVoiceSign');
1630
+ const unimplementedGetVoiceSign = (params) => Promise.reject('unimplemented method GetVoiceSign');
1631
+ const createLiveMsg = (command, data = {}, toUserIds = []) => ({
1632
+ command,
1633
+ front_request_id: uuid(),
1634
+ data: Object.assign(Object.assign({}, data), { to_user_ids: Array.isArray(toUserIds) ? toUserIds : [toUserIds] }),
1635
+ });
1636
+ const _clearLiveInstanceIfNeed = () => {
1637
+ var _a, _b;
1638
+ if (window === null || window === void 0 ? void 0 : window.__Realsee_Live__) {
1639
+ (_b = (_a = window === null || window === void 0 ? void 0 : window.__Realsee_Live__) === null || _a === void 0 ? void 0 : _a.dispose) === null || _b === void 0 ? void 0 : _b.call(_a);
1640
+ window.__Realsee_Live__ = null;
1641
+ }
1475
1642
  };
1476
- /**
1477
- * 创建 `live` 实例。
1478
- */
1479
- function createLive(options) {
1480
- var liveController = new LiveController(options);
1481
- var createLiveMsg = function (command, data, toUserIds) {
1482
- if (data === void 0) { data = {}; }
1483
- toUserIds = toUserIds
1484
- ? Array.isArray(toUserIds)
1485
- ? toUserIds
1486
- : [toUserIds]
1487
- : [];
1488
- if (toUserIds)
1489
- data['to_user_ids'] = toUserIds;
1490
- return { command: command, front_request_id: uuid(), data: data };
1491
- };
1492
- var LiveTpl = /** @class */ (function (_super) {
1493
- __extends(LiveTpl, _super);
1494
- function LiveTpl() {
1495
- var _this = this;
1496
- var _a, _b;
1497
- _this = _super.call(this) || this;
1498
- _this.keyframes = new Subscribe();
1499
- var jsBridge = (function () {
1500
- if (options.jsBridge)
1501
- return options.jsBridge;
1502
- if (options.useBuiltInJsBridge)
1503
- return new JSBridge__default["default"]();
1504
- return undefined;
1505
- })();
1506
- liveController.options.jsBridge = jsBridge;
1507
- // 没有传rtc实例时
1508
- if (!options.rtc) {
1509
- // 取指定的内部rtc类型
1510
- if (options.rtcType) {
1511
- if (!options.getVoiceSign) {
1512
- throw new Error('GetVoiceSign method must be passed when using built-in RTC instances');
1513
- }
1514
- var getVoiceSign = (_a = options.getVoiceSign) !== null && _a !== void 0 ? _a : unimplementedGetVoiceSign;
1515
- switch (options.rtcType) {
1516
- case exports.RTCType.RealseeVRWebViewRTC: {
1517
- // 内置的 VRWebViewRTC
1518
- if (!jsBridge) {
1519
- throw new Error('JsBridge instance must be passed when using built-in VRWebViewRTC instances');
1643
+ class Live extends Subscribe {
1644
+ constructor(opts) {
1645
+ var _a;
1646
+ super();
1647
+ /**
1648
+ * 带看的配置
1649
+ */
1650
+ this._options = {};
1651
+ /**
1652
+ * 帧数据监听
1653
+ */
1654
+ this.keyframes = new Subscribe();
1655
+ /**
1656
+ * 内置的一些数据
1657
+ */
1658
+ this._buildInData = {
1659
+ keyframes: {},
1660
+ };
1661
+ /**
1662
+ * 根据键值取帧数据
1663
+ * @param key 帧数据的键值
1664
+ * @returns
1665
+ */
1666
+ this.getFramesByKey = (key) => this.snapshot[key];
1667
+ /**
1668
+ * 发送帧数据(需要能够被序列化)
1669
+ * @param key 帧数据键值
1670
+ * @param frame 帧数据本体
1671
+ * @returns
1672
+ */
1673
+ this.sendKeyframe = (key, frame) => {
1674
+ if (this.state !== exports.LiveState.OPEN)
1675
+ return false;
1676
+ this._buildInData.keyframes = Object.assign(Object.assign({}, this._buildInData.keyframes), { [key]: frame });
1677
+ const liveMsg = createLiveMsg(exports.Command.KeyframeSync, this.snapshot);
1678
+ try {
1679
+ this._controller.sendMessage(liveMsg);
1680
+ return true;
1681
+ }
1682
+ catch (e) {
1683
+ logger$1.error(e);
1684
+ return false;
1685
+ }
1686
+ };
1687
+ /**
1688
+ * 带看控制器
1689
+ */
1690
+ this._controller = new LiveController();
1691
+ /**
1692
+ * 添加带看控制的事件监听
1693
+ */
1694
+ this._addLiveControllerEventListeners = () => {
1695
+ this._controller.on('stateChange', this._handleStateChange);
1696
+ this._controller.on('message', this._handleMessage);
1697
+ };
1698
+ /**
1699
+ * 移除带看控制的事件监听
1700
+ */
1701
+ this._removeLiveControllerEventListeners = () => {
1702
+ this._controller.off('stateChange', this._handleStateChange);
1703
+ this._controller.off('message', this._handleMessage);
1704
+ };
1705
+ /**
1706
+ * 带看状态变化
1707
+ * @param state
1708
+ * @returns
1709
+ */
1710
+ this._handleStateChange = (state, prevState) => this.emit('stateChange', state, prevState);
1711
+ /**
1712
+ * 消息接收
1713
+ * @param liveMsg
1714
+ */
1715
+ this._handleMessage = (liveMsg) => __awaiter(this, void 0, void 0, function* () {
1716
+ var _b, _c, _d, _e, _f, _g;
1717
+ if (typeof liveMsg === 'object') {
1718
+ const { command, data, frontRequestId, code, message } = liveMsg;
1719
+ if (code === 'SUCCESS') {
1720
+ switch (command) {
1721
+ /**
1722
+ * 自己的状态变化
1723
+ */
1724
+ case exports.Command.SelfUserInfo: {
1725
+ const selfInfo = data;
1726
+ if (!equal(this.selfInfo, selfInfo, { deep: true })) {
1727
+ this._buildInData.selfInfo = selfInfo;
1728
+ this.emit('selfInfoUpdate', this._buildInData.selfInfo, frontRequestId);
1520
1729
  }
1521
- liveController.options.rtc = new VRWebViewRTC({
1522
- jsBridge: jsBridge,
1523
- getVoiceSign: getVoiceSign,
1524
- });
1525
1730
  break;
1526
1731
  }
1527
- case exports.RTCType.RealseeBrowserChimeRTC: {
1528
- // 内置的 RealseeBrowserChimeRTC
1529
- liveController.options.rtc = new BrowserRTC4Chime({
1530
- getVoiceSign: getVoiceSign,
1531
- logLevel: options.__debug__ ? amazonChimeSdkJs.LogLevel.DEBUG : amazonChimeSdkJs.LogLevel.ERROR,
1532
- });
1732
+ /**
1733
+ * 房间信息变化
1734
+ */
1735
+ case exports.Command.RoomInfo: {
1736
+ const roomInfo = data;
1737
+ this._buildInData.roomInfo = Object.assign({}, roomInfo);
1738
+ this.emit('readyKeyframeSync', (roomInfo.last_frame || {}));
1533
1739
  break;
1534
1740
  }
1535
- case exports.RTCType.RealseeBrowserRTC: {
1536
- // 内置的 RealseeBrowserRTC
1537
- liveController.options.rtc = new BrowserRTC({
1538
- getVoiceSign: getVoiceSign,
1539
- });
1741
+ /**
1742
+ * 语音信息变化
1743
+ */
1744
+ case exports.Command.RTCInfo: {
1745
+ const { voice_id: voiceId, type } = data;
1746
+ this._buildInData.rtcInfo = { voiceId, type };
1747
+ if (!((_b = this.$RTC) === null || _b === void 0 ? void 0 : _b.joined)) {
1748
+ const result = yield ((_c = this.$RTC) === null || _c === void 0 ? void 0 : _c.join({
1749
+ voiceId,
1750
+ userId: ((_d = this.selfInfo) === null || _d === void 0 ? void 0 : _d.id) || '',
1751
+ roomId: (_e = this.roomInfo) === null || _e === void 0 ? void 0 : _e.info.room_code,
1752
+ type,
1753
+ }));
1754
+ if (result) {
1755
+ const status = (_f = this._options.initialMicroStatus) !== null && _f !== void 0 ? _f : exports.MicroStatus.OPEN;
1756
+ yield ((_g = this.$RTC) === null || _g === void 0 ? void 0 : _g.toggleMicro(status === exports.MicroStatus.OPEN));
1757
+ }
1758
+ else {
1759
+ logger$1.error('加入语音房间失败');
1760
+ }
1761
+ }
1762
+ else {
1763
+ logger$1.warn('已加入语音房间,无需重复加入!');
1764
+ }
1540
1765
  break;
1541
1766
  }
1767
+ /**
1768
+ * 房间用户列表变化
1769
+ */
1770
+ case exports.Command.UserList: {
1771
+ const userList = data;
1772
+ this._buildInData.userList = userList;
1773
+ this.emit('userListUpdate', this.userList, frontRequestId);
1774
+ break;
1775
+ }
1776
+ /**
1777
+ * 自定义事件广播
1778
+ */
1779
+ case exports.Command.CustomEvent: {
1780
+ const evtMsg = data;
1781
+ this.emit('broadcast', evtMsg, frontRequestId);
1782
+ break;
1783
+ }
1784
+ /**
1785
+ * 帧数据同步
1786
+ */
1787
+ case exports.Command.KeyframeSync: {
1788
+ const remoteKeyframes = data;
1789
+ // 此处做一层 diff,仅跟本地数据不一致的情况下才广播数据。
1790
+ const keyframes = Object.keys(remoteKeyframes).reduce((accu, curr) => {
1791
+ if (equal(remoteKeyframes[curr], this._buildInData.keyframes[curr], {
1792
+ deep: true,
1793
+ })) {
1794
+ return accu;
1795
+ }
1796
+ const params = [
1797
+ remoteKeyframes[curr],
1798
+ this._buildInData.keyframes[curr],
1799
+ frontRequestId,
1800
+ ];
1801
+ const evtName = curr;
1802
+ this.keyframes.emit(evtName, ...params);
1803
+ this._buildInData.keyframes[curr] = remoteKeyframes[curr];
1804
+ accu[curr] = remoteKeyframes[curr];
1805
+ return accu;
1806
+ }, {});
1807
+ this.emit('keyframes', keyframes, frontRequestId);
1808
+ break;
1809
+ }
1810
+ /**
1811
+ * 内置消息
1812
+ */
1813
+ case exports.Command.BuiltinMsg: {
1814
+ const builtinMsg = data;
1815
+ this.emit('builtinEvent', builtinMsg);
1816
+ if (builtinMsg.event_type === exports.BuiltinEventType.UserChange) {
1817
+ this.emit('userChange', builtinMsg);
1818
+ }
1819
+ if (builtinMsg.event_type === exports.BuiltinEventType.RoomChange) {
1820
+ this.emit('roomChange', builtinMsg);
1821
+ }
1822
+ /**
1823
+ * 下发指令自己操作麦克风
1824
+ */
1825
+ if (builtinMsg.event_type === exports.BuiltinEventType.UserChange &&
1826
+ builtinMsg.action === exports.BuiltinActionType.UserMicroStatus) {
1827
+ yield this.toggleMicro(builtinMsg.data.status === exports.MicroStatus.OPEN);
1828
+ }
1829
+ /**
1830
+ * 如果下发指令退出房间,则 关闭麦克风 及 销毁 WebSocket
1831
+ */
1832
+ if (builtinMsg.event_type === exports.BuiltinEventType.RoomChange &&
1833
+ builtinMsg.action === exports.BuiltinActionType.RoomClose) {
1834
+ yield this.exit();
1835
+ }
1836
+ break;
1837
+ }
1838
+ /**
1839
+ * 被踢出房间
1840
+ */
1841
+ case exports.Command.UserKickOut: {
1842
+ this.emit('kickOut');
1843
+ break;
1844
+ }
1845
+ /**
1846
+ * 其它未知广播
1847
+ */
1542
1848
  default: {
1543
- throw new Error('unknown built-in RTC type');
1849
+ console.warn('unknown command: ', command);
1544
1850
  }
1545
1851
  }
1546
1852
  }
1547
- // 都不满足时取内置
1548
- if (options.useBuiltInRTC) {
1549
- if (!options.getVoiceSign) {
1550
- throw new Error('GetVoiceSign method must be passed when using built-in RTC instances');
1551
- }
1552
- var getVoiceSign = (_b = options.getVoiceSign) !== null && _b !== void 0 ? _b : unimplementedGetVoiceSign;
1553
- if (!jsBridge) {
1554
- throw new Error('jsBridge instance must be passed when using built-in RTC instances');
1555
- }
1556
- // vrwebview 默认
1557
- if ((isRealseeVRWebview && (isAndroid || isIOS)) || isWxMiniProgram) {
1558
- liveController.options.rtc = new VRWebViewRTC({
1559
- jsBridge: jsBridge,
1560
- getVoiceSign: getVoiceSign,
1561
- });
1562
- }
1563
- else {
1564
- // 其它终端使用
1565
- liveController.options.rtc =
1566
- options.builtInRTCType === exports.BuiltInRTCType.RealseeXChimeRTC
1567
- ? new BrowserRTC4Chime({ getVoiceSign: getVoiceSign })
1568
- : new BrowserRTC({ getVoiceSign: getVoiceSign });
1569
- }
1853
+ else {
1854
+ this.emit('error', liveMsg);
1570
1855
  }
1571
1856
  }
1572
- if (!liveController.options.rtc) {
1573
- console.warn('unused rtc');
1857
+ });
1858
+ /**
1859
+ * 清理带看缓存的数据
1860
+ */
1861
+ this._clearLiveData = () => {
1862
+ this._buildInData = { keyframes: {} };
1863
+ };
1864
+ /**
1865
+ * 连接带看
1866
+ * @param options
1867
+ * @returns
1868
+ */
1869
+ this.connect = (options = {}) => __awaiter(this, void 0, void 0, function* () {
1870
+ var _h, _j, _k, _l;
1871
+ // 检查 url 和 票据获取接口实现
1872
+ this._options.url = (_j = (_h = options.url) !== null && _h !== void 0 ? _h : this._options.url) !== null && _j !== void 0 ? _j : '';
1873
+ this._options.getTicket = (_k = options.getTicket) !== null && _k !== void 0 ? _k : this._options.getTicket;
1874
+ this._options.initialMicroStatus =
1875
+ (_l = options.rtcMicStatus) !== null && _l !== void 0 ? _l : this._options.initialMicroStatus;
1876
+ if (!/^ws(s):\/\//.test(this._options.url) ||
1877
+ typeof this._options.getTicket !== 'function') {
1878
+ if (!/^ws(s):\/\//.test(this._options.url)) {
1879
+ return new Error('Illegal realsee live room link');
1880
+ }
1881
+ if (typeof this._options.getTicket !== 'function') {
1882
+ return new Error('getTicket muse be function');
1883
+ }
1884
+ return false;
1574
1885
  }
1575
- // 默认自动连接
1576
- if (liveController.options.url && liveController.options.getTicket) {
1577
- _this.connect();
1886
+ const { force = false } = options;
1887
+ // 检测一下麦克风权限,hack
1888
+ if (this._options.rtc && this._options.jsBridge) {
1889
+ const res = yield this._options.jsBridge.detectMicro();
1890
+ if (!res) {
1891
+ return new Error('Failed to obtain microphone authorization');
1892
+ }
1578
1893
  }
1579
- // 健康检查:WHY --> 在某些WebView特殊场景下 WebSocket.readyState 发生变化时不会出发error\close等事件;
1580
- // 因此,开启一个定时任务监测 WebSocket.readyState 状态的更新
1581
- var healthCheck = (function (healthCheck) {
1582
- if (!healthCheck)
1583
- return 0;
1584
- if (healthCheck === true)
1585
- return 3000;
1586
- var duration = Number(healthCheck);
1587
- if (duration > 0)
1588
- return duration;
1589
- return 3000;
1590
- })(liveController.options.healthCheck);
1591
- if (healthCheck) {
1592
- liveController.healthCheckId = setInterval(function () { return liveController.checkReadyState(_this); }, healthCheck);
1894
+ // 检查是否已有实例在使用
1895
+ const currentState = this.state;
1896
+ if (currentState === exports.LiveState.CONNECTING ||
1897
+ currentState === exports.LiveState.OPEN) {
1898
+ if (force) {
1899
+ try {
1900
+ yield this._controller.close('force close by connect');
1901
+ }
1902
+ catch (e) {
1903
+ console.warn(e);
1904
+ }
1905
+ }
1906
+ else {
1907
+ return new Error('已有Live实例正在连接中,请勿重复连接!');
1908
+ }
1593
1909
  }
1594
- return _this;
1595
- }
1596
- Object.defineProperty(LiveTpl.prototype, "options", {
1597
- get: function () {
1598
- return Object.freeze(Object.assign({}, liveController.options));
1599
- },
1600
- enumerable: false,
1601
- configurable: true
1602
- });
1603
- Object.defineProperty(LiveTpl.prototype, "readyState", {
1604
- get: function () {
1605
- liveController.checkReadyState(this);
1606
- return liveController.readyState;
1607
- },
1608
- enumerable: false,
1609
- configurable: true
1910
+ // 建立连接
1911
+ this._clearLiveData();
1912
+ const url = appendUri(this._options.url, {
1913
+ ticket: yield this._options.getTicket(),
1914
+ force: Number(!!force),
1915
+ });
1916
+ this._controller.open(url);
1917
+ return true;
1610
1918
  });
1611
- Object.defineProperty(LiveTpl.prototype, "url", {
1612
- get: function () {
1613
- var _a;
1614
- return ((_a = liveController.webSocket) === null || _a === void 0 ? void 0 : _a.url) || '';
1615
- },
1616
- enumerable: false,
1617
- configurable: true
1919
+ /**
1920
+ * 退出带看
1921
+ * @returns
1922
+ */
1923
+ this.exit = () => __awaiter(this, void 0, void 0, function* () {
1924
+ var _m;
1925
+ this._clearLiveData();
1926
+ try {
1927
+ /** 退出强制关闭语音 */
1928
+ (_m = this.$RTC) === null || _m === void 0 ? void 0 : _m.quit();
1929
+ yield this.updateStatus(exports.BuiltinEventType.RoomChange, exports.BuiltinActionType.RoomClose, {});
1930
+ }
1931
+ catch (e) {
1932
+ logger$1.warn(e);
1933
+ }
1934
+ return yield this._controller.close('user exit');
1618
1935
  });
1619
- Object.defineProperty(LiveTpl.prototype, "selfInfo", {
1620
- get: function () {
1621
- return liveController.selfUserInfo;
1622
- },
1623
- enumerable: false,
1624
- configurable: true
1936
+ /**
1937
+ * 销毁带看
1938
+ * @returns
1939
+ */
1940
+ this.dispose = () => __awaiter(this, void 0, void 0, function* () {
1941
+ this._removeLiveControllerEventListeners();
1942
+ this._clearLiveData();
1943
+ return yield this._controller.dispose();
1625
1944
  });
1626
- Object.defineProperty(LiveTpl.prototype, "userList", {
1627
- get: function () {
1628
- return liveController.userList || [];
1629
- },
1630
- enumerable: false,
1631
- configurable: true
1945
+ /**
1946
+ * 设置自己的用户信息
1947
+ * @param userInfo
1948
+ * @returns
1949
+ */
1950
+ this.setSelfInfo = (userInfo) => __awaiter(this, void 0, void 0, function* () {
1951
+ return yield this.updateStatus(exports.BuiltinEventType.UserChange, exports.BuiltinActionType.UserInfo, userInfo);
1632
1952
  });
1633
- Object.defineProperty(LiveTpl.prototype, "snapshot", {
1634
- get: function () {
1635
- return liveController.keyframes || {};
1636
- },
1637
- enumerable: false,
1638
- configurable: true
1953
+ // 仅用于用户自己的麦克风控制
1954
+ this.toggleMicro = (microStatus) => __awaiter(this, void 0, void 0, function* () {
1955
+ var _o, _p, _q;
1956
+ if (!((_p = (_o = this.selfInfo) === null || _o === void 0 ? void 0 : _o.permission) === null || _p === void 0 ? void 0 : _p.control_own_micro))
1957
+ return false;
1958
+ const result = yield ((_q = this.$RTC) === null || _q === void 0 ? void 0 : _q.toggleMicro(microStatus));
1959
+ if (result) {
1960
+ yield this.updateStatus(exports.BuiltinEventType.UserChange, exports.BuiltinActionType.UserMicroStatus, {
1961
+ status: microStatus ? exports.MicroStatus.OPEN : exports.MicroStatus.CLOSE,
1962
+ }, []);
1963
+ }
1964
+ return result;
1639
1965
  });
1640
- Object.defineProperty(LiveTpl.prototype, "$RTC", {
1641
- get: function () {
1642
- return liveController.options.rtc;
1643
- },
1644
- enumerable: false,
1645
- configurable: true
1966
+ /**
1967
+ * 控制别人的麦
1968
+ * @param microStatus
1969
+ * @param toUserIds
1970
+ * @returns
1971
+ */
1972
+ this.forbidMicro = (microStatus, toUserIds) => __awaiter(this, void 0, void 0, function* () {
1973
+ var _r, _s;
1974
+ if (typeof this._options.canForbidUserMicro === 'function' &&
1975
+ !this._options.canForbidUserMicro(toUserIds)) {
1976
+ return false;
1977
+ }
1978
+ if (!((_s = (_r = this.selfInfo) === null || _r === void 0 ? void 0 : _r.permission) === null || _s === void 0 ? void 0 : _s.control_other_micro)) {
1979
+ return false;
1980
+ }
1981
+ return yield this.updateStatus(exports.BuiltinEventType.UserChange, exports.BuiltinActionType.UserMicroStatus, {
1982
+ status: microStatus,
1983
+ }, toUserIds);
1646
1984
  });
1647
- Object.defineProperty(LiveTpl.prototype, "jsBridge", {
1648
- get: function () {
1649
- return liveController.options.jsBridge;
1650
- },
1651
- enumerable: false,
1652
- configurable: true
1985
+ /**
1986
+ * 控制别人的同步全量帧数据权限
1987
+ * @param sync
1988
+ * @param toUserIds
1989
+ * @returns
1990
+ */
1991
+ this.forbidSync = (sync, toUserIds) => __awaiter(this, void 0, void 0, function* () {
1992
+ var _t, _u;
1993
+ if (typeof this._options.canForbidUserSync === 'function' &&
1994
+ !this._options.canForbidUserSync(toUserIds)) {
1995
+ return false;
1996
+ }
1997
+ if (!((_u = (_t = this.selfInfo) === null || _t === void 0 ? void 0 : _t.permission) === null || _u === void 0 ? void 0 : _u.control_other_sync)) {
1998
+ return false;
1999
+ }
2000
+ return yield this.updateStatus(exports.BuiltinEventType.UserChange, exports.BuiltinActionType.UserPermission, { sync_frame: sync }, toUserIds);
1653
2001
  });
1654
- LiveTpl.prototype.setSelfInfo = function (userInfo) {
1655
- return __awaiter(this, void 0, void 0, function () {
1656
- var error_1;
1657
- return __generator(this, function (_a) {
1658
- switch (_a.label) {
1659
- case 0:
1660
- if (this.readyState !== exports.WebSocketState.OPEN) {
1661
- return [2 /*return*/, new Error('The connection is not open and ready to communicate.')];
1662
- }
1663
- _a.label = 1;
1664
- case 1:
1665
- _a.trys.push([1, 3, , 4]);
1666
- return [4 /*yield*/, this.updateStatus(exports.BuiltinEventType.UserChange, exports.BuiltinActionType.UserInfo, userInfo)];
1667
- case 2: return [2 /*return*/, _a.sent()];
1668
- case 3:
1669
- error_1 = _a.sent();
1670
- return [2 /*return*/, error_1];
1671
- case 4: return [2 /*return*/];
1672
- }
1673
- });
1674
- });
1675
- };
1676
- LiveTpl.prototype.getFramesByKey = function (key) {
1677
- return liveController.keyframes[key];
1678
- };
1679
- LiveTpl.prototype.sendKeyframe = function (key, frame) {
1680
- if (this.readyState !== exports.WebSocketState.OPEN) {
1681
- return new Error('The connection is not open and ready to communicate.');
2002
+ /**
2003
+ * 把用户踢出带看
2004
+ * @param toUserIds
2005
+ * @returns
2006
+ */
2007
+ this.kick = (toUserIds) => __awaiter(this, void 0, void 0, function* () {
2008
+ var _v, _w;
2009
+ if (typeof this._options.canForbidUserKick === 'function' &&
2010
+ !this._options.canForbidUserKick(toUserIds)) {
2011
+ return false;
1682
2012
  }
1683
- liveController.keyframes[key] = frame;
1684
- var liveMsg = createLiveMsg(exports.Command.KeyframeSync, this.snapshot);
1685
- liveController.sendMessage(liveMsg);
1686
- return true;
1687
- };
1688
- LiveTpl.prototype.broadcast = function (data, toUserIds, timeout) {
1689
- var _this = this;
1690
- if (this.readyState !== exports.WebSocketState.OPEN) {
1691
- return new Error('The connection is not open and ready to communicate.');
2013
+ if (!((_w = (_v = this.selfInfo) === null || _v === void 0 ? void 0 : _v.permission) === null || _w === void 0 ? void 0 : _w.change_other_status)) {
2014
+ return false;
1692
2015
  }
1693
- return new Promise(function (resolve, reject) {
1694
- var customEvent = createLiveMsg(exports.Command.CustomEvent, data, toUserIds);
1695
- var front_request_id = customEvent.front_request_id;
1696
- liveController.sendMessage(customEvent);
1697
- var timeoutId = timeout
1698
- ? setTimeout(function () {
1699
- reject(new Error('RESPONSE TIMEOUT'));
1700
- _this.off('broadcast', broadcast);
1701
- }, timeout)
1702
- : undefined;
1703
- var broadcast = function (data, frontRequestId) {
1704
- if (frontRequestId !== front_request_id)
1705
- return;
1706
- _this.off('broadcast', broadcast);
1707
- resolve(data);
1708
- if (timeoutId)
1709
- clearInterval(timeoutId);
1710
- };
1711
- _this.on('broadcast', broadcast);
1712
- });
1713
- };
1714
- LiveTpl.prototype.updateStatus = function (evtType, atnType, status, toUserIds) {
1715
- return __awaiter(this, void 0, void 0, function () {
1716
- var data, liveMsg;
1717
- return __generator(this, function (_a) {
1718
- // TODO 统一规则,不能联合类型
1719
- if (this.readyState !== exports.WebSocketState.OPEN) {
1720
- return [2 /*return*/, false];
1721
- }
1722
- data = Object.assign({ event_type: evtType, action: atnType }, { data: status });
1723
- liveMsg = createLiveMsg(exports.Command.BuiltinMsg, data, toUserIds);
1724
- liveController.sendMessage(liveMsg);
1725
- return [2 /*return*/, true];
1726
- });
1727
- });
1728
- };
1729
- // 仅用于用户自己的麦克风控制
1730
- LiveTpl.prototype.toggleMicro = function (microStatus) {
1731
- var _a, _b;
1732
- return __awaiter(this, void 0, void 0, function () {
1733
- return __generator(this, function (_c) {
1734
- switch (_c.label) {
1735
- case 0:
1736
- if (!((_b = (_a = this.selfInfo) === null || _a === void 0 ? void 0 : _a.permission) === null || _b === void 0 ? void 0 : _b.control_own_micro))
1737
- return [2 /*return*/, false];
1738
- return [4 /*yield*/, this.$RTC.toggleMicro(microStatus)];
1739
- case 1:
1740
- _c.sent();
1741
- return [4 /*yield*/, this.updateStatus(exports.BuiltinEventType.UserChange, exports.BuiltinActionType.UserMicroStatus, {
1742
- status: microStatus ? exports.MicroStatus.OPEN : exports.MicroStatus.CLOSE,
1743
- }, [])];
1744
- case 2: return [2 /*return*/, _c.sent()];
2016
+ return yield this.updateStatus(exports.BuiltinEventType.UserChange, exports.BuiltinActionType.UserStatus, {
2017
+ status: 'KICK_OUT',
2018
+ }, toUserIds);
2019
+ });
2020
+ this._addLiveControllerEventListeners();
2021
+ this._options = Object.assign({ initialMicroStatus: exports.MicroStatus.OPEN }, opts);
2022
+ // 第一步检查jsbridge
2023
+ this._options.jsBridge = (() => {
2024
+ if (opts.jsBridge)
2025
+ return opts.jsBridge;
2026
+ if (opts.useBuiltInJsBridge)
2027
+ return new JSBridge__default["default"]();
2028
+ return undefined;
2029
+ })();
2030
+ // 第二步检查getVoiceSign
2031
+ this._options.getVoiceSign = (_a = opts.getVoiceSign) !== null && _a !== void 0 ? _a : unimplementedGetVoiceSign;
2032
+ // 第二步检查rtc
2033
+ this._options.rtc = (() => {
2034
+ // 优先取rtc实例
2035
+ if (opts.rtc)
2036
+ return opts.rtc;
2037
+ // 取指定的内部rtc类型
2038
+ if (opts.rtcType) {
2039
+ if (!opts.getVoiceSign) {
2040
+ logger$1.error('GetVoiceSign method must be passed when using built-in RTC instances');
2041
+ }
2042
+ switch (opts.rtcType) {
2043
+ case exports.RTCType.RealseeVRWebViewRTC: {
2044
+ // 内置的 VRWebViewRTC
2045
+ if (this._options.jsBridge) {
2046
+ return new VRWebViewRTC({
2047
+ jsBridge: this._options.jsBridge,
2048
+ getVoiceSign: this._options.getVoiceSign,
2049
+ });
2050
+ }
2051
+ else {
2052
+ logger$1.error('JsBridge instance must be passed when using built-in VRWebViewRTC instances');
2053
+ return undefined;
2054
+ }
1745
2055
  }
1746
- });
1747
- });
1748
- };
1749
- LiveTpl.prototype.forbidMicro = function (microStatus, toUserIds) {
1750
- var _a, _b;
1751
- return __awaiter(this, void 0, void 0, function () {
1752
- return __generator(this, function (_c) {
1753
- switch (_c.label) {
1754
- case 0:
1755
- if (liveController.options.canForbidUserMicro &&
1756
- !liveController.options.canForbidUserMicro(toUserIds)) {
1757
- return [2 /*return*/, false];
1758
- }
1759
- if (!((_b = (_a = this.selfInfo) === null || _a === void 0 ? void 0 : _a.permission) === null || _b === void 0 ? void 0 : _b.control_other_micro)) {
1760
- return [2 /*return*/, false];
1761
- }
1762
- return [4 /*yield*/, this.updateStatus(exports.BuiltinEventType.UserChange, exports.BuiltinActionType.UserMicroStatus, {
1763
- status: microStatus,
1764
- }, toUserIds)];
1765
- case 1: return [2 /*return*/, _c.sent()];
2056
+ case exports.RTCType.RealseeBrowserChimeRTC: {
2057
+ // 内置的 RealseeBrowserChimeRTC
2058
+ return new BrowserRTC4Chime({
2059
+ getVoiceSign: this._options.getVoiceSign,
2060
+ logLevel: opts.__debug__ ? LogLevel.DEBUG : LogLevel.ERROR,
2061
+ });
1766
2062
  }
1767
- });
1768
- });
1769
- };
1770
- /**
1771
- * @deprecated 暂不可用
1772
- */
1773
- LiveTpl.prototype.forbidSync = function (sync, toUserIds) {
1774
- var _a, _b;
1775
- return __awaiter(this, void 0, void 0, function () {
1776
- return __generator(this, function (_c) {
1777
- switch (_c.label) {
1778
- case 0:
1779
- if (liveController.options.canForbidUserSync &&
1780
- !liveController.options.canForbidUserSync(toUserIds)) {
1781
- return [2 /*return*/, false];
1782
- }
1783
- if (!((_b = (_a = this.selfInfo) === null || _a === void 0 ? void 0 : _a.permission) === null || _b === void 0 ? void 0 : _b.control_other_sync)) {
1784
- return [2 /*return*/, false];
1785
- }
1786
- return [4 /*yield*/, this.updateStatus(exports.BuiltinEventType.UserChange, exports.BuiltinActionType.UserPermission, { sync_frame: sync }, toUserIds)];
1787
- case 1: return [2 /*return*/, _c.sent()];
2063
+ case exports.RTCType.RealseeBrowserRTC: {
2064
+ // 内置的 RealseeBrowserRTC
2065
+ return new BrowserRTC({
2066
+ getVoiceSign: this._options.getVoiceSign,
2067
+ });
1788
2068
  }
1789
- });
1790
- });
1791
- };
1792
- LiveTpl.prototype.kick = function (toUserIds) {
1793
- var _a, _b;
1794
- return __awaiter(this, void 0, void 0, function () {
1795
- return __generator(this, function (_c) {
1796
- switch (_c.label) {
1797
- case 0:
1798
- if (liveController.options.canForbidUserKick &&
1799
- !liveController.options.canForbidUserKick(toUserIds)) {
1800
- return [2 /*return*/, false];
1801
- }
1802
- if (!((_b = (_a = this.selfInfo) === null || _a === void 0 ? void 0 : _a.permission) === null || _b === void 0 ? void 0 : _b.change_other_status)) {
1803
- return [2 /*return*/, false];
1804
- }
1805
- return [4 /*yield*/, this.updateStatus(exports.BuiltinEventType.UserChange, exports.BuiltinActionType.UserStatus, {
1806
- status: 'KICK_OUT',
1807
- }, toUserIds)];
1808
- case 1: return [2 /*return*/, _c.sent()];
2069
+ default: {
2070
+ logger$1.error('unknown built-in RTC type');
2071
+ return undefined;
1809
2072
  }
1810
- });
1811
- });
1812
- };
1813
- LiveTpl.prototype.exit = function () {
1814
- return __awaiter(this, void 0, void 0, function () {
1815
- var e_1;
1816
- return __generator(this, function (_a) {
1817
- switch (_a.label) {
1818
- case 0:
1819
- _a.trys.push([0, 2, , 3]);
1820
- this.$RTC.quit();
1821
- return [4 /*yield*/, this.updateStatus(exports.BuiltinEventType.RoomChange, exports.BuiltinActionType.RoomClose, {})];
1822
- case 1:
1823
- _a.sent();
1824
- return [3 /*break*/, 3];
1825
- case 2:
1826
- e_1 = _a.sent();
1827
- console.log(e_1);
1828
- return [3 /*break*/, 3];
1829
- case 3: return [2 /*return*/, liveController.dispose()];
2073
+ }
2074
+ }
2075
+ // 都不满足时取内置
2076
+ if (opts.useBuiltInRTC) {
2077
+ if (!opts.getVoiceSign) {
2078
+ logger$1.error('GetVoiceSign method must be passed when using built-in RTC instances');
2079
+ }
2080
+ if (this._options.jsBridge) {
2081
+ if ((isRealseeVRWebview && (isAndroid || isIOS)) || isWxMiniProgram) {
2082
+ return new VRWebViewRTC({
2083
+ jsBridge: this._options.jsBridge,
2084
+ getVoiceSign: this._options.getVoiceSign,
2085
+ });
1830
2086
  }
1831
- });
1832
- });
1833
- };
1834
- LiveTpl.prototype.connect = function (options) {
1835
- if (options === void 0) { options = {}; }
1836
- return __awaiter(this, void 0, void 0, function () {
1837
- var microAuth, error, error, force, error, error, url, _a, _b, _c;
1838
- var _d;
1839
- var _this = this;
1840
- return __generator(this, function (_e) {
1841
- switch (_e.label) {
1842
- case 0: return [4 /*yield*/, this.$RTC.detectMicro()];
1843
- case 1:
1844
- microAuth = _e.sent();
1845
- if (!microAuth) {
1846
- error = new Error('系统监测麦克风未授权~');
1847
- this.emit('ws.error', { type: exports.WebSocketErrorType.MicroAuth, error: error });
1848
- return [2 /*return*/, error];
1849
- }
1850
- // WebSocket 正在连接中,规避重复连接
1851
- if (liveController.connecting) {
1852
- error = new Error('WebSocket 正在连接中,请勿重复连接 ...');
1853
- this.emit('ws.error', {
1854
- type: exports.WebSocketErrorType.DuplicateConnect,
1855
- error: error,
1856
- });
1857
- return [2 /*return*/, error];
1858
- }
1859
- force = options.force;
1860
- if (!force) {
1861
- if (this.readyState === exports.WebSocketState.CONNECTING ||
1862
- this.readyState === exports.WebSocketState.OPEN) {
1863
- return [2 /*return*/, true];
1864
- }
1865
- }
1866
- // WebSocket URL 逻辑
1867
- if (options.url) {
1868
- liveController.options.url = options.url;
1869
- }
1870
- if (options.getTicket) {
1871
- liveController.options.getTicket = options.getTicket;
1872
- }
1873
- if (!liveController.options.url ||
1874
- !liveController.options.url.startsWith('ws')) {
1875
- error = new Error("WebSocket URL \u672A\u914D\u7F6E\u6216\u683C\u5F0F\u4E0D\u5408\u6CD5\uFF1A\"".concat(liveController.options.url, "\""));
1876
- this.emit('ws.error', { type: exports.WebSocketErrorType.IllegalURL, error: error });
1877
- return [2 /*return*/, error];
1878
- }
1879
- if (!liveController.options.getTicket) {
1880
- error = new Error("getTicket() \u672A\u914D\u7F6E!");
1881
- this.emit('ws.error', { type: exports.WebSocketErrorType.IllegalArgs, error: error });
1882
- return [2 /*return*/, error];
1883
- }
1884
- // 连接锁
1885
- liveController.connecting = true;
1886
- // 连接前销毁之前绑定的事件
1887
- liveController.disposeWebSocket();
1888
- this.emit('ws.beforeConnect');
1889
- if (!(force || options.url || !this.url)) return [3 /*break*/, 3];
1890
- _b = appendUri;
1891
- _c = [liveController.options.url];
1892
- _d = {};
1893
- return [4 /*yield*/, liveController.options.getTicket()];
1894
- case 2:
1895
- _a = _b.apply(void 0, _c.concat([(_d.ticket = _e.sent(),
1896
- _d.force = Number(!!force),
1897
- _d)]));
1898
- return [3 /*break*/, 4];
1899
- case 3:
1900
- _a = this.url;
1901
- _e.label = 4;
1902
- case 4:
1903
- url = _a;
1904
- liveController.webSocket = new WebSocket(url);
1905
- liveController.onEvtOpnListener = function () {
1906
- liveController.checkReadyState(_this);
1907
- _this.emit('ws.afterConnect');
1908
- };
1909
- liveController.onEvtMsgListener = function (evt) {
1910
- liveController.checkReadyState(_this);
1911
- try {
1912
- var liveMsg = parseLiveMsg(evt.data);
1913
- if (liveMsg === false)
1914
- return;
1915
- liveController.handleMessage(liveMsg, _this);
1916
- }
1917
- catch (error) {
1918
- // 未知错误
1919
- _this.emit('ws.error', {
1920
- type: exports.WebSocketErrorType.Unknown,
1921
- error: error,
1922
- target: evt,
1923
- });
1924
- }
1925
- };
1926
- liveController.onEvtErrListener = function (evt) {
1927
- live.emit('ws.error', { type: exports.WebSocketErrorType.Error, target: evt });
1928
- liveController.checkReadyState(_this);
1929
- };
1930
- liveController.onEvtCLEListener = function (evt) {
1931
- liveController.checkReadyState(_this);
1932
- var code = Number(evt.code);
1933
- if (code === 1000)
1934
- return;
1935
- // 异常退出不一定会触发'error'事件,根据 evt.code 一些类型的退出也算是 error 行为
1936
- var errMsg = parseWSClsErr(code);
1937
- live.emit('ws.error', {
1938
- target: evt,
1939
- type: exports.WebSocketErrorType.Close,
1940
- closeError: errMsg,
1941
- });
1942
- };
1943
- liveController.webSocket.addEventListener('open', liveController.onEvtOpnListener);
1944
- liveController.webSocket.addEventListener('message', liveController.onEvtMsgListener);
1945
- liveController.webSocket.addEventListener('error', liveController.onEvtErrListener);
1946
- liveController.webSocket.addEventListener('close', liveController.onEvtCLEListener);
1947
- return [4 /*yield*/, new Promise(function (resolve, reject) {
1948
- var success = function () {
1949
- resolve(true);
1950
- liveController.connecting = false;
1951
- _this.off('ws.error', fail);
1952
- };
1953
- var fail = function (error) {
1954
- reject(error.error
1955
- ? error.error
1956
- : new Error('WebSocket connection failed!'));
1957
- liveController.connecting = false;
1958
- _this.off('ws.afterConnect', success);
1959
- };
1960
- _this.once('ws.afterConnect', success);
1961
- _this.once('ws.error', fail);
1962
- })];
1963
- case 5: return [2 /*return*/, _e.sent()];
2087
+ else {
2088
+ // 其它终端使用
2089
+ return opts.builtInRTCType === exports.BuiltInRTCType.RealseeXChimeRTC
2090
+ ? new BrowserRTC4Chime({
2091
+ getVoiceSign: this._options.getVoiceSign,
2092
+ })
2093
+ : new BrowserRTC({ getVoiceSign: this._options.getVoiceSign });
1964
2094
  }
1965
- });
1966
- });
1967
- };
1968
- LiveTpl.prototype.revoke = function () {
1969
- return __awaiter(this, void 0, void 0, function () {
1970
- return __generator(this, function (_a) {
1971
- return [2 /*return*/, true];
1972
- });
1973
- });
1974
- };
1975
- return LiveTpl;
1976
- }(Subscribe));
1977
- var live = new LiveTpl();
1978
- // 如果是调试环境则将内部状态暴露出来
1979
- if (options.__debug__) {
1980
- Object.assign(live, { __controller__: liveController });
1981
- Object.assign(window, { $live: live });
1982
- }
1983
- return live;
2095
+ }
2096
+ else {
2097
+ logger$1.error('jsBridge instance must be passed when using built-in RTC instances');
2098
+ return undefined;
2099
+ }
2100
+ }
2101
+ return undefined;
2102
+ })();
2103
+ if (!this._options.rtc) {
2104
+ logger$1.warn('unused rtc');
2105
+ }
2106
+ // 第三步进行自动连接
2107
+ if (this._options.url && this._options.getTicket) {
2108
+ this.connect();
2109
+ }
2110
+ if (this._options.__debug__) {
2111
+ Object.assign(window, { $liveController: this._controller, $live: this });
2112
+ }
2113
+ }
2114
+ get options() {
2115
+ return Object.freeze(this._options || {});
2116
+ }
2117
+ /**
2118
+ * 带看状态
2119
+ */
2120
+ get state() {
2121
+ return this._controller.state;
2122
+ }
2123
+ /**
2124
+ * 兼容老逻辑
2125
+ * @deprecated 请直接读取 state 属性字段,未来将移除该属性
2126
+ */
2127
+ get readyState() {
2128
+ return this._controller.state;
2129
+ }
2130
+ /**
2131
+ * 获取当前WebSocket连接的URL。(注意:这个是WebSocket连接的完整连接,附带一些query参数)。
2132
+ * @deprecated 带看不需要关注底层ws的相关信息,未来将移除
2133
+ */
2134
+ get url() {
2135
+ return this.options.url;
2136
+ }
2137
+ /**
2138
+ * 获取当前live使用的RTC实例
2139
+ */
2140
+ get $RTC() {
2141
+ return this._options.rtc;
2142
+ }
2143
+ /**
2144
+ * 获取当前live使用的jsBridge实例
2145
+ */
2146
+ get jsBridge() {
2147
+ return this._options.jsBridge;
2148
+ }
2149
+ /**
2150
+ * 当前帧数据快照
2151
+ */
2152
+ get snapshot() {
2153
+ return this._buildInData.keyframes;
2154
+ }
2155
+ /**
2156
+ * 当前用户信息
2157
+ */
2158
+ get selfInfo() {
2159
+ return this._buildInData.selfInfo;
2160
+ }
2161
+ /**
2162
+ * 当前用户列表
2163
+ */
2164
+ get userList() {
2165
+ return this._buildInData.userList || [];
2166
+ }
2167
+ /**
2168
+ * 当前带看房间信息
2169
+ */
2170
+ get roomInfo() {
2171
+ return this._buildInData.roomInfo;
2172
+ }
2173
+ /**
2174
+ * 修改状态
2175
+ * @param evtType
2176
+ * @param atnType
2177
+ * @param status
2178
+ * @param toUserIds
2179
+ * @returns
2180
+ */
2181
+ updateStatus(evtType, atnType, status, toUserIds) {
2182
+ return __awaiter(this, void 0, void 0, function* () {
2183
+ if (this.state !== exports.LiveState.OPEN)
2184
+ return false;
2185
+ const data = Object.assign({ event_type: evtType, action: atnType }, { data: status });
2186
+ const liveMsg = createLiveMsg(exports.Command.BuiltinMsg, data, toUserIds);
2187
+ try {
2188
+ this._controller.sendMessage(liveMsg);
2189
+ return true;
2190
+ }
2191
+ catch (e) {
2192
+ logger$1.error(e);
2193
+ return false;
2194
+ }
2195
+ });
2196
+ }
2197
+ /**
2198
+ * 自定义广播
2199
+ * @param request 广播请求的数据
2200
+ * @param toUserIds
2201
+ * @param timeout
2202
+ * @returns
2203
+ */
2204
+ broadcast(request, toUserIds, timeout) {
2205
+ if (this.state !== exports.LiveState.OPEN)
2206
+ return false;
2207
+ return new Promise((resolve, reject) => {
2208
+ const customEvent = createLiveMsg(exports.Command.CustomEvent, request, toUserIds);
2209
+ const front_request_id = customEvent.front_request_id;
2210
+ const timeoutId = timeout
2211
+ ? setTimeout(() => {
2212
+ reject(new Error('RESPONSE TIMEOUT'));
2213
+ this.off('broadcast', broadcastRes);
2214
+ }, timeout)
2215
+ : undefined;
2216
+ const broadcastRes = (data, frontRequestId) => {
2217
+ if (frontRequestId !== front_request_id)
2218
+ return;
2219
+ if (timeoutId)
2220
+ clearTimeout(timeoutId);
2221
+ this.off('broadcast', broadcastRes);
2222
+ resolve(data);
2223
+ };
2224
+ this.on('broadcast', broadcastRes);
2225
+ try {
2226
+ this._controller.sendMessage(customEvent);
2227
+ }
2228
+ catch (e) {
2229
+ reject(e);
2230
+ }
2231
+ });
2232
+ }
1984
2233
  }
1985
2234
 
2235
+ /**
2236
+ * 创建`Live`实例
2237
+ * @param opts
2238
+ * @returns
2239
+ */
2240
+ const createLive = (opts) => {
2241
+ _clearLiveInstanceIfNeed();
2242
+ return new Live(opts);
2243
+ };
2244
+
1986
2245
  /**
1987
2246
  * 创建 {@link LiveReact} 实例,并提供 `React` 技术栈相关工具链。
1988
2247
  */
1989
2248
  function createLiveReact(options) {
1990
- var LiveContext = React__default["default"].createContext(null);
1991
- var live = createLive(options);
1992
- var jsBridge = live.jsBridge;
1993
- function LiveProvider(props) {
1994
- return (React__default["default"].createElement(LiveContext.Provider, { value: props.live || live }, props.children));
1995
- }
1996
- function useLiveInstance() {
1997
- var context = React__default["default"].useContext(LiveContext);
2249
+ const LiveContext = React.createContext(null);
2250
+ const live = createLive(options);
2251
+ const jsBridge = live.jsBridge;
2252
+ const LiveProvider = (props) => (React__default["default"].createElement(LiveContext.Provider, { value: live }, props.children));
2253
+ /**
2254
+ * 使用live实例
2255
+ * @returns
2256
+ */
2257
+ const useLiveInstance = () => {
2258
+ const context = React__default["default"].useContext(LiveContext);
1998
2259
  if (!context)
1999
2260
  throw new Error('LiveProvider never found.');
2000
2261
  return context;
2001
- }
2262
+ };
2002
2263
  /**
2264
+ * 不建议这样使用
2003
2265
  * @deprecated
2004
2266
  * @returns
2005
2267
  */
2006
- function unsafe__useLiveInstance() {
2007
- return useLiveInstance();
2008
- }
2009
- function useRTCInstance() {
2010
- var live = useLiveInstance();
2011
- return live.$RTC;
2012
- }
2268
+ const unsafe__useLiveInstance = () => useLiveInstance();
2013
2269
  /**
2270
+ * 使用rtc实例
2271
+ */
2272
+ const useRTCInstance = () => useLiveInstance().$RTC;
2273
+ /**
2274
+ * 不建议这样使用
2014
2275
  * @deprecated
2015
2276
  * @returns
2016
2277
  */
2017
- function unsafe__useRTCInstance() {
2018
- return useRTCInstance();
2019
- }
2020
- function useConnect() {
2021
- var _this = this;
2022
- var live = useLiveInstance();
2023
- return function (options) { return __awaiter(_this, void 0, void 0, function () { return __generator(this, function (_a) {
2024
- switch (_a.label) {
2025
- case 0: return [4 /*yield*/, live.connect(options)];
2026
- case 1: return [2 /*return*/, _a.sent()];
2027
- }
2028
- }); }); };
2029
- }
2030
- function useCurrentWebSocketUrl() {
2031
- var live = useLiveInstance();
2032
- var _a = React__default["default"].useState(undefined), state = _a[0], setState = _a[1];
2033
- React__default["default"].useEffect(function () {
2034
- var onWSBeforeConnect = function () { return setState(live.url); };
2035
- live.on('ws.beforeConnect', onWSBeforeConnect);
2036
- return function () { return live.off('ws.beforeConnect', onWSBeforeConnect); };
2037
- }, [live]);
2038
- return state;
2039
- }
2040
- function useKeyframeUpdateCallback(name, callback, deps) {
2041
- if (deps === void 0) { deps = []; }
2042
- var live = useLiveInstance();
2043
- var dependencyList = __spreadArray([live, name], deps, true);
2044
- var dispose = function () { return live.keyframes.off(name, callback); };
2045
- React__default["default"].useEffect(function () {
2046
- live.keyframes.on(name, callback);
2278
+ const unsafe__useRTCInstance = () => useRTCInstance();
2279
+ /**
2280
+ * 带看连接操作
2281
+ */
2282
+ const useConnect = (options) => __awaiter(this, void 0, void 0, function* () { return yield useLiveInstance().connect(options); });
2283
+ /**
2284
+ *
2285
+ * @param name
2286
+ * @param callback
2287
+ * @param deps
2288
+ * @returns
2289
+ */
2290
+ function useKeyframeUpdateCallback(key, callback, deps = []) {
2291
+ const live = useLiveInstance();
2292
+ const dependencyList = [live, name, ...deps];
2293
+ const dispose = () => live.keyframes.off(key, callback);
2294
+ React__default["default"].useEffect(() => {
2295
+ live.keyframes.on(key, callback);
2047
2296
  return dispose;
2048
2297
  }, dependencyList);
2049
2298
  return dispose;
2050
2299
  }
2300
+ /**
2301
+ * 带看的一些操作
2302
+ * @returns
2303
+ */
2051
2304
  function useLiveAction() {
2052
- var live = useLiveInstance();
2053
- var toggleMicro = React__default["default"].useCallback(function (microStatus) { return live.toggleMicro(microStatus); }, [live]);
2054
- var broadcast = React__default["default"].useCallback(function (data, toUserIds, timeout) {
2055
- if (timeout === void 0) { timeout = 0; }
2056
- return live.broadcast(data, toUserIds, timeout);
2057
- }, [live]);
2058
- var exit = React__default["default"].useCallback(function () { return live.exit(); }, [live]);
2059
- var kick = React__default["default"].useCallback(function (toUserIds) { return live.kick(toUserIds); }, [live]);
2060
- var forbidMicro = React__default["default"].useCallback(function (micro, toUserIds) {
2061
- return live.forbidMicro(micro, toUserIds);
2062
- }, [live]);
2063
- // const forbidSync = React.useCallback(
2064
- // (sync: boolean, toUserIds?: string | string[] | undefined) =>
2065
- // live.forbidSync(sync, toUserIds),
2066
- // [live],
2067
- // );
2068
- var getFramesByKey = React__default["default"].useCallback(function (key) { return live.getFramesByKey(key); }, [live]);
2069
- var sendKeyframe = React__default["default"].useCallback(function (key, frame) {
2070
- return live.sendKeyframe(key, frame);
2071
- }, [live]);
2072
- var setSelfInfo = React__default["default"].useCallback(function (userInfo) { return live.setSelfInfo(userInfo); }, [live]);
2073
- var updateStatus = React__default["default"].useCallback(function (evtType, atnType, status, toUserIds) { return live.updateStatus(evtType, atnType, status, toUserIds); }, [live]);
2305
+ const live = useLiveInstance();
2306
+ const connect = React__default["default"].useCallback((options) => __awaiter(this, void 0, void 0, function* () { return yield live.connect(options); }), [live]);
2307
+ const toggleMicro = React__default["default"].useCallback((microStatus) => live.toggleMicro(microStatus), [live]);
2308
+ const broadcast = React__default["default"].useCallback((data, toUserIds, timeout = 0) => __awaiter(this, void 0, void 0, function* () { return yield live.broadcast(data, toUserIds, timeout); }), [live]);
2309
+ const exit = React__default["default"].useCallback(() => __awaiter(this, void 0, void 0, function* () { return yield live.exit(); }), [live]);
2310
+ const kick = React__default["default"].useCallback((toUserIds) => __awaiter(this, void 0, void 0, function* () { return yield live.kick(toUserIds); }), [live]);
2311
+ const forbidMicro = React__default["default"].useCallback((micro, toUserIds = []) => __awaiter(this, void 0, void 0, function* () { return yield live.forbidMicro(micro, toUserIds); }), [live]);
2312
+ const forbidSync = React__default["default"].useCallback((sync, toUserIds = []) => live.forbidSync(sync, toUserIds), [live]);
2313
+ const getFramesByKey = React__default["default"].useCallback((key) => live.getFramesByKey(key), [live]);
2314
+ const sendKeyframe = React__default["default"].useCallback((key, frame) => live.sendKeyframe(key, frame), [live]);
2315
+ const setSelfInfo = React__default["default"].useCallback((userInfo) => live.setSelfInfo(userInfo), [live]);
2316
+ const updateStatus = React__default["default"].useCallback((evtType, atnType, status, toUserIds) => live.updateStatus(evtType, atnType, status, toUserIds), [live]);
2074
2317
  return {
2075
- broadcast: broadcast,
2076
- exit: exit,
2077
- kick: kick,
2078
- toggleMicro: toggleMicro,
2079
- forbidMicro: forbidMicro,
2080
- // forbidSync,
2081
- sendKeyframe: sendKeyframe,
2082
- getFramesByKey: getFramesByKey,
2083
- setSelfInfo: setSelfInfo,
2084
- updateStatus: updateStatus,
2318
+ connect,
2319
+ broadcast,
2320
+ exit,
2321
+ kick,
2322
+ toggleMicro,
2323
+ forbidMicro,
2324
+ forbidSync,
2325
+ sendKeyframe,
2326
+ getFramesByKey,
2327
+ setSelfInfo,
2328
+ updateStatus,
2085
2329
  };
2086
2330
  }
2087
2331
  function useKeyframe(key) {
2088
- var live = useLiveInstance();
2089
- var _a = React__default["default"].useState(live.getFramesByKey(key)), state = _a[0], updateState = _a[1];
2090
- React__default["default"].useEffect(function () {
2091
- var onUpdate = function (nextKeyframes) {
2092
- return updateState(nextKeyframes);
2093
- };
2094
- var evtName = key;
2095
- var callback = onUpdate;
2332
+ const live = useLiveInstance();
2333
+ const [state, updateState] = React__default["default"].useState(live.getFramesByKey(key));
2334
+ React__default["default"].useEffect(() => {
2335
+ const onUpdate = (nextKeyframes) => updateState(nextKeyframes);
2336
+ const evtName = key;
2337
+ const callback = onUpdate;
2096
2338
  live.keyframes.on(evtName, callback);
2097
- return function () { return live.keyframes.off(evtName, callback); };
2339
+ return () => live.keyframes.off(evtName, callback);
2098
2340
  }, [live]);
2099
- var setState = React__default["default"].useCallback(function (frame) { return live.sendKeyframe(key, frame); }, [live]);
2341
+ const setState = React__default["default"].useCallback((frame) => live.sendKeyframe(key, frame), [live]);
2100
2342
  return [state, setState];
2101
2343
  }
2102
- function useLiveEventCallback(name, callback, deps) {
2103
- if (deps === void 0) { deps = []; }
2104
- var live = useLiveInstance();
2105
- var dispose = function () { return live.off(name, callback); };
2106
- var dependencyList = __spreadArray([live, name], deps, true);
2107
- React__default["default"].useEffect(function () {
2344
+ function useLiveEventCallback(name, callback, deps = []) {
2345
+ const live = useLiveInstance();
2346
+ const dispose = () => live.off(name, callback);
2347
+ const dependencyList = [live, name, ...deps];
2348
+ React__default["default"].useEffect(() => {
2108
2349
  live.on(name, callback);
2109
2350
  return dispose;
2110
2351
  }, dependencyList);
2111
2352
  return dispose;
2112
2353
  }
2113
2354
  /**
2114
- * @deprecated
2355
+ * 带看状态
2115
2356
  * @returns
2116
2357
  */
2117
- function useReadyState() {
2118
- var live = useLiveInstance();
2119
- var _a = React__default["default"].useState(live.readyState), state = _a[0], updateState = _a[1];
2120
- React__default["default"].useEffect(function () {
2121
- var readyStateUpdate = function (readyState) {
2122
- return updateState(readyState);
2123
- };
2124
- live.on('ws.readyStateUpdate', readyStateUpdate);
2125
- return function () { return live.off('ws.readyStateUpdate', readyStateUpdate); };
2358
+ function useLiveState() {
2359
+ const live = useLiveInstance();
2360
+ const [state, updateState] = React__default["default"].useState(live.state);
2361
+ React__default["default"].useEffect(() => {
2362
+ const stateChange = (state) => updateState(state);
2363
+ live.on('stateChange', stateChange);
2364
+ return () => live.off('stateChange', stateChange);
2126
2365
  }, [live]);
2127
2366
  return state;
2128
2367
  }
2129
2368
  function useRTCAction() {
2130
- var live = useLiveInstance();
2131
- var join = React__default["default"].useCallback(function (options) { return live.$RTC.join(options); }, [live]);
2132
- var quit = React__default["default"].useCallback(function () { return live.$RTC.quit(); }, [live]);
2133
- var shock = React__default["default"].useCallback(function () { var _a, _b; return (_b = (_a = live.$RTC).shock) === null || _b === void 0 ? void 0 : _b.call(_a); }, [live]);
2134
- var toggleMicro = React__default["default"].useCallback(function (flag) { return live.$RTC.toggleMicro(flag); }, [live]);
2135
- var detectMicro = React__default["default"].useCallback(function () { return live.$RTC.detectMicro(); }, [live]);
2369
+ const live = useLiveInstance();
2370
+ const join = React__default["default"].useCallback((options) => live.$RTC.join(options), [live]);
2371
+ const quit = React__default["default"].useCallback(() => live.$RTC.quit(), [live]);
2372
+ const shock = React__default["default"].useCallback(() => { var _a, _b; return (_b = (_a = live.$RTC).shock) === null || _b === void 0 ? void 0 : _b.call(_a); }, [live]);
2373
+ const toggleMicro = React__default["default"].useCallback((flag) => live.$RTC.toggleMicro(flag), [live]);
2374
+ const detectMicro = React__default["default"].useCallback(() => live.$RTC.detectMicro(), [live]);
2136
2375
  return {
2137
- join: join,
2138
- quit: quit,
2139
- shock: shock,
2140
- toggleMicro: toggleMicro,
2141
- detectMicro: detectMicro,
2376
+ join,
2377
+ quit,
2378
+ shock,
2379
+ toggleMicro,
2380
+ detectMicro,
2142
2381
  };
2143
2382
  }
2144
- function useRTCEventCallback(name, callback, deps) {
2145
- if (deps === void 0) { deps = []; }
2146
- var live = useLiveInstance();
2147
- var dispose = function () { return live.$RTC.off(name, callback); };
2148
- var dependencyList = __spreadArray([live, name], deps, true);
2149
- React__default["default"].useEffect(function () {
2383
+ function useRTCEventCallback(name, callback, deps = []) {
2384
+ const live = useLiveInstance();
2385
+ const dispose = () => live.$RTC.off(name, callback);
2386
+ const dependencyList = [live, name, ...deps];
2387
+ React__default["default"].useEffect(() => {
2150
2388
  live.$RTC.on(name, callback);
2151
2389
  return dispose;
2152
2390
  }, dependencyList);
2153
2391
  return dispose;
2154
2392
  }
2155
2393
  function useSelfInfo() {
2156
- var _this = this;
2157
- var live = useLiveInstance();
2158
- var _a = React__default["default"].useState(live.selfInfo || {}), state = _a[0], updateState = _a[1];
2159
- var selfInfoUpdate = function (userInfo) {
2160
- return updateState(userInfo);
2161
- };
2162
- React__default["default"].useEffect(function () {
2394
+ const live = useLiveInstance();
2395
+ const [state, updateState] = React__default["default"].useState(live.selfInfo || {});
2396
+ const selfInfoUpdate = (userInfo) => updateState(userInfo);
2397
+ React__default["default"].useEffect(() => {
2163
2398
  live.on('selfInfoUpdate', selfInfoUpdate);
2164
- return function () { return live.off('selfInfoUpdate', selfInfoUpdate); };
2399
+ return () => live.off('selfInfoUpdate', selfInfoUpdate);
2165
2400
  }, [live]);
2166
- var setState = React__default["default"].useCallback(function (userInfo) { return __awaiter(_this, void 0, void 0, function () {
2167
- return __generator(this, function (_a) {
2168
- switch (_a.label) {
2169
- case 0: return [4 /*yield*/, live.setSelfInfo(userInfo)];
2170
- case 1: return [2 /*return*/, _a.sent()];
2171
- }
2172
- });
2173
- }); }, [live]);
2401
+ const setState = React__default["default"].useCallback((userInfo) => __awaiter(this, void 0, void 0, function* () {
2402
+ return yield live.setSelfInfo(userInfo);
2403
+ }), [live]);
2174
2404
  return [state, setState];
2175
2405
  }
2176
- function useSnapshot() {
2177
- var live = useLiveInstance();
2178
- var _a = React__default["default"].useState(live.snapshot), state = _a[0], setState = _a[1];
2179
- React__default["default"].useEffect(function () {
2180
- var onKeyframes = function (keyframes) { return setState(keyframes); };
2406
+ function useKeyframesSnapshot() {
2407
+ const live = useLiveInstance();
2408
+ const [state, setState] = React__default["default"].useState(live.snapshot);
2409
+ React__default["default"].useEffect(() => {
2410
+ const onKeyframes = (keyframes) => setState(keyframes);
2181
2411
  live.on('keyframes', onKeyframes);
2182
- return function () { return live.off('keyframes', onKeyframes); };
2412
+ return () => live.off('keyframes', onKeyframes);
2183
2413
  });
2184
2414
  return state;
2185
2415
  }
2186
2416
  function useUserList() {
2187
- var live = useLiveInstance();
2188
- var _a = React__default["default"].useState(live.userList), state = _a[0], updateState = _a[1];
2189
- var userListUpdate = function (userList) { return updateState(userList); };
2190
- React__default["default"].useEffect(function () {
2417
+ const live = useLiveInstance();
2418
+ const [state, updateState] = React__default["default"].useState(live.userList);
2419
+ const userListUpdate = (userList) => updateState(userList);
2420
+ React__default["default"].useEffect(() => {
2191
2421
  live.on('userListUpdate', userListUpdate);
2192
- return function () { return live.off('userListUpdate', userListUpdate); };
2422
+ return () => live.off('userListUpdate', userListUpdate);
2193
2423
  }, [live]);
2194
2424
  return state;
2195
2425
  }
2196
- /**
2197
- *
2198
- * @param name
2199
- * @param callback
2200
- * @param deps
2201
- * @returns
2202
- * @deprecated
2203
- */
2204
- function useWebSocketEventCallback(name, callback, deps) {
2205
- if (deps === void 0) { deps = []; }
2206
- var live = useLiveInstance();
2207
- var dispose = function () { return live.off(name, callback); };
2208
- var dependencyList = __spreadArray([live, name], deps, true);
2209
- React__default["default"].useEffect(function () {
2210
- live.on(name, callback);
2211
- return dispose;
2212
- }, dependencyList);
2213
- return dispose;
2214
- }
2215
2426
  return {
2216
- live: live,
2217
- jsBridge: jsBridge,
2218
- LiveProvider: LiveProvider,
2219
- unsafe__useLiveInstance: unsafe__useLiveInstance,
2220
- unsafe__useRTCInstance: unsafe__useRTCInstance,
2221
- useCurrentWebSocketUrl: useCurrentWebSocketUrl,
2222
- useConnect: useConnect,
2223
- useKeyframe: useKeyframe,
2224
- useKeyframeUpdateCallback: useKeyframeUpdateCallback,
2225
- useLiveAction: useLiveAction,
2226
- useLiveEventCallback: useLiveEventCallback,
2227
- useReadyState: useReadyState,
2228
- useRTCAction: useRTCAction,
2229
- useRTCEventCallback: useRTCEventCallback,
2230
- useSelfInfo: useSelfInfo,
2231
- useSnapshot: useSnapshot,
2232
- useUserList: useUserList,
2233
- useWebSocketEventCallback: useWebSocketEventCallback,
2427
+ live,
2428
+ jsBridge,
2429
+ LiveProvider,
2430
+ unsafe__useLiveInstance,
2431
+ unsafe__useRTCInstance,
2432
+ useConnect,
2433
+ useKeyframe,
2434
+ useKeyframeUpdateCallback,
2435
+ useLiveAction,
2436
+ useLiveEventCallback,
2437
+ useLiveState,
2438
+ useRTCAction,
2439
+ useRTCEventCallback,
2440
+ useSelfInfo,
2441
+ useKeyframesSnapshot,
2442
+ useUserList,
2234
2443
  };
2235
2444
  }
2236
2445