fcr-core
Version:
Core APIs for building online scenes
272 lines (268 loc) • 16.3 kB
JavaScript
"use strict";
require("core-js/modules/es.array.push.js");
require("core-js/modules/esnext.function.metadata.js");
require("core-js/modules/esnext.map.delete-all.js");
require("core-js/modules/esnext.map.emplace.js");
require("core-js/modules/esnext.map.every.js");
require("core-js/modules/esnext.map.filter.js");
require("core-js/modules/esnext.map.find.js");
require("core-js/modules/esnext.map.find-key.js");
require("core-js/modules/esnext.map.includes.js");
require("core-js/modules/esnext.map.key-of.js");
require("core-js/modules/esnext.map.map-keys.js");
require("core-js/modules/esnext.map.map-values.js");
require("core-js/modules/esnext.map.merge.js");
require("core-js/modules/esnext.map.reduce.js");
require("core-js/modules/esnext.map.some.js");
require("core-js/modules/esnext.map.update.js");
require("core-js/modules/esnext.symbol.metadata.js");
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.FcrWhiteboardControlImpl = void 0;
var _enums = require("../whiteboard-control/enums");
var _forgeRoom = require("@netless/forge-room");
var _forgeWhiteboard = require("@netless/forge-whiteboard");
var _forgeRtm = require("@netless/forge-rtm");
var _asyncRetry = require("agora-foundation/lib/utilities/async-retry");
var _imports = require("../../imports");
var _mainWindow = require("./main-window");
var _user = require("../../utilities/user");
var _observable = require("agora-foundation/lib/utilities/observable");
var _type = require("../../type");
var _logger = require("../../utilities/logger");
var _error = require("../../utilities/error");
var _validateParams = _interopRequireDefault(require("../../utilities/validate-params"));
var _schema = require("../../schema");
var _packageInfo = require("../../utilities/package-info");
let _initProto, _setBackgroundColorDecs;
function _applyDecs(e, t, r, n, o, a) { function i(e, t, r) { return function (n, o) { return r && r(n), e[t].call(n, o); }; } function c(e, t) { for (var r = 0; r < e.length; r++) e[r].call(t); return t; } function s(e, t, r, n) { if ("function" != typeof e && (n || void 0 !== e)) throw new TypeError(t + " must " + (r || "be") + " a function" + (n ? "" : " or undefined")); return e; } function applyDec(e, t, r, n, o, a, c, u, l, f, p, d, h) { function m(e) { if (!h(e)) throw new TypeError("Attempted to access private element on non-instance"); } var y, v = t[0], g = t[3], b = !u; if (!b) { r || Array.isArray(v) || (v = [v]); var w = {}, S = [], A = 3 === o ? "get" : 4 === o || d ? "set" : "value"; f ? (p || d ? w = { get: _setFunctionName(function () { return g(this); }, n, "get"), set: function (e) { t[4](this, e); } } : w[A] = g, p || _setFunctionName(w[A], n, 2 === o ? "" : A)) : p || (w = Object.getOwnPropertyDescriptor(e, n)); } for (var P = e, j = v.length - 1; j >= 0; j -= r ? 2 : 1) { var D = v[j], E = r ? v[j - 1] : void 0, I = {}, O = { kind: ["field", "accessor", "method", "getter", "setter", "class"][o], name: n, metadata: a, addInitializer: function (e, t) { if (e.v) throw Error("attempted to call addInitializer after decoration was finished"); s(t, "An initializer", "be", !0), c.push(t); }.bind(null, I) }; try { if (b) (y = s(D.call(E, P, O), "class decorators", "return")) && (P = y);else { var k, F; O.static = l, O.private = f, f ? 2 === o ? k = function (e) { return m(e), w.value; } : (o < 4 && (k = i(w, "get", m)), 3 !== o && (F = i(w, "set", m))) : (k = function (e) { return e[n]; }, (o < 2 || 4 === o) && (F = function (e, t) { e[n] = t; })); var N = O.access = { has: f ? h.bind() : function (e) { return n in e; } }; if (k && (N.get = k), F && (N.set = F), P = D.call(E, d ? { get: w.get, set: w.set } : w[A], O), d) { if ("object" == typeof P && P) (y = s(P.get, "accessor.get")) && (w.get = y), (y = s(P.set, "accessor.set")) && (w.set = y), (y = s(P.init, "accessor.init")) && S.push(y);else if (void 0 !== P) throw new TypeError("accessor decorators must return an object with get, set, or init properties or void 0"); } else s(P, (p ? "field" : "method") + " decorators", "return") && (p ? S.push(P) : w[A] = P); } } finally { I.v = !0; } } return (p || d) && u.push(function (e, t) { for (var r = S.length - 1; r >= 0; r--) t = S[r].call(e, t); return t; }), p || b || (f ? d ? u.push(i(w, "get"), i(w, "set")) : u.push(2 === o ? w[A] : i.call.bind(w[A])) : Object.defineProperty(e, n, w)), P; } function u(e, t) { return Object.defineProperty(e, Symbol.metadata || Symbol.for("Symbol.metadata"), { configurable: !0, enumerable: !0, value: t }); } if (arguments.length >= 6) var l = a[Symbol.metadata || Symbol.for("Symbol.metadata")]; var f = Object.create(null == l ? null : l), p = function (e, t, r, n) { var o, a, i = [], s = function (t) { return _checkInRHS(t) === e; }, u = new Map(); function l(e) { e && i.push(c.bind(null, e)); } for (var f = 0; f < t.length; f++) { var p = t[f]; if (Array.isArray(p)) { var d = p[1], h = p[2], m = p.length > 3, y = 16 & d, v = !!(8 & d), g = 0 == (d &= 7), b = h + "/" + v; if (!g && !m) { var w = u.get(b); if (!0 === w || 3 === w && 4 !== d || 4 === w && 3 !== d) throw Error("Attempted to decorate a public method/accessor that has the same name as a previously decorated public method/accessor. This is not currently supported by the decorators plugin. Property name was: " + h); u.set(b, !(d > 2) || d); } applyDec(v ? e : e.prototype, p, y, m ? "#" + h : _toPropertyKey(h), d, n, v ? a = a || [] : o = o || [], i, v, m, g, 1 === d, v && m ? s : r); } } return l(o), l(a), i; }(e, t, o, f); return r.length || u(e, f), { e: p, get c() { var t = []; return r.length && [u(applyDec(e, [r], n, e.name, 5, f, t), f), c.bind(null, t, e)]; } }; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; }
function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
function _setFunctionName(e, t, n) { "symbol" == typeof t && (t = (t = t.description) ? "[" + t + "]" : ""); try { Object.defineProperty(e, "name", { configurable: !0, value: n ? n + " " + t : t }); } catch (e) {} return e; }
function _checkInRHS(e) { if (Object(e) !== e) throw TypeError("right-hand side of 'in' should be an object, got " + (null !== e ? typeof e : "null")); return e; }
class FcrWhiteboardControlImpl {
static #_ = (() => [_initProto] = _applyDecs(this, [[_imports.trace, 2, "open"], [_imports.trace, 2, "close"], [_imports.trace, 2, "active"], [_imports.trace, 2, "inactive"], [[_imports.bound, _imports.trace], 2, "getConnectionState"], [[_imports.bound, _imports.trace], 2, "getMainWindow"], [_imports.bound, 2, "getBoardActiveInfo"], [_setBackgroundColorDecs, 2, "setBackgroundColor"], [[_imports.bound, _imports.trace], 2, "getBackgroundColor"], [[_imports.bound, _imports.trace], 2, "getActivity"], [[_imports.bound, _imports.trace], 2, "getOwnerId"], [_imports.bound, 2, "_notifyObservers"], [_imports.bound, 2, "_updateConnnectionState"], [_imports.bound, 2, "_getToken"]], []).e)();
[(_setBackgroundColorDecs = [_imports.bound, _imports.trace, (0, _validateParams.default)(_schema.stringSchema)], "logger")] = (() => (_initProto(this), (0, _logger.createLogger)({
prefix: 'FcrWhiteboardControlImpl'
})))();
_observable = (() => new _observable.AgoraObservable())();
_connectState = (() => _type.FcrConnectionState.DISCONNECTED)();
_needRetry = true;
_FORGE_WHITEBOARD_APP_ID = 'MainWhiteboard';
constructor(_scene, _api, _engine, _sharedCache) {
this._scene = _scene;
this._api = _api;
this._engine = _engine;
this._sharedCache = _sharedCache;
this._roomCache = _sharedCache.getRoomCache(this._scene.sceneId);
this._addLogObserver();
_scene.addObserver(this._notifyObservers());
this.logger.info(`Whitebaord Version: forge-whiteboard@${(0, _packageInfo.getDependenciesInfo)('@netless/forge-whiteboard')}, forge-room@${(0, _packageInfo.getDependenciesInfo)('@netless/forge-room')}, forge-rtm@${(0, _packageInfo.getDependenciesInfo)('@netless/forge-rtm')}`);
}
async open() {
// 此宽高为设计稿中的白板尺寸,如无特殊需求,不建议修改
const width = 1920;
const height = 1220;
const roomId = this._scene.sceneId;
const userId = this._scene.localUser.getLocalUserId();
const nickName = this._scene.getUser(userId)?.userName;
const {
data
} = await this._getToken(roomId, userId);
const {
boardAppId: appIdentifier,
boardId,
boardRegion: region,
boardToken: roomToken
} = data || {};
// @ts-ignore
const rtmClient = this._engine._rtmClient._client;
const rtmProvider = new _forgeRtm.RTMProvider_2_2(rtmClient);
const wbRoom = new _forgeRoom.Room(boardId, rtmProvider);
// rtmProvider.addListener('connectionStatusChange', (state: ConnectionStatus) => {
// switch (state) {
// case 'CONNECTED':
// this._updateConnnectionState(FcrConnectionState.CONNECTED);
// break;
// case 'RECONNECTING':
// this._updateConnnectionState(FcrConnectionState.RECONNECTING);
// break;
// case 'CONNECTING':
// this._updateConnnectionState(FcrConnectionState.CONNECTING);
// break;
// case 'DISCONNECTED':
// this._updateConnnectionState(FcrConnectionState.DISCONNECTED);
// break;
// }
// });
// 由于白板用的也是 rtm 的链接状态,主应用也通过监听 rtm 状态的变化来显示加载动画,所以白板不再需要监听 rtm 状态的变化,三端、产品和测试已同步
// 白板的 rtm 状态和加入房间更新的状态用的是同一个枚举,在弱网环境下有冲突会导致问题,去掉之后即不再有此问题
wbRoom.applicationManager.registerApplication(_forgeWhiteboard.WhiteboardApplication);
try {
this._updateConnnectionState(_type.FcrConnectionState.CONNECTING);
this.logger.info('[whiteboard]: join board room, state: CONNECTING');
const retriesMax = 10;
await (0, _asyncRetry.retryAttempt)(async () => {
await wbRoom.joinRoom({
userId,
nickName,
roomToken,
sdkConfig: {
// @ts-ignore
region,
appIdentifier
}
});
this._boardRoom = wbRoom;
this.logger.info({
appIdentifier,
boardId,
region,
roomToken
});
const whiteboard = await wbRoom.applicationManager.launchApplication(_forgeWhiteboard.WhiteboardApplication, {
width,
height,
defaultToolbarStyle: {
tool: 'laser'
}
}, this._FORGE_WHITEBOARD_APP_ID);
whiteboard.enableCameraByMouse = false;
whiteboard.enableCameraByTouch = false;
whiteboard.setViewModeToMain();
// wbRoom.applicationManager.on('terminal', () => {
// this._updateConnnectionState(FcrConnectionState.DISCONNECTED);
// });
this._boardView = new _mainWindow.FcrBoardMainWindowImpl(whiteboard, this._scene, this._sharedCache, wbRoom);
this._needRetry = false;
this.logger.info('[whiteboard]: join board room success, state: CONNECTED');
this._updateConnnectionState(_type.FcrConnectionState.CONNECTED);
}, [], {
retriesMax
}).fail(async _ref => {
let {
error,
timeFn,
currentRetry
} = _ref;
this.logger.info(`[whiteboard]: failed to join board room, error: ${error.message}, current retry: ${currentRetry}`);
this._needRetry && (await timeFn());
this.logger.info(`[whiteboard]: continue attemptting? need retry: ${this._needRetry}`);
return this._needRetry;
}).abort(() => {
this.logger.info('[whiteboard]: join board room aborted, state: DISCONNECTED');
this._updateConnnectionState(_type.FcrConnectionState.DISCONNECTED);
}).exec();
} catch (e) {
this.logger.info('[whiteboard]: join board room failed, state: DISCONNECTED');
this._updateConnnectionState(_type.FcrConnectionState.DISCONNECTED);
}
return this._boardView;
}
async close() {
this._needRetry = false;
this._boardRoom?.applicationManager.terminateApplication(this._FORGE_WHITEBOARD_APP_ID);
await this._boardRoom?.leaveRoom();
this._boardRoom = undefined;
this._boardView = undefined;
}
async active() {
return (0, _error.handleRequestError)(() => this._api.toggleWhiteboardActivityState(this._scene.sceneId, _enums.FcrSharePermissionState.ON), _error.FcrErrorModuleCode.ROOM_WHITEBOARD, 'active failed');
}
async inactive() {
return (0, _error.handleRequestError)(() => this._api.toggleWhiteboardActivityState(this._scene.sceneId, _enums.FcrSharePermissionState.OFF), _error.FcrErrorModuleCode.ROOM_WHITEBOARD, 'inactive failed');
}
getConnectionState() {
return this._connectState;
}
getMainWindow() {
return this._boardView;
}
getBoardActiveInfo() {
const {
state,
ownerUserUuid: ownerUserId
} = this._scene.getScenePropertiesByKeyPath('widgets.netlessBoard');
if (state === _enums.FcrSharePermissionState.ON) {
return {
isActive: true,
ownerUserId
};
} else {
return {
isActive: false,
ownerUserId: null
};
}
}
async setBackgroundColor(backgroundColor) {
await this._api.setBackgroundColor({
roomId: this._scene.sceneId,
backgroundColor
});
this._boardView?.setBackgroundColor(backgroundColor);
}
getBackgroundColor() {
return this._scene.getScenePropertiesByKeyPath('widgets.netlessBoard.extra.backgroundColor');
}
getActivity() {
return this._scene.getScenePropertiesByKeyPath('widgets.netlessBoard').state === 1;
}
getOwnerId() {
return this._scene.getScenePropertiesByKeyPath('widgets.netlessBoard.ownerUserUuid');
}
addObserver(observer) {
this._observable.addObserver(observer);
}
removeObserver(observer) {
this._observable.removeObserver(observer);
}
_notifyObservers() {
return {
onScenePropertiesUpdated: (_, event) => {
const operatorUser = (0, _user.convertRteUserToFcrUser)(event.operatorUser, this._roomCache);
const getByKeyPath = value => this._scene.getScenePropertiesByKeyPath(value);
if (event.cause?.cmd === 10) {
const {
state,
ownerUserUuid
} = getByKeyPath('widgets.netlessBoard') ?? {
state: 0
};
const {
backgroundColor: bgColor
} = getByKeyPath('widgets.netlessBoard.extra') ?? {
backgroundColor: '#ffffff'
};
const widgetCauseReason = getByKeyPath('event.cause.data.widgetCause.data.reason');
const widgetCauseCmd = event.cause.data?.widgetCause?.cmd;
if (state === 1) {
this._observable.notifyObservers('onActive', ownerUserUuid, operatorUser);
}
if (state === 0) {
this._observable.notifyObservers('onInactive', widgetCauseReason, operatorUser);
}
if (widgetCauseCmd && widgetCauseCmd === 100101) {
this._observable.notifyObservers('onBackgroundColorUpdated', bgColor, operatorUser);
}
}
}
};
}
_updateConnnectionState(state) {
this._connectState = state;
this._observable.notifyObservers('onConnectionStateUpdated', state);
}
async _getToken(roomId, userId) {
return await (0, _error.handleRequestError)(() => this._api.getWhiteboardToken({
roomId,
userId
}), _error.FcrErrorModuleCode.ROOM_WHITEBOARD, 'get whiteboard token failed');
}
_addLogObserver() {
this.addObserver((0, _logger.generateLogObserver)(this.logger, ['onActive', 'onInactive', 'onBackgroundColorUpdated', 'onConnectionStateUpdated']));
}
}
exports.FcrWhiteboardControlImpl = FcrWhiteboardControlImpl;