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 23KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747
  1. import EventEmitter from 'events';
  2. import { urlObjectToString } from '../../../react/features/base/util/uri';
  3. import {
  4. PostMessageTransportBackend,
  5. Transport
  6. } from '../../transport';
  7. import electronPopupsConfig from './electronPopupsConfig.json';
  8. const logger = require('jitsi-meet-logger').getLogger(__filename);
  9. const ALWAYS_ON_TOP_FILENAMES = [
  10. 'css/all.css', 'libs/alwaysontop.min.js'
  11. ];
  12. /**
  13. * Maps the names of the commands expected by the API with the name of the
  14. * commands expected by jitsi-meet
  15. */
  16. const commands = {
  17. avatarUrl: 'avatar-url',
  18. displayName: 'display-name',
  19. email: 'email',
  20. hangup: 'video-hangup',
  21. submitFeedback: 'submit-feedback',
  22. toggleAudio: 'toggle-audio',
  23. toggleChat: 'toggle-chat',
  24. toggleFilmStrip: 'toggle-film-strip',
  25. toggleShareScreen: 'toggle-share-screen',
  26. toggleVideo: 'toggle-video'
  27. };
  28. /**
  29. * Maps the names of the events expected by the API with the name of the
  30. * events expected by jitsi-meet
  31. */
  32. const events = {
  33. 'avatar-changed': 'avatarChanged',
  34. 'audio-availability-changed': 'audioAvailabilityChanged',
  35. 'audio-mute-status-changed': 'audioMuteStatusChanged',
  36. 'display-name-change': 'displayNameChange',
  37. 'email-change': 'emailChange',
  38. 'feedback-submitted': 'feedbackSubmitted',
  39. 'incoming-message': 'incomingMessage',
  40. 'outgoing-message': 'outgoingMessage',
  41. 'participant-joined': 'participantJoined',
  42. 'participant-left': 'participantLeft',
  43. 'video-ready-to-close': 'readyToClose',
  44. 'video-conference-joined': 'videoConferenceJoined',
  45. 'video-conference-left': 'videoConferenceLeft',
  46. 'video-availability-changed': 'videoAvailabilityChanged',
  47. 'video-mute-status-changed': 'videoMuteStatusChanged',
  48. 'screen-sharing-status-changed': 'screenSharingStatusChanged'
  49. };
  50. /**
  51. * Last id of api object
  52. * @type {number}
  53. */
  54. let id = 0;
  55. /**
  56. * Adds given number to the numberOfParticipants property of given APIInstance.
  57. *
  58. * @param {JitsiMeetExternalAPI} APIInstance - The instance of the API.
  59. * @param {int} number - The number of participants to be added to
  60. * numberOfParticipants property (this parameter can be negative number if the
  61. * numberOfParticipants should be decreased).
  62. * @returns {void}
  63. */
  64. function changeParticipantNumber(APIInstance, number) {
  65. APIInstance._numberOfParticipants += number;
  66. }
  67. /**
  68. * Generates the URL for the iframe.
  69. *
  70. * @param {string} domain - The domain name of the server that hosts the
  71. * conference.
  72. * @param {string} [options] - Another optional parameters.
  73. * @param {Object} [options.configOverwrite] - Object containing configuration
  74. * options defined in config.js to be overridden.
  75. * @param {Object} [options.interfaceConfigOverwrite] - Object containing
  76. * configuration options defined in interface_config.js to be overridden.
  77. * @param {string} [options.jwt] - The JWT token if needed by jitsi-meet for
  78. * authentication.
  79. * @param {boolean} [options.noSSL] - If the value is true https won't be used.
  80. * @param {string} [options.roomName] - The name of the room to join.
  81. * @returns {string} The URL.
  82. */
  83. function generateURL(domain, options = {}) {
  84. return urlObjectToString({
  85. ...options,
  86. url:
  87. `${options.noSSL ? 'http' : 'https'}://${
  88. domain}/#jitsi_meet_external_api_id=${id}`
  89. });
  90. }
  91. /**
  92. * Parses the arguments passed to the constructor. If the old format is used
  93. * the function translates the arguments to the new format.
  94. *
  95. * @param {Array} args - The arguments to be parsed.
  96. * @returns {Object} JS object with properties.
  97. */
  98. function parseArguments(args) {
  99. if (!args.length) {
  100. return {};
  101. }
  102. const firstArg = args[0];
  103. switch (typeof firstArg) {
  104. case 'string': // old arguments format
  105. case undefined: // eslint-disable-line no-case-declarations
  106. // not sure which format but we are trying to parse the old
  107. // format because if the new format is used everything will be undefined
  108. // anyway.
  109. const [
  110. roomName,
  111. width,
  112. height,
  113. parentNode,
  114. configOverwrite,
  115. interfaceConfigOverwrite,
  116. noSSL,
  117. jwt,
  118. onload
  119. ] = args;
  120. return {
  121. roomName,
  122. width,
  123. height,
  124. parentNode,
  125. configOverwrite,
  126. interfaceConfigOverwrite,
  127. noSSL,
  128. jwt,
  129. onload
  130. };
  131. case 'object': // new arguments format
  132. return args[0];
  133. default:
  134. throw new Error('Can\'t parse the arguments!');
  135. }
  136. }
  137. /**
  138. * Compute valid values for height and width. If a number is specified it's
  139. * treated as pixel units. If the value is expressed in px, em, pt or
  140. * percentage, it's used as is.
  141. *
  142. * @param {any} value - The value to be parsed.
  143. * @returns {string|undefined} The parsed value that can be used for setting
  144. * sizes through the style property. If invalid value is passed the method
  145. * retuns undefined.
  146. */
  147. function parseSizeParam(value) {
  148. let parsedValue;
  149. // This regex parses values of the form 100px, 100em, 100pt or 100%.
  150. // Values like 100 or 100px are handled outside of the regex, and
  151. // invalid values will be ignored and the minimum will be used.
  152. const re = /([0-9]*\.?[0-9]+)(em|pt|px|%)$/;
  153. if (typeof value === 'string' && String(value).match(re) !== null) {
  154. parsedValue = value;
  155. } else if (typeof value === 'number') {
  156. parsedValue = `${value}px`;
  157. }
  158. return parsedValue;
  159. }
  160. /**
  161. * The IFrame API interface class.
  162. */
  163. export default class JitsiMeetExternalAPI extends EventEmitter {
  164. /**
  165. * Constructs new API instance. Creates iframe and loads Jitsi Meet in it.
  166. *
  167. * @param {string} domain - The domain name of the server that hosts the
  168. * conference.
  169. * @param {Object} [options] - Optional arguments.
  170. * @param {string} [options.roomName] - The name of the room to join.
  171. * @param {number|string} [options.width] - Width of the iframe. Check
  172. * parseSizeParam for format details.
  173. * @param {number|string} [options.height] - Height of the iframe. Check
  174. * parseSizeParam for format details.
  175. * @param {DOMElement} [options.parentNode] - The node that will contain the
  176. * iframe.
  177. * @param {Object} [options.configOverwrite] - Object containing
  178. * configuration options defined in config.js to be overridden.
  179. * @param {Object} [options.interfaceConfigOverwrite] - Object containing
  180. * configuration options defined in interface_config.js to be overridden.
  181. * @param {boolean} [options.noSSL] - If the value is true https won't be
  182. * used.
  183. * @param {string} [options.jwt] - The JWT token if needed by jitsi-meet for
  184. * authentication.
  185. * @param {string} [options.onload] - The onload function that will listen
  186. * for iframe onload event.
  187. * @param {Array<Object>} [options.invitees] - Array of objects containing
  188. * information about new participants that will be invited in the call.
  189. */
  190. constructor(domain, ...args) {
  191. super();
  192. const {
  193. roomName = '',
  194. width = '100%',
  195. height = '100%',
  196. parentNode = document.body,
  197. configOverwrite = {},
  198. interfaceConfigOverwrite = {},
  199. noSSL = false,
  200. jwt = undefined,
  201. onload = undefined,
  202. invitees
  203. } = parseArguments(args);
  204. this._parentNode = parentNode;
  205. this._url = generateURL(domain, {
  206. configOverwrite,
  207. interfaceConfigOverwrite,
  208. jwt,
  209. noSSL,
  210. roomName
  211. });
  212. this._createIFrame(height, width, onload);
  213. this._transport = new Transport({
  214. backend: new PostMessageTransportBackend({
  215. postisOptions: {
  216. scope: `jitsi_meet_external_api_${id}`,
  217. window: this._frame.contentWindow
  218. }
  219. })
  220. });
  221. this.invite(invitees);
  222. this._isLargeVideoVisible = true;
  223. this._numberOfParticipants = 0;
  224. this._participants = {};
  225. this._myUserID = undefined;
  226. this._onStageParticipant = undefined;
  227. this._setupListeners();
  228. id++;
  229. }
  230. /**
  231. * Creates the iframe element.
  232. *
  233. * @param {number|string} height - The height of the iframe. Check
  234. * parseSizeParam for format details.
  235. * @param {number|string} width - The with of the iframe. Check
  236. * parseSizeParam for format details.
  237. * @param {Function} onload - The function that will listen
  238. * for onload event.
  239. * @returns {void}
  240. *
  241. * @private
  242. */
  243. _createIFrame(height, width, onload) {
  244. const frameName = `jitsiConferenceFrame${id}`;
  245. this._frame = document.createElement('iframe');
  246. this._frame.allow = 'camera; microphone';
  247. this._frame.src = this._url;
  248. this._frame.name = frameName;
  249. this._frame.id = frameName;
  250. this._setSize(height, width);
  251. this._frame.setAttribute('allowFullScreen', 'true');
  252. this._frame.style.border = 0;
  253. if (onload) {
  254. // waits for iframe resources to load
  255. // and fires event when it is done
  256. this._frame.onload = onload;
  257. }
  258. this._frame = this._parentNode.appendChild(this._frame);
  259. }
  260. /**
  261. * Returns arrays with the all resources for the always on top feature.
  262. *
  263. * @returns {Array<string>}
  264. */
  265. _getAlwaysOnTopResources() {
  266. const iframeWindow = this._frame.contentWindow;
  267. const iframeDocument = iframeWindow.document;
  268. let baseURL = '';
  269. const base = iframeDocument.querySelector('base');
  270. if (base && base.href) {
  271. baseURL = base.href;
  272. } else {
  273. const { protocol, host } = iframeWindow.location;
  274. baseURL = `${protocol}//${host}`;
  275. }
  276. return ALWAYS_ON_TOP_FILENAMES.map(
  277. filename => (new URL(filename, baseURL)).href
  278. );
  279. }
  280. /**
  281. * Returns the id of the on stage participant.
  282. *
  283. * @returns {string} - The id of the on stage participant.
  284. */
  285. _getOnStageParticipant() {
  286. return this._onStageParticipant;
  287. }
  288. /**
  289. * Getter for the large video element in Jitsi Meet.
  290. *
  291. * @returns {HTMLElement|undefined} - The large video.
  292. */
  293. _getLargeVideo() {
  294. const iframe = this.getIFrame();
  295. if (!this._isLargeVideoVisible
  296. || !iframe
  297. || !iframe.contentWindow
  298. || !iframe.contentWindow.document) {
  299. return;
  300. }
  301. return iframe.contentWindow.document.getElementById('largeVideo');
  302. }
  303. /**
  304. * Sets the size of the iframe element.
  305. *
  306. * @param {number|string} height - The height of the iframe.
  307. * @param {number|string} width - The with of the iframe.
  308. * @returns {void}
  309. *
  310. * @private
  311. */
  312. _setSize(height, width) {
  313. const parsedHeight = parseSizeParam(height);
  314. const parsedWidth = parseSizeParam(width);
  315. if (parsedHeight !== undefined) {
  316. this._frame.style.height = parsedHeight;
  317. }
  318. if (parsedWidth !== undefined) {
  319. this._frame.style.width = parsedWidth;
  320. }
  321. }
  322. /**
  323. * Setups listeners that are used internally for JitsiMeetExternalAPI.
  324. *
  325. * @returns {void}
  326. *
  327. * @private
  328. */
  329. _setupListeners() {
  330. this._transport.on('event', ({ name, ...data }) => {
  331. const userID = data.id;
  332. switch (name) {
  333. case 'video-conference-joined':
  334. this._myUserID = userID;
  335. this._participants[userID] = {
  336. avatarURL: data.avatarURL
  337. };
  338. // eslint-disable-next-line no-fallthrough
  339. case 'participant-joined': {
  340. this._participants[userID] = this._participants[userID] || {};
  341. this._participants[userID].displayName = data.displayName;
  342. this._participants[userID].formattedDisplayName
  343. = data.formattedDisplayName;
  344. changeParticipantNumber(this, 1);
  345. break;
  346. }
  347. case 'participant-left':
  348. changeParticipantNumber(this, -1);
  349. delete this._participants[userID];
  350. break;
  351. case 'display-name-change': {
  352. const user = this._participants[userID];
  353. if (user) {
  354. user.displayName = data.displayname;
  355. user.formattedDisplayName = data.formattedDisplayName;
  356. }
  357. break;
  358. }
  359. case 'email-change': {
  360. const user = this._participants[userID];
  361. if (user) {
  362. user.email = data.email;
  363. }
  364. break;
  365. }
  366. case 'avatar-changed': {
  367. const user = this._participants[userID];
  368. if (user) {
  369. user.avatarURL = data.avatarURL;
  370. }
  371. break;
  372. }
  373. case 'on-stage-participant-changed':
  374. this._onStageParticipant = userID;
  375. this.emit('largeVideoChanged');
  376. break;
  377. case 'large-video-visibility-changed':
  378. this._isLargeVideoVisible = data.isVisible;
  379. this.emit('largeVideoChanged');
  380. break;
  381. case 'video-conference-left':
  382. changeParticipantNumber(this, -1);
  383. delete this._participants[this._myUserID];
  384. break;
  385. }
  386. const eventName = events[name];
  387. if (eventName) {
  388. this.emit(eventName, data);
  389. return true;
  390. }
  391. return false;
  392. });
  393. }
  394. /**
  395. * Adds event listener to Meet Jitsi.
  396. *
  397. * @param {string} event - The name of the event.
  398. * @param {Function} listener - The listener.
  399. * @returns {void}
  400. *
  401. * @deprecated
  402. * NOTE: This method is not removed for backward comatability purposes.
  403. */
  404. addEventListener(event, listener) {
  405. this.on(event, listener);
  406. }
  407. /**
  408. * Adds event listeners to Meet Jitsi.
  409. *
  410. * @param {Object} listeners - The object key should be the name of
  411. * the event and value - the listener.
  412. * Currently we support the following
  413. * events:
  414. * incomingMessage - receives event notifications about incoming
  415. * messages. The listener will receive object with the following structure:
  416. * {{
  417. * 'from': from,//JID of the user that sent the message
  418. * 'nick': nick,//the nickname of the user that sent the message
  419. * 'message': txt//the text of the message
  420. * }}
  421. * outgoingMessage - receives event notifications about outgoing
  422. * messages. The listener will receive object with the following structure:
  423. * {{
  424. * 'message': txt//the text of the message
  425. * }}
  426. * displayNameChanged - receives event notifications about display name
  427. * change. The listener will receive object with the following structure:
  428. * {{
  429. * jid: jid,//the JID of the participant that changed his display name
  430. * displayname: displayName //the new display name
  431. * }}
  432. * participantJoined - receives event notifications about new participant.
  433. * The listener will receive object with the following structure:
  434. * {{
  435. * jid: jid //the jid of the participant
  436. * }}
  437. * participantLeft - receives event notifications about the participant that
  438. * left the room.
  439. * The listener will receive object with the following structure:
  440. * {{
  441. * jid: jid //the jid of the participant
  442. * }}
  443. * video-conference-joined - receives event notifications about the local
  444. * user has successfully joined the video conference.
  445. * The listener will receive object with the following structure:
  446. * {{
  447. * roomName: room //the room name of the conference
  448. * }}
  449. * video-conference-left - receives event notifications about the local user
  450. * has left the video conference.
  451. * The listener will receive object with the following structure:
  452. * {{
  453. * roomName: room //the room name of the conference
  454. * }}
  455. * screenSharingStatusChanged - receives event notifications about
  456. * turning on/off the local user screen sharing.
  457. * The listener will receive object with the following structure:
  458. * {{
  459. * on: on //whether screen sharing is on
  460. * }}
  461. * readyToClose - all hangup operations are completed and Jitsi Meet is
  462. * ready to be disposed.
  463. * @returns {void}
  464. *
  465. * @deprecated
  466. * NOTE: This method is not removed for backward comatability purposes.
  467. */
  468. addEventListeners(listeners) {
  469. for (const event in listeners) { // eslint-disable-line guard-for-in
  470. this.addEventListener(event, listeners[event]);
  471. }
  472. }
  473. /**
  474. * Removes the listeners and removes the Jitsi Meet frame.
  475. *
  476. * @returns {void}
  477. */
  478. dispose() {
  479. this._transport.dispose();
  480. this.removeAllListeners();
  481. if (this._frame) {
  482. this._frame.parentNode.removeChild(this._frame);
  483. }
  484. }
  485. /**
  486. * Executes command. The available commands are:
  487. * displayName - sets the display name of the local participant to the value
  488. * passed in the arguments array.
  489. * toggleAudio - mutes / unmutes audio with no arguments.
  490. * toggleVideo - mutes / unmutes video with no arguments.
  491. * toggleFilmStrip - hides / shows the filmstrip with no arguments.
  492. * If the command doesn't require any arguments the parameter should be set
  493. * to empty array or it may be omitted.
  494. *
  495. * @param {string} name - The name of the command.
  496. * @returns {void}
  497. */
  498. executeCommand(name, ...args) {
  499. if (!(name in commands)) {
  500. logger.error('Not supported command name.');
  501. return;
  502. }
  503. this._transport.sendEvent({
  504. data: args,
  505. name: commands[name]
  506. });
  507. }
  508. /**
  509. * Executes commands. The available commands are:
  510. * displayName - sets the display name of the local participant to the value
  511. * passed in the arguments array.
  512. * toggleAudio - mutes / unmutes audio. no arguments
  513. * toggleVideo - mutes / unmutes video. no arguments
  514. * toggleFilmStrip - hides / shows the filmstrip. no arguments
  515. * toggleChat - hides / shows chat. no arguments.
  516. * toggleShareScreen - starts / stops screen sharing. no arguments.
  517. *
  518. * @param {Object} commandList - The object with commands to be executed.
  519. * The keys of the object are the commands that will be executed and the
  520. * values are the arguments for the command.
  521. * @returns {void}
  522. */
  523. executeCommands(commandList) {
  524. for (const key in commandList) { // eslint-disable-line guard-for-in
  525. this.executeCommand(key, commandList[key]);
  526. }
  527. }
  528. /**
  529. * Check if the audio is available.
  530. *
  531. * @returns {Promise} - Resolves with true if the audio available, with
  532. * false if not and rejects on failure.
  533. */
  534. isAudioAvailable() {
  535. return this._transport.sendRequest({
  536. name: 'is-audio-available'
  537. });
  538. }
  539. /**
  540. * Invite people to the call.
  541. *
  542. * @param {Array<Object>} invitees - The invitees.
  543. * @returns {Promise} - Resolves on success and rejects on failure.
  544. */
  545. invite(invitees) {
  546. return this._transport.sendRequest({
  547. name: 'invite',
  548. invitees
  549. });
  550. }
  551. /**
  552. * Returns the audio mute status.
  553. *
  554. * @returns {Promise} - Resolves with the audio mute status and rejects on
  555. * failure.
  556. */
  557. isAudioMuted() {
  558. return this._transport.sendRequest({
  559. name: 'is-audio-muted'
  560. });
  561. }
  562. /**
  563. * Returns the avatar URL of a participant.
  564. *
  565. * @param {string} participantId - The id of the participant.
  566. * @returns {string} The avatar URL.
  567. */
  568. getAvatarURL(participantId) {
  569. const { avatarURL } = this._participants[participantId] || {};
  570. return avatarURL;
  571. }
  572. /**
  573. * Returns the display name of a participant.
  574. *
  575. * @param {string} participantId - The id of the participant.
  576. * @returns {string} The display name.
  577. */
  578. getDisplayName(participantId) {
  579. const { displayName } = this._participants[participantId] || {};
  580. return displayName;
  581. }
  582. /**
  583. * Returns the email of a participant.
  584. *
  585. * @param {string} participantId - The id of the participant.
  586. * @returns {string} The email.
  587. */
  588. getEmail(participantId) {
  589. const { email } = this._participants[participantId] || {};
  590. return email;
  591. }
  592. /**
  593. * Returns the formatted display name of a participant.
  594. *
  595. * @param {string} participantId - The id of the participant.
  596. * @returns {string} The formatted display name.
  597. */
  598. _getFormattedDisplayName(participantId) {
  599. const { formattedDisplayName }
  600. = this._participants[participantId] || {};
  601. return formattedDisplayName;
  602. }
  603. /**
  604. * Returns the iframe that loads Jitsi Meet.
  605. *
  606. * @returns {HTMLElement} The iframe.
  607. */
  608. getIFrame() {
  609. return this._frame;
  610. }
  611. /**
  612. * Returns the number of participants in the conference. The local
  613. * participant is included.
  614. *
  615. * @returns {int} The number of participants in the conference.
  616. */
  617. getNumberOfParticipants() {
  618. return this._numberOfParticipants;
  619. }
  620. /**
  621. * Check if the video is available.
  622. *
  623. * @returns {Promise} - Resolves with true if the video available, with
  624. * false if not and rejects on failure.
  625. */
  626. isVideoAvailable() {
  627. return this._transport.sendRequest({
  628. name: 'is-video-available'
  629. });
  630. }
  631. /**
  632. * Returns the audio mute status.
  633. *
  634. * @returns {Promise} - Resolves with the audio mute status and rejects on
  635. * failure.
  636. */
  637. isVideoMuted() {
  638. return this._transport.sendRequest({
  639. name: 'is-video-muted'
  640. });
  641. }
  642. /**
  643. * Removes event listener.
  644. *
  645. * @param {string} event - The name of the event.
  646. * @returns {void}
  647. *
  648. * @deprecated
  649. * NOTE: This method is not removed for backward comatability purposes.
  650. */
  651. removeEventListener(event) {
  652. this.removeAllListeners(event);
  653. }
  654. /**
  655. * Removes event listeners.
  656. *
  657. * @param {Array<string>} eventList - Array with the names of the events.
  658. * @returns {void}
  659. *
  660. * @deprecated
  661. * NOTE: This method is not removed for backward comatability purposes.
  662. */
  663. removeEventListeners(eventList) {
  664. eventList.forEach(event => this.removeEventListener(event));
  665. }
  666. /**
  667. * Returns the configuration for electron for the windows that are open
  668. * from Jitsi Meet.
  669. *
  670. * @returns {Promise<Object>}
  671. *
  672. * NOTE: For internal use only.
  673. */
  674. _getElectronPopupsConfig() {
  675. return Promise.resolve(electronPopupsConfig);
  676. }
  677. }