Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

external_api.js 45KB

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