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

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