fcr-core
Version:
Core APIs for building online scenes
348 lines (345 loc) • 21.5 kB
JavaScript
"use strict";
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.FcrUserControlImpl = void 0;
require("core-js/modules/es.array.push.js");
require("core-js/modules/esnext.iterator.constructor.js");
require("core-js/modules/esnext.iterator.find.js");
require("core-js/modules/esnext.iterator.for-each.js");
require("core-js/modules/esnext.iterator.map.js");
require("core-js/modules/esnext.iterator.reduce.js");
var _imports = require("../../imports");
var _type = require("../../type");
var _user = require("../../utilities/user");
var _type2 = require("./type");
var _collection = require("../../utilities/collection");
var _logger = require("../../utilities/logger");
var _error = require("../../utilities/error");
var _validateParams = _interopRequireDefault(require("../../utilities/validate-params"));
var _schema = require("../../schema");
let _initProto, _getUserDecs, _updateUserNameDecs, _updateUserPropertiesDecs, _updateIncrementUserPropertiesDecs, _deleteUserPropertiesDecs, _getUserPropertiesByUserIdDecs, _getUserPropertiesByKeyPathDecs, _updateRemoteUserRoleDecs, _claimHostDecs, _kickOutDecs, _kickOutByUserIdsDecs, _kickOutByUserRolesDecs, _mergeAudioStreamDecs;
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; }
/**
* @internal
*/
class FcrUserControlImpl {
static #_ = (() => [_initProto] = _applyDecs(this, [[_imports.bound, 2, "getLocalUser"], [_imports.bound, 2, "getUsers"], [_imports.bound, 2, "getUserList"], [_getUserDecs, 2, "getUser"], [[_imports.bound, _imports.trace], 2, "getAllUserCount"], [_imports.bound, 2, "getWaterMarkContent"], [[_imports.bound, _imports.trace], 2, "fetchUserList"], [_updateUserNameDecs, 2, "updateUserName"], [_updateUserPropertiesDecs, 2, "updateUserProperties"], [_updateIncrementUserPropertiesDecs, 2, "updateIncrementUserProperties"], [_deleteUserPropertiesDecs, 2, "deleteUserProperties"], [[_imports.bound, _imports.trace], 2, "getUserProperties"], [_getUserPropertiesByUserIdDecs, 2, "getUserPropertiesByUserId"], [_getUserPropertiesByKeyPathDecs, 2, "getUserPropertiesByKeyPath"], [_updateRemoteUserRoleDecs, 2, "updateRemoteUserRole"], [[_imports.bound, _imports.trace], 2, "revokeHost"], [_claimHostDecs, 2, "claimHost"], [_kickOutDecs, 2, "kickOut"], [_kickOutByUserIdsDecs, 2, "kickOutByUserIds"], [_kickOutByUserRolesDecs, 2, "kickOutByUserRoles"], [_mergeAudioStreamDecs, 2, "mergeAudioStream"]], []).e)();
//@internal
[(_getUserDecs = [_imports.bound, (0, _validateParams.default)(_schema.stringSchema)], _updateUserNameDecs = [_imports.bound, _imports.trace, (0, _validateParams.default)(_schema.stringSchema, _schema.stringSchema)], _updateUserPropertiesDecs = [_imports.bound, _imports.trace, (0, _validateParams.default)(_schema.stringKeyUnknownValueSchema, _schema.stringKeyUnknownValueSchema, _schema.stringSchema)], _updateIncrementUserPropertiesDecs = [_imports.bound, _imports.trace, (0, _validateParams.default)(_schema.stringKeyNumberValueSchema, _schema.stringKeyUnknownValueSchema, _schema.stringSchema)], _deleteUserPropertiesDecs = [_imports.bound, _imports.trace, (0, _validateParams.default)(_schema.stringArraySchema, _schema.stringKeyUnknownValueSchema, _schema.stringSchema)], _getUserPropertiesByUserIdDecs = [_imports.bound, _imports.trace, (0, _validateParams.default)(_schema.stringSchema)], _getUserPropertiesByKeyPathDecs = [_imports.bound, _imports.trace, (0, _validateParams.default)(_schema.stringSchema, _schema.stringSchema)], _updateRemoteUserRoleDecs = [_imports.bound, _imports.trace, (0, _validateParams.default)(_schema.stringSchema, _schema.fcrUserRoleSchema)], _claimHostDecs = [_imports.bound, _imports.trace, (0, _validateParams.default)(_schema.stringSchema)], _kickOutDecs = [_imports.bound, _imports.trace, (0, _validateParams.default)(_schema.stringSchema, _schema.fcrUserKickedOutTypeSchema)], _kickOutByUserIdsDecs = [_imports.trace, (0, _validateParams.default)(_schema.stringArraySchema, _schema.fcrUserKickedOutTypeSchema)], _kickOutByUserRolesDecs = [_imports.trace, (0, _validateParams.default)(_schema.fcrUserRolesSchema, _schema.fcrUserKickedOutTypeSchema)], _mergeAudioStreamDecs = [_imports.trace, (0, _validateParams.default)(_schema.stringSchema)], "logger")] = (() => (_initProto(this), (0, _logger.createLogger)({
prefix: 'FcrUserControlImpl'
})))();
//@internal
_observable = (() => new _imports.AgoraObservable())();
//@internal
_userMapByUserId = {};
//@internal
_userList = [];
//@internal
//@internal
//@internal
_sceneObserver = {
onRemoteUsersJoined: (roomId, events) => {
events.forEach(event => {
const userProperties = this._scene.getUserPropertiesByUserId(event.userInfo.userId);
this._roomCache.setUserPlatform(event.userInfo.userId, userProperties?.platform);
this._roomCache.setUserAvatar(event.userInfo.userId, userProperties?.avatar);
});
const fcrUserEvents = events.map(e => {
return {
userInfo: e.userInfo && (0, _user.convertRteUserToFcrUser)(e.userInfo, this._roomCache),
operatorUser: e.operatorUser && (0, _user.convertRteUserToFcrUser)(e.operatorUser, this._roomCache)
};
});
fcrUserEvents.forEach(event => {
const user = event.userInfo;
const exists = user.userId in this._userMapByUserId;
if (exists) {
this.logger.warn(`[FcrUserControl] user joined when the user already exists, userId: ${user.userId}`);
} else {
this._userMapByUserId[user.userId] = user;
this._userList.push(user);
}
});
this._observable.notifyObservers('onRemoteUsersJoined', roomId, fcrUserEvents);
},
onRemoteUsersLeft: (roomId, events) => {
const fcrUserEvents = events.map(e => {
return {
userInfo: e.userInfo && (0, _user.convertRteUserToFcrUser)(e.userInfo, this._roomCache),
userProperties: e.userProperties,
operatorUser: e.operatorUser && (0, _user.convertRteUserToFcrUser)(e.operatorUser, this._roomCache),
reason: e.cause?.cmd === 5 ? _type2.FcrUserLeftReason.kickOut : _type2.FcrUserLeftReason.LeaveRoom
};
});
fcrUserEvents.forEach(event => {
const user = event.userInfo;
const exists = user.userId in this._userMapByUserId;
if (!exists) {
this.logger.warn(`[FcrUserControl] user left when the user does not exist, userId: ${user.userId}`);
} else {
delete this._userMapByUserId[user.userId];
const index = this._userList.findIndex(u => user.userId === u.userId);
if (index !== -1) {
this._userList.splice(index, 1);
}
}
});
events.forEach(event => {
this._roomCache.deleteUserPlatform(event.userInfo.userId);
this._roomCache.deleteUserAvatar(event.userInfo.userId);
});
this._observable.notifyObservers('onRemoteUsersLeft', roomId, fcrUserEvents);
},
onUserUpdated: (sceneId, event) => {
const fcrUserUpdatedEvent = {
modifiedUser: event.modifiedUser && (0, _user.convertRteUserToFcrUser)(event.modifiedUser, this._roomCache),
operatorUser: event.operatorUser && (0, _user.convertRteUserToFcrUser)(event.operatorUser, this._roomCache),
reason: event.reason
};
const user = fcrUserUpdatedEvent.modifiedUser;
const exists = user.userId in this._userMapByUserId;
if (!exists) {
this.logger.warn(`[FcrUserControl] user updated when the user does not exist, userId: ${user.userId}`);
} else {
this._userMapByUserId[user.userId] = user;
const index = this._userList.findIndex(u => user.userId === u.userId);
if (index !== -1) {
this._userList.splice(index, 1, user);
}
}
this._observable.notifyObservers('onUserInfoUpdated', sceneId, fcrUserUpdatedEvent);
},
onAllUserCountUpdated: (sceneId, count) => {
this._observable.notifyObservers('onAllUserCountUpdated', sceneId, count);
},
onUserPropertiesUpdated: (roomId, event) => {
if (event.cause?.cmd === 5 && event.modifiedUser.userId === this._localUserId) {
const {
changedProperties
} = event;
const dirtyStateMap = {
'0': _type2.FcrUserKickedOutType.Once,
'1': _type2.FcrUserKickedOutType.Forever,
'2': 2
};
const key = (0, _imports.get)(changedProperties, 'dirty.state');
const type = dirtyStateMap[key];
this._observable.notifyObservers('onLocalUserKickedOut', roomId, {
type
});
}
if (event.cause?.cmd === 8) {
const changedProperties = {};
for (const key in event.changedProperties) {
if (key.startsWith('flexProps')) {
changedProperties[key] = event.changedProperties[key];
}
}
if (Object.keys(changedProperties).length > 0) {
const structure = (0, _collection.convertToStructure)(changedProperties);
this._observable.notifyObservers('onUserPropertiesUpdated', roomId, {
...event,
changedProperties: structure['flexProps']
});
}
}
},
onUserPropertiesDeleted: (roomId, event) => {
if (event.cause?.cmd === 8) {
const changedKeyPaths = [];
for (const keyPath of event.changedKeyPaths) {
if (keyPath.startsWith('flexProps')) {
changedKeyPaths.push(keyPath);
}
}
if (changedKeyPaths.length > 0) {
this._observable.notifyObservers('onUserPropertiesDeleted', roomId, {
...event,
changedKeyPaths
});
}
}
}
};
constructor(_scene, _api, _sharedCache) {
this._scene = _scene;
this._api = _api;
this._sharedCache = _sharedCache;
this._roomCache = _sharedCache.getRoomCache(this._scene.sceneId);
const users = this._scene.getUsers();
Object.keys(users).forEach(userId => {
const userProperties = this._scene.getUserPropertiesByUserId(userId);
this._roomCache.setUserAvatar(userId, userProperties?.avatar);
this._roomCache.setUserPlatform(userId, userProperties?.platform);
});
this._userMapByUserId = Object.keys(users).reduce((prev, userId) => {
prev[userId] = (0, _user.convertRteUserToFcrUser)(users[userId], this._roomCache);
return prev;
}, {});
this._userList = this._scene.getUserList().map(user => {
return (0, _user.convertRteUserToFcrUser)(user, this._roomCache);
});
this._localUserId = this._scene.localUser.getLocalUserId();
this._addLogObserver();
this._scene.addObserver(this._sceneObserver);
}
// @trace
getLocalUser() {
const localUserId = this._scene.localUser.getLocalUserId();
const localUser = this._scene.getUser(localUserId);
return (0, _user.convertRteUserToFcrUser)(localUser, this._roomCache);
}
// @trace
getUsers() {
return this._userMapByUserId;
}
// @trace
getUserList() {
return this._userList;
}
getUser(userId) {
const user = this._scene.getUser(userId);
if (user) {
return (0, _user.convertRteUserToFcrUser)(user, this._roomCache);
}
}
getAllUserCount() {
return this._scene.getUserCount();
}
getWaterMarkContent() {
const {
userId
} = this.getLocalUser();
return (0, _imports.get)(this._scene.getUserPropertiesByUserId(userId), 'security.watermark.content');
}
async fetchUserList(params) {
return await this._scene.fetchUserList(params);
}
async updateUserName(userId, userName) {
return (0, _error.handleRequestError)(() => this._api.updateUserName({
roomId: this._scene.sceneId,
userId,
userName
}), _error.FcrErrorModuleCode.ROOM_USER, 'update user name failed');
}
updateUserProperties(properties, cause, userId) {
return (0, _error.handleRequestError)(() => this._api.updateUserProperties({
roomId: this._scene.sceneId,
userUuid: userId,
properties,
cause
}), _error.FcrErrorModuleCode.ROOM_USER, 'update user properties failed');
}
updateIncrementUserProperties(increments, cause, userId) {
return (0, _error.handleRequestError)(() => this._api.updateUserProperties({
roomId: this._scene.sceneId,
userUuid: userId,
increments,
cause
}), _error.FcrErrorModuleCode.ROOM_USER, 'update increment user properties failed');
}
async deleteUserProperties(keyPath, cause, userId) {
await (0, _error.handleRequestError)(() => this._api.deleteUserProperties({
roomId: this._scene.sceneId,
userUuid: userId,
properties: keyPath,
cause
}), _error.FcrErrorModuleCode.ROOM_USER, 'delete user properties failed');
}
getUserProperties() {
const userProperties = this._scene.getUserProperties();
const res = {};
for (const userId in userProperties) {
res[userId] = userProperties[userId]?.['flexProps'];
}
return res;
}
getUserPropertiesByUserId(userId) {
return this._scene.getUserPropertiesByUserId(userId)?.['flexProps'];
}
getUserPropertiesByKeyPath(keyPath, userId) {
return this._scene.getUserPropertiesByKeyPath('flexProps.' + keyPath, userId);
}
async updateRemoteUserRole(userId, userRole) {
await (0, _error.handleRequestError)(() => this._api.updateUserRole({
roomId: this._scene.sceneId,
userId,
localRole: userRole === _type.FcrUserRole.HOST ? _type.FcrUserRoleToStringMap[_type.FcrUserRole.PARTICIPANT] : undefined,
remoteRole: _type.FcrUserRoleToStringMap[userRole]
}), _error.FcrErrorModuleCode.ROOM_USER, 'update remote user role failed');
}
async revokeHost() {
const userList = this.getUserList();
const originHostUser = userList.find(user => user.userRole === _type.FcrUserRole.HOST);
if (originHostUser) {
await (0, _error.handleRequestError)(() => this._api.revokeUserRole({
roomId: this._scene.sceneId,
localRole: _type.FcrUserRoleToStringMap[_type.FcrUserRole.HOST],
remoteRole: _type.FcrUserRoleToStringMap[_type.FcrUserRole.PARTICIPANT],
userId: originHostUser?.userId
}), _error.FcrErrorModuleCode.ROOM_USER, 'revoke host failed');
}
}
async claimHost(hostKey) {
const {
userId
} = this.getLocalUser();
return await (0, _error.handleRequestError)(() => this._api.claimHost({
roomId: this._scene.sceneId,
hostKey,
userId
}), _error.FcrErrorModuleCode.ROOM_USER, 'claim host by ticket failed');
}
async kickOut(userId, type) {
await (0, _error.handleRequestError)(() => this._api.kickOut(userId, type, {
roomId: this._scene.sceneId
}), _error.FcrErrorModuleCode.ROOM_USER, 'kick out failed');
}
async kickOutByUserIds(userIds, type) {
return (0, _error.handleRequestError)(() => this._api.kickOutByUserIds(userIds, type, {
roomId: this._scene.sceneId
}), _error.FcrErrorModuleCode.ROOM_USER, 'kick out by user ids failed');
}
async kickOutByUserRoles(userRoles, type) {
return (0, _error.handleRequestError)(() => this._api.kickOutByUserRoles(type, {
roomId: this._scene.sceneId
}, userRoles.map(role => _type.FcrUserRoleToStringMap[role])), _error.FcrErrorModuleCode.ROOM_USER, 'kick out by user roles failed');
}
mergeAudioStream(userId) {
return (0, _error.handleRequestError)(() => this._api.mergeAudioStream(userId, {
roomId: this._scene.sceneId
}), _error.FcrErrorModuleCode.ROOM_USER, 'merge audio stream failed');
}
addObserver(observer) {
this._observable.addObserver(observer);
}
removeObserver(observer) {
this._observable.removeObserver(observer);
}
_addLogObserver() {
this.addObserver((0, _logger.generateLogObserver)(this.logger, ['onRemoteUsersJoined', 'onRemoteUsersLeft', 'onUserInfoUpdated', 'onAllUserCountUpdated', 'onLocalUserKickedOut', 'onUserPropertiesUpdated', 'onUserPropertiesDeleted']));
}
}
exports.FcrUserControlImpl = FcrUserControlImpl;