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

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