您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

external_api.js 45KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382
  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. 'notification-triggered': 'notificationTriggered',
  126. 'outgoing-message': 'outgoingMessage',
  127. 'participant-joined': 'participantJoined',
  128. 'participant-kicked-out': 'participantKickedOut',
  129. 'participant-left': 'participantLeft',
  130. 'participant-role-changed': 'participantRoleChanged',
  131. 'participants-pane-toggled': 'participantsPaneToggled',
  132. 'password-required': 'passwordRequired',
  133. 'peer-connection-failure': 'peerConnectionFailure',
  134. 'prejoin-screen-loaded': 'prejoinScreenLoaded',
  135. 'proxy-connection-event': 'proxyConnectionEvent',
  136. 'raise-hand-updated': 'raiseHandUpdated',
  137. 'recording-link-available': 'recordingLinkAvailable',
  138. 'recording-status-changed': 'recordingStatusChanged',
  139. 'participant-menu-button-clicked': 'participantMenuButtonClick',
  140. 'video-ready-to-close': 'readyToClose',
  141. 'video-conference-joined': 'videoConferenceJoined',
  142. 'video-conference-left': 'videoConferenceLeft',
  143. 'video-availability-changed': 'videoAvailabilityChanged',
  144. 'video-mute-status-changed': 'videoMuteStatusChanged',
  145. 'video-quality-changed': 'videoQualityChanged',
  146. 'screen-sharing-status-changed': 'screenSharingStatusChanged',
  147. 'dominant-speaker-changed': 'dominantSpeakerChanged',
  148. 'subject-change': 'subjectChange',
  149. 'suspend-detected': 'suspendDetected',
  150. 'tile-view-changed': 'tileViewChanged',
  151. 'toolbar-button-clicked': 'toolbarButtonClicked'
  152. };
  153. /**
  154. * Last id of api object.
  155. *
  156. * @type {number}
  157. */
  158. let id = 0;
  159. /**
  160. * Adds given number to the numberOfParticipants property of given APIInstance.
  161. *
  162. * @param {JitsiMeetExternalAPI} APIInstance - The instance of the API.
  163. * @param {int} number - The number of participants to be added to
  164. * numberOfParticipants property (this parameter can be negative number if the
  165. * numberOfParticipants should be decreased).
  166. * @returns {void}
  167. */
  168. function changeParticipantNumber(APIInstance, number) {
  169. APIInstance._numberOfParticipants += number;
  170. }
  171. /**
  172. * Generates the URL for the iframe.
  173. *
  174. * @param {string} domain - The domain name of the server that hosts the
  175. * conference.
  176. * @param {string} [options] - Another optional parameters.
  177. * @param {Object} [options.configOverwrite] - Object containing configuration
  178. * options defined in config.js to be overridden.
  179. * @param {Object} [options.interfaceConfigOverwrite] - Object containing
  180. * configuration options defined in interface_config.js to be overridden.
  181. * @param {string} [options.jwt] - The JWT token if needed by jitsi-meet for
  182. * authentication.
  183. * @param {string} [options.lang] - The meeting's default language.
  184. * @param {string} [options.roomName] - The name of the room to join.
  185. * @returns {string} The URL.
  186. */
  187. function generateURL(domain, options = {}) {
  188. return urlObjectToString({
  189. ...options,
  190. url: `https://${domain}/#jitsi_meet_external_api_id=${id}`
  191. });
  192. }
  193. /**
  194. * Parses the arguments passed to the constructor. If the old format is used
  195. * the function translates the arguments to the new format.
  196. *
  197. * @param {Array} args - The arguments to be parsed.
  198. * @returns {Object} JS object with properties.
  199. */
  200. function parseArguments(args) {
  201. if (!args.length) {
  202. return {};
  203. }
  204. const firstArg = args[0];
  205. switch (typeof firstArg) {
  206. case 'string': // old arguments format
  207. case 'undefined': {
  208. // Not sure which format but we are trying to parse the old
  209. // format because if the new format is used everything will be undefined
  210. // anyway.
  211. const [
  212. roomName,
  213. width,
  214. height,
  215. parentNode,
  216. configOverwrite,
  217. interfaceConfigOverwrite,
  218. jwt,
  219. onload,
  220. lang
  221. ] = args;
  222. return {
  223. roomName,
  224. width,
  225. height,
  226. parentNode,
  227. configOverwrite,
  228. interfaceConfigOverwrite,
  229. jwt,
  230. onload,
  231. lang
  232. };
  233. }
  234. case 'object': // new arguments format
  235. return args[0];
  236. default:
  237. throw new Error('Can\'t parse the arguments!');
  238. }
  239. }
  240. /**
  241. * Compute valid values for height and width. If a number is specified it's
  242. * treated as pixel units. If the value is expressed in px, em, pt or
  243. * percentage, it's used as is.
  244. *
  245. * @param {any} value - The value to be parsed.
  246. * @returns {string|undefined} The parsed value that can be used for setting
  247. * sizes through the style property. If invalid value is passed the method
  248. * returns undefined.
  249. */
  250. function parseSizeParam(value) {
  251. let parsedValue;
  252. // This regex parses values of the form 100px, 100em, 100pt or 100%.
  253. // Values like 100 or 100px are handled outside of the regex, and
  254. // invalid values will be ignored and the minimum will be used.
  255. const re = /([0-9]*\.?[0-9]+)(em|pt|px|%)$/;
  256. if (typeof value === 'string' && String(value).match(re) !== null) {
  257. parsedValue = value;
  258. } else if (typeof value === 'number') {
  259. parsedValue = `${value}px`;
  260. }
  261. return parsedValue;
  262. }
  263. /**
  264. * The IFrame API interface class.
  265. */
  266. export default class JitsiMeetExternalAPI extends EventEmitter {
  267. /**
  268. * Constructs new API instance. Creates iframe and loads Jitsi Meet in it.
  269. *
  270. * @param {string} domain - The domain name of the server that hosts the
  271. * conference.
  272. * @param {Object} [options] - Optional arguments.
  273. * @param {string} [options.roomName] - The name of the room to join.
  274. * @param {number|string} [options.width] - Width of the iframe. Check
  275. * parseSizeParam for format details.
  276. * @param {number|string} [options.height] - Height of the iframe. Check
  277. * parseSizeParam for format details.
  278. * @param {DOMElement} [options.parentNode] - The node that will contain the
  279. * iframe.
  280. * @param {Object} [options.configOverwrite] - Object containing
  281. * configuration options defined in config.js to be overridden.
  282. * @param {Object} [options.interfaceConfigOverwrite] - Object containing
  283. * configuration options defined in interface_config.js to be overridden.
  284. * @param {string} [options.jwt] - The JWT token if needed by jitsi-meet for
  285. * authentication.
  286. * @param {string} [options.lang] - The meeting's default language.
  287. * @param {string} [options.onload] - The onload function that will listen
  288. * for iframe onload event.
  289. * @param {Array<Object>} [options.invitees] - Array of objects containing
  290. * information about new participants that will be invited in the call.
  291. * @param {Array<Object>} [options.devices] - Array of objects containing
  292. * information about the initial devices that will be used in the call.
  293. * @param {Object} [options.userInfo] - Object containing information about
  294. * the participant opening the meeting.
  295. * @param {string} [options.e2eeKey] - The key used for End-to-End encryption.
  296. * THIS IS EXPERIMENTAL.
  297. * @param {string} [options.release] - The key used for specifying release if enabled on the backend.
  298. */
  299. constructor(domain, ...args) {
  300. super();
  301. const {
  302. roomName = '',
  303. width = '100%',
  304. height = '100%',
  305. parentNode = document.body,
  306. configOverwrite = {},
  307. interfaceConfigOverwrite = {},
  308. jwt = undefined,
  309. lang = undefined,
  310. onload = undefined,
  311. invitees,
  312. devices,
  313. userInfo,
  314. e2eeKey,
  315. release
  316. } = parseArguments(args);
  317. const localStorageContent = jitsiLocalStorage.getItem('jitsiLocalStorage');
  318. this._parentNode = parentNode;
  319. this._url = generateURL(domain, {
  320. configOverwrite,
  321. interfaceConfigOverwrite,
  322. jwt,
  323. lang,
  324. roomName,
  325. devices,
  326. userInfo,
  327. appData: {
  328. localStorageContent
  329. },
  330. release
  331. });
  332. this._createIFrame(height, width, onload);
  333. this._transport = new Transport({
  334. backend: new PostMessageTransportBackend({
  335. postisOptions: {
  336. allowedOrigin: new URL(this._url).origin,
  337. scope: `jitsi_meet_external_api_${id}`,
  338. window: this._frame.contentWindow
  339. }
  340. })
  341. });
  342. if (Array.isArray(invitees) && invitees.length > 0) {
  343. this.invite(invitees);
  344. }
  345. this._tmpE2EEKey = e2eeKey;
  346. this._isLargeVideoVisible = false;
  347. this._isPrejoinVideoVisible = false;
  348. this._numberOfParticipants = 0;
  349. this._participants = {};
  350. this._myUserID = undefined;
  351. this._onStageParticipant = undefined;
  352. this._setupListeners();
  353. id++;
  354. }
  355. /**
  356. * Creates the iframe element.
  357. *
  358. * @param {number|string} height - The height of the iframe. Check
  359. * parseSizeParam for format details.
  360. * @param {number|string} width - The with of the iframe. Check
  361. * parseSizeParam for format details.
  362. * @param {Function} onload - The function that will listen
  363. * for onload event.
  364. * @returns {void}
  365. *
  366. * @private
  367. */
  368. _createIFrame(height, width, onload) {
  369. const frameName = `jitsiConferenceFrame${id}`;
  370. this._frame = document.createElement('iframe');
  371. this._frame.allow = 'camera; microphone; display-capture; autoplay; clipboard-write';
  372. this._frame.name = frameName;
  373. this._frame.id = frameName;
  374. this._setSize(height, width);
  375. this._frame.sandbox = 'allow-scripts allow-same-origin allow-popups allow-forms allow-downloads';
  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 = this._parentNode.appendChild(this._frame);
  384. this._frame.src = this._url;
  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. }