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

external_api.js 45KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388
  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; hid';
  372. this._frame.name = frameName;
  373. this._frame.id = frameName;
  374. this._setSize(height, width);
  375. this._frame.sandbox = [
  376. 'allow-scripts',
  377. 'allow-same-origin',
  378. 'allow-popups',
  379. 'allow-forms',
  380. 'allow-downloads',
  381. 'allow-top-navigation-by-user-activation'
  382. ].join(' ');
  383. this._frame.setAttribute('allowFullScreen', 'true');
  384. this._frame.style.border = 0;
  385. if (onload) {
  386. // waits for iframe resources to load
  387. // and fires event when it is done
  388. this._frame.onload = onload;
  389. }
  390. this._frame.src = this._url;
  391. this._frame = this._parentNode.appendChild(this._frame);
  392. }
  393. /**
  394. * Returns arrays with the all resources for the always on top feature.
  395. *
  396. * @returns {Array<string>}
  397. */
  398. _getAlwaysOnTopResources() {
  399. const iframeWindow = this._frame.contentWindow;
  400. const iframeDocument = iframeWindow.document;
  401. let baseURL = '';
  402. const base = iframeDocument.querySelector('base');
  403. if (base && base.href) {
  404. baseURL = base.href;
  405. } else {
  406. const { protocol, host } = iframeWindow.location;
  407. baseURL = `${protocol}//${host}`;
  408. }
  409. return ALWAYS_ON_TOP_FILENAMES.map(
  410. filename => new URL(filename, baseURL).href
  411. );
  412. }
  413. /**
  414. * Returns the formatted display name of a participant.
  415. *
  416. * @param {string} participantId - The id of the participant.
  417. * @returns {string} The formatted display name.
  418. */
  419. _getFormattedDisplayName(participantId) {
  420. const { formattedDisplayName }
  421. = this._participants[participantId] || {};
  422. return formattedDisplayName;
  423. }
  424. /**
  425. * Returns the id of the on stage participant.
  426. *
  427. * @returns {string} - The id of the on stage participant.
  428. */
  429. _getOnStageParticipant() {
  430. return this._onStageParticipant;
  431. }
  432. /**
  433. * Getter for the large video element in Jitsi Meet.
  434. *
  435. * @returns {HTMLElement|undefined} - The large video.
  436. */
  437. _getLargeVideo() {
  438. const iframe = this.getIFrame();
  439. if (!this._isLargeVideoVisible
  440. || !iframe
  441. || !iframe.contentWindow
  442. || !iframe.contentWindow.document) {
  443. return;
  444. }
  445. return iframe.contentWindow.document.getElementById('largeVideo');
  446. }
  447. /**
  448. * Getter for the prejoin video element in Jitsi Meet.
  449. *
  450. * @returns {HTMLElement|undefined} - The prejoin video.
  451. */
  452. _getPrejoinVideo() {
  453. const iframe = this.getIFrame();
  454. if (!this._isPrejoinVideoVisible
  455. || !iframe
  456. || !iframe.contentWindow
  457. || !iframe.contentWindow.document) {
  458. return;
  459. }
  460. return iframe.contentWindow.document.getElementById('prejoinVideo');
  461. }
  462. /**
  463. * Getter for participant specific video element in Jitsi Meet.
  464. *
  465. * @param {string|undefined} participantId - Id of participant to return the video for.
  466. *
  467. * @returns {HTMLElement|undefined} - The requested video. Will return the local video
  468. * by default if participantId is undefined.
  469. */
  470. _getParticipantVideo(participantId) {
  471. const iframe = this.getIFrame();
  472. if (!iframe
  473. || !iframe.contentWindow
  474. || !iframe.contentWindow.document) {
  475. return;
  476. }
  477. if (typeof participantId === 'undefined' || participantId === this._myUserID) {
  478. return iframe.contentWindow.document.getElementById('localVideo_container');
  479. }
  480. return iframe.contentWindow.document.querySelector(`#participant_${participantId} video`);
  481. }
  482. /**
  483. * Sets the size of the iframe element.
  484. *
  485. * @param {number|string} height - The height of the iframe.
  486. * @param {number|string} width - The with of the iframe.
  487. * @returns {void}
  488. *
  489. * @private
  490. */
  491. _setSize(height, width) {
  492. const parsedHeight = parseSizeParam(height);
  493. const parsedWidth = parseSizeParam(width);
  494. if (parsedHeight !== undefined) {
  495. this._height = height;
  496. this._frame.style.height = parsedHeight;
  497. }
  498. if (parsedWidth !== undefined) {
  499. this._width = width;
  500. this._frame.style.width = parsedWidth;
  501. }
  502. }
  503. /**
  504. * Setups listeners that are used internally for JitsiMeetExternalAPI.
  505. *
  506. * @returns {void}
  507. *
  508. * @private
  509. */
  510. _setupListeners() {
  511. this._transport.on('event', ({ name, ...data }) => {
  512. const userID = data.id;
  513. switch (name) {
  514. case 'video-conference-joined': {
  515. if (typeof this._tmpE2EEKey !== 'undefined') {
  516. this.executeCommand(commands.e2eeKey, this._tmpE2EEKey);
  517. this._tmpE2EEKey = undefined;
  518. }
  519. this._myUserID = userID;
  520. this._participants[userID] = {
  521. email: data.email,
  522. avatarURL: data.avatarURL
  523. };
  524. }
  525. // eslint-disable-next-line no-fallthrough
  526. case 'participant-joined': {
  527. this._participants[userID] = this._participants[userID] || {};
  528. this._participants[userID].displayName = data.displayName;
  529. this._participants[userID].formattedDisplayName
  530. = data.formattedDisplayName;
  531. changeParticipantNumber(this, 1);
  532. break;
  533. }
  534. case 'participant-left':
  535. changeParticipantNumber(this, -1);
  536. delete this._participants[userID];
  537. break;
  538. case 'display-name-change': {
  539. const user = this._participants[userID];
  540. if (user) {
  541. user.displayName = data.displayname;
  542. user.formattedDisplayName = data.formattedDisplayName;
  543. }
  544. break;
  545. }
  546. case 'email-change': {
  547. const user = this._participants[userID];
  548. if (user) {
  549. user.email = data.email;
  550. }
  551. break;
  552. }
  553. case 'avatar-changed': {
  554. const user = this._participants[userID];
  555. if (user) {
  556. user.avatarURL = data.avatarURL;
  557. }
  558. break;
  559. }
  560. case 'on-stage-participant-changed':
  561. this._onStageParticipant = userID;
  562. this.emit('largeVideoChanged');
  563. break;
  564. case 'large-video-visibility-changed':
  565. this._isLargeVideoVisible = data.isVisible;
  566. this.emit('largeVideoChanged');
  567. break;
  568. case 'prejoin-screen-loaded':
  569. this._participants[userID] = {
  570. displayName: data.displayName,
  571. formattedDisplayName: data.formattedDisplayName
  572. };
  573. break;
  574. case 'on-prejoin-video-changed':
  575. this._isPrejoinVideoVisible = data.isVisible;
  576. this.emit('prejoinVideoChanged');
  577. break;
  578. case 'video-conference-left':
  579. changeParticipantNumber(this, -1);
  580. delete this._participants[this._myUserID];
  581. break;
  582. case 'video-quality-changed':
  583. this._videoQuality = data.videoQuality;
  584. break;
  585. case 'breakout-rooms-updated':
  586. this.updateNumberOfParticipants(data.rooms);
  587. break;
  588. case 'local-storage-changed':
  589. jitsiLocalStorage.setItem('jitsiLocalStorage', data.localStorageContent);
  590. // Since this is internal event we don't need to emit it to the consumer of the API.
  591. return true;
  592. }
  593. const eventName = events[name];
  594. if (eventName) {
  595. this.emit(eventName, data);
  596. return true;
  597. }
  598. return false;
  599. });
  600. }
  601. /**
  602. * Update number of participants based on all rooms.
  603. *
  604. * @param {Object} rooms - Rooms available rooms in the conference.
  605. * @returns {void}
  606. */
  607. updateNumberOfParticipants(rooms) {
  608. if (!rooms || !Object.keys(rooms).length) {
  609. return;
  610. }
  611. const allParticipants = Object.keys(rooms).reduce((prev, roomItemKey) => {
  612. if (rooms[roomItemKey]?.participants) {
  613. return Object.keys(rooms[roomItemKey].participants).length + prev;
  614. }
  615. return prev;
  616. }, 0);
  617. this._numberOfParticipants = allParticipants;
  618. }
  619. /**
  620. * Returns the rooms info in the conference.
  621. *
  622. * @returns {Object} Rooms info.
  623. */
  624. async getRoomsInfo() {
  625. return this._transport.sendRequest({
  626. name: 'rooms-info'
  627. });
  628. }
  629. /**
  630. * Adds event listener to Meet Jitsi.
  631. *
  632. * @param {string} event - The name of the event.
  633. * @param {Function} listener - The listener.
  634. * @returns {void}
  635. *
  636. * @deprecated
  637. * NOTE: This method is not removed for backward comatability purposes.
  638. */
  639. addEventListener(event, listener) {
  640. this.on(event, listener);
  641. }
  642. /**
  643. * Adds event listeners to Meet Jitsi.
  644. *
  645. * @param {Object} listeners - The object key should be the name of
  646. * the event and value - the listener.
  647. * Currently we support the following
  648. * events:
  649. * {@code log} - receives event notifications whenever information has
  650. * been logged and has a log level specified within {@code config.apiLogLevels}.
  651. * The listener will receive object with the following structure:
  652. * {{
  653. * logLevel: the message log level
  654. * arguments: an array of strings that compose the actual log message
  655. * }}
  656. * {@code chatUpdated} - receives event notifications about chat state being
  657. * updated. The listener will receive object with the following structure:
  658. * {{
  659. * 'unreadCount': unreadCounter, // the unread message(s) counter,
  660. * 'isOpen': isOpen, // whether the chat panel is open or not
  661. * }}
  662. * {@code incomingMessage} - receives event notifications about incoming
  663. * messages. The listener will receive object with the following structure:
  664. * {{
  665. * 'from': from,//JID of the user that sent the message
  666. * 'nick': nick,//the nickname of the user that sent the message
  667. * 'message': txt//the text of the message
  668. * }}
  669. * {@code outgoingMessage} - receives event notifications about outgoing
  670. * messages. The listener will receive object with the following structure:
  671. * {{
  672. * 'message': txt//the text of the message
  673. * }}
  674. * {@code displayNameChanged} - receives event notifications about display
  675. * name change. The listener will receive object with the following
  676. * structure:
  677. * {{
  678. * jid: jid,//the JID of the participant that changed his display name
  679. * displayname: displayName //the new display name
  680. * }}
  681. * {@code participantJoined} - receives event notifications about new
  682. * participant.
  683. * The listener will receive object with the following structure:
  684. * {{
  685. * jid: jid //the jid of the participant
  686. * }}
  687. * {@code participantLeft} - receives event notifications about the
  688. * participant that left the room.
  689. * The listener will receive object with the following structure:
  690. * {{
  691. * jid: jid //the jid of the participant
  692. * }}
  693. * {@code videoConferenceJoined} - receives event notifications about the
  694. * local user has successfully joined the video conference.
  695. * The listener will receive object with the following structure:
  696. * {{
  697. * roomName: room //the room name of the conference
  698. * }}
  699. * {@code videoConferenceLeft} - receives event notifications about the
  700. * local user has left the video conference.
  701. * The listener will receive object with the following structure:
  702. * {{
  703. * roomName: room //the room name of the conference
  704. * }}
  705. * {@code screenSharingStatusChanged} - receives event notifications about
  706. * turning on/off the local user screen sharing.
  707. * The listener will receive object with the following structure:
  708. * {{
  709. * on: on //whether screen sharing is on
  710. * }}
  711. * {@code dominantSpeakerChanged} - receives event notifications about
  712. * change in the dominant speaker.
  713. * The listener will receive object with the following structure:
  714. * {{
  715. * id: participantId //participantId of the new dominant speaker
  716. * }}
  717. * {@code suspendDetected} - receives event notifications about detecting suspend event in host computer.
  718. * {@code readyToClose} - all hangup operations are completed and Jitsi Meet
  719. * is ready to be disposed.
  720. * @returns {void}
  721. *
  722. * @deprecated
  723. * NOTE: This method is not removed for backward comatability purposes.
  724. */
  725. addEventListeners(listeners) {
  726. for (const event in listeners) { // eslint-disable-line guard-for-in
  727. this.addEventListener(event, listeners[event]);
  728. }
  729. }
  730. /**
  731. * Captures the screenshot of the large video.
  732. *
  733. * @returns {Promise<string>} - Resolves with a base64 encoded image data of the screenshot
  734. * if large video is detected, an error otherwise.
  735. */
  736. captureLargeVideoScreenshot() {
  737. return this._transport.sendRequest({
  738. name: 'capture-largevideo-screenshot'
  739. });
  740. }
  741. /**
  742. * Removes the listeners and removes the Jitsi Meet frame.
  743. *
  744. * @returns {void}
  745. */
  746. dispose() {
  747. this.emit('_willDispose');
  748. this._transport.dispose();
  749. this.removeAllListeners();
  750. if (this._frame && this._frame.parentNode) {
  751. this._frame.parentNode.removeChild(this._frame);
  752. }
  753. }
  754. /**
  755. * Executes command. The available commands are:
  756. * {@code displayName} - Sets the display name of the local participant to
  757. * the value passed in the arguments array.
  758. * {@code subject} - Sets the subject of the conference, the value passed
  759. * in the arguments array. Note: Available only for moderator.
  760. *
  761. * {@code toggleAudio} - Mutes / unmutes audio with no arguments.
  762. * {@code toggleVideo} - Mutes / unmutes video with no arguments.
  763. * {@code toggleFilmStrip} - Hides / shows the filmstrip with no arguments.
  764. *
  765. * If the command doesn't require any arguments the parameter should be set
  766. * to empty array or it may be omitted.
  767. *
  768. * @param {string} name - The name of the command.
  769. * @returns {void}
  770. */
  771. executeCommand(name, ...args) {
  772. if (!(name in commands)) {
  773. console.error('Not supported command name.');
  774. return;
  775. }
  776. this._transport.sendEvent({
  777. data: args,
  778. name: commands[name]
  779. });
  780. }
  781. /**
  782. * Executes commands. The available commands are:
  783. * {@code displayName} - Sets the display name of the local participant to
  784. * the value passed in the arguments array.
  785. * {@code toggleAudio} - Mutes / unmutes audio. No arguments.
  786. * {@code toggleVideo} - Mutes / unmutes video. No arguments.
  787. * {@code toggleFilmStrip} - Hides / shows the filmstrip. No arguments.
  788. * {@code toggleChat} - Hides / shows chat. No arguments.
  789. * {@code toggleShareScreen} - Starts / stops screen sharing. No arguments.
  790. *
  791. * @param {Object} commandList - The object with commands to be executed.
  792. * The keys of the object are the commands that will be executed and the
  793. * values are the arguments for the command.
  794. * @returns {void}
  795. */
  796. executeCommands(commandList) {
  797. for (const key in commandList) { // eslint-disable-line guard-for-in
  798. this.executeCommand(key, commandList[key]);
  799. }
  800. }
  801. /**
  802. * Returns Promise that resolves with a list of available devices.
  803. *
  804. * @returns {Promise}
  805. */
  806. getAvailableDevices() {
  807. return getAvailableDevices(this._transport);
  808. }
  809. /**
  810. * Gets a list of the currently sharing participant id's.
  811. *
  812. * @returns {Promise} - Resolves with the list of participant id's currently sharing.
  813. */
  814. getContentSharingParticipants() {
  815. return this._transport.sendRequest({
  816. name: 'get-content-sharing-participants'
  817. });
  818. }
  819. /**
  820. * Returns Promise that resolves with current selected devices.
  821. *
  822. * @returns {Promise}
  823. */
  824. getCurrentDevices() {
  825. return getCurrentDevices(this._transport);
  826. }
  827. /**
  828. * Returns any custom avatars backgrounds.
  829. *
  830. * @returns {Promise} - Resolves with the list of custom avatar backgrounds.
  831. */
  832. getCustomAvatarBackgrounds() {
  833. return this._transport.sendRequest({
  834. name: 'get-custom-avatar-backgrounds'
  835. });
  836. }
  837. /**
  838. * Returns the current livestream url.
  839. *
  840. * @returns {Promise} - Resolves with the current livestream URL if exists, with
  841. * undefined if not and rejects on failure.
  842. */
  843. getLivestreamUrl() {
  844. return this._transport.sendRequest({
  845. name: 'get-livestream-url'
  846. });
  847. }
  848. /**
  849. * Returns the conference participants information.
  850. *
  851. * @returns {Array<Object>} - Returns an array containing participants
  852. * information like participant id, display name, avatar URL and email.
  853. */
  854. getParticipantsInfo() {
  855. const participantIds = Object.keys(this._participants);
  856. const participantsInfo = Object.values(this._participants);
  857. participantsInfo.forEach((participant, idx) => {
  858. participant.participantId = participantIds[idx];
  859. });
  860. return participantsInfo;
  861. }
  862. /**
  863. * Returns the current video quality setting.
  864. *
  865. * @returns {number}
  866. */
  867. getVideoQuality() {
  868. return this._videoQuality;
  869. }
  870. /**
  871. * Check if the audio is available.
  872. *
  873. * @returns {Promise} - Resolves with true if the audio available, with
  874. * false if not and rejects on failure.
  875. */
  876. isAudioAvailable() {
  877. return this._transport.sendRequest({
  878. name: 'is-audio-available'
  879. });
  880. }
  881. /**
  882. * Returns Promise that resolves with true if the device change is available
  883. * and with false if not.
  884. *
  885. * @param {string} [deviceType] - Values - 'output', 'input' or undefined.
  886. * Default - 'input'.
  887. * @returns {Promise}
  888. */
  889. isDeviceChangeAvailable(deviceType) {
  890. return isDeviceChangeAvailable(this._transport, deviceType);
  891. }
  892. /**
  893. * Returns Promise that resolves with true if the device list is available
  894. * and with false if not.
  895. *
  896. * @returns {Promise}
  897. */
  898. isDeviceListAvailable() {
  899. return isDeviceListAvailable(this._transport);
  900. }
  901. /**
  902. * Returns Promise that resolves with true if multiple audio input is supported
  903. * and with false if not.
  904. *
  905. * @returns {Promise}
  906. */
  907. isMultipleAudioInputSupported() {
  908. return isMultipleAudioInputSupported(this._transport);
  909. }
  910. /**
  911. * Invite people to the call.
  912. *
  913. * @param {Array<Object>} invitees - The invitees.
  914. * @returns {Promise} - Resolves on success and rejects on failure.
  915. */
  916. invite(invitees) {
  917. if (!Array.isArray(invitees) || invitees.length === 0) {
  918. return Promise.reject(new TypeError('Invalid Argument'));
  919. }
  920. return this._transport.sendRequest({
  921. name: 'invite',
  922. invitees
  923. });
  924. }
  925. /**
  926. * Returns the audio mute status.
  927. *
  928. * @returns {Promise} - Resolves with the audio mute status and rejects on
  929. * failure.
  930. */
  931. isAudioMuted() {
  932. return this._transport.sendRequest({
  933. name: 'is-audio-muted'
  934. });
  935. }
  936. /**
  937. * Returns the audio disabled status.
  938. *
  939. * @returns {Promise} - Resolves with the audio disabled status and rejects on
  940. * failure.
  941. */
  942. isAudioDisabled() {
  943. return this._transport.sendRequest({
  944. name: 'is-audio-disabled'
  945. });
  946. }
  947. /**
  948. * Returns the moderation on status on the given mediaType.
  949. *
  950. * @param {string} mediaType - The media type for which to check moderation.
  951. * @returns {Promise} - Resolves with the moderation on status and rejects on
  952. * failure.
  953. */
  954. isModerationOn(mediaType) {
  955. return this._transport.sendRequest({
  956. name: 'is-moderation-on',
  957. mediaType
  958. });
  959. }
  960. /**
  961. * Returns force muted status of the given participant id for the given media type.
  962. *
  963. * @param {string} participantId - The id of the participant to check.
  964. * @param {string} mediaType - The media type for which to check.
  965. * @returns {Promise} - Resolves with the force muted status and rejects on
  966. * failure.
  967. */
  968. isParticipantForceMuted(participantId, mediaType) {
  969. return this._transport.sendRequest({
  970. name: 'is-participant-force-muted',
  971. participantId,
  972. mediaType
  973. });
  974. }
  975. /**
  976. * Returns whether the participants pane is open.
  977. *
  978. * @returns {Promise} - Resolves with true if the participants pane is open
  979. * and with false if not.
  980. */
  981. isParticipantsPaneOpen() {
  982. return this._transport.sendRequest({
  983. name: 'is-participants-pane-open'
  984. });
  985. }
  986. /**
  987. * Returns screen sharing status.
  988. *
  989. * @returns {Promise} - Resolves with screensharing status and rejects on failure.
  990. */
  991. isSharingScreen() {
  992. return this._transport.sendRequest({
  993. name: 'is-sharing-screen'
  994. });
  995. }
  996. /**
  997. * Returns whether meeting is started silent.
  998. *
  999. * @returns {Promise} - Resolves with start silent status.
  1000. */
  1001. isStartSilent() {
  1002. return this._transport.sendRequest({
  1003. name: 'is-start-silent'
  1004. });
  1005. }
  1006. /**
  1007. * Returns the avatar URL of a participant.
  1008. *
  1009. * @param {string} participantId - The id of the participant.
  1010. * @returns {string} The avatar URL.
  1011. */
  1012. getAvatarURL(participantId) {
  1013. const { avatarURL } = this._participants[participantId] || {};
  1014. return avatarURL;
  1015. }
  1016. /**
  1017. * Gets the deployment info.
  1018. *
  1019. * @returns {Promise} - Resolves with the deployment info object.
  1020. */
  1021. getDeploymentInfo() {
  1022. return this._transport.sendRequest({
  1023. name: 'deployment-info'
  1024. });
  1025. }
  1026. /**
  1027. * Returns the display name of a participant.
  1028. *
  1029. * @param {string} participantId - The id of the participant.
  1030. * @returns {string} The display name.
  1031. */
  1032. getDisplayName(participantId) {
  1033. const { displayName } = this._participants[participantId] || {};
  1034. return displayName;
  1035. }
  1036. /**
  1037. * Returns the email of a participant.
  1038. *
  1039. * @param {string} participantId - The id of the participant.
  1040. * @returns {string} The email.
  1041. */
  1042. getEmail(participantId) {
  1043. const { email } = this._participants[participantId] || {};
  1044. return email;
  1045. }
  1046. /**
  1047. * Returns the iframe that loads Jitsi Meet.
  1048. *
  1049. * @returns {HTMLElement} The iframe.
  1050. */
  1051. getIFrame() {
  1052. return this._frame;
  1053. }
  1054. /**
  1055. * Returns the number of participants in the conference from all rooms. The local
  1056. * participant is included.
  1057. *
  1058. * @returns {int} The number of participants in the conference.
  1059. */
  1060. getNumberOfParticipants() {
  1061. return this._numberOfParticipants;
  1062. }
  1063. /**
  1064. * Check if the video is available.
  1065. *
  1066. * @returns {Promise} - Resolves with true if the video available, with
  1067. * false if not and rejects on failure.
  1068. */
  1069. isVideoAvailable() {
  1070. return this._transport.sendRequest({
  1071. name: 'is-video-available'
  1072. });
  1073. }
  1074. /**
  1075. * Returns the audio mute status.
  1076. *
  1077. * @returns {Promise} - Resolves with the audio mute status and rejects on
  1078. * failure.
  1079. */
  1080. isVideoMuted() {
  1081. return this._transport.sendRequest({
  1082. name: 'is-video-muted'
  1083. });
  1084. }
  1085. /**
  1086. * Returns the list of breakout rooms.
  1087. *
  1088. * @returns {Promise} Resolves with the list of breakout rooms.
  1089. */
  1090. listBreakoutRooms() {
  1091. return this._transport.sendRequest({
  1092. name: 'list-breakout-rooms'
  1093. });
  1094. }
  1095. /**
  1096. * Pins a participant's video on to the stage view.
  1097. *
  1098. * @param {string} participantId - Participant id (JID) of the participant
  1099. * that needs to be pinned on the stage view.
  1100. * @param {string} [videoType] - Indicates the type of thumbnail to be pinned when multistream support is enabled.
  1101. * Accepts "camera" or "desktop" values. Default is "camera". Any invalid values will be ignored and default will
  1102. * be used.
  1103. * @returns {void}
  1104. */
  1105. pinParticipant(participantId, videoType) {
  1106. this.executeCommand('pinParticipant', participantId, videoType);
  1107. }
  1108. /**
  1109. * Removes event listener.
  1110. *
  1111. * @param {string} event - The name of the event.
  1112. * @returns {void}
  1113. *
  1114. * @deprecated
  1115. * NOTE: This method is not removed for backward comatability purposes.
  1116. */
  1117. removeEventListener(event) {
  1118. this.removeAllListeners(event);
  1119. }
  1120. /**
  1121. * Removes event listeners.
  1122. *
  1123. * @param {Array<string>} eventList - Array with the names of the events.
  1124. * @returns {void}
  1125. *
  1126. * @deprecated
  1127. * NOTE: This method is not removed for backward comatability purposes.
  1128. */
  1129. removeEventListeners(eventList) {
  1130. eventList.forEach(event => this.removeEventListener(event));
  1131. }
  1132. /**
  1133. * Resizes the large video container as per the dimensions provided.
  1134. *
  1135. * @param {number} width - Width that needs to be applied on the large video container.
  1136. * @param {number} height - Height that needs to be applied on the large video container.
  1137. * @returns {void}
  1138. */
  1139. resizeLargeVideo(width, height) {
  1140. if (width <= this._width && height <= this._height) {
  1141. this.executeCommand('resizeLargeVideo', width, height);
  1142. }
  1143. }
  1144. /**
  1145. * Passes an event along to the local conference participant to establish
  1146. * or update a direct peer connection. This is currently used for developing
  1147. * wireless screensharing with room integration and it is advised against to
  1148. * use as its api may change.
  1149. *
  1150. * @param {Object} event - An object with information to pass along.
  1151. * @param {Object} event.data - The payload of the event.
  1152. * @param {string} event.from - The jid of the sender of the event. Needed
  1153. * when a reply is to be sent regarding the event.
  1154. * @returns {void}
  1155. */
  1156. sendProxyConnectionEvent(event) {
  1157. this._transport.sendEvent({
  1158. data: [ event ],
  1159. name: 'proxy-connection-event'
  1160. });
  1161. }
  1162. /**
  1163. * Sets the audio input device to the one with the label or id that is
  1164. * passed.
  1165. *
  1166. * @param {string} label - The label of the new device.
  1167. * @param {string} deviceId - The id of the new device.
  1168. * @returns {Promise}
  1169. */
  1170. setAudioInputDevice(label, deviceId) {
  1171. return setAudioInputDevice(this._transport, label, deviceId);
  1172. }
  1173. /**
  1174. * Sets the audio output device to the one with the label or id that is
  1175. * passed.
  1176. *
  1177. * @param {string} label - The label of the new device.
  1178. * @param {string} deviceId - The id of the new device.
  1179. * @returns {Promise}
  1180. */
  1181. setAudioOutputDevice(label, deviceId) {
  1182. return setAudioOutputDevice(this._transport, label, deviceId);
  1183. }
  1184. /**
  1185. * Displays the given participant on the large video. If no participant id is specified,
  1186. * dominant and pinned speakers will be taken into consideration while selecting the
  1187. * the large video participant.
  1188. *
  1189. * @param {string} participantId - Jid of the participant to be displayed on the large video.
  1190. * @param {string} [videoType] - Indicates the type of video to be set when multistream support is enabled.
  1191. * Accepts "camera" or "desktop" values. Default is "camera". Any invalid values will be ignored and default will
  1192. * be used.
  1193. * @returns {void}
  1194. */
  1195. setLargeVideoParticipant(participantId, videoType) {
  1196. this.executeCommand('setLargeVideoParticipant', participantId, videoType);
  1197. }
  1198. /**
  1199. * Sets the video input device to the one with the label or id that is
  1200. * passed.
  1201. *
  1202. * @param {string} label - The label of the new device.
  1203. * @param {string} deviceId - The id of the new device.
  1204. * @returns {Promise}
  1205. */
  1206. setVideoInputDevice(label, deviceId) {
  1207. return setVideoInputDevice(this._transport, label, deviceId);
  1208. }
  1209. /**
  1210. * Starts a file recording or streaming session depending on the passed on params.
  1211. * For RTMP streams, `rtmpStreamKey` must be passed on. `rtmpBroadcastID` is optional.
  1212. * For youtube streams, `youtubeStreamKey` must be passed on. `youtubeBroadcastID` is optional.
  1213. * For dropbox recording, recording `mode` should be `file` and a dropbox oauth2 token must be provided.
  1214. * For file recording, recording `mode` should be `file` and optionally `shouldShare` could be passed on.
  1215. * No other params should be passed.
  1216. *
  1217. * @param {Object} options - An object with config options to pass along.
  1218. * @param { string } options.mode - Recording mode, either `file` or `stream`.
  1219. * @param { string } options.dropboxToken - Dropbox oauth2 token.
  1220. * @param { boolean } options.shouldShare - Whether the recording should be shared with the participants or not.
  1221. * Only applies to certain jitsi meet deploys.
  1222. * @param { string } options.rtmpStreamKey - The RTMP stream key.
  1223. * @param { string } options.rtmpBroadcastID - The RTMP broadcast ID.
  1224. * @param { string } options.youtubeStreamKey - The youtube stream key.
  1225. * @param { string } options.youtubeBroadcastID - The youtube broadcast ID.
  1226. * @returns {void}
  1227. */
  1228. startRecording(options) {
  1229. this.executeCommand('startRecording', options);
  1230. }
  1231. /**
  1232. * Stops a recording or streaming session that is in progress.
  1233. *
  1234. * @param {string} mode - `file` or `stream`.
  1235. * @returns {void}
  1236. */
  1237. stopRecording(mode) {
  1238. this.executeCommand('stopRecording', mode);
  1239. }
  1240. /**
  1241. * Sets e2ee enabled/disabled.
  1242. *
  1243. * @param {boolean} enabled - The new value for e2ee enabled.
  1244. * @returns {void}
  1245. */
  1246. toggleE2EE(enabled) {
  1247. this.executeCommand('toggleE2EE', enabled);
  1248. }
  1249. /**
  1250. * Sets the key and keyIndex for e2ee.
  1251. *
  1252. * @param {Object} keyInfo - Json containing key information.
  1253. * @param {CryptoKey} [keyInfo.encryptionKey] - The encryption key.
  1254. * @param {number} [keyInfo.index] - The index of the encryption key.
  1255. * @returns {void}
  1256. */
  1257. async setMediaEncryptionKey(keyInfo) {
  1258. const { key, index } = keyInfo;
  1259. if (key) {
  1260. const exportedKey = await crypto.subtle.exportKey('raw', key);
  1261. this.executeCommand('setMediaEncryptionKey', JSON.stringify({
  1262. exportedKey: Array.from(new Uint8Array(exportedKey)),
  1263. index }));
  1264. } else {
  1265. this.executeCommand('setMediaEncryptionKey', JSON.stringify({
  1266. exportedKey: false,
  1267. index }));
  1268. }
  1269. }
  1270. }