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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558
  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. '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'}://${
  83. domain}/#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._createIFrame(height, width);
  200. this._transport = new Transport({
  201. backend: new PostMessageTransportBackend({
  202. postisOptions: {
  203. scope: `jitsi_meet_external_api_${id}`,
  204. window: this._frame.contentWindow
  205. }
  206. })
  207. });
  208. this._numberOfParticipants = 1;
  209. this._setupListeners();
  210. id++;
  211. }
  212. /**
  213. * Creates the iframe element.
  214. *
  215. * @param {number|string} height - The height of the iframe. Check
  216. * parseSizeParam for format details.
  217. * @param {number|string} width - The with of the iframe. Check
  218. * parseSizeParam for format details.
  219. * @returns {void}
  220. *
  221. * @private
  222. */
  223. _createIFrame(height, width) {
  224. const frameName = `jitsiConferenceFrame${id}`;
  225. this._frame = document.createElement('iframe');
  226. this._frame.allow = 'camera; microphone';
  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. const iframeWindow = this._frame.contentWindow;
  242. const iframeDocument = iframeWindow.document;
  243. let baseURL = '';
  244. const base = iframeDocument.querySelector('base');
  245. if (base && base.href) {
  246. baseURL = base.href;
  247. } else {
  248. const { protocol, host } = iframeWindow.location;
  249. baseURL = `${protocol}//${host}`;
  250. }
  251. return ALWAYS_ON_TOP_FILENAMES.map(
  252. filename => (new URL(filename, baseURL)).href
  253. );
  254. }
  255. /**
  256. * Sets the size of the iframe element.
  257. *
  258. * @param {number|string} height - The height of the iframe.
  259. * @param {number|string} width - The with of the iframe.
  260. * @returns {void}
  261. *
  262. * @private
  263. */
  264. _setSize(height, width) {
  265. const parsedHeight = parseSizeParam(height);
  266. const parsedWidth = parseSizeParam(width);
  267. if (parsedHeight !== undefined) {
  268. this._frame.style.height = parsedHeight;
  269. }
  270. if (parsedWidth !== undefined) {
  271. this._frame.style.width = parsedWidth;
  272. }
  273. }
  274. /**
  275. * Setups listeners that are used internally for JitsiMeetExternalAPI.
  276. *
  277. * @returns {void}
  278. *
  279. * @private
  280. */
  281. _setupListeners() {
  282. this._transport.on('event', ({ name, ...data }) => {
  283. if (name === 'participant-joined') {
  284. changeParticipantNumber(this, 1);
  285. } else if (name === 'participant-left') {
  286. changeParticipantNumber(this, -1);
  287. }
  288. const eventName = events[name];
  289. if (eventName) {
  290. this.emit(eventName, data);
  291. return true;
  292. }
  293. return false;
  294. });
  295. }
  296. /**
  297. * Adds event listener to Meet Jitsi.
  298. *
  299. * @param {string} event - The name of the event.
  300. * @param {Function} listener - The listener.
  301. * @returns {void}
  302. *
  303. * @deprecated
  304. * NOTE: This method is not removed for backward comatability purposes.
  305. */
  306. addEventListener(event, listener) {
  307. this.on(event, listener);
  308. }
  309. /**
  310. * Adds event listeners to Meet Jitsi.
  311. *
  312. * @param {Object} listeners - The object key should be the name of
  313. * the event and value - the listener.
  314. * Currently we support the following
  315. * events:
  316. * incomingMessage - receives event notifications about incoming
  317. * messages. The listener will receive object with the following structure:
  318. * {{
  319. * 'from': from,//JID of the user that sent the message
  320. * 'nick': nick,//the nickname of the user that sent the message
  321. * 'message': txt//the text of the message
  322. * }}
  323. * outgoingMessage - receives event notifications about outgoing
  324. * messages. The listener will receive object with the following structure:
  325. * {{
  326. * 'message': txt//the text of the message
  327. * }}
  328. * displayNameChanged - receives event notifications about display name
  329. * change. The listener will receive object with the following structure:
  330. * {{
  331. * jid: jid,//the JID of the participant that changed his display name
  332. * displayname: displayName //the new display name
  333. * }}
  334. * participantJoined - receives event notifications about new participant.
  335. * The listener will receive object with the following structure:
  336. * {{
  337. * jid: jid //the jid of the participant
  338. * }}
  339. * participantLeft - receives event notifications about the participant that
  340. * left the room.
  341. * The listener will receive object with the following structure:
  342. * {{
  343. * jid: jid //the jid of the participant
  344. * }}
  345. * video-conference-joined - receives event notifications about the local
  346. * user has successfully joined the video conference.
  347. * The listener will receive object with the following structure:
  348. * {{
  349. * roomName: room //the room name of the conference
  350. * }}
  351. * video-conference-left - receives event notifications about the local user
  352. * has left the video conference.
  353. * The listener will receive object with the following structure:
  354. * {{
  355. * roomName: room //the room name of the conference
  356. * }}
  357. * readyToClose - all hangup operations are completed and Jitsi Meet is
  358. * ready to be disposed.
  359. * @returns {void}
  360. *
  361. * @deprecated
  362. * NOTE: This method is not removed for backward comatability purposes.
  363. */
  364. addEventListeners(listeners) {
  365. for (const event in listeners) { // eslint-disable-line guard-for-in
  366. this.addEventListener(event, listeners[event]);
  367. }
  368. }
  369. /**
  370. * Removes the listeners and removes the Jitsi Meet frame.
  371. *
  372. * @returns {void}
  373. */
  374. dispose() {
  375. this._transport.dispose();
  376. this.removeAllListeners();
  377. if (this._frame) {
  378. this._frame.parentNode.removeChild(this._frame);
  379. }
  380. }
  381. /**
  382. * Executes command. The available commands are:
  383. * displayName - sets the display name of the local participant to the value
  384. * passed in the arguments array.
  385. * toggleAudio - mutes / unmutes audio with no arguments.
  386. * toggleVideo - mutes / unmutes video with no arguments.
  387. * toggleFilmStrip - hides / shows the filmstrip with no arguments.
  388. * If the command doesn't require any arguments the parameter should be set
  389. * to empty array or it may be omitted.
  390. *
  391. * @param {string} name - The name of the command.
  392. * @returns {void}
  393. */
  394. executeCommand(name, ...args) {
  395. if (!(name in commands)) {
  396. logger.error('Not supported command name.');
  397. return;
  398. }
  399. this._transport.sendEvent({
  400. data: args,
  401. name: commands[name]
  402. });
  403. }
  404. /**
  405. * Executes commands. The available commands are:
  406. * displayName - sets the display name of the local participant to the value
  407. * passed in the arguments array.
  408. * toggleAudio - mutes / unmutes audio. no arguments
  409. * toggleVideo - mutes / unmutes video. no arguments
  410. * toggleFilmStrip - hides / shows the filmstrip. no arguments
  411. * toggleChat - hides / shows chat. no arguments.
  412. * toggleContactList - hides / shows contact list. no arguments.
  413. * toggleShareScreen - starts / stops screen sharing. no arguments.
  414. *
  415. * @param {Object} commandList - The object with commands to be executed.
  416. * The keys of the object are the commands that will be executed and the
  417. * values are the arguments for the command.
  418. * @returns {void}
  419. */
  420. executeCommands(commandList) {
  421. for (const key in commandList) { // eslint-disable-line guard-for-in
  422. this.executeCommand(key, commandList[key]);
  423. }
  424. }
  425. /**
  426. * Check if the audio is available.
  427. *
  428. * @returns {Promise} - Resolves with true if the audio available, with
  429. * false if not and rejects on failure.
  430. */
  431. isAudioAvailable() {
  432. return this._transport.sendRequest({
  433. name: 'is-audio-available'
  434. });
  435. }
  436. /**
  437. * Returns the audio mute status.
  438. *
  439. * @returns {Promise} - Resolves with the audio mute status and rejects on
  440. * failure.
  441. */
  442. isAudioMuted() {
  443. return this._transport.sendRequest({
  444. name: 'is-audio-muted'
  445. });
  446. }
  447. /**
  448. * Returns the iframe that loads Jitsi Meet.
  449. *
  450. * @returns {HTMLElement} The iframe.
  451. */
  452. getIFrame() {
  453. return this._frame;
  454. }
  455. /**
  456. * Returns the number of participants in the conference. The local
  457. * participant is included.
  458. *
  459. * @returns {int} The number of participants in the conference.
  460. */
  461. getNumberOfParticipants() {
  462. return this._numberOfParticipants;
  463. }
  464. /**
  465. * Check if the video is available.
  466. *
  467. * @returns {Promise} - Resolves with true if the video available, with
  468. * false if not and rejects on failure.
  469. */
  470. isVideoAvailable() {
  471. return this._transport.sendRequest({
  472. name: 'is-video-available'
  473. });
  474. }
  475. /**
  476. * Returns the audio mute status.
  477. *
  478. * @returns {Promise} - Resolves with the audio mute status and rejects on
  479. * failure.
  480. */
  481. isVideoMuted() {
  482. return this._transport.sendRequest({
  483. name: 'is-video-muted'
  484. });
  485. }
  486. /**
  487. * Removes event listener.
  488. *
  489. * @param {string} event - The name of the event.
  490. * @returns {void}
  491. *
  492. * @deprecated
  493. * NOTE: This method is not removed for backward comatability purposes.
  494. */
  495. removeEventListener(event) {
  496. this.removeAllListeners(event);
  497. }
  498. /**
  499. * Removes event listeners.
  500. *
  501. * @param {Array<string>} eventList - Array with the names of the events.
  502. * @returns {void}
  503. *
  504. * @deprecated
  505. * NOTE: This method is not removed for backward comatability purposes.
  506. */
  507. removeEventListeners(eventList) {
  508. eventList.forEach(event => this.removeEventListener(event));
  509. }
  510. }