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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (33) hide show
  1. package/dist/live/controller.d.ts +75 -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 +162 -0
  5. package/dist/realsee-live.cjs.development.js +1555 -1446
  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 +1557 -1448
  10. package/dist/realsee-live.esm.js.map +1 -1
  11. package/dist/realsee-live.umd.development.js +51482 -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 +130 -0
  23. package/dist/utils/logger.d.ts +16 -0
  24. package/docs/assets/search.js +1 -1
  25. package/docs/enums/LiveState.html +7 -0
  26. package/docs/index.html +1 -1
  27. package/docs/interfaces/LiveOptions.html +16 -19
  28. package/docs/modules.html +34 -40
  29. package/package.json +2 -2
  30. package/dist/typings/live/Live.d.ts +0 -128
  31. package/dist/typings/react/LiveReact.d.ts +0 -164
  32. package/docs/interfaces/Live.html +0 -116
  33. 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,83 @@ 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);
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
+ this.jsBridge.callAndListen('live/userVolumes', (userVolumes) => {
622
+ this.emit('userVolumes', userVolumes);
764
623
  });
765
- _this.jsBridge.callAndListen('live/weakNetwork', function (weakNetwork) {
624
+ this.jsBridge.callAndListen('live/weakNetwork', (weakNetwork) => {
766
625
  if (weakNetwork)
767
- _this.emit('weakNetwork');
626
+ this.emit('weakNetwork');
768
627
  });
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];
628
+ }
629
+ get jsBridge() {
630
+ return this.options.jsBridge;
631
+ }
632
+ join(options) {
633
+ return __awaiter(this, void 0, void 0, function* () {
634
+ this.emit('joinWillStart');
635
+ const { sdkAppId, userId, userSig } = yield this.options.getVoiceSign(options);
636
+ this.type = options.type;
637
+ const [res, error] = yield this.jsBridge.callAndBackfeed(`live/join?sdkAppID=${sdkAppId}&userID=${userId}&roomID=${Number(options.voiceId)}&userSig=${userSig}`);
638
+ if (!res) {
639
+ this.emit('error', error ? error : new Error('加入房间失败:未知异常。'));
640
+ this.joined = false;
641
+ }
642
+ else {
643
+ if (res.code === exports.RTCJoinedInfoCodeEnum.Success) {
644
+ this.emit('joined');
645
+ this.joined = true;
807
646
  }
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
- }
822
- this.joined = false;
823
- return [2 /*return*/, !!res];
647
+ else {
648
+ this.emit('error', res);
649
+ this.joined = false;
824
650
  }
825
- });
651
+ }
652
+ return this.joined;
826
653
  });
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
- });
654
+ }
655
+ quit() {
656
+ return __awaiter(this, void 0, void 0, function* () {
657
+ const [res, error] = yield this.jsBridge.callAndBackfeed('live/quit');
658
+ if (res === null) {
659
+ this.emit('error', error ? error : new Error('退出房间失败:未知异常。'));
660
+ }
661
+ this.joined = false;
662
+ return !!res;
843
663
  });
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
- });
664
+ }
665
+ detectMicro() {
666
+ return __awaiter(this, void 0, void 0, function* () {
667
+ const [res, error] = yield this.jsBridge.detectMicro();
668
+ if (res === null) {
669
+ this.emit('error', error ? error : new Error('麦克风监测异常!'));
670
+ return false;
671
+ }
672
+ return res;
861
673
  });
862
- };
863
- VRWebViewRTC.prototype.shock = function () {
674
+ }
675
+ toggleMicro(flag) {
676
+ return __awaiter(this, void 0, void 0, function* () {
677
+ const [res, error] = yield this.jsBridge.callAndBackfeed(`live/toggleMicro?flag=${!!flag ? 1 : 0}`);
678
+ if (res === null) {
679
+ this.emit('error', error ? error : new Error('麦克风监测异常!'));
680
+ return false;
681
+ }
682
+ this.micro = res;
683
+ return res;
684
+ });
685
+ }
686
+ shock() {
864
687
  this.jsBridge.shock(1);
865
- };
866
- return VRWebViewRTC;
867
- }(CoreRTC));
688
+ }
689
+ }
868
690
 
869
691
  /**
870
692
  * WebSocket 通信指令
@@ -949,8 +771,8 @@ exports.MicroStatus = void 0;
949
771
  */
950
772
  function parseLiveMsg(jsonTxt) {
951
773
  try {
952
- var msg = JSON.parse(jsonTxt);
953
- var resMsg_1 = {
774
+ const msg = JSON.parse(jsonTxt);
775
+ const resMsg = {
954
776
  code: msg.code,
955
777
  message: msg.message,
956
778
  command: msg.command,
@@ -961,11 +783,11 @@ function parseLiveMsg(jsonTxt) {
961
783
  triggerUserID: msg.trigger_user_id,
962
784
  data: msg.data || {},
963
785
  };
964
- var undefinedKeys = Object.keys(resMsg_1).filter(function (key) { return resMsg_1[key] === undefined; });
786
+ const undefinedKeys = Object.keys(resMsg).filter((key) => resMsg[key] === undefined);
965
787
  if (undefinedKeys.length > 0) {
966
- console.warn("\u63A8\u9001\u6570\u636E\u683C\u5F0F\u5F02\u5E38\uFF1A".concat(undefinedKeys.join(" "), " \u503C\u4E0D\u5B58\u5728\uFF01"));
788
+ console.warn(`推送数据格式异常:${undefinedKeys.join(" ")} 值不存在!`);
967
789
  }
968
- return resMsg_1;
790
+ return resMsg;
969
791
  }
970
792
  catch (error) {
971
793
  // notcare? 过滤掉所有不符合规范的数据
@@ -973,6 +795,23 @@ function parseLiveMsg(jsonTxt) {
973
795
  }
974
796
  }
975
797
 
798
+ exports.LiveState = void 0;
799
+ (function (LiveState) {
800
+ LiveState[LiveState["NOTINITIALIZED"] = -1] = "NOTINITIALIZED";
801
+ /**
802
+ * 正在链接中
803
+ */
804
+ LiveState[LiveState["CONNECTING"] = 0] = "CONNECTING";
805
+ /**
806
+ * 已经链接并且可以通讯
807
+ */
808
+ LiveState[LiveState["OPEN"] = 1] = "OPEN";
809
+ /**
810
+ * 连接已关闭或者链接失败
811
+ */
812
+ LiveState[LiveState["CLOSED"] = 3] = "CLOSED";
813
+ })(exports.LiveState || (exports.LiveState = {}));
814
+
976
815
  /**
977
816
  * 用户当前状态枚举。
978
817
  */
@@ -1102,20 +941,45 @@ function parseWSClsErr(code) {
1102
941
  return exports.WebSocketCloseError.Err_unknown;
1103
942
  }
1104
943
 
944
+ function getDefaultExportFromCjs (x) {
945
+ return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
946
+ }
947
+
948
+ function createCommonjsModule(fn) {
949
+ var module = { exports: {} };
950
+ return fn(module, module.exports), module.exports;
951
+ }
952
+
953
+ var LogLevel_1 = createCommonjsModule(function (module, exports) {
954
+ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
955
+ // SPDX-License-Identifier: Apache-2.0
956
+ Object.defineProperty(exports, "__esModule", { value: true });
957
+ exports.LogLevel = void 0;
958
+ var LogLevel;
959
+ (function (LogLevel) {
960
+ LogLevel[LogLevel["DEBUG"] = 0] = "DEBUG";
961
+ LogLevel[LogLevel["INFO"] = 1] = "INFO";
962
+ LogLevel[LogLevel["WARN"] = 2] = "WARN";
963
+ LogLevel[LogLevel["ERROR"] = 3] = "ERROR";
964
+ LogLevel[LogLevel["OFF"] = 4] = "OFF";
965
+ })(LogLevel = exports.LogLevel || (exports.LogLevel = {}));
966
+ exports.default = LogLevel;
967
+
968
+ });
969
+
970
+ var LogLevel = /*@__PURE__*/getDefaultExportFromCjs(LogLevel_1);
971
+
1105
972
  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
- }, '');
973
+ const hasQuery = uri.indexOf('?') !== -1;
974
+ const newQuery = Object.keys(query).reduce((accu, curr, idx) => `${accu}${(idx === 0 && !hasQuery) ? '?' : '&'}${curr}=${query[curr]}`, '');
1111
975
  return uri + newQuery;
1112
976
  }
1113
977
 
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);
978
+ const userAgent = globalThis.navigator.userAgent;
979
+ const isAndroid = /android/gi.test(userAgent);
980
+ const isIOS = /iPhone|iPad\s+OS/gi.test(userAgent);
981
+ const isWxMiniProgram = /MicroMessenger/gi.test(userAgent) && /miniProgram/gi.test(userAgent);
982
+ const isRealseeVRWebview = /realsee/gi.test(userAgent);
1119
983
 
