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

external_api.js 42KB

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