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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460
  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. * The IFrame API interface class.
  126. */
  127. export default class JitsiMeetExternalAPI extends EventEmitter {
  128. /**
  129. * Constructs new API instance. Creates iframe and loads Jitsi Meet in it.
  130. *
  131. * @param {string} domain - The domain name of the server that hosts the
  132. * conference.
  133. * @param {string} [roomName] - The name of the room to join.
  134. * @param {number} [width] - Width of the iframe.
  135. * @param {number} [height] - Height of the iframe.
  136. * @param {DOMElement} [parentNode] - The node that will contain the
  137. * iframe.
  138. * @param {Object} [configOverwrite] - Object containing configuration
  139. * options defined in config.js to be overridden.
  140. * @param {Object} [interfaceConfigOverwrite] - Object containing
  141. * configuration options defined in interface_config.js to be overridden.
  142. * @param {boolean} [noSSL] - If the value is true https won't be used.
  143. * @param {string} [jwt] - The JWT token if needed by jitsi-meet for
  144. * authentication.
  145. */
  146. constructor(domain, // eslint-disable-line max-params
  147. roomName = '',
  148. width = MIN_WIDTH,
  149. height = MIN_HEIGHT,
  150. parentNode = document.body,
  151. configOverwrite = {},
  152. interfaceConfigOverwrite = {},
  153. noSSL = false,
  154. jwt = undefined) {
  155. super();
  156. this.parentNode = parentNode;
  157. this.url = generateURL(domain, {
  158. configOverwrite,
  159. interfaceConfigOverwrite,
  160. jwt,
  161. noSSL,
  162. roomName
  163. });
  164. this._createIFrame(height, width);
  165. this._transport = new Transport({
  166. backend: new PostMessageTransportBackend({
  167. postisOptions: {
  168. scope: `jitsi_meet_external_api_${id}`,
  169. window: this.frame.contentWindow
  170. }
  171. })
  172. });
  173. this.numberOfParticipants = 1;
  174. this._setupListeners();
  175. id++;
  176. }
  177. /**
  178. * Creates the iframe element.
  179. *
  180. * @param {number} height - The height of the iframe.
  181. * @param {number} width - The with of the iframe.
  182. * @returns {void}
  183. *
  184. * @private
  185. */
  186. _createIFrame(height, width) {
  187. // Compute valid values for height and width. If a number is specified
  188. // it's treated as pixel units and our minimum constraints are applied.
  189. // If the value is expressed in em, pt or percentage, it's used as is.
  190. // Also protect ourselves from undefined, because
  191. // Math.max(undefined, 100) === NaN, obviously.
  192. //
  193. // This regex parses values of the form 100em, 100pt or 100%. Values
  194. // like 100 or 100px are handled outside of the regex, and invalid
  195. // values will be ignored and the minimum will be used.
  196. const re = /([0-9]*\.?[0-9]+)(em|pt|%)$/;
  197. /* eslint-disable no-param-reassign */
  198. if (String(height).match(re) === null) {
  199. height = parseInt(height, 10) || MIN_HEIGHT;
  200. height = `${Math.max(height, MIN_HEIGHT)}px`;
  201. }
  202. if (String(width).match(re) === null) {
  203. width = parseInt(width, 10) || MIN_WIDTH;
  204. width = `${Math.max(width, MIN_WIDTH)}px`;
  205. }
  206. /* eslint-enable no-param-reassign */
  207. this.iframeHolder
  208. = this.parentNode.appendChild(document.createElement('div'));
  209. this.iframeHolder.id = `jitsiConference${id}`;
  210. this.iframeHolder.style.width = width;
  211. this.iframeHolder.style.height = height;
  212. this.frameName = `jitsiConferenceFrame${id}`;
  213. this.frame = document.createElement('iframe');
  214. this.frame.src = this.url;
  215. this.frame.name = this.frameName;
  216. this.frame.id = this.frameName;
  217. this.frame.width = '100%';
  218. this.frame.height = '100%';
  219. this.frame.setAttribute('allowFullScreen', 'true');
  220. this.frame.style.border = 0;
  221. this.frame = this.iframeHolder.appendChild(this.frame);
  222. }
  223. /**
  224. * Setups listeners that are used internally for JitsiMeetExternalAPI.
  225. *
  226. * @returns {void}
  227. *
  228. * @private
  229. */
  230. _setupListeners() {
  231. this._transport.on('event', ({ name, ...data }) => {
  232. if (name === 'participant-joined') {
  233. changeParticipantNumber(this, 1);
  234. } else if (name === 'participant-left') {
  235. changeParticipantNumber(this, -1);
  236. }
  237. const eventName = events[name];
  238. if (eventName) {
  239. this.emit(eventName, data);
  240. return true;
  241. }
  242. return false;
  243. });
  244. }
  245. /**
  246. * Adds event listener to Meet Jitsi.
  247. *
  248. * @param {string} event - The name of the event.
  249. * @param {Function} listener - The listener.
  250. * @returns {void}
  251. *
  252. * @deprecated
  253. * NOTE: This method is not removed for backward comatability purposes.
  254. */
  255. addEventListener(event, listener) {
  256. this.on(event, listener);
  257. }
  258. /**
  259. * Adds event listeners to Meet Jitsi.
  260. *
  261. * @param {Object} listeners - The object key should be the name of
  262. * the event and value - the listener.
  263. * Currently we support the following
  264. * events:
  265. * incomingMessage - receives event notifications about incoming
  266. * messages. The listener will receive object with the following structure:
  267. * {{
  268. * 'from': from,//JID of the user that sent the message
  269. * 'nick': nick,//the nickname of the user that sent the message
  270. * 'message': txt//the text of the message
  271. * }}
  272. * outgoingMessage - receives event notifications about outgoing
  273. * messages. The listener will receive object with the following structure:
  274. * {{
  275. * 'message': txt//the text of the message
  276. * }}
  277. * displayNameChanged - receives event notifications about display name
  278. * change. The listener will receive object with the following structure:
  279. * {{
  280. * jid: jid,//the JID of the participant that changed his display name
  281. * displayname: displayName //the new display name
  282. * }}
  283. * participantJoined - receives event notifications about new participant.
  284. * The listener will receive object with the following structure:
  285. * {{
  286. * jid: jid //the jid of the participant
  287. * }}
  288. * participantLeft - receives event notifications about the participant that
  289. * left the room.
  290. * The listener will receive object with the following structure:
  291. * {{
  292. * jid: jid //the jid of the participant
  293. * }}
  294. * video-conference-joined - receives event notifications about the local
  295. * user has successfully joined the video conference.
  296. * The listener will receive object with the following structure:
  297. * {{
  298. * roomName: room //the room name of the conference
  299. * }}
  300. * video-conference-left - receives event notifications about the local user
  301. * has left the video conference.
  302. * The listener will receive object with the following structure:
  303. * {{
  304. * roomName: room //the room name of the conference
  305. * }}
  306. * readyToClose - all hangup operations are completed and Jitsi Meet is
  307. * ready to be disposed.
  308. * @returns {void}
  309. *
  310. * @deprecated
  311. * NOTE: This method is not removed for backward comatability purposes.
  312. */
  313. addEventListeners(listeners) {
  314. for (const event in listeners) { // eslint-disable-line guard-for-in
  315. this.addEventListener(event, listeners[event]);
  316. }
  317. }
  318. /**
  319. * Removes the listeners and removes the Jitsi Meet frame.
  320. *
  321. * @returns {void}
  322. */
  323. dispose() {
  324. this._transport.dispose();
  325. this.removeAllListeners();
  326. if (this.iframeHolder) {
  327. this.iframeHolder.parentNode.removeChild(this.iframeHolder);
  328. }
  329. }
  330. /**
  331. * Executes command. The available commands are:
  332. * displayName - sets the display name of the local participant to the value
  333. * passed in the arguments array.
  334. * toggleAudio - mutes / unmutes audio with no arguments.
  335. * toggleVideo - mutes / unmutes video with no arguments.
  336. * toggleFilmStrip - hides / shows the filmstrip with no arguments.
  337. * If the command doesn't require any arguments the parameter should be set
  338. * to empty array or it may be omitted.
  339. *
  340. * @param {string} name - The name of the command.
  341. * @returns {void}
  342. */
  343. executeCommand(name, ...args) {
  344. if (!(name in commands)) {
  345. logger.error('Not supported command name.');
  346. return;
  347. }
  348. this._transport.sendEvent({
  349. data: args,
  350. name: commands[name]
  351. });
  352. }
  353. /**
  354. * Executes commands. The available commands are:
  355. * displayName - sets the display name of the local participant to the value
  356. * passed in the arguments array.
  357. * toggleAudio - mutes / unmutes audio. no arguments
  358. * toggleVideo - mutes / unmutes video. no arguments
  359. * toggleFilmStrip - hides / shows the filmstrip. no arguments
  360. * toggleChat - hides / shows chat. no arguments.
  361. * toggleContactList - hides / shows contact list. no arguments.
  362. * toggleShareScreen - starts / stops screen sharing. no arguments.
  363. *
  364. * @param {Object} commandList - The object with commands to be executed.
  365. * The keys of the object are the commands that will be executed and the
  366. * values are the arguments for the command.
  367. * @returns {void}
  368. */
  369. executeCommands(commandList) {
  370. for (const key in commandList) { // eslint-disable-line guard-for-in
  371. this.executeCommand(key, commandList[key]);
  372. }
  373. }
  374. /**
  375. * Returns the iframe that loads Jitsi Meet.
  376. *
  377. * @returns {HTMLElement} The iframe.
  378. */
  379. getIFrame() {
  380. return this.frame;
  381. }
  382. /**
  383. * Returns the number of participants in the conference. The local
  384. * participant is included.
  385. *
  386. * @returns {int} The number of participants in the conference.
  387. */
  388. getNumberOfParticipants() {
  389. return this.numberOfParticipants;
  390. }
  391. /**
  392. * Removes event listener.
  393. *
  394. * @param {string} event - The name of the event.
  395. * @returns {void}
  396. *
  397. * @deprecated
  398. * NOTE: This method is not removed for backward comatability purposes.
  399. */
  400. removeEventListener(event) {
  401. this.removeAllListeners(event);
  402. }
  403. /**
  404. * Removes event listeners.
  405. *
  406. * @param {Array<string>} eventList - Array with the names of the events.
  407. * @returns {void}
  408. *
  409. * @deprecated
  410. * NOTE: This method is not removed for backward comatability purposes.
  411. */
  412. removeEventListeners(eventList) {
  413. eventList.forEach(event => this.removeEventListener(event));
  414. }
  415. }