1120
984
  /**
1121
985
  * 判断是否是真实的对象类型
@@ -1147,12 +1011,12 @@ function baseIsEqual(value, other) {
1147
1011
  * @returns
1148
1012
  */
1149
1013
  function objEqualShallow(value, other) {
1150
- var valueProps = Object.getOwnPropertyNames(value);
1151
- var otherProps = Object.getOwnPropertyNames(other);
1014
+ const valueProps = Object.getOwnPropertyNames(value);
1015
+ const otherProps = Object.getOwnPropertyNames(other);
1152
1016
  if (valueProps.length !== otherProps.length)
1153
1017
  return false;
1154
- for (var i = 0, len = valueProps.length; i < len; i++) {
1155
- var propName = valueProps[i];
1018
+ for (let i = 0, len = valueProps.length; i < len; i++) {
1019
+ const propName = valueProps[i];
1156
1020
  if (!baseIsEqual(value[propName], other[propName]))
1157
1021
  return false;
1158
1022
  }
@@ -1167,7 +1031,7 @@ function objEqualShallow(value, other) {
1167
1031
  function arrayEqualShallow(value, other) {
1168
1032
  if (value.length !== other.length)
1169
1033
  return false;
1170
- for (var i = 0, len = value.length; i < len; i++) {
1034
+ for (let i = 0, len = value.length; i < len; i++) {
1171
1035
  if (!baseIsEqual(value[i], other[i]))
1172
1036
  return false;
1173
1037
  }
@@ -1212,7 +1076,7 @@ function isDeepEqual(value, other) {
1212
1076
  function arrayEqualDeep(value, other) {
1213
1077
  if (value.length !== other.length)
1214
1078
  return false;
1215
- for (var i = 0, len = value.length; i < len; i++) {
1079
+ for (let i = 0, len = value.length; i < len; i++) {
1216
1080
  if (!isDeepEqual(value[i], other[i]))
1217
1081
  return false;
1218
1082
  }
@@ -1225,12 +1089,12 @@ function arrayEqualDeep(value, other) {
1225
1089
  * @returns
1226
1090
  */
1227
1091
  function objEqualDeep(value, other) {
1228
- var valueProps = Object.getOwnPropertyNames(value);
1229
- var otherProps = Object.getOwnPropertyNames(other);
1092
+ const valueProps = Object.getOwnPropertyNames(value);
1093
+ const otherProps = Object.getOwnPropertyNames(other);
1230
1094
  if (valueProps.length !== otherProps.length)
1231
1095
  return false;
1232
- for (var i = 0, len = valueProps.length; i < len; i++) {
1233
- var propName = valueProps[i];
1096
+ for (let i = 0, len = valueProps.length; i < len; i++) {
1097
+ const propName = valueProps[i];
1234
1098
  if (!isDeepEqual(value[propName], other[propName]))
1235
1099
  return false;
1236
1100
  }
@@ -1244,993 +1108,1238 @@ function objEqualDeep(value, other) {
1244
1108
  * @returns {boolean} 是否相等。
1245
1109
  */
1246
1110
  function equal(value, other, opt) {
1247
- if (opt === void 0) { opt = { deep: false }; }
1248
1111
  if (!opt.deep)
1249
1112
  return isShallowEqual(value, other);
1250
1113
  return isDeepEqual(value, other);
1251
1114
  }
1252
1115
 
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 = {};
1116
+ /**
1117
+ * 输出格式化日志
1118
+ */
1119
+ // 获取当前时间
1120
+ const getTime = () => {
1121
+ const date = new Date();
1122
+ const year = date.getFullYear();
1123
+ const month = (date.getMonth() + 1).toString().padStart(2, '0'); //月份是从0开始的
1124
+ const day = date.getDate().toString().padStart(2, '0');
1125
+ const hour = date.getHours().toString().padStart(2, '0');
1126
+ const min = date.getMinutes().toString().padStart(2, '0');
1127
+ const sec = date.getSeconds().toString().padStart(2, '0');
1128
+ const ms = date.getMilliseconds();
1129
+ return `[${year}-${month}-${day} ${hour}:${min}:${sec}.${ms}]`;
1130
+ };
1131
+ var LOG_LEVEL;
1132
+ (function (LOG_LEVEL) {
1133
+ LOG_LEVEL["info"] = "INFO";
1134
+ LOG_LEVEL["log"] = "LOG";
1135
+ LOG_LEVEL["error"] = "ERROR";
1136
+ LOG_LEVEL["warn"] = "WARN";
1137
+ })(LOG_LEVEL || (LOG_LEVEL = {}));
1138
+ // 输出日志
1139
+ const echo = (logLevel, args = []) => {
1140
+ args.unshift(`Realsee Live ${getTime()} <${logLevel}> `);
1141
+ switch (logLevel) {
1142
+ case LOG_LEVEL.info:
1143
+ return console.info(...args);
1144
+ case LOG_LEVEL.error:
1145
+ return console.error(...args);
1146
+ case LOG_LEVEL.warn:
1147
+ return console.warn(...args);
1148
+ default:
1149
+ return console.log(...args);
1150
+ }
1151
+ };
1152
+ const log = (...args) => echo(LOG_LEVEL.log, args);
1153
+ const info = (...args) => echo(LOG_LEVEL.info, args);
1154
+ const error = (...args) => echo(LOG_LEVEL.error, args);
1155
+ const warn = (...args) => echo(LOG_LEVEL.warn, args);
1156
+ const logger = {
1157
+ log,
1158
+ info,
1159
+ error,
1160
+ warn,
1161
+ };
1162
+ var logger$1 = logger;
1163
+
1164
+ /**
1165
+ * 具有鲁棒性的WebSocket封装
1166
+ * 1、自动重连
1167
+ * 2、可根据网络情况进行重连
1168
+ */
1169
+ class RobustWebSocket extends Subscribe {
1170
+ constructor(options) {
1171
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-call
1172
+ super();
1173
+ this._options = {
1174
+ timeout: 10000,
1175
+ shouldReconnect: (event, ws) => {
1176
+ if (event.code === 1008 || event.code === 1011)
1177
+ return;
1178
+ return [0, 3000, 10000][ws.attempts];
1179
+ },
1180
+ should1000Reconnect: false,
1181
+ ignoreConnectivityEvents: false,
1182
+ automaticOpen: false,
1183
+ };
1184
+ this._attempts = 0;
1185
+ this._reconnects = -1;
1186
+ this._reconnectWhenOnlineAgain = false;
1187
+ this._explicitlyClosed = false;
1188
+ this._connectivityEventsAttached = false;
1260
1189
  /**
1261
- * 检测 WebSocket.readyState 状态
1190
+ * 清理连接中的请求
1262
1191
  */
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;
1271
- }
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;
1192
+ this._clearPendingReconnectIfNeeded = () => {
1193
+ if (this._pendingReconnect) {
1194
+ clearTimeout(this._pendingReconnect);
1195
+ this._pendingReconnect = undefined;
1196
+ }
1279
1197
  };
1280
- this.dispose = function () {
1281
- _this.disposeWebSocket();
1282
- _this.connecting = false;
1283
- if (_this.healthCheckId) {
1284
- clearInterval(_this.healthCheckId);
1285
- _this.healthCheckId = undefined;
1198
+ /**
1199
+ * 当网页连接上网络进行重连
1200
+ * @param event
1201
+ */
1202
+ this._online = (event) => {
1203
+ if (this._reconnectWhenOnlineAgain) {
1204
+ this._clearPendingReconnectIfNeeded();
1205
+ this._reconnect(event);
1286
1206
  }
1287
- return true;
1288
1207
  };
1289
1208
  /**
1290
- * 销毁WebSocket相关依赖。
1209
+ * 当网页断开网络进行关闭
1291
1210
  */
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;
1211
+ this._offline = () => {
1212
+ var _a;
1213
+ this._reconnectWhenOnlineAgain = true;
1214
+ (_a = this._realWebSocket) === null || _a === void 0 ? void 0 : _a.close(1000);
1215
+ };
1216
+ /**
1217
+ * 解除网络监听事件
1218
+ */
1219
+ this._detachConnectivityEvents = () => {
1220
+ if (this._connectivityEventsAttached) {
1221
+ globalThis === null || globalThis === void 0 ? void 0 : globalThis.removeEventListener('online', this._online);
1222
+ globalThis === null || globalThis === void 0 ? void 0 : globalThis.removeEventListener('offline', this._offline);
1223
+ this._connectivityEventsAttached = false;
1224
+ }
1225
+ };
1226
+ /**
1227
+ * 注册网络监听事件
1228
+ */
1229
+ this._attachConnectivityEvents = () => {
1230
+ if (!this._connectivityEventsAttached) {
1231
+ globalThis === null || globalThis === void 0 ? void 0 : globalThis.addEventListener('online', this._online);
1232
+ globalThis === null || globalThis === void 0 ? void 0 : globalThis.addEventListener('offline', this._offline);
1233
+ this._connectivityEventsAttached = true;
1298
1234
  }
1299
- if (_this.onEvtMsgListener) {
1300
- _this.webSocket.removeEventListener('message', _this.onEvtMsgListener);
1301
- _this.onEvtMsgListener = undefined;
1235
+ };
1236
+ /**
1237
+ * 发送消息
1238
+ * @param data
1239
+ * @returns
1240
+ */
1241
+ this.send = (data) => { var _a; return (_a = this._realWebSocket) === null || _a === void 0 ? void 0 : _a.send(data); };
1242
+ /**
1243
+ * 关闭连接
1244
+ * @param code 代码
1245
+ * @param reason 原因
1246
+ * @returns
1247
+ */
1248
+ this.close = (code, reason) => {
1249
+ var _a;
1250
+ if (typeof code !== 'number') {
1251
+ reason = code;
1252
+ code = 1000;
1302
1253
  }
1303
- if (_this.onEvtErrListener) {
1304
- _this.webSocket.removeEventListener('error', _this.onEvtErrListener);
1305
- _this.onEvtErrListener = undefined;
1254
+ this._clearPendingReconnectIfNeeded();
1255
+ this._reconnectWhenOnlineAgain = false;
1256
+ this._explicitlyClosed = true;
1257
+ this._detachConnectivityEvents();
1258
+ return (_a = this._realWebSocket) === null || _a === void 0 ? void 0 : _a.close(code, reason);
1259
+ };
1260
+ /**
1261
+ * 进行ws连接
1262
+ */
1263
+ this.open = (url) => {
1264
+ var _a, _b;
1265
+ if (url) {
1266
+ this._url = url;
1306
1267
  }
1307
- if (_this.onEvtCLEListener) {
1308
- _this.webSocket.removeEventListener('close', _this.onEvtCLEListener);
1309
- _this.onEvtCLEListener = undefined;
1268
+ if (((_a = this._realWebSocket) === null || _a === void 0 ? void 0 : _a.readyState) !== WebSocket.OPEN &&
1269
+ ((_b = this._realWebSocket) === null || _b === void 0 ? void 0 : _b.readyState) !== WebSocket.CONNECTING) {
1270
+ this._clearPendingReconnectIfNeeded();
1271
+ this._reconnectWhenOnlineAgain = false;
1272
+ this._explicitlyClosed = false;
1273
+ this._createWebSocket();
1310
1274
  }
1311
- _this.webSocket.close();
1312
- _this.webSocket = undefined;
1313
- return true;
1314
1275
  };
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
- }
1276
+ /**
1277
+ * 创建ws连接
1278
+ */
1279
+ this._createWebSocket = () => {
1280
+ var _a, _b, _c;
1281
+ const newUrl = typeof this._url === 'string' ? this._url : (_a = this._url) === null || _a === void 0 ? void 0 : _a.call(this, this);
1282
+ if (!newUrl)
1283
+ return;
1284
+ this._pendingReconnect = undefined;
1285
+ this._realWebSocket = new WebSocket(newUrl, this._protocols || undefined);
1286
+ this._attempts = this._attempts + 1;
1287
+ this.emit('connecting', new CustomEvent('connecting', {
1288
+ detail: { attempts: this._attempts, reconnects: this._reconnects },
1289
+ }));
1290
+ const timeoutCallback = () => {
1291
+ this._connectTimeout = undefined;
1292
+ this._detachConnectivityEvents();
1293
+ this.emit('timeout', new CustomEvent('connecting', {
1294
+ detail: {
1295
+ attempts: this._attempts,
1296
+ reconnects: this._reconnects,
1297
+ },
1298
+ }));
1299
+ };
1300
+ this._connectTimeout = setTimeout(timeoutCallback, (_b = this._options) === null || _b === void 0 ? void 0 : _b.timeout);
1301
+ this._dispatchWebSocketEvent();
1302
+ if (!((_c = this._options) === null || _c === void 0 ? void 0 : _c.ignoreConnectivityEvents)) {
1303
+ this._attachConnectivityEvents();
1453
1304
  }
1305
+ };
1306
+ /**
1307
+ * 分发ws事件
1308
+ */
1309
+ this._dispatchWebSocketEvent = () => {
1310
+ var _a, _b, _c, _d;
1311
+ (_a = this._realWebSocket) === null || _a === void 0 ? void 0 : _a.addEventListener('open', this._webSocketOpenHandler);
1312
+ (_b = this._realWebSocket) === null || _b === void 0 ? void 0 : _b.addEventListener('close', this._webSocketCloseHandler);
1313
+ (_c = this._realWebSocket) === null || _c === void 0 ? void 0 : _c.addEventListener('error', this._webSocketErrorHandler);
1314
+ (_d = this._realWebSocket) === null || _d === void 0 ? void 0 : _d.addEventListener('message', this._webSocketMessageHandler);
1315
+ };
1316
+ /**
1317
+ * ws连接事件
1318
+ * @returns
1319
+ */
1320
+ this._webSocketOpenHandler = (event) => {
1321
+ if (this._connectTimeout) {
1322
+ clearTimeout(this._connectTimeout);
1323
+ this._connectTimeout = undefined;
1324
+ }
1325
+ const reconnects = ++this._reconnects;
1326
+ const attempts = this._attempts;
1327
+ this._attempts = 0;
1328
+ this._reconnectWhenOnlineAgain = false;
1329
+ return this.emit('open', Object.assign(event, { detail: { reconnects, attempts } }));
1330
+ };
1331
+ /**
1332
+ * ws 关闭事件
1333
+ * @param event
1334
+ * @returns
1335
+ */
1336
+ this._webSocketCloseHandler = (event) => {
1337
+ this._reconnect(event);
1338
+ return this.emit('close', event);
1339
+ };
1340
+ /**
1341
+ * ws 异常
1342
+ * @param event
1343
+ * @returns
1344
+ */
1345
+ this._webSocketErrorHandler = (event) => {
1346
+ return this.emit('error', new CustomEvent('error', { detail: { error: event } }));
1347
+ };
1348
+ /**
1349
+ * ws消息
1350
+ * @param event
1351
+ * @returns
1352
+ */
1353
+ this._webSocketMessageHandler = (event) => {
1354
+ return this.emit('message', event);
1355
+ };
1356
+ if (options) {
1357
+ this.setOptions(options);
1454
1358
  }
1455
- else {
1456
- live.emit('error', liveMsg);
1359
+ }
1360
+ get attempts() {
1361
+ return this._attempts;
1362
+ }
1363
+ setOptions(options) {
1364
+ if (!options)
1365
+ return;
1366
+ this._url = options.url;
1367
+ this._protocols = options.protocols;
1368
+ const opts = Object.assign(this._options, options.robustOptions || {});
1369
+ if (typeof (opts === null || opts === void 0 ? void 0 : opts.timeout) !== 'number') {
1370
+ throw new Error('timeout must be the number of milliseconds to timeout a connection attempt');
1457
1371
  }
1458
- };
1372
+ if (typeof (opts === null || opts === void 0 ? void 0 : opts.shouldReconnect) !== 'function') {
1373
+ 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.');
1374
+ }
1375
+ this._options = opts;
1376
+ if (this._options.automaticOpen) {
1377
+ this._createWebSocket();
1378
+ }
1379
+ }
1380
+ /**
1381
+ * 进行重连
1382
+ * @param event
1383
+ * @returns
1384
+ */
1385
+ _reconnect(event) {
1386
+ var _a, _b, _c, _d;
1387
+ if ((!((_a = this._options) === null || _a === void 0 ? void 0 : _a.should1000Reconnect) && event.code === 1000) ||
1388
+ this._explicitlyClosed) {
1389
+ this._attempts = 0;
1390
+ return;
1391
+ }
1392
+ if (((_b = globalThis === null || globalThis === void 0 ? void 0 : globalThis.navigator) === null || _b === void 0 ? void 0 : _b.onLine) === false) {
1393
+ this._reconnectWhenOnlineAgain = true;
1394
+ return;
1395
+ }
1396
+ 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);
1397
+ if (typeof delay === 'number') {
1398
+ this._pendingReconnect = setTimeout(this._createWebSocket, delay);
1399
+ }
1400
+ }
1401
+ }
1402
+
1403
+ class LiveController extends Subscribe {
1404
+ constructor() {
1405
+ super();
1406
+ /**
1407
+ * ws代理器
1408
+ */
1409
+ this._ws = new RobustWebSocket();
1410
+ /**
1411
+ * 带看连接状态
1412
+ */
1413
+ this._state = exports.LiveState.NOTINITIALIZED;
1414
+ /**
1415
+ * 添加事件监听
1416
+ */
1417
+ this._addWebSocketEventListeners = () => {
1418
+ this._ws.on('close', this._handleCloseEvent);
1419
+ this._ws.on('connecting', this._handleConnectingEvent);
1420
+ this._ws.on('error', this._handleErrorEvent);
1421
+ this._ws.on('message', this._handleMessageEvent);
1422
+ this._ws.on('open', this._handleOpenEvent);
1423
+ this._ws.on('timeout', this._handleTimeoutEvent);
1424
+ };
1425
+ /**
1426
+ * 移除事件监听
1427
+ */
1428
+ this._removeWebSocketEventListeners = () => {
1429
+ this._ws.off('close', this._handleCloseEvent);
1430
+ this._ws.off('connecting', this._handleConnectingEvent);
1431
+ this._ws.off('error', this._handleErrorEvent);
1432
+ this._ws.off('message', this._handleMessageEvent);
1433
+ this._ws.off('open', this._handleOpenEvent);
1434
+ this._ws.off('timeout', this._handleTimeoutEvent);
1435
+ };
1436
+ /**
1437
+ * 处理房间关闭事件
1438
+ * @param event
1439
+ */
1440
+ this._handleCloseEvent = (event) => {
1441
+ logger$1.info(`live room closed bacause of ${event.code}-${event.reason || parseWSClsErr(event.code)}`);
1442
+ this.state = exports.LiveState.CLOSED;
1443
+ };
1444
+ /**
1445
+ * 连接中
1446
+ * @param event
1447
+ */
1448
+ this._handleConnectingEvent = (event) => {
1449
+ logger$1.info(`live room is connecting`, event.detail);
1450
+ this.state = exports.LiveState.CONNECTING;
1451
+ };
1452
+ /**
1453
+ * 连接发送异常
1454
+ * @param event
1455
+ */
1456
+ this._handleErrorEvent = (event) => {
1457
+ logger$1.error(`live room error`, event);
1458
+ this.state = exports.LiveState.CLOSED;
1459
+ };
1460
+ /**
1461
+ * 接收到消息
1462
+ * @param event
1463
+ */
1464
+ this._handleMessageEvent = (event) => {
1465
+ // logger.info('live room received message ', event.data);
1466
+ let message = (() => {
1467
+ try {
1468
+ return JSON.parse(event.data);
1469
+ }
1470
+ catch (e) {
1471
+ return event.data;
1472
+ }
1473
+ })();
1474
+ this.emit('message', message);
1475
+ };
1476
+ /**
1477
+ * 连接建立成功
1478
+ * @param event
1479
+ */
1480
+ this._handleOpenEvent = (event) => {
1481
+ logger$1.info('live room open', event.detail);
1482
+ this.state = exports.LiveState.OPEN;
1483
+ };
1484
+ /**
1485
+ * 处理超时
1486
+ * @param event
1487
+ */
1488
+ this._handleTimeoutEvent = (event) => {
1489
+ logger$1.error('live room connect timeout!', event.detail);
1490
+ this.state = exports.LiveState.CLOSED;
1491
+ };
1492
+ /**
1493
+ * 释放资源,释放之后需要重新实例化
1494
+ * @returns
1495
+ */
1496
+ this.dispose = () => __awaiter(this, void 0, void 0, function* () {
1497
+ this._removeWebSocketEventListeners();
1498
+ return yield this.close('live room close by controller disposed!');
1499
+ });
1500
+ /**
1501
+ * 开启房间链接
1502
+ * @param url 房间链接
1503
+ * @returns
1504
+ */
1505
+ this.open = (url) => this._ws.open(url);
1506
+ /**
1507
+ * 关闭房间
1508
+ * @param code
1509
+ * @param reason
1510
+ */
1511
+ this.close = (code, reason) => new Promise((resolve) => {
1512
+ this._ws.once('close', () => resolve(true));
1513
+ this._ws.close(code, reason);
1514
+ });
1515
+ this._addWebSocketEventListeners();
1516
+ }
1517
+ set state(state) {
1518
+ const prevState = JSON.parse(JSON.stringify(this._state));
1519
+ this._state = state;
1520
+ this.emit('stateChange', this.state, prevState);
1521
+ }
1522
+ get state() {
1523
+ return this._state;
1524
+ }
1459
1525
  /**
1460
1526
  * 发送数据
1461
1527
  * @param data
1462
1528
  */
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
- }());
1529
+ sendMessage(data = '') {
1530
+ if (data === undefined || data === null || data === '') {
1531
+ throw new Error('live message is empty!');
1532
+ }
1533
+ if (this.state === exports.LiveState.OPEN) {
1534
+ return this._ws.send(JSON.stringify(data));
1535
+ }
1536
+ else {
1537
+ throw new Error('live has not yet been initialized!');
1538
+ }
1539
+ }
1540
+ }
1472
1541
 
1473
- var unimplementedGetVoiceSign = function (params) {
1474
- return Promise.reject('unimplemented method GetVoiceSign');
1542
+ const unimplementedGetVoiceSign = (params) => Promise.reject('unimplemented method GetVoiceSign');
1543
+ const createLiveMsg = (command, data = {}, toUserIds = []) => ({
1544
+ command,
1545
+ front_request_id: uuid(),
1546
+ data: Object.assign(Object.assign({}, data), { to_user_ids: Array.isArray(toUserIds) ? toUserIds : [toUserIds] }),
1547
+ });
1548
+ const _clearLiveInstanceIfNeed = () => {
1549
+ var _a, _b;
1550
+ if (window === null || window === void 0 ? void 0 : window.__Realsee_Live__) {
1551
+ (_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);
1552
+ window.__Realsee_Live__ = null;
1553
+ }
1475
1554
  };
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');
1555
+ class Live extends Subscribe {
1556
+ constructor(opts) {
1557
+ var _a;
1558
+ super();
1559
+ /**
1560
+ * 带看的配置
1561
+ */
1562
+ this._options = {};
1563
+ /**
1564
+ * 帧数据监听
1565
+ */
1566
+ this.keyframes = new Subscribe();
1567
+ /**
1568
+ * 内置的一些数据
1569
+ */
1570
+ this._buildInData = {
1571
+ keyframes: {},
1572
+ };
1573
+ /**
1574
+ * 根据键值取帧数据
1575
+ * @param key 帧数据的键值
1576
+ * @returns
1577
+ */
1578
+ this.getFramesByKey = (key) => this.snapshot[key];
1579
+ /**
1580
+ * 发送帧数据(需要能够被序列化)
1581
+ * @param key 帧数据键值
1582
+ * @param frame 帧数据本体
1583
+ * @returns
1584
+ */
1585
+ this.sendKeyframe = (key, frame) => {
1586
+ if (this.state !== exports.LiveState.OPEN)
1587
+ return false;
1588
+ this._buildInData.keyframes = Object.assign(Object.assign({}, this._buildInData.keyframes), { [key]: frame });
1589
+ const liveMsg = createLiveMsg(exports.Command.KeyframeSync, this.snapshot);
1590
+ try {
1591
+ this._controller.sendMessage(liveMsg);
1592
+ return true;
1593
+ }
1594
+ catch (e) {
1595
+ logger$1.error(e);
1596
+ return false;
1597
+ }
1598
+ };
1599
+ /**
1600
+ * 带看控制器
1601
+ */
1602
+ this._controller = new LiveController();
1603
+ /**
1604
+ * 添加带看控制的事件监听
1605
+ */
1606
+ this._addLiveControllerEventListeners = () => {
1607
+ this._controller.on('stateChange', this._handleStateChange);
1608
+ this._controller.on('message', this._handleMessage);
1609
+ };
1610
+ /**
1611
+ * 移除带看控制的事件监听
1612
+ */
1613
+ this._removeLiveControllerEventListeners = () => {
1614
+ this._controller.off('stateChange', this._handleStateChange);
1615
+ this._controller.off('message', this._handleMessage);
1616
+ };
1617
+ /**
1618
+ * 带看状态变化
1619
+ * @param state
1620
+ * @returns
1621
+ */
1622
+ this._handleStateChange = (state, prevState) => this.emit('stateChange', state, prevState);
1623
+ this._handleMessage = (liveMsg) => __awaiter(this, void 0, void 0, function* () {
1624
+ var _b, _c, _d, _e, _f, _g;
1625
+ if (typeof liveMsg === 'object') {
1626
+ const { command, data, frontRequestId, code, message } = liveMsg;
1627
+ if (code === 'SUCCESS') {
1628
+ switch (command) {
1629
+ /**
1630
+ * 自己的状态变化
1631
+ */
1632
+ case exports.Command.SelfUserInfo: {
1633
+ const selfInfo = data;
1634
+ if (!equal(this.selfInfo, selfInfo, { deep: true })) {
1635
+ this._buildInData.selfInfo = selfInfo;
1636
+ this.emit('selfInfoUpdate', this._buildInData.selfInfo, frontRequestId);
1520
1637
  }
1521
- liveController.options.rtc = new VRWebViewRTC({
1522
- jsBridge: jsBridge,
1523
- getVoiceSign: getVoiceSign,
1524
- });
1525
1638
  break;
1526
1639
  }
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
- });
1640
+ /**
1641
+ * 房间信息变化
1642
+ */
1643
+ case exports.Command.RoomInfo: {
1644
+ const roomInfo = data;
1645
+ this._buildInData.roomInfo = Object.assign({}, roomInfo);
1646
+ this.emit('readyKeyframeSync', (roomInfo.last_frame || {}));
1533
1647
  break;
1534
1648
  }
1535
- case exports.RTCType.RealseeBrowserRTC: {
1536
- // 内置的 RealseeBrowserRTC
1537
- liveController.options.rtc = new BrowserRTC({
1538
- getVoiceSign: getVoiceSign,
1539
- });
1649
+ /**
1650
+ * 语音信息变化
1651
+ */
1652
+ case exports.Command.RTCInfo: {
1653
+ const { voice_id: voiceId, type } = data;
1654
+ if (!((_b = this.$RTC) === null || _b === void 0 ? void 0 : _b.joined)) {
1655
+ const result = yield ((_c = this.$RTC) === null || _c === void 0 ? void 0 : _c.join({
1656
+ voiceId,
1657
+ userId: ((_d = this.selfInfo) === null || _d === void 0 ? void 0 : _d.id) || '',
1658
+ roomId: (_e = this.roomInfo) === null || _e === void 0 ? void 0 : _e.info.room_code,
1659
+ type,
1660
+ }));
1661
+ if (result) {
1662
+ const status = (_f = this._options.initialMicroStatus) !== null && _f !== void 0 ? _f : exports.MicroStatus.OPEN;
1663
+ yield ((_g = this.$RTC) === null || _g === void 0 ? void 0 : _g.toggleMicro(status === exports.MicroStatus.OPEN));
1664
+ }
1665
+ else {
1666
+ logger$1.error('加入语音房间失败');
1667
+ }
1668
+ }
1669
+ else {
1670
+ logger$1.warn('已加入语音房间,无需重复加入!');
1671
+ }
1672
+ break;
1673
+ }
1674
+ /**
1675
+ * 房间用户列表变化
1676
+ */
1677
+ case exports.Command.UserList: {
1678
+ const userList = data;
1679
+ this._buildInData.userList = userList;
1680
+ this.emit('userListUpdate', this.userList, frontRequestId);
1681
+ break;
1682
+ }
1683
+ /**
1684
+ * 自定义事件广播
1685
+ */
1686
+ case exports.Command.CustomEvent: {
1687
+ const evtMsg = data;
1688
+ this.emit('broadcast', evtMsg, frontRequestId);
1689
+ break;
1690
+ }
1691
+ /**
1692
+ * 帧数据同步
1693
+ */
1694
+ case exports.Command.KeyframeSync: {
1695
+ const remoteKeyframes = data;
1696
+ // 此处做一层 diff,仅跟本地数据不一致的情况下才广播数据。
1697
+ const keyframes = Object.keys(remoteKeyframes).reduce((accu, curr) => {
1698
+ if (equal(remoteKeyframes[curr], this._buildInData.keyframes[curr], {
1699
+ deep: true,
1700
+ })) {
1701
+ return accu;
1702
+ }
1703
+ const params = [
1704
+ remoteKeyframes[curr],
1705
+ this._buildInData.keyframes[curr],
1706
+ frontRequestId,
1707
+ ];
1708
+ const evtName = curr;
1709
+ this.keyframes.emit(evtName, ...params);
1710
+ this._buildInData.keyframes[curr] = remoteKeyframes[curr];
1711
+ accu[curr] = remoteKeyframes[curr];
1712
+ return accu;
1713
+ }, {});
1714
+ this.emit('keyframes', keyframes, frontRequestId);
1540
1715
  break;
1541
1716
  }
1717
+ /**
1718
+ * 内置消息
1719
+ */
1720
+ case exports.Command.BuiltinMsg: {
1721
+ const builtinMsg = data;
1722
+ this.emit('builtinEvent', builtinMsg);
1723
+ if (builtinMsg.event_type === exports.BuiltinEventType.UserChange) {
1724
+ this.emit('userChange', builtinMsg);
1725
+ }
1726
+ if (builtinMsg.event_type === exports.BuiltinEventType.RoomChange) {
1727
+ this.emit('roomChange', builtinMsg);
1728
+ }
1729
+ /**
1730
+ * 下发指令自己操作麦克风
1731
+ */
1732
+ if (builtinMsg.event_type === exports.BuiltinEventType.UserChange &&
1733
+ builtinMsg.action === exports.BuiltinActionType.UserMicroStatus) {
1734
+ yield this.toggleMicro(builtinMsg.data.status === exports.MicroStatus.OPEN);
1735
+ }
1736
+ /**
1737
+ * 如果下发指令退出房间,则 关闭麦克风 及 销毁 WebSocket
1738
+ */
1739
+ if (builtinMsg.event_type === exports.BuiltinEventType.RoomChange &&
1740
+ builtinMsg.action === exports.BuiltinActionType.RoomClose) {
1741
+ yield this.exit();
1742
+ }
1743
+ break;
1744
+ }
1745
+ /**
1746
+ * 被踢出房间
1747
+ */
1748
+ case exports.Command.UserKickOut: {
1749
+ this.emit('kickOut');
1750
+ break;
1751
+ }
1752
+ /**
1753
+ * 其它未知广播
1754
+ */
1542
1755
  default: {
1543
- throw new Error('unknown built-in RTC type');
1756
+ console.warn('unknown command: ', command);
1544
1757
  }
1545
1758
  }
1546
1759
  }
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
- });
1760
+ else {
1761
+ this.emit('error', liveMsg);
1762
+ }
1763
+ }
1764
+ });
1765
+ /**
1766
+ * 清理带看缓存的数据
1767
+ */
1768
+ this._clearLiveData = () => {
1769
+ this._buildInData = { keyframes: {} };
1770
+ };
1771
+ /**
1772
+ * 连接带看
1773
+ * @param options
1774
+ * @returns
1775
+ */
1776
+ this.connect = (options = {}) => __awaiter(this, void 0, void 0, function* () {
1777
+ var _h, _j, _k, _l;
1778
+ // 检查 url 和 票据获取接口实现
1779
+ this._options.url = (_j = (_h = options.url) !== null && _h !== void 0 ? _h : this._options.url) !== null && _j !== void 0 ? _j : '';
1780
+ this._options.getTicket = (_k = options.getTicket) !== null && _k !== void 0 ? _k : this._options.getTicket;
1781
+ this._options.initialMicroStatus =
1782
+ (_l = options.rtcMicStatus) !== null && _l !== void 0 ? _l : this._options.initialMicroStatus;
1783
+ if (!/^ws(s):\/\//.test(this._options.url) ||
1784
+ typeof this._options.getTicket !== 'function') {
1785
+ if (!/^ws(s):\/\//.test(this._options.url)) {
1786
+ return new Error('Illegal realsee live room link');
1787
+ }
1788
+ if (typeof this._options.getTicket !== 'function') {
1789
+ return new Error('getTicket muse be function');
1790
+ }
1791
+ return false;
1792
+ }
1793
+ const { force = false } = options;
1794
+ // 检查是否已有实例在使用
1795
+ const currentState = this.state;
1796
+ if (currentState === exports.LiveState.CONNECTING ||
1797
+ currentState === exports.LiveState.OPEN) {
1798
+ if (force) {
1799
+ try {
1800
+ yield this._controller.close('force close by connect');
1562
1801
  }
1563
- else {
1564
- // 其它终端使用
1565
- liveController.options.rtc =
1566
- options.builtInRTCType === exports.BuiltInRTCType.RealseeXChimeRTC
1567
- ? new BrowserRTC4Chime({ getVoiceSign: getVoiceSign })
1568
- : new BrowserRTC({ getVoiceSign: getVoiceSign });
1802
+ catch (e) {
1803
+ console.warn(e);
1569
1804
  }
1570
1805
  }
1806
+ else {
1807
+ return new Error('已有Live实例正在连接中,请勿重复连接!');
1808
+ }
1571
1809
  }
1572
- if (!liveController.options.rtc) {
1573
- console.warn('unused rtc');
1574
- }
1575
- // 默认自动连接
1576
- if (liveController.options.url && liveController.options.getTicket) {
1577
- _this.connect();
1810
+ // 建立连接
1811
+ this._clearLiveData();
1812
+ const url = appendUri(this._options.url, {
1813
+ ticket: yield this._options.getTicket(),
1814
+ force: Number(!!force),
1815
+ });
1816
+ this._controller.open(url);
1817
+ return true;
1818
+ });
1819
+ /**
1820
+ * 退出带看
1821
+ * @returns
1822
+ */
1823
+ this.exit = () => __awaiter(this, void 0, void 0, function* () {
1824
+ var _m;
1825
+ this._clearLiveData();
1826
+ try {
1827
+ /** 退出强制关闭语音 */
1828
+ (_m = this.$RTC) === null || _m === void 0 ? void 0 : _m.quit();
1829
+ yield this.updateStatus(exports.BuiltinEventType.RoomChange, exports.BuiltinActionType.RoomClose, {});
1578
1830
  }
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);
1831
+ catch (e) {
1832
+ logger$1.warn(e);
1593
1833
  }
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
1834
+ return yield this._controller.close('user exit');
1610
1835
  });
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
1618
- });
1619
- Object.defineProperty(LiveTpl.prototype, "selfInfo", {
1620
- get: function () {
1621
- return liveController.selfUserInfo;
1622
- },
1623
- enumerable: false,
1624
- configurable: true
1836
+ /**
1837
+ * 销毁带看
1838
+ * @returns
1839
+ */
1840
+ this.dispose = () => __awaiter(this, void 0, void 0, function* () {
1841
+ this._removeLiveControllerEventListeners();
1842
+ this._clearLiveData();
1843
+ return yield this._controller.dispose();
1625
1844
  });
1626
- Object.defineProperty(LiveTpl.prototype, "userList", {
1627
- get: function () {
1628
- return liveController.userList || [];
1629
- },
1630
- enumerable: false,
1631
- configurable: true
1845
+ /**
1846
+ * 设置自己的用户信息
1847
+ * @param userInfo
1848
+ * @returns
1849
+ */
1850
+ this.setSelfInfo = (userInfo) => __awaiter(this, void 0, void 0, function* () {
1851
+ return yield this.updateStatus(exports.BuiltinEventType.UserChange, exports.BuiltinActionType.UserInfo, userInfo);
1632
1852
  });
1633
- Object.defineProperty(LiveTpl.prototype, "snapshot", {
1634
- get: function () {
1635
- return liveController.keyframes || {};
1636
- },
1637
- enumerable: false,
1638
- configurable: true
1853
+ // 仅用于用户自己的麦克风控制
1854
+ this.toggleMicro = (microStatus) => __awaiter(this, void 0, void 0, function* () {
1855
+ var _o, _p, _q;
1856
+ if (!((_p = (_o = this.selfInfo) === null || _o === void 0 ? void 0 : _o.permission) === null || _p === void 0 ? void 0 : _p.control_own_micro))
1857
+ return false;
1858
+ const result = yield ((_q = this.$RTC) === null || _q === void 0 ? void 0 : _q.toggleMicro(microStatus));
1859
+ if (result) {
1860
+ yield this.updateStatus(exports.BuiltinEventType.UserChange, exports.BuiltinActionType.UserMicroStatus, {
1861
+ status: microStatus ? exports.MicroStatus.OPEN : exports.MicroStatus.CLOSE,
1862
+ }, []);
1863
+ }
1864
+ return result;
1639
1865
  });
1640
- Object.defineProperty(LiveTpl.prototype, "$RTC", {
1641
- get: function () {
1642
- return liveController.options.rtc;
1643
- },
1644
- enumerable: false,
1645
- configurable: true
1866
+ /**
1867
+ * 控制别人的麦
1868
+ * @param microStatus
1869
+ * @param toUserIds
1870
+ * @returns
1871
+ */
1872
+ this.forbidMicro = (microStatus, toUserIds) => __awaiter(this, void 0, void 0, function* () {
1873
+ var _r, _s;
1874
+ if (typeof this._options.canForbidUserMicro === 'function' &&
1875
+ !this._options.canForbidUserMicro(toUserIds)) {
1876
+ return false;
1877
+ }
1878
+ if (!((_s = (_r = this.selfInfo) === null || _r === void 0 ? void 0 : _r.permission) === null || _s === void 0 ? void 0 : _s.control_other_micro)) {
1879
+ return false;
1880
+ }
1881
+ return yield this.updateStatus(exports.BuiltinEventType.UserChange, exports.BuiltinActionType.UserMicroStatus, {
1882
+ status: microStatus,
1883
+ }, toUserIds);
1646
1884
  });
1647
- Object.defineProperty(LiveTpl.prototype, "jsBridge", {
1648
- get: function () {
1649
- return liveController.options.jsBridge;
1650
- },
1651
- enumerable: false,
1652
- configurable: true
1885
+ /**
1886
+ * 控制别人的同步全量帧数据权限
1887
+ * @param sync
1888
+ * @param toUserIds
1889
+ * @returns
1890
+ */
1891
+ this.forbidSync = (sync, toUserIds) => __awaiter(this, void 0, void 0, function* () {
1892
+ var _t, _u;
1893
+ if (typeof this._options.canForbidUserSync === 'function' &&
1894
+ !this._options.canForbidUserSync(toUserIds)) {
1895
+ return false;
1896
+ }
1897
+ if (!((_u = (_t = this.selfInfo) === null || _t === void 0 ? void 0 : _t.permission) === null || _u === void 0 ? void 0 : _u.control_other_sync)) {
1898
+ return false;
1899
+ }
1900
+ return yield this.updateStatus(exports.BuiltinEventType.UserChange, exports.BuiltinActionType.UserPermission, { sync_frame: sync }, toUserIds);
1653
1901
  });
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.');
1902
+ /**
1903
+ * 把用户踢出带看
1904
+ * @param toUserIds
1905
+ * @returns
1906
+ */
1907
+ this.kick = (toUserIds) => __awaiter(this, void 0, void 0, function* () {
1908
+ var _v, _w;
1909
+ if (typeof this._options.canForbidUserKick === 'function' &&
1910
+ !this._options.canForbidUserKick(toUserIds)) {
1911
+ return false;
1682
1912
  }
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.');
1913
+ if (!((_w = (_v = this.selfInfo) === null || _v === void 0 ? void 0 : _v.permission) === null || _w === void 0 ? void 0 : _w.change_other_status)) {
1914
+ return false;
1692
1915
  }
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()];
1916
+ return yield this.updateStatus(exports.BuiltinEventType.UserChange, exports.BuiltinActionType.UserStatus, {
1917
+ status: 'KICK_OUT',
1918
+ }, toUserIds);
1919
+ });
1920
+ this._addLiveControllerEventListeners();
1921
+ this._options = Object.assign({ initialMicroStatus: exports.MicroStatus.OPEN }, opts);
1922
+ // 第一步检查jsbridge
1923
+ this._options.jsBridge = (() => {
1924
+ if (opts.jsBridge)
1925
+ return opts.jsBridge;
1926
+ if (opts.useBuiltInJsBridge)
1927
+ return new JSBridge__default["default"]();
1928
+ return undefined;
1929
+ })();
1930
+ // 第二步检查getVoiceSign
1931
+ this._options.getVoiceSign = (_a = opts.getVoiceSign) !== null && _a !== void 0 ? _a : unimplementedGetVoiceSign;
1932
+ // 第二步检查rtc
1933
+ this._options.rtc = (() => {
1934
+ // 优先取rtc实例
1935
+ if (opts.rtc)
1936
+ return opts.rtc;
1937
+ // 取指定的内部rtc类型
1938
+ if (opts.rtcType) {
1939
+ if (!opts.getVoiceSign) {
1940
+ logger$1.error('GetVoiceSign method must be passed when using built-in RTC instances');
1941
+ }
1942
+ switch (opts.rtcType) {
1943
+ case exports.RTCType.RealseeVRWebViewRTC: {
1944
+ // 内置的 VRWebViewRTC
1945
+ if (this._options.jsBridge) {
1946
+ return new VRWebViewRTC({
1947
+ jsBridge: this._options.jsBridge,
1948
+ getVoiceSign: this._options.getVoiceSign,
1949
+ });
1950
+ }
1951
+ else {
1952
+ logger$1.error('JsBridge instance must be passed when using built-in VRWebViewRTC instances');
1953
+ return undefined;
1954
+ }
1745
1955
  }
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()];
1956
+ case exports.RTCType.RealseeBrowserChimeRTC: {
1957
+ // 内置的 RealseeBrowserChimeRTC
1958
+ return new BrowserRTC4Chime({
1959
+ getVoiceSign: this._options.getVoiceSign,
1960
+ logLevel: opts.__debug__ ? LogLevel.DEBUG : LogLevel.ERROR,
1961
+ });
1766
1962
  }
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()];
1963
+ case exports.RTCType.RealseeBrowserRTC: {
1964
+ // 内置的 RealseeBrowserRTC
1965
+ return new BrowserRTC({
1966
+ getVoiceSign: this._options.getVoiceSign,
1967
+ });
1788
1968
  }
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()];
1969
+ default: {
1970
+ logger$1.error('unknown built-in RTC type');
1971
+ return undefined;
1809
1972
  }
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()];
1973
+ }
1974
+ }
1975
+ // 都不满足时取内置
1976
+ if (opts.useBuiltInRTC) {
1977
+ if (!opts.getVoiceSign) {
1978
+ logger$1.error('GetVoiceSign method must be passed when using built-in RTC instances');
1979
+ }
1980
+ if (this._options.jsBridge) {
1981
+ if ((isRealseeVRWebview && (isAndroid || isIOS)) || isWxMiniProgram) {
1982
+ return new VRWebViewRTC({
1983
+ jsBridge: this._options.jsBridge,
1984
+ getVoiceSign: this._options.getVoiceSign,
1985
+ });
1830
1986
  }
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()];
1987
+ else {
1988
+ // 其它终端使用
1989
+ return opts.builtInRTCType === exports.BuiltInRTCType.RealseeXChimeRTC
1990
+ ? new BrowserRTC4Chime({
1991
+ getVoiceSign: this._options.getVoiceSign,
1992
+ })
1993
+ : new BrowserRTC({ getVoiceSign: this._options.getVoiceSign });
1964
1994
  }
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;
1995
+ }
1996
+ else {
1997
+ logger$1.error('jsBridge instance must be passed when using built-in RTC instances');
1998
+ return undefined;
1999
+ }
2000
+ }
2001
+ return undefined;
2002
+ })();
2003
+ if (!this._options.rtc) {
2004
+ logger$1.warn('unused rtc');
2005
+ }
2006
+ // 第三步进行自动连接
2007
+ if (this._options.url && this._options.getTicket) {
2008
+ this.connect();
2009
+ }
2010
+ if (this._options.__debug__) {
2011
+ Object.assign(window, { $liveController: this._controller, $live: this });
2012
+ }
2013
+ }
2014
+ get options() {
2015
+ return Object.freeze(this._options || {});
2016
+ }
2017
+ /**
2018
+ * 带看状态
2019
+ */
2020
+ get state() {
2021
+ return this._controller.state;
2022
+ }
2023
+ /**
2024
+ * 兼容老逻辑
2025
+ * @deprecated 请直接读取 state 属性字段,未来将移除该属性
2026
+ */
2027
+ get readyState() {
2028
+ return this._controller.state;
2029
+ }
2030
+ /**
2031
+ * 获取当前WebSocket连接的URL。(注意:这个是WebSocket连接的完整连接,附带一些query参数)。
2032
+ * @deprecated 带看不需要关注底层ws的相关信息,未来将移除
2033
+ */
2034
+ get url() {
2035
+ return this.options.url;
2036
+ }
2037
+ /**
2038
+ * 获取当前live使用的RTC实例
2039
+ */
2040
+ get $RTC() {
2041
+ return this._options.rtc;
2042
+ }
2043
+ /**
2044
+ * 获取当前live使用的jsBridge实例
2045
+ */
2046
+ get jsBridge() {
2047
+ return this._options.jsBridge;
2048
+ }
2049
+ /**
2050
+ * 当前帧数据快照
2051
+ */
2052
+ get snapshot() {
2053
+ return this._buildInData.keyframes;
2054
+ }
2055
+ /**
2056
+ * 当前用户信息
2057
+ */
2058
+ get selfInfo() {
2059
+ return this._buildInData.selfInfo;
2060
+ }
2061
+ /**
2062
+ * 当前用户列表
2063
+ */
2064
+ get userList() {
2065
+ return this._buildInData.userList || [];
2066
+ }
2067
+ /**
2068
+ * 当前带看房间信息
2069
+ */
2070
+ get roomInfo() {
2071
+ return this._buildInData.roomInfo;
2072
+ }
2073
+ /**
2074
+ * 修改状态
2075
+ * @param evtType
2076
+ * @param atnType
2077
+ * @param status
2078
+ * @param toUserIds
2079
+ * @returns
2080
+ */
2081
+ updateStatus(evtType, atnType, status, toUserIds) {
2082
+ return __awaiter(this, void 0, void 0, function* () {
2083
+ if (this.state !== exports.LiveState.OPEN)
2084
+ return false;
2085
+ const data = Object.assign({ event_type: evtType, action: atnType }, { data: status });
2086
+ const liveMsg = createLiveMsg(exports.Command.BuiltinMsg, data, toUserIds);
2087
+ try {
2088
+ this._controller.sendMessage(liveMsg);
2089
+ return true;
2090
+ }
2091
+ catch (e) {
2092
+ logger$1.error(e);
2093
+ return false;
2094
+ }
2095
+ });
2096
+ }
2097
+ /**
2098
+ * 自定义广播
2099
+ * @param request 广播请求的数据
2100
+ * @param toUserIds
2101
+ * @param timeout
2102
+ * @returns
2103
+ */
2104
+ broadcast(request, toUserIds, timeout) {
2105
+ if (this.state !== exports.LiveState.OPEN)
2106
+ return false;
2107
+ return new Promise((resolve, reject) => {
2108
+ const customEvent = createLiveMsg(exports.Command.CustomEvent, request, toUserIds);
2109
+ const front_request_id = customEvent.front_request_id;
2110
+ const timeoutId = timeout
2111
+ ? setTimeout(() => {
2112
+ reject(new Error('RESPONSE TIMEOUT'));
2113
+ this.off('broadcast', broadcastRes);
2114
+ }, timeout)
2115
+ : undefined;
2116
+ const broadcastRes = (data, frontRequestId) => {
2117
+ if (frontRequestId !== front_request_id)
2118
+ return;
2119
+ if (timeoutId)
2120
+ clearTimeout(timeoutId);
2121
+ this.off('broadcast', broadcastRes);
2122
+ resolve(data);
2123
+ };
2124
+ this.on('broadcast', broadcastRes);
2125
+ try {
2126
+ this._controller.sendMessage(customEvent);
2127
+ }
2128
+ catch (e) {
2129
+ reject(e);
2130
+ }
2131
+ });
2132
+ }
1984
2133
  }
1985
2134
 
2135
+ /**
2136
+ * 创建`Live`实例
2137
+ * @param opts
2138
+ * @returns
2139
+ */
2140
+ const createLive = (opts) => {
2141
+ _clearLiveInstanceIfNeed();
2142
+ return new Live(opts);
2143
+ };
2144
+
1986
2145
  /**
1987
2146
  * 创建 {@link LiveReact} 实例,并提供 `React` 技术栈相关工具链。
1988
2147
  */
1989
2148
  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);
2149
+ const LiveContext = React.createContext(null);
2150
+ const live = createLive(options);
2151
+ const jsBridge = live.jsBridge;
2152
+ const LiveProvider = (props) => (React__default["default"].createElement(LiveContext.Provider, { value: live }, props.children));
2153
+ /**
2154
+ * 使用live实例
2155
+ * @returns
2156
+ */
2157
+ const useLiveInstance = () => {
2158
+ const context = React__default["default"].useContext(LiveContext);
1998
2159
  if (!context)
1999
2160
  throw new Error('LiveProvider never found.');
2000
2161
  return context;
2001
- }
2162
+ };
2002
2163
  /**
2164
+ * 不建议这样使用
2003
2165
  * @deprecated
2004
2166
  * @returns
2005
2167
  */
2006
- function unsafe__useLiveInstance() {
2007
- return useLiveInstance();
2008
- }
2009
- function useRTCInstance() {
2010
- var live = useLiveInstance();
2011
- return live.$RTC;
2012
- }
2168
+ const unsafe__useLiveInstance = React.useCallback(() => useLiveInstance(), [useLiveInstance]);
2169
+ /**
2170
+ * 使用rtc实例
2171
+ */
2172
+ const useRTCInstance = React.useCallback(() => useLiveInstance().$RTC, [useLiveInstance]);
2013
2173
  /**
2174
+ * 不建议这样使用
2014
2175
  * @deprecated
2015
2176
  * @returns
2016
2177
  */
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);
2178
+ const unsafe__useRTCInstance = React.useCallback(() => useRTCInstance(), [useRTCInstance]);
2179
+ /**
2180
+ * 带看连接操作
2181
+ */
2182
+ const useConnect = React.useCallback((options) => __awaiter(this, void 0, void 0, function* () { return yield useLiveInstance().connect(options); }), []);
2183
+ /**
2184
+ *
2185
+ * @param name
2186
+ * @param callback
2187
+ * @param deps
2188
+ * @returns
2189
+ */
2190
+ function useKeyframeUpdateCallback(key, callback, deps = []) {
2191
+ const live = useLiveInstance();
2192
+ const dependencyList = [live, name, ...deps];
2193
+ const dispose = () => live.keyframes.off(key, callback);
2194
+ React__default["default"].useEffect(() => {
2195
+ live.keyframes.on(key, callback);
2047
2196
  return dispose;
2048
2197
  }, dependencyList);
2049
2198
  return dispose;
2050
2199
  }
2200
+ /**
2201
+ * 带看的一些操作
2202
+ * @returns
2203
+ */
2051
2204
  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]);
2205
+ const live = useLiveInstance();
2206
+ const connect = React__default["default"].useCallback((options) => __awaiter(this, void 0, void 0, function* () { return yield live.connect(options); }), [live]);
2207
+ const toggleMicro = React__default["default"].useCallback((microStatus) => live.toggleMicro(microStatus), [live]);
2208
+ 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]);
2209
+ const exit = React__default["default"].useCallback(() => __awaiter(this, void 0, void 0, function* () { return yield live.exit(); }), [live]);
2210
+ const kick = React__default["default"].useCallback((toUserIds) => __awaiter(this, void 0, void 0, function* () { return yield live.kick(toUserIds); }), [live]);
2211
+ const forbidMicro = React__default["default"].useCallback((micro, toUserIds = []) => __awaiter(this, void 0, void 0, function* () { return yield live.forbidMicro(micro, toUserIds); }), [live]);
2212
+ const forbidSync = React__default["default"].useCallback((sync, toUserIds = []) => live.forbidSync(sync, toUserIds), [live]);
2213
+ const getFramesByKey = React__default["default"].useCallback((key) => live.getFramesByKey(key), [live]);
2214
+ const sendKeyframe = React__default["default"].useCallback((key, frame) => live.sendKeyframe(key, frame), [live]);
2215
+ const setSelfInfo = React__default["default"].useCallback((userInfo) => live.setSelfInfo(userInfo), [live]);
2216
+ const updateStatus = React__default["default"].useCallback((evtType, atnType, status, toUserIds) => live.updateStatus(evtType, atnType, status, toUserIds), [live]);
2074
2217
  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,
2218
+ connect,
2219
+ broadcast,
2220
+ exit,
2221
+ kick,
2222
+ toggleMicro,
2223
+ forbidMicro,
2224
+ forbidSync,
2225
+ sendKeyframe,
2226
+ getFramesByKey,
2227
+ setSelfInfo,
2228
+ updateStatus,
2085
2229
  };
2086
2230
  }
2087
2231
  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;
2232
+ const live = useLiveInstance();
2233
+ const [state, updateState] = React__default["default"].useState(live.getFramesByKey(key));
2234
+ React__default["default"].useEffect(() => {
2235
+ const onUpdate = (nextKeyframes) => updateState(nextKeyframes);
2236
+ const evtName = key;
2237
+ const callback = onUpdate;
2096
2238
  live.keyframes.on(evtName, callback);
2097
- return function () { return live.keyframes.off(evtName, callback); };
2239
+ return () => live.keyframes.off(evtName, callback);
2098
2240
  }, [live]);
2099
- var setState = React__default["default"].useCallback(function (frame) { return live.sendKeyframe(key, frame); }, [live]);
2241
+ const setState = React__default["default"].useCallback((frame) => live.sendKeyframe(key, frame), [live]);
2100
2242
  return [state, setState];
2101
2243
  }
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 () {
2244
+ function useLiveEventCallback(name, callback, deps = []) {
2245
+ const live = useLiveInstance();
2246
+ const dispose = () => live.off(name, callback);
2247
+ const dependencyList = [live, name, ...deps];
2248
+ React__default["default"].useEffect(() => {
2108
2249
  live.on(name, callback);
2109
2250
  return dispose;
2110
2251
  }, dependencyList);
2111
2252
  return dispose;
2112
2253
  }
2113
2254
  /**
2114
- * @deprecated
2255
+ * 带看状态
2115
2256
  * @returns
2116
2257
  */
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); };
2258
+ function useLiveState() {
2259
+ const live = useLiveInstance();
2260
+ const [state, updateState] = React__default["default"].useState(live.state);
2261
+ React__default["default"].useEffect(() => {
2262
+ const stateChange = (state) => updateState(state);
2263
+ live.on('stateChange', stateChange);
2264
+ return () => live.off('stateChange', stateChange);
2126
2265
  }, [live]);
2127
2266
  return state;
2128
2267
  }
2129
2268
  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]);
