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