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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695
  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. */
  186. constructor(domain, ...args) {
  187. super();
  188. const {
  189. roomName = '',
  190. width = '100%',
  191. height = '100%',
  192. parentNode = document.body,
  193. configOverwrite = {},
  194. interfaceConfigOverwrite = {},
  195. noSSL = false,
  196. jwt = undefined,
  197. onload = undefined
  198. } = parseArguments(args);
  199. this._parentNode = parentNode;
  200. this._url = generateURL(domain, {
  201. configOverwrite,
  202. interfaceConfigOverwrite,
  203. jwt,
  204. noSSL,
  205. roomName
  206. });
  207. this._createIFrame(height, width, onload);
  208. this._transport = new Transport({
  209. backend: new PostMessageTransportBackend({
  210. postisOptions: {
  211. scope: `jitsi_meet_external_api_${id}`,
  212. window: this._frame.contentWindow
  213. }
  214. })
  215. });
  216. this._isLargeVideoVisible = true;
  217. this._numberOfParticipants = 0;
  218. this._participants = {};
  219. this._myUserID = undefined;
  220. this._onStageParticipant = undefined;
  221. this._setupListeners();
  222. id++;
  223. }
  224. /**
  225. * Creates the iframe element.
  226. *
  227. * @param {number|string} height - The height of the iframe. Check
  228. * parseSizeParam for format details.
  229. * @param {number|string} width - The with of the iframe. Check
  230. * parseSizeParam for format details.
  231. * @param {Function} onload - The function that will listen
  232. * for onload event.
  233. * @returns {void}
  234. *
  235. * @private
  236. */
  237. _createIFrame(height, width, onload) {
  238. const frameName = `jitsiConferenceFrame${id}`;
  239. this._frame = document.createElement('iframe');
  240. this._frame.allow = 'camera; microphone';
  241. this._frame.src = this._url;
  242. this._frame.name = frameName;
  243. this._frame.id = frameName;
  244. this._setSize(height, width);
  245. this._frame.setAttribute('allowFullScreen', 'true');
  246. this._frame.style.border = 0;
  247. if (onload) {
  248. // waits for iframe resources to load
  249. // and fires event when it is done
  250. this._frame.onload = onload;
  251. }
  252. this._frame = this._parentNode.appendChild(this._frame);
  253. }
  254. /**
  255. * Returns arrays with the all resources for the always on top feature.
  256. *
  257. * @returns {Array<string>}
  258. */
  259. _getAlwaysOnTopResources() {
  260. const iframeWindow = this._frame.contentWindow;
  261. const iframeDocument = iframeWindow.document;
  262. let baseURL = '';
  263. const base = iframeDocument.querySelector('base');
  264. if (base && base.href) {
  265. baseURL = base.href;
  266. } else {
  267. const { protocol, host } = iframeWindow.location;
  268. baseURL = `${protocol}//${host}`;
  269. }
  270. return ALWAYS_ON_TOP_FILENAMES.map(
  271. filename => (new URL(filename, baseURL)).href
  272. );
  273. }
  274. /**
  275. * Returns the id of the on stage participant.
  276. *
  277. * @returns {string} - The id of the on stage participant.
  278. */
  279. _getOnStageParticipant() {
  280. return this._onStageParticipant;
  281. }
  282. /**
  283. * Getter for the large video element in Jitsi Meet.
  284. *
  285. * @returns {HTMLElement|undefined} - The large video.
  286. */
  287. _getLargeVideo() {
  288. const iframe = this.getIFrame();
  289. if (!this._isLargeVideoVisible
  290. || !iframe
  291. || !iframe.contentWindow
  292. || !iframe.contentWindow.document) {
  293. return;
  294. }
  295. return iframe.contentWindow.document.getElementById('largeVideo');
  296. }
  297. /**
  298. * Sets the size of the iframe element.
  299. *
  300. * @param {number|string} height - The height of the iframe.
  301. * @param {number|string} width - The with of the iframe.
  302. * @returns {void}
  303. *
  304. * @private
  305. */
  306. _setSize(height, width) {
  307. const parsedHeight = parseSizeParam(height);
  308. const parsedWidth = parseSizeParam(width);
  309. if (parsedHeight !== undefined) {
  310. this._frame.style.height = parsedHeight;
  311. }
  312. if (parsedWidth !== undefined) {
  313. this._frame.style.width = parsedWidth;
  314. }
  315. }
  316. /**
  317. * Setups listeners that are used internally for JitsiMeetExternalAPI.
  318. *
  319. * @returns {void}
  320. *
  321. * @private
  322. */
  323. _setupListeners() {
  324. this._transport.on('event', ({ name, ...data }) => {
  325. const userID = data.id;
  326. switch (name) {
  327. case 'video-conference-joined':
  328. this._myUserID = userID;
  329. this._participants[userID] = {
  330. avatarURL: data.avatarURL
  331. };
  332. // eslint-disable-next-line no-fallthrough
  333. case 'participant-joined': {
  334. this._participants[userID] = this._participants[userID] || {};
  335. this._participants[userID].displayName = data.displayName;
  336. this._participants[userID].formattedDisplayName
  337. = data.formattedDisplayName;
  338. changeParticipantNumber(this, 1);
  339. break;
  340. }
  341. case 'participant-left':
  342. changeParticipantNumber(this, -1);
  343. delete this._participants[userID];
  344. break;
  345. case 'display-name-change': {
  346. const user = this._participants[userID];
  347. if (user) {
  348. user.displayName = data.displayname;
  349. user.formattedDisplayName = data.formattedDisplayName;
  350. }
  351. break;
  352. }
  353. case 'avatar-changed': {
  354. const user = this._participants[userID];
  355. if (user) {
  356. user.avatarURL = data.avatarURL;
  357. }
  358. break;
  359. }
  360. case 'on-stage-participant-changed':
  361. this._onStageParticipant = userID;
  362. this.emit('largeVideoChanged');
  363. break;
  364. case 'large-video-visibility-changed':
  365. this._isLargeVideoVisible = data.isVisible;
  366. this.emit('largeVideoChanged');
  367. break;
  368. case 'video-conference-left':
  369. changeParticipantNumber(this, -1);
  370. delete this._participants[this._myUserID];
  371. break;
  372. }
  373. const eventName = events[name];
  374. if (eventName) {
  375. this.emit(eventName, data);
  376. return true;
  377. }
  378. return false;
  379. });
  380. }
  381. /**
  382. * Adds event listener to Meet Jitsi.
  383. *
  384. * @param {string} event - The name of the event.
  385. * @param {Function} listener - The listener.
  386. * @returns {void}
  387. *
  388. * @deprecated
  389. * NOTE: This method is not removed for backward comatability purposes.
  390. */
  391. addEventListener(event, listener) {
  392. this.on(event, listener);
  393. }
  394. /**
  395. * Adds event listeners to Meet Jitsi.
  396. *
  397. * @param {Object} listeners - The object key should be the name of
  398. * the event and value - the listener.
  399. * Currently we support the following
  400. * events:
  401. * incomingMessage - receives event notifications about incoming
  402. * messages. The listener will receive object with the following structure:
  403. * {{
  404. * 'from': from,//JID of the user that sent the message
  405. * 'nick': nick,//the nickname of the user that sent the message
  406. * 'message': txt//the text of the message
  407. * }}
  408. * outgoingMessage - receives event notifications about outgoing
  409. * messages. The listener will receive object with the following structure:
  410. * {{
  411. * 'message': txt//the text of the message
  412. * }}
  413. * displayNameChanged - receives event notifications about display name
  414. * change. The listener will receive object with the following structure:
  415. * {{
  416. * jid: jid,//the JID of the participant that changed his display name
  417. * displayname: displayName //the new display name
  418. * }}
  419. * participantJoined - receives event notifications about new participant.
  420. * The listener will receive object with the following structure:
  421. * {{
  422. * jid: jid //the jid of the participant
  423. * }}
  424. * participantLeft - receives event notifications about the participant that
  425. * left the room.
  426. * The listener will receive object with the following structure:
  427. * {{
  428. * jid: jid //the jid of the participant
  429. * }}
  430. * video-conference-joined - receives event notifications about the local
  431. * user has successfully joined the video conference.
  432. * The listener will receive object with the following structure:
  433. * {{
  434. * roomName: room //the room name of the conference
  435. * }}
  436. * video-conference-left - receives event notifications about the local user
  437. * has left the video conference.
  438. * The listener will receive object with the following structure:
  439. * {{
  440. * roomName: room //the room name of the conference
  441. * }}
  442. * screenSharingStatusChanged - receives event notifications about
  443. * turning on/off the local user screen sharing.
  444. * The listener will receive object with the following structure:
  445. * {{
  446. * on: on //whether screen sharing is on
  447. * }}
  448. * readyToClose - all hangup operations are completed and Jitsi Meet is
  449. * ready to be disposed.
  450. * @returns {void}
  451. *
  452. * @deprecated
  453. * NOTE: This method is not removed for backward comatability purposes.
  454. */
  455. addEventListeners(listeners) {
  456. for (const event in listeners) { // eslint-disable-line guard-for-in
  457. this.addEventListener(event, listeners[event]);
  458. }
  459. }
  460. /**
  461. * Removes the listeners and removes the Jitsi Meet frame.
  462. *
  463. * @returns {void}
  464. */
  465. dispose() {
  466. this._transport.dispose();
  467. this.removeAllListeners();
  468. if (this._frame) {
  469. this._frame.parentNode.removeChild(this._frame);
  470. }
  471. }
  472. /**
  473. * Executes command. The available commands are:
  474. * displayName - sets the display name of the local participant to the value
  475. * passed in the arguments array.
  476. * toggleAudio - mutes / unmutes audio with no arguments.
  477. * toggleVideo - mutes / unmutes video with no arguments.
  478. * toggleFilmStrip - hides / shows the filmstrip with no arguments.
  479. * If the command doesn't require any arguments the parameter should be set
  480. * to empty array or it may be omitted.
  481. *
  482. * @param {string} name - The name of the command.
  483. * @returns {void}
  484. */
  485. executeCommand(name, ...args) {
  486. if (!(name in commands)) {
  487. logger.error('Not supported command name.');
  488. return;
  489. }
  490. this._transport.sendEvent({
  491. data: args,
  492. name: commands[name]
  493. });
  494. }
  495. /**
  496. * Executes commands. The available commands are:
  497. * displayName - sets the display name of the local participant to the value
  498. * passed in the arguments array.
  499. * toggleAudio - mutes / unmutes audio. no arguments
  500. * toggleVideo - mutes / unmutes video. no arguments
  501. * toggleFilmStrip - hides / shows the filmstrip. no arguments
  502. * toggleChat - hides / shows chat. no arguments.
  503. * toggleShareScreen - starts / stops screen sharing. no arguments.
  504. *
  505. * @param {Object} commandList - The object with commands to be executed.
  506. * The keys of the object are the commands that will be executed and the
  507. * values are the arguments for the command.
  508. * @returns {void}
  509. */
  510. executeCommands(commandList) {
  511. for (const key in commandList) { // eslint-disable-line guard-for-in
  512. this.executeCommand(key, commandList[key]);
  513. }
  514. }
  515. /**
  516. * Check if the audio is available.
  517. *
  518. * @returns {Promise} - Resolves with true if the audio available, with
  519. * false if not and rejects on failure.
  520. */
  521. isAudioAvailable() {
  522. return this._transport.sendRequest({
  523. name: 'is-audio-available'
  524. });
  525. }
  526. /**
  527. * Returns the audio mute status.
  528. *
  529. * @returns {Promise} - Resolves with the audio mute status and rejects on
  530. * failure.
  531. */
  532. isAudioMuted() {
  533. return this._transport.sendRequest({
  534. name: 'is-audio-muted'
  535. });
  536. }
  537. /**
  538. * Returns the avatar URL of a participant.
  539. *
  540. * @param {string} participantId - The id of the participant.
  541. * @returns {string} The avatar URL.
  542. */
  543. getAvatarURL(participantId) {
  544. const { avatarURL } = this._participants[participantId] || {};
  545. return avatarURL;
  546. }
  547. /**
  548. * Returns the display name of a participant.
  549. *
  550. * @param {string} participantId - The id of the participant.
  551. * @returns {string} The display name.
  552. */
  553. getDisplayName(participantId) {
  554. const { displayName } = this._participants[participantId] || {};
  555. return displayName;
  556. }
  557. /**
  558. * Returns the formatted display name of a participant.
  559. *
  560. * @param {string} participantId - The id of the participant.
  561. * @returns {string} The formatted display name.
  562. */
  563. _getFormattedDisplayName(participantId) {
  564. const { formattedDisplayName }
  565. = this._participants[participantId] || {};
  566. return formattedDisplayName;
  567. }
  568. /**
  569. * Returns the iframe that loads Jitsi Meet.
  570. *
  571. * @returns {HTMLElement} The iframe.
  572. */
  573. getIFrame() {
  574. return this._frame;
  575. }
  576. /**
  577. * Returns the number of participants in the conference. The local
  578. * participant is included.
  579. *
  580. * @returns {int} The number of participants in the conference.
  581. */
  582. getNumberOfParticipants() {
  583. return this._numberOfParticipants;
  584. }
  585. /**
  586. * Check if the video is available.
  587. *
  588. * @returns {Promise} - Resolves with true if the video available, with
  589. * false if not and rejects on failure.
  590. */
  591. isVideoAvailable() {
  592. return this._transport.sendRequest({
  593. name: 'is-video-available'
  594. });
  595. }
  596. /**
  597. * Returns the audio mute status.
  598. *
  599. * @returns {Promise} - Resolves with the audio mute status and rejects on
  600. * failure.
  601. */
  602. isVideoMuted() {
  603. return this._transport.sendRequest({
  604. name: 'is-video-muted'
  605. });
  606. }
  607. /**
  608. * Removes event listener.
  609. *
  610. * @param {string} event - The name of the event.
  611. * @returns {void}
  612. *
  613. * @deprecated
  614. * NOTE: This method is not removed for backward comatability purposes.
  615. */
  616. removeEventListener(event) {
  617. this.removeAllListeners(event);
  618. }
  619. /**
  620. * Removes event listeners.
  621. *
  622. * @param {Array<string>} eventList - Array with the names of the events.
  623. * @returns {void}
  624. *
  625. * @deprecated
  626. * NOTE: This method is not removed for backward comatability purposes.
  627. */
  628. removeEventListeners(eventList) {
  629. eventList.forEach(event => this.removeEventListener(event));
  630. }
  631. }