2269
+ const live = useLiveInstance();
2270
+ const join = React__default["default"].useCallback((options) => live.$RTC.join(options), [live]);
2271
+ const quit = React__default["default"].useCallback(() => live.$RTC.quit(), [live]);
2272
+ 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]);
2273
+ const toggleMicro = React__default["default"].useCallback((flag) => live.$RTC.toggleMicro(flag), [live]);
2274
+ const detectMicro = React__default["default"].useCallback(() => live.$RTC.detectMicro(), [live]);
2136
2275
  return {
2137
- join: join,
2138
- quit: quit,
2139
- shock: shock,
2140
- toggleMicro: toggleMicro,
2141
- detectMicro: detectMicro,
2276
+ join,
2277
+ quit,
2278
+ shock,
2279
+ toggleMicro,
2280
+ detectMicro,
2142
2281
  };
2143
2282
  }
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 () {
2283
+ function useRTCEventCallback(name, callback, deps = []) {
2284
+ const live = useLiveInstance();
2285
+ const dispose = () => live.$RTC.off(name, callback);
2286
+ const dependencyList = [live, name, ...deps];
2287
+ React__default["default"].useEffect(() => {
2150
2288
  live.$RTC.on(name, callback);
2151
2289
  return dispose;
2152
2290
  }, dependencyList);
2153
2291
  return dispose;
2154
2292
  }
2155
2293
  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 () {
2294
+ const live = useLiveInstance();
2295
+ const [state, updateState] = React__default["default"].useState(live.selfInfo || {});
2296
+ const selfInfoUpdate = (userInfo) => updateState(userInfo);
2297
+ React__default["default"].useEffect(() => {
2163
2298
  live.on('selfInfoUpdate', selfInfoUpdate);
2164
- return function () { return live.off('selfInfoUpdate', selfInfoUpdate); };
2299
+ return () => live.off('selfInfoUpdate', selfInfoUpdate);
2165
2300
  }, [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]);
2301
+ const setState = React__default["default"].useCallback((userInfo) => __awaiter(this, void 0, void 0, function* () {
2302
+ return yield live.setSelfInfo(userInfo);
2303
+ }), [live]);
2174
2304
  return [state, setState];
2175
2305
  }
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); };
2306
+ function useKeyframesSnapshot() {
2307
+ const live = useLiveInstance();
2308
+ const [state, setState] = React__default["default"].useState(live.snapshot);
2309
+ React__default["default"].useEffect(() => {
2310
+ const onKeyframes = (keyframes) => setState(keyframes);
2181
2311
  live.on('keyframes', onKeyframes);
2182
- return function () { return live.off('keyframes', onKeyframes); };
2312
+ return () => live.off('keyframes', onKeyframes);
2183
2313
  });
2184
2314
  return state;
2185
2315
  }
2186
2316
  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 () {
2317
+ const live = useLiveInstance();
2318
+ const [state, updateState] = React__default["default"].useState(live.userList);
2319
+ const userListUpdate = (userList) => updateState(userList);
2320
+ React__default["default"].useEffect(() => {
2191
2321
  live.on('userListUpdate', userListUpdate);
2192
- return function () { return live.off('userListUpdate', userListUpdate); };
2322
+ return () => live.off('userListUpdate', userListUpdate);
2193
2323
  }, [live]);
2194
2324
  return state;
2195
2325
  }
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
2326
  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,
2327
+ live,
2328
+ jsBridge,
2329
+ LiveProvider,
2330
+ unsafe__useLiveInstance,
2331
+ unsafe__useRTCInstance,
2332
+ useConnect,
2333
+ useKeyframe,
2334
+ useKeyframeUpdateCallback,
2335
+ useLiveAction,
2336
+ useLiveEventCallback,
2337
+ useLiveState,
2338
+ useRTCAction,
2339
+ useRTCEventCallback,
2340
+ useSelfInfo,
2341
+ useKeyframesSnapshot,
2342
+ useUserList,
2234
2343
  };
2235
2344
  }
2236
2345