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

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