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

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