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

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