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

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