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

external_api.js 42KB

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