You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

external_api.js 45KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381
  1. import { jitsiLocalStorage } from '@jitsi/js-utils/jitsi-local-storage';
  2. import EventEmitter from 'events';
  3. import { urlObjectToString } from '../../../react/features/base/util/uri';
  4. import {
  5. PostMessageTransportBackend,
  6. Transport
  7. } from '../../transport';
  8. import {
  9. getAvailableDevices,
  10. getCurrentDevices,
  11. isDeviceChangeAvailable,
  12. isDeviceListAvailable,
  13. isMultipleAudioInputSupported,
  14. setAudioInputDevice,
  15. setAudioOutputDevice,
  16. setVideoInputDevice
  17. } from './functions';
  18. const ALWAYS_ON_TOP_FILENAMES = [
  19. 'css/all.css', 'libs/alwaysontop.min.js'
  20. ];
  21. /**
  22. * Maps the names of the commands expected by the API with the name of the
  23. * commands expected by jitsi-meet.
  24. */
  25. const commands = {
  26. addBreakoutRoom: 'add-breakout-room',
  27. answerKnockingParticipant: 'answer-knocking-participant',
  28. approveVideo: 'approve-video',
  29. askToUnmute: 'ask-to-unmute',
  30. autoAssignToBreakoutRooms: 'auto-assign-to-breakout-rooms',
  31. avatarUrl: 'avatar-url',
  32. cancelPrivateChat: 'cancel-private-chat',
  33. closeBreakoutRoom: 'close-breakout-room',
  34. displayName: 'display-name',
  35. e2eeKey: 'e2ee-key',
  36. endConference: 'end-conference',
  37. email: 'email',
  38. grantModerator: 'grant-moderator',
  39. hangup: 'video-hangup',
  40. hideNotification: 'hide-notification',
  41. initiatePrivateChat: 'initiate-private-chat',
  42. joinBreakoutRoom: 'join-breakout-room',
  43. localSubject: 'local-subject',
  44. kickParticipant: 'kick-participant',
  45. muteEveryone: 'mute-everyone',
  46. overwriteConfig: 'overwrite-config',
  47. overwriteNames: 'overwrite-names',
  48. password: 'password',
  49. pinParticipant: 'pin-participant',
  50. rejectParticipant: 'reject-participant',
  51. removeBreakoutRoom: 'remove-breakout-room',
  52. resizeFilmStrip: 'resize-film-strip',
  53. resizeLargeVideo: 'resize-large-video',
  54. sendChatMessage: 'send-chat-message',
  55. sendEndpointTextMessage: 'send-endpoint-text-message',
  56. sendParticipantToRoom: 'send-participant-to-room',
  57. sendTones: 'send-tones',
  58. setAssumedBandwidthBps: 'set-assumed-bandwidth-bps',
  59. setFollowMe: 'set-follow-me',
  60. setLargeVideoParticipant: 'set-large-video-participant',
  61. setMediaEncryptionKey: 'set-media-encryption-key',
  62. setNoiseSuppressionEnabled: 'set-noise-suppression-enabled',
  63. setParticipantVolume: 'set-participant-volume',
  64. setSubtitles: 'set-subtitles',
  65. setTileView: 'set-tile-view',
  66. setVideoQuality: 'set-video-quality',
  67. showNotification: 'show-notification',
  68. startRecording: 'start-recording',
  69. startShareVideo: 'start-share-video',
  70. stopRecording: 'stop-recording',
  71. stopShareVideo: 'stop-share-video',
  72. subject: 'subject',
  73. submitFeedback: 'submit-feedback',
  74. toggleAudio: 'toggle-audio',
  75. toggleCamera: 'toggle-camera',
  76. toggleCameraMirror: 'toggle-camera-mirror',
  77. toggleChat: 'toggle-chat',
  78. toggleE2EE: 'toggle-e2ee',
  79. toggleFilmStrip: 'toggle-film-strip',
  80. toggleLobby: 'toggle-lobby',
  81. toggleModeration: 'toggle-moderation',
  82. toggleNoiseSuppression: 'toggle-noise-suppression',
  83. toggleParticipantsPane: 'toggle-participants-pane',
  84. toggleRaiseHand: 'toggle-raise-hand',
  85. toggleShareScreen: 'toggle-share-screen',
  86. toggleSubtitles: 'toggle-subtitles',
  87. toggleTileView: 'toggle-tile-view',
  88. toggleVirtualBackgroundDialog: 'toggle-virtual-background',
  89. toggleVideo: 'toggle-video'
  90. };
  91. /**
  92. * Maps the names of the events expected by the API with the name of the
  93. * events expected by jitsi-meet.
  94. */
  95. const events = {
  96. 'avatar-changed': 'avatarChanged',
  97. 'audio-availability-changed': 'audioAvailabilityChanged',
  98. 'audio-mute-status-changed': 'audioMuteStatusChanged',
  99. 'audio-or-video-sharing-toggled': 'audioOrVideoSharingToggled',
  100. 'breakout-rooms-updated': 'breakoutRoomsUpdated',
  101. 'browser-support': 'browserSupport',
  102. 'camera-error': 'cameraError',
  103. 'chat-updated': 'chatUpdated',
  104. 'content-sharing-participants-changed': 'contentSharingParticipantsChanged',
  105. 'data-channel-closed': 'dataChannelClosed',
  106. 'data-channel-opened': 'dataChannelOpened',
  107. 'device-list-changed': 'deviceListChanged',
  108. 'display-name-change': 'displayNameChange',
  109. 'email-change': 'emailChange',
  110. 'error-occurred': 'errorOccurred',
  111. 'endpoint-text-message-received': 'endpointTextMessageReceived',
  112. 'face-landmark-detected': 'faceLandmarkDetected',
  113. 'feedback-submitted': 'feedbackSubmitted',
  114. 'feedback-prompt-displayed': 'feedbackPromptDisplayed',
  115. 'filmstrip-display-changed': 'filmstripDisplayChanged',
  116. 'incoming-message': 'incomingMessage',
  117. 'knocking-participant': 'knockingParticipant',
  118. 'log': 'log',
  119. 'mic-error': 'micError',
  120. 'moderation-participant-approved': 'moderationParticipantApproved',
  121. 'moderation-participant-rejected': 'moderationParticipantRejected',
  122. 'moderation-status-changed': 'moderationStatusChanged',
  123. 'mouse-enter': 'mouseEnter',
  124. 'mouse-leave': 'mouseLeave',
  125. 'mouse-move': 'mouseMove',
  126. 'notification-triggered': 'notificationTriggered',
  127. 'outgoing-message': 'outgoingMessage',
  128. 'participant-joined': 'participantJoined',
  129. 'participant-kicked-out': 'participantKickedOut',
  130. 'participant-left': 'participantLeft',
  131. 'participant-role-changed': 'participantRoleChanged',
  132. 'participants-pane-toggled': 'participantsPaneToggled',
  133. 'password-required': 'passwordRequired',
  134. 'peer-connection-failure': 'peerConnectionFailure',
  135. 'prejoin-screen-loaded': 'prejoinScreenLoaded',
  136. 'proxy-connection-event': 'proxyConnectionEvent',
  137. 'raise-hand-updated': 'raiseHandUpdated',
  138. 'recording-link-available': 'recordingLinkAvailable',
  139. 'recording-status-changed': 'recordingStatusChanged',
  140. 'participant-menu-button-clicked': 'participantMenuButtonClick',
  141. 'video-ready-to-close': 'readyToClose',
  142. 'video-conference-joined': 'videoConferenceJoined',
  143. 'video-conference-left': 'videoConferenceLeft',
  144. 'video-availability-changed': 'videoAvailabilityChanged',
  145. 'video-mute-status-changed': 'videoMuteStatusChanged',
  146. 'video-quality-changed': 'videoQualityChanged',
  147. 'screen-sharing-status-changed': 'screenSharingStatusChanged',
  148. 'dominant-speaker-changed': 'dominantSpeakerChanged',
  149. 'subject-change': 'subjectChange',
  150. 'suspend-detected': 'suspendDetected',
  151. 'tile-view-changed': 'tileViewChanged',
  152. 'toolbar-button-clicked': 'toolbarButtonClicked'
  153. };
  154. /**
  155. * Last id of api object.
  156. *
  157. * @type {number}
  158. */
  159. let id = 0;
  160. /**
  161. * Adds given number to the numberOfParticipants property of given APIInstance.
  162. *
  163. * @param {JitsiMeetExternalAPI} APIInstance - The instance of the API.
  164. * @param {int} number - The number of participants to be added to
  165. * numberOfParticipants property (this parameter can be negative number if the
  166. * numberOfParticipants should be decreased).
  167. * @returns {void}
  168. */
  169. function changeParticipantNumber(APIInstance, number) {
  170. APIInstance._numberOfParticipants += number;
  171. }
  172. /**
  173. * Generates the URL for the iframe.
  174. *
  175. * @param {string} domain - The domain name of the server that hosts the
  176. * conference.
  177. * @param {string} [options] - Another optional parameters.
  178. * @param {Object} [options.configOverwrite] - Object containing configuration
  179. * options defined in config.js to be overridden.
  180. * @param {Object} [options.interfaceConfigOverwrite] - Object containing
  181. * configuration options defined in interface_config.js to be overridden.
  182. * @param {string} [options.jwt] - The JWT token if needed by jitsi-meet for
  183. * authentication.
  184. * @param {string} [options.lang] - The meeting's default language.
  185. * @param {string} [options.roomName] - The name of the room to join.
  186. * @returns {string} The URL.
  187. */
  188. function generateURL(domain, options = {}) {
  189. return urlObjectToString({
  190. ...options,
  191. url: `https://${domain}/#jitsi_meet_external_api_id=${id}`
  192. });
  193. }
  194. /**
  195. * Parses the arguments passed to the constructor. If the old format is used
  196. * the function translates the arguments to the new format.
  197. *
  198. * @param {Array} args - The arguments to be parsed.
  199. * @returns {Object} JS object with properties.
  200. */
  201. function parseArguments(args) {
  202. if (!args.length) {
  203. return {};
  204. }
  205. const firstArg = args[0];
  206. switch (typeof firstArg) {
  207. case 'string': // old arguments format
  208. case 'undefined': {
  209. // Not sure which format but we are trying to parse the old
  210. // format because if the new format is used everything will be undefined
  211. // anyway.
  212. const [
  213. roomName,
  214. width,
  215. height,
  216. parentNode,
  217. configOverwrite,
  218. interfaceConfigOverwrite,
  219. jwt,
  220. onload,
  221. lang
  222. ] = args;
  223. return {
  224. roomName,
  225. width,
  226. height,
  227. parentNode,
  228. configOverwrite,
  229. interfaceConfigOverwrite,
  230. jwt,
  231. onload,
  232. lang
  233. };
  234. }
  235. case 'object': // new arguments format
  236. return args[0];
  237. default:
  238. throw new Error('Can\'t parse the arguments!');
  239. }
  240. }
  241. /**
  242. * Compute valid values for height and width. If a number is specified it's
  243. * treated as pixel units. If the value is expressed in px, em, pt or
  244. * percentage, it's used as is.
  245. *
  246. * @param {any} value - The value to be parsed.
  247. * @returns {string|undefined} The parsed value that can be used for setting
  248. * sizes through the style property. If invalid value is passed the method
  249. * returns undefined.
  250. */
  251. function parseSizeParam(value) {
  252. let parsedValue;
  253. // This regex parses values of the form 100px, 100em, 100pt or 100%.
  254. // Values like 100 or 100px are handled outside of the regex, and
  255. // invalid values will be ignored and the minimum will be used.
  256. const re = /([0-9]*\.?[0-9]+)(em|pt|px|%)$/;
  257. if (typeof value === 'string' && String(value).match(re) !== null) {
  258. parsedValue = value;
  259. } else if (typeof value === 'number') {
  260. parsedValue = `${value}px`;
  261. }
  262. return parsedValue;
  263. }
  264. /**
  265. * The IFrame API interface class.
  266. */
  267. export default class JitsiMeetExternalAPI extends EventEmitter {
  268. /**
  269. * Constructs new API instance. Creates iframe and loads Jitsi Meet in it.
  270. *
  271. * @param {string} domain - The domain name of the server that hosts the
  272. * conference.
  273. * @param {Object} [options] - Optional arguments.
  274. * @param {string} [options.roomName] - The name of the room to join.
  275. * @param {number|string} [options.width] - Width of the iframe. Check
  276. * parseSizeParam for format details.
  277. * @param {number|string} [options.height] - Height of the iframe. Check
  278. * parseSizeParam for format details.
  279. * @param {DOMElement} [options.parentNode] - The node that will contain the
  280. * iframe.
  281. * @param {Object} [options.configOverwrite] - Object containing
  282. * configuration options defined in config.js to be overridden.
  283. * @param {Object} [options.interfaceConfigOverwrite] - Object containing
  284. * configuration options defined in interface_config.js to be overridden.
  285. * @param {string} [options.jwt] - The JWT token if needed by jitsi-meet for
  286. * authentication.
  287. * @param {string} [options.lang] - The meeting's default language.
  288. * @param {string} [options.onload] - The onload function that will listen
  289. * for iframe onload event.
  290. * @param {Array<Object>} [options.invitees] - Array of objects containing
  291. * information about new participants that will be invited in the call.
  292. * @param {Array<Object>} [options.devices] - Array of objects containing
  293. * information about the initial devices that will be used in the call.
  294. * @param {Object} [options.userInfo] - Object containing information about
  295. * the participant opening the meeting.
  296. * @param {string} [options.e2eeKey] - The key used for End-to-End encryption.
  297. * THIS IS EXPERIMENTAL.
  298. * @param {string} [options.release] - The key used for specifying release if enabled on the backend.
  299. */
  300. constructor(domain, ...args) {
  301. super();
  302. const {
  303. roomName = '',
  304. width = '100%',
  305. height = '100%',
  306. parentNode = document.body,
  307. configOverwrite = {},
  308. interfaceConfigOverwrite = {},
  309. jwt = undefined,
  310. lang = undefined,
  311. onload = undefined,
  312. invitees,
  313. devices,
  314. userInfo,
  315. e2eeKey,
  316. release
  317. } = parseArguments(args);
  318. const localStorageContent = jitsiLocalStorage.getItem('jitsiLocalStorage');
  319. this._parentNode = parentNode;
  320. this._url = generateURL(domain, {
  321. configOverwrite,
  322. interfaceConfigOverwrite,
  323. jwt,
  324. lang,
  325. roomName,
  326. devices,
  327. userInfo,
  328. appData: {
  329. localStorageContent
  330. },
  331. release
  332. });
  333. this._createIFrame(height, width, onload);
  334. this._transport = new Transport({
  335. backend: new PostMessageTransportBackend({
  336. postisOptions: {
  337. allowedOrigin: new URL(this._url).origin,
  338. scope: `jitsi_meet_external_api_${id}`,
  339. window: this._frame.contentWindow
  340. }
  341. })
  342. });
  343. if (Array.isArray(invitees) && invitees.length > 0) {
  344. this.invite(invitees);
  345. }
  346. this._tmpE2EEKey = e2eeKey;
  347. this._isLargeVideoVisible = false;
  348. this._isPrejoinVideoVisible = false;
  349. this._numberOfParticipants = 0;
  350. this._participants = {};
  351. this._myUserID = undefined;
  352. this._onStageParticipant = undefined;
  353. this._setupListeners();
  354. id++;
  355. }
  356. /**
  357. * Creates the iframe element.
  358. *
  359. * @param {number|string} height - The height of the iframe. Check
  360. * parseSizeParam for format details.
  361. * @param {number|string} width - The with of the iframe. Check
  362. * parseSizeParam for format details.
  363. * @param {Function} onload - The function that will listen
  364. * for onload event.
  365. * @returns {void}
  366. *
  367. * @private
  368. */
  369. _createIFrame(height, width, onload) {
  370. const frameName = `jitsiConferenceFrame${id}`;
  371. this._frame = document.createElement('iframe');
  372. this._frame.allow = 'camera; microphone; display-capture; autoplay; clipboard-write; hid';
  373. this._frame.name = frameName;
  374. this._frame.id = frameName;
  375. this._setSize(height, width);
  376. this._frame.setAttribute('allowFullScreen', 'true');
  377. this._frame.style.border = 0;
  378. if (onload) {
  379. // waits for iframe resources to load
  380. // and fires event when it is done
  381. this._frame.onload = onload;
  382. }
  383. this._frame.src = this._url;
  384. this._frame = this._parentNode.appendChild(this._frame);
  385. }
  386. /**
  387. * Returns arrays with the all resources for the always on top feature.
  388. *
  389. * @returns {Array<string>}
  390. */
  391. _getAlwaysOnTopResources() {
  392. const iframeWindow = this._frame.contentWindow;
  393. const iframeDocument = iframeWindow.document;
  394. let baseURL = '';
  395. const base = iframeDocument.querySelector('base');
  396. if (base && base.href) {
  397. baseURL = base.href;
  398. } else {
  399. const { protocol, host } = iframeWindow.location;
  400. baseURL = `${protocol}//${host}`;
  401. }
  402. return ALWAYS_ON_TOP_FILENAMES.map(
  403. filename => new URL(filename, baseURL).href
  404. );
  405. }
  406. /**
  407. * Returns the formatted display name of a participant.
  408. *
  409. * @param {string} participantId - The id of the participant.
  410. * @returns {string} The formatted display name.
  411. */
  412. _getFormattedDisplayName(participantId) {
  413. const { formattedDisplayName }
  414. = this._participants[participantId] || {};
  415. return formattedDisplayName;
  416. }
  417. /**
  418. * Returns the id of the on stage participant.
  419. *
  420. * @returns {string} - The id of the on stage participant.
  421. */
  422. _getOnStageParticipant() {
  423. return this._onStageParticipant;
  424. }
  425. /**
  426. * Getter for the large video element in Jitsi Meet.
  427. *
  428. * @returns {HTMLElement|undefined} - The large video.
  429. */
  430. _getLargeVideo() {
  431. const iframe = this.getIFrame();
  432. if (!this._isLargeVideoVisible
  433. || !iframe
  434. || !iframe.contentWindow
  435. || !iframe.contentWindow.document) {
  436. return;
  437. }
  438. return iframe.contentWindow.document.getElementById('largeVideo');
  439. }
  440. /**
  441. * Getter for the prejoin video element in Jitsi Meet.
  442. *
  443. * @returns {HTMLElement|undefined} - The prejoin video.
  444. */
  445. _getPrejoinVideo() {
  446. const iframe = this.getIFrame();
  447. if (!this._isPrejoinVideoVisible
  448. || !iframe
  449. || !iframe.contentWindow
  450. || !iframe.contentWindow.document) {
  451. return;
  452. }
  453. return iframe.contentWindow.document.getElementById('prejoinVideo');
  454. }
  455. /**
  456. * Getter for participant specific video element in Jitsi Meet.
  457. *
  458. * @param {string|undefined} participantId - Id of participant to return the video for.
  459. *
  460. * @returns {HTMLElement|undefined} - The requested video. Will return the local video
  461. * by default if participantId is undefined.
  462. */
  463. _getParticipantVideo(participantId) {
  464. const iframe = this.getIFrame();
  465. if (!iframe
  466. || !iframe.contentWindow
  467. || !iframe.contentWindow.document) {
  468. return;
  469. }
  470. if (typeof participantId === 'undefined' || participantId === this._myUserID) {
  471. return iframe.contentWindow.document.getElementById('localVideo_container');
  472. }
  473. return iframe.contentWindow.document.querySelector(`#participant_${participantId} video`);
  474. }
  475. /**
  476. * Sets the size of the iframe element.
  477. *
  478. * @param {number|string} height - The height of the iframe.
  479. * @param {number|string} width - The with of the iframe.
  480. * @returns {void}
  481. *
  482. * @private
  483. */
  484. _setSize(height, width) {
  485. const parsedHeight = parseSizeParam(height);
  486. const parsedWidth = parseSizeParam(width);
  487. if (parsedHeight !== undefined) {
  488. this._height = height;
  489. this._frame.style.height = parsedHeight;
  490. }
  491. if (parsedWidth !== undefined) {
  492. this._width = width;
  493. this._frame.style.width = parsedWidth;
  494. }
  495. }
  496. /**
  497. * Setups listeners that are used internally for JitsiMeetExternalAPI.
  498. *
  499. * @returns {void}
  500. *
  501. * @private
  502. */
  503. _setupListeners() {
  504. this._transport.on('event', ({ name, ...data }) => {
  505. const userID = data.id;
  506. switch (name) {
  507. case 'video-conference-joined': {
  508. if (typeof this._tmpE2EEKey !== 'undefined') {
  509. this.executeCommand(commands.e2eeKey, this._tmpE2EEKey);
  510. this._tmpE2EEKey = undefined;
  511. }
  512. this._myUserID = userID;
  513. this._participants[userID] = {
  514. email: data.email,
  515. avatarURL: data.avatarURL
  516. };
  517. }
  518. // eslint-disable-next-line no-fallthrough
  519. case 'participant-joined': {
  520. this._participants[userID] = this._participants[userID] || {};
  521. this._participants[userID].displayName = data.displayName;
  522. this._participants[userID].formattedDisplayName
  523. = data.formattedDisplayName;
  524. changeParticipantNumber(this, 1);
  525. break;
  526. }
  527. case 'participant-left':
  528. changeParticipantNumber(this, -1);
  529. delete this._participants[userID];
  530. break;
  531. case 'display-name-change': {
  532. const user = this._participants[userID];
  533. if (user) {
  534. user.displayName = data.displayname;
  535. user.formattedDisplayName = data.formattedDisplayName;
  536. }
  537. break;
  538. }
  539. case 'email-change': {
  540. const user = this._participants[userID];
  541. if (user) {
  542. user.email = data.email;
  543. }
  544. break;
  545. }
  546. case 'avatar-changed': {
  547. const user = this._participants[userID];
  548. if (user) {
  549. user.avatarURL = data.avatarURL;
  550. }
  551. break;
  552. }
  553. case 'on-stage-participant-changed':
  554. this._onStageParticipant = userID;
  555. this.emit('largeVideoChanged');
  556. break;
  557. case 'large-video-visibility-changed':
  558. this._isLargeVideoVisible = data.isVisible;
  559. this.emit('largeVideoChanged');
  560. break;
  561. case 'prejoin-screen-loaded':
  562. this._participants[userID] = {
  563. displayName: data.displayName,
  564. formattedDisplayName: data.formattedDisplayName
  565. };
  566. break;
  567. case 'on-prejoin-video-changed':
  568. this._isPrejoinVideoVisible = data.isVisible;
  569. this.emit('prejoinVideoChanged');
  570. break;
  571. case 'video-conference-left':
  572. changeParticipantNumber(this, -1);
  573. delete this._participants[this._myUserID];
  574. break;
  575. case 'video-quality-changed':
  576. this._videoQuality = data.videoQuality;
  577. break;
  578. case 'breakout-rooms-updated':
  579. this.updateNumberOfParticipants(data.rooms);
  580. break;
  581. case 'local-storage-changed':
  582. jitsiLocalStorage.setItem('jitsiLocalStorage', data.localStorageContent);
  583. // Since this is internal event we don't need to emit it to the consumer of the API.
  584. return true;
  585. }
  586. const eventName = events[name];
  587. if (eventName) {
  588. this.emit(eventName, data);
  589. return true;
  590. }
  591. return false;
  592. });
  593. }
  594. /**
  595. * Update number of participants based on all rooms.
  596. *
  597. * @param {Object} rooms - Rooms available rooms in the conference.
  598. * @returns {void}
  599. */
  600. updateNumberOfParticipants(rooms) {
  601. if (!rooms || !Object.keys(rooms).length) {
  602. return;
  603. }
  604. const allParticipants = Object.keys(rooms).reduce((prev, roomItemKey) => {
  605. if (rooms[roomItemKey]?.participants) {
  606. return Object.keys(rooms[roomItemKey].participants).length + prev;
  607. }
  608. return prev;
  609. }, 0);
  610. this._numberOfParticipants = allParticipants;
  611. }
  612. /**
  613. * Returns the rooms info in the conference.
  614. *
  615. * @returns {Object} Rooms info.
  616. */
  617. async getRoomsInfo() {
  618. return this._transport.sendRequest({
  619. name: 'rooms-info'
  620. });
  621. }
  622. /**
  623. * Adds event listener to Meet Jitsi.
  624. *
  625. * @param {string} event - The name of the event.
  626. * @param {Function} listener - The listener.
  627. * @returns {void}
  628. *
  629. * @deprecated
  630. * NOTE: This method is not removed for backward comatability purposes.
  631. */
  632. addEventListener(event, listener) {
  633. this.on(event, listener);
  634. }
  635. /**
  636. * Adds event listeners to Meet Jitsi.
  637. *
  638. * @param {Object} listeners - The object key should be the name of
  639. * the event and value - the listener.
  640. * Currently we support the following
  641. * events:
  642. * {@code log} - receives event notifications whenever information has
  643. * been logged and has a log level specified within {@code config.apiLogLevels}.
  644. * The listener will receive object with the following structure:
  645. * {{
  646. * logLevel: the message log level
  647. * arguments: an array of strings that compose the actual log message
  648. * }}
  649. * {@code chatUpdated} - receives event notifications about chat state being
  650. * updated. The listener will receive object with the following structure:
  651. * {{
  652. * 'unreadCount': unreadCounter, // the unread message(s) counter,
  653. * 'isOpen': isOpen, // whether the chat panel is open or not
  654. * }}
  655. * {@code incomingMessage} - receives event notifications about incoming
  656. * messages. The listener will receive object with the following structure:
  657. * {{
  658. * 'from': from,//JID of the user that sent the message
  659. * 'nick': nick,//the nickname of the user that sent the message
  660. * 'message': txt//the text of the message
  661. * }}
  662. * {@code outgoingMessage} - receives event notifications about outgoing
  663. * messages. The listener will receive object with the following structure:
  664. * {{
  665. * 'message': txt//the text of the message
  666. * }}
  667. * {@code displayNameChanged} - receives event notifications about display
  668. * name change. The listener will receive object with the following
  669. * structure:
  670. * {{
  671. * jid: jid,//the JID of the participant that changed his display name
  672. * displayname: displayName //the new display name
  673. * }}
  674. * {@code participantJoined} - receives event notifications about new
  675. * participant.
  676. * The listener will receive object with the following structure:
  677. * {{
  678. * jid: jid //the jid of the participant
  679. * }}
  680. * {@code participantLeft} - receives event notifications about the
  681. * participant that left the room.
  682. * The listener will receive object with the following structure:
  683. * {{
  684. * jid: jid //the jid of the participant
  685. * }}
  686. * {@code videoConferenceJoined} - receives event notifications about the
  687. * local user has successfully joined the video conference.
  688. * The listener will receive object with the following structure:
  689. * {{
  690. * roomName: room //the room name of the conference
  691. * }}
  692. * {@code videoConferenceLeft} - receives event notifications about the
  693. * local user has left the video conference.
  694. * The listener will receive object with the following structure:
  695. * {{
  696. * roomName: room //the room name of the conference
  697. * }}
  698. * {@code screenSharingStatusChanged} - receives event notifications about
  699. * turning on/off the local user screen sharing.
  700. * The listener will receive object with the following structure:
  701. * {{
  702. * on: on //whether screen sharing is on
  703. * }}
  704. * {@code dominantSpeakerChanged} - receives event notifications about
  705. * change in the dominant speaker.
  706. * The listener will receive object with the following structure:
  707. * {{
  708. * id: participantId //participantId of the new dominant speaker
  709. * }}
  710. * {@code suspendDetected} - receives event notifications about detecting suspend event in host computer.
  711. * {@code readyToClose} - all hangup operations are completed and Jitsi Meet
  712. * is ready to be disposed.
  713. * @returns {void}
  714. *
  715. * @deprecated
  716. * NOTE: This method is not removed for backward comatability purposes.
  717. */
  718. addEventListeners(listeners) {
  719. for (const event in listeners) { // eslint-disable-line guard-for-in
  720. this.addEventListener(event, listeners[event]);
  721. }
  722. }
  723. /**
  724. * Captures the screenshot of the large video.
  725. *
  726. * @returns {Promise<string>} - Resolves with a base64 encoded image data of the screenshot
  727. * if large video is detected, an error otherwise.
  728. */
  729. captureLargeVideoScreenshot() {
  730. return this._transport.sendRequest({
  731. name: 'capture-largevideo-screenshot'
  732. });
  733. }
  734. /**
  735. * Removes the listeners and removes the Jitsi Meet frame.
  736. *
  737. * @returns {void}
  738. */
  739. dispose() {
  740. this.emit('_willDispose');
  741. this._transport.dispose();
  742. this.removeAllListeners();
  743. if (this._frame && this._frame.parentNode) {
  744. this._frame.parentNode.removeChild(this._frame);
  745. }
  746. }
  747. /**
  748. * Executes command. The available commands are:
  749. * {@code displayName} - Sets the display name of the local participant to
  750. * the value passed in the arguments array.
  751. * {@code subject} - Sets the subject of the conference, the value passed
  752. * in the arguments array. Note: Available only for moderator.
  753. *
  754. * {@code toggleAudio} - Mutes / unmutes audio with no arguments.
  755. * {@code toggleVideo} - Mutes / unmutes video with no arguments.
  756. * {@code toggleFilmStrip} - Hides / shows the filmstrip with no arguments.
  757. *
  758. * If the command doesn't require any arguments the parameter should be set
  759. * to empty array or it may be omitted.
  760. *
  761. * @param {string} name - The name of the command.
  762. * @returns {void}
  763. */
  764. executeCommand(name, ...args) {
  765. if (!(name in commands)) {
  766. console.error('Not supported command name.');
  767. return;
  768. }
  769. this._transport.sendEvent({
  770. data: args,
  771. name: commands[name]
  772. });
  773. }
  774. /**
  775. * Executes commands. The available commands are:
  776. * {@code displayName} - Sets the display name of the local participant to
  777. * the value passed in the arguments array.
  778. * {@code toggleAudio} - Mutes / unmutes audio. No arguments.
  779. * {@code toggleVideo} - Mutes / unmutes video. No arguments.
  780. * {@code toggleFilmStrip} - Hides / shows the filmstrip. No arguments.
  781. * {@code toggleChat} - Hides / shows chat. No arguments.
  782. * {@code toggleShareScreen} - Starts / stops screen sharing. No arguments.
  783. *
  784. * @param {Object} commandList - The object with commands to be executed.
  785. * The keys of the object are the commands that will be executed and the
  786. * values are the arguments for the command.
  787. * @returns {void}
  788. */
  789. executeCommands(commandList) {
  790. for (const key in commandList) { // eslint-disable-line guard-for-in
  791. this.executeCommand(key, commandList[key]);
  792. }
  793. }
  794. /**
  795. * Returns Promise that resolves with a list of available devices.
  796. *
  797. * @returns {Promise}
  798. */
  799. getAvailableDevices() {
  800. return getAvailableDevices(this._transport);
  801. }
  802. /**
  803. * Gets a list of the currently sharing participant id's.
  804. *
  805. * @returns {Promise} - Resolves with the list of participant id's currently sharing.
  806. */
  807. getContentSharingParticipants() {
  808. return this._transport.sendRequest({
  809. name: 'get-content-sharing-participants'
  810. });
  811. }
  812. /**
  813. * Returns Promise that resolves with current selected devices.
  814. *
  815. * @returns {Promise}
  816. */
  817. getCurrentDevices() {
  818. return getCurrentDevices(this._transport);
  819. }
  820. /**
  821. * Returns any custom avatars backgrounds.
  822. *
  823. * @returns {Promise} - Resolves with the list of custom avatar backgrounds.
  824. */
  825. getCustomAvatarBackgrounds() {
  826. return this._transport.sendRequest({
  827. name: 'get-custom-avatar-backgrounds'
  828. });
  829. }
  830. /**
  831. * Returns the current livestream url.
  832. *
  833. * @returns {Promise} - Resolves with the current livestream URL if exists, with
  834. * undefined if not and rejects on failure.
  835. */
  836. getLivestreamUrl() {
  837. return this._transport.sendRequest({
  838. name: 'get-livestream-url'
  839. });
  840. }
  841. /**
  842. * Returns the conference participants information.
  843. *
  844. * @returns {Array<Object>} - Returns an array containing participants
  845. * information like participant id, display name, avatar URL and email.
  846. */
  847. getParticipantsInfo() {
  848. const participantIds = Object.keys(this._participants);
  849. const participantsInfo = Object.values(this._participants);
  850. participantsInfo.forEach((participant, idx) => {
  851. participant.participantId = participantIds[idx];
  852. });
  853. return participantsInfo;
  854. }
  855. /**
  856. * Returns the current video quality setting.
  857. *
  858. * @returns {number}
  859. */
  860. getVideoQuality() {
  861. return this._videoQuality;
  862. }
  863. /**
  864. * Check if the audio is available.
  865. *
  866. * @returns {Promise} - Resolves with true if the audio available, with
  867. * false if not and rejects on failure.
  868. */
  869. isAudioAvailable() {
  870. return this._transport.sendRequest({
  871. name: 'is-audio-available'
  872. });
  873. }
  874. /**
  875. * Returns Promise that resolves with true if the device change is available
  876. * and with false if not.
  877. *
  878. * @param {string} [deviceType] - Values - 'output', 'input' or undefined.
  879. * Default - 'input'.
  880. * @returns {Promise}
  881. */
  882. isDeviceChangeAvailable(deviceType) {
  883. return isDeviceChangeAvailable(this._transport, deviceType);
  884. }
  885. /**
  886. * Returns Promise that resolves with true if the device list is available
  887. * and with false if not.
  888. *
  889. * @returns {Promise}
  890. */
  891. isDeviceListAvailable() {
  892. return isDeviceListAvailable(this._transport);
  893. }
  894. /**
  895. * Returns Promise that resolves with true if multiple audio input is supported
  896. * and with false if not.
  897. *
  898. * @returns {Promise}
  899. */
  900. isMultipleAudioInputSupported() {
  901. return isMultipleAudioInputSupported(this._transport);
  902. }
  903. /**
  904. * Invite people to the call.
  905. *
  906. * @param {Array<Object>} invitees - The invitees.
  907. * @returns {Promise} - Resolves on success and rejects on failure.
  908. */
  909. invite(invitees) {
  910. if (!Array.isArray(invitees) || invitees.length === 0) {
  911. return Promise.reject(new TypeError('Invalid Argument'));
  912. }
  913. return this._transport.sendRequest({
  914. name: 'invite',
  915. invitees
  916. });
  917. }
  918. /**
  919. * Returns the audio mute status.
  920. *
  921. * @returns {Promise} - Resolves with the audio mute status and rejects on
  922. * failure.
  923. */
  924. isAudioMuted() {
  925. return this._transport.sendRequest({
  926. name: 'is-audio-muted'
  927. });
  928. }
  929. /**
  930. * Returns the audio disabled status.
  931. *
  932. * @returns {Promise} - Resolves with the audio disabled status and rejects on
  933. * failure.
  934. */
  935. isAudioDisabled() {
  936. return this._transport.sendRequest({
  937. name: 'is-audio-disabled'
  938. });
  939. }
  940. /**
  941. * Returns the moderation on status on the given mediaType.
  942. *
  943. * @param {string} mediaType - The media type for which to check moderation.
  944. * @returns {Promise} - Resolves with the moderation on status and rejects on
  945. * failure.
  946. */
  947. isModerationOn(mediaType) {
  948. return this._transport.sendRequest({
  949. name: 'is-moderation-on',
  950. mediaType
  951. });
  952. }
  953. /**
  954. * Returns force muted status of the given participant id for the given media type.
  955. *
  956. * @param {string} participantId - The id of the participant to check.
  957. * @param {string} mediaType - The media type for which to check.
  958. * @returns {Promise} - Resolves with the force muted status and rejects on
  959. * failure.
  960. */
  961. isParticipantForceMuted(participantId, mediaType) {
  962. return this._transport.sendRequest({
  963. name: 'is-participant-force-muted',
  964. participantId,
  965. mediaType
  966. });
  967. }
  968. /**
  969. * Returns whether the participants pane is open.
  970. *
  971. * @returns {Promise} - Resolves with true if the participants pane is open
  972. * and with false if not.
  973. */
  974. isParticipantsPaneOpen() {
  975. return this._transport.sendRequest({
  976. name: 'is-participants-pane-open'
  977. });
  978. }
  979. /**
  980. * Returns screen sharing status.
  981. *
  982. * @returns {Promise} - Resolves with screensharing status and rejects on failure.
  983. */
  984. isSharingScreen() {
  985. return this._transport.sendRequest({
  986. name: 'is-sharing-screen'
  987. });
  988. }
  989. /**
  990. * Returns whether meeting is started silent.
  991. *
  992. * @returns {Promise} - Resolves with start silent status.
  993. */
  994. isStartSilent() {
  995. return this._transport.sendRequest({
  996. name: 'is-start-silent'
  997. });
  998. }
  999. /**
  1000. * Returns the avatar URL of a participant.
  1001. *
  1002. * @param {string} participantId - The id of the participant.
  1003. * @returns {string} The avatar URL.
  1004. */
  1005. getAvatarURL(participantId) {
  1006. const { avatarURL } = this._participants[participantId] || {};
  1007. return avatarURL;
  1008. }
  1009. /**
  1010. * Gets the deployment info.
  1011. *
  1012. * @returns {Promise} - Resolves with the deployment info object.
  1013. */
  1014. getDeploymentInfo() {
  1015. return this._transport.sendRequest({
  1016. name: 'deployment-info'
  1017. });
  1018. }
  1019. /**
  1020. * Returns the display name of a participant.
  1021. *
  1022. * @param {string} participantId - The id of the participant.
  1023. * @returns {string} The display name.
  1024. */
  1025. getDisplayName(participantId) {
  1026. const { displayName } = this._participants[participantId] || {};
  1027. return displayName;
  1028. }
  1029. /**
  1030. * Returns the email of a participant.
  1031. *
  1032. * @param {string} participantId - The id of the participant.
  1033. * @returns {string} The email.
  1034. */
  1035. getEmail(participantId) {
  1036. const { email } = this._participants[participantId] || {};
  1037. return email;
  1038. }
  1039. /**
  1040. * Returns the iframe that loads Jitsi Meet.
  1041. *
  1042. * @returns {HTMLElement} The iframe.
  1043. */
  1044. getIFrame() {
  1045. return this._frame;
  1046. }
  1047. /**
  1048. * Returns the number of participants in the conference from all rooms. The local
  1049. * participant is included.
  1050. *
  1051. * @returns {int} The number of participants in the conference.
  1052. */
  1053. getNumberOfParticipants() {
  1054. return this._numberOfParticipants;
  1055. }
  1056. /**
  1057. * Check if the video is available.
  1058. *
  1059. * @returns {Promise} - Resolves with true if the video available, with
  1060. * false if not and rejects on failure.
  1061. */
  1062. isVideoAvailable() {
  1063. return this._transport.sendRequest({
  1064. name: 'is-video-available'
  1065. });
  1066. }
  1067. /**
  1068. * Returns the audio mute status.
  1069. *
  1070. * @returns {Promise} - Resolves with the audio mute status and rejects on
  1071. * failure.
  1072. */
  1073. isVideoMuted() {
  1074. return this._transport.sendRequest({
  1075. name: 'is-video-muted'
  1076. });
  1077. }
  1078. /**
  1079. * Returns the list of breakout rooms.
  1080. *
  1081. * @returns {Promise} Resolves with the list of breakout rooms.
  1082. */
  1083. listBreakoutRooms() {
  1084. return this._transport.sendRequest({
  1085. name: 'list-breakout-rooms'
  1086. });
  1087. }
  1088. /**
  1089. * Pins a participant's video on to the stage view.
  1090. *
  1091. * @param {string} participantId - Participant id (JID) of the participant
  1092. * that needs to be pinned on the stage view.
  1093. * @param {string} [videoType] - Indicates the type of thumbnail to be pinned when multistream support is enabled.
  1094. * Accepts "camera" or "desktop" values. Default is "camera". Any invalid values will be ignored and default will
  1095. * be used.
  1096. * @returns {void}
  1097. */
  1098. pinParticipant(participantId, videoType) {
  1099. this.executeCommand('pinParticipant', participantId, videoType);
  1100. }
  1101. /**
  1102. * Removes event listener.
  1103. *
  1104. * @param {string} event - The name of the event.
  1105. * @returns {void}
  1106. *
  1107. * @deprecated
  1108. * NOTE: This method is not removed for backward comatability purposes.
  1109. */
  1110. removeEventListener(event) {
  1111. this.removeAllListeners(event);
  1112. }
  1113. /**
  1114. * Removes event listeners.
  1115. *
  1116. * @param {Array<string>} eventList - Array with the names of the events.
  1117. * @returns {void}
  1118. *
  1119. * @deprecated
  1120. * NOTE: This method is not removed for backward comatability purposes.
  1121. */
  1122. removeEventListeners(eventList) {
  1123. eventList.forEach(event => this.removeEventListener(event));
  1124. }
  1125. /**
  1126. * Resizes the large video container as per the dimensions provided.
  1127. *
  1128. * @param {number} width - Width that needs to be applied on the large video container.
  1129. * @param {number} height - Height that needs to be applied on the large video container.
  1130. * @returns {void}
  1131. */
  1132. resizeLargeVideo(width, height) {
  1133. if (width <= this._width && height <= this._height) {
  1134. this.executeCommand('resizeLargeVideo', width, height);
  1135. }
  1136. }
  1137. /**
  1138. * Passes an event along to the local conference participant to establish
  1139. * or update a direct peer connection. This is currently used for developing
  1140. * wireless screensharing with room integration and it is advised against to
  1141. * use as its api may change.
  1142. *
  1143. * @param {Object} event - An object with information to pass along.
  1144. * @param {Object} event.data - The payload of the event.
  1145. * @param {string} event.from - The jid of the sender of the event. Needed
  1146. * when a reply is to be sent regarding the event.
  1147. * @returns {void}
  1148. */
  1149. sendProxyConnectionEvent(event) {
  1150. this._transport.sendEvent({
  1151. data: [ event ],
  1152. name: 'proxy-connection-event'
  1153. });
  1154. }
  1155. /**
  1156. * Sets the audio input device to the one with the label or id that is
  1157. * passed.
  1158. *
  1159. * @param {string} label - The label of the new device.
  1160. * @param {string} deviceId - The id of the new device.
  1161. * @returns {Promise}
  1162. */
  1163. setAudioInputDevice(label, deviceId) {
  1164. return setAudioInputDevice(this._transport, label, deviceId);
  1165. }
  1166. /**
  1167. * Sets the audio output device to the one with the label or id that is
  1168. * passed.
  1169. *
  1170. * @param {string} label - The label of the new device.
  1171. * @param {string} deviceId - The id of the new device.
  1172. * @returns {Promise}
  1173. */
  1174. setAudioOutputDevice(label, deviceId) {
  1175. return setAudioOutputDevice(this._transport, label, deviceId);
  1176. }
  1177. /**
  1178. * Displays the given participant on the large video. If no participant id is specified,
  1179. * dominant and pinned speakers will be taken into consideration while selecting the
  1180. * the large video participant.
  1181. *
  1182. * @param {string} participantId - Jid of the participant to be displayed on the large video.
  1183. * @param {string} [videoType] - Indicates the type of video to be set when multistream support is enabled.
  1184. * Accepts "camera" or "desktop" values. Default is "camera". Any invalid values will be ignored and default will
  1185. * be used.
  1186. * @returns {void}
  1187. */
  1188. setLargeVideoParticipant(participantId, videoType) {
  1189. this.executeCommand('setLargeVideoParticipant', participantId, videoType);
  1190. }
  1191. /**
  1192. * Sets the video input device to the one with the label or id that is
  1193. * passed.
  1194. *
  1195. * @param {string} label - The label of the new device.
  1196. * @param {string} deviceId - The id of the new device.
  1197. * @returns {Promise}
  1198. */
  1199. setVideoInputDevice(label, deviceId) {
  1200. return setVideoInputDevice(this._transport, label, deviceId);
  1201. }
  1202. /**
  1203. * Starts a file recording or streaming session depending on the passed on params.
  1204. * For RTMP streams, `rtmpStreamKey` must be passed on. `rtmpBroadcastID` is optional.
  1205. * For youtube streams, `youtubeStreamKey` must be passed on. `youtubeBroadcastID` is optional.
  1206. * For dropbox recording, recording `mode` should be `file` and a dropbox oauth2 token must be provided.
  1207. * For file recording, recording `mode` should be `file` and optionally `shouldShare` could be passed on.
  1208. * No other params should be passed.
  1209. *
  1210. * @param {Object} options - An object with config options to pass along.
  1211. * @param { string } options.mode - Recording mode, either `file` or `stream`.
  1212. * @param { string } options.dropboxToken - Dropbox oauth2 token.
  1213. * @param { boolean } options.shouldShare - Whether the recording should be shared with the participants or not.
  1214. * Only applies to certain jitsi meet deploys.
  1215. * @param { string } options.rtmpStreamKey - The RTMP stream key.
  1216. * @param { string } options.rtmpBroadcastID - The RTMP broadcast ID.
  1217. * @param { string } options.youtubeStreamKey - The youtube stream key.
  1218. * @param { string } options.youtubeBroadcastID - The youtube broadcast ID.
  1219. * @returns {void}
  1220. */
  1221. startRecording(options) {
  1222. this.executeCommand('startRecording', options);
  1223. }
  1224. /**
  1225. * Stops a recording or streaming session that is in progress.
  1226. *
  1227. * @param {string} mode - `file` or `stream`.
  1228. * @returns {void}
  1229. */
  1230. stopRecording(mode) {
  1231. this.executeCommand('stopRecording', mode);
  1232. }
  1233. /**
  1234. * Sets e2ee enabled/disabled.
  1235. *
  1236. * @param {boolean} enabled - The new value for e2ee enabled.
  1237. * @returns {void}
  1238. */
  1239. toggleE2EE(enabled) {
  1240. this.executeCommand('toggleE2EE', enabled);
  1241. }
  1242. /**
  1243. * Sets the key and keyIndex for e2ee.
  1244. *
  1245. * @param {Object} keyInfo - Json containing key information.
  1246. * @param {CryptoKey} [keyInfo.encryptionKey] - The encryption key.
  1247. * @param {number} [keyInfo.index] - The index of the encryption key.
  1248. * @returns {void}
  1249. */
  1250. async setMediaEncryptionKey(keyInfo) {
  1251. const { key, index } = keyInfo;
  1252. if (key) {
  1253. const exportedKey = await crypto.subtle.exportKey('raw', key);
  1254. this.executeCommand('setMediaEncryptionKey', JSON.stringify({
  1255. exportedKey: Array.from(new Uint8Array(exportedKey)),
  1256. index }));
  1257. } else {
  1258. this.executeCommand('setMediaEncryptionKey', JSON.stringify({
  1259. exportedKey: false,
  1260. index }));
  1261. }
  1262. }
  1263. }