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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428
  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. 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(Math.max(height, MIN_HEIGHT),
  165. Math.max(width, MIN_WIDTH));
  166. this._transport = new Transport({
  167. backend: new PostMessageTransportBackend({
  168. postisOptions: {
  169. scope: `jitsi_meet_external_api_${id}`,
  170. window: this.frame.contentWindow
  171. }
  172. })
  173. });
  174. this.numberOfParticipants = 1;
  175. this._setupListeners();
  176. id++;
  177. }
  178. /**
  179. * Creates the iframe element.
  180. *
  181. * @param {number} height - The height of the iframe.
  182. * @param {number} width - The with of the iframe.
  183. * @returns {void}
  184. *
  185. * @private
  186. */
  187. _createIFrame(height, width) {
  188. this.iframeHolder
  189. = this.parentNode.appendChild(document.createElement('div'));
  190. this.iframeHolder.id = `jitsiConference${id}`;
  191. this.iframeHolder.style.width = `${width}px`;
  192. this.iframeHolder.style.height = `${height}px`;
  193. this.frameName = `jitsiConferenceFrame${id}`;
  194. this.frame = document.createElement('iframe');
  195. this.frame.src = this.url;
  196. this.frame.name = this.frameName;
  197. this.frame.id = this.frameName;
  198. this.frame.width = '100%';
  199. this.frame.height = '100%';
  200. this.frame.setAttribute('allowFullScreen', 'true');
  201. this.frame = this.iframeHolder.appendChild(this.frame);
  202. }
  203. /**
  204. * Setups listeners that are used internally for JitsiMeetExternalAPI.
  205. *
  206. * @returns {void}
  207. *
  208. * @private
  209. */
  210. _setupListeners() {
  211. this._transport.on('event', ({ name, ...data }) => {
  212. if (name === 'participant-joined') {
  213. changeParticipantNumber(this, 1);
  214. } else if (name === 'participant-left') {
  215. changeParticipantNumber(this, -1);
  216. }
  217. const eventName = events[name];
  218. if (eventName) {
  219. this.emit(eventName, data);
  220. return true;
  221. }
  222. return false;
  223. });
  224. }
  225. /**
  226. * Adds event listener to Meet Jitsi.
  227. *
  228. * @param {string} event - The name of the event.
  229. * @param {Function} listener - The listener.
  230. * @returns {void}
  231. *
  232. * @deprecated
  233. * NOTE: This method is not removed for backward comatability purposes.
  234. */
  235. addEventListener(event, listener) {
  236. this.on(event, listener);
  237. }
  238. /**
  239. * Adds event listeners to Meet Jitsi.
  240. *
  241. * @param {Object} listeners - The object key should be the name of
  242. * the event and value - the listener.
  243. * Currently we support the following
  244. * events:
  245. * incomingMessage - receives event notifications about incoming
  246. * messages. The listener will receive object with the following structure:
  247. * {{
  248. * 'from': from,//JID of the user that sent the message
  249. * 'nick': nick,//the nickname of the user that sent the message
  250. * 'message': txt//the text of the message
  251. * }}
  252. * outgoingMessage - receives event notifications about outgoing
  253. * messages. The listener will receive object with the following structure:
  254. * {{
  255. * 'message': txt//the text of the message
  256. * }}
  257. * displayNameChanged - receives event notifications about display name
  258. * change. The listener will receive object with the following structure:
  259. * {{
  260. * jid: jid,//the JID of the participant that changed his display name
  261. * displayname: displayName //the new display name
  262. * }}
  263. * participantJoined - receives event notifications about new participant.
  264. * The listener will receive object with the following structure:
  265. * {{
  266. * jid: jid //the jid of the participant
  267. * }}
  268. * participantLeft - receives event notifications about the participant that
  269. * left the room.
  270. * The listener will receive object with the following structure:
  271. * {{
  272. * jid: jid //the jid of the participant
  273. * }}
  274. * video-conference-joined - receives event notifications about the local
  275. * user has successfully joined the video conference.
  276. * The listener will receive object with the following structure:
  277. * {{
  278. * roomName: room //the room name of the conference
  279. * }}
  280. * video-conference-left - receives event notifications about the local user
  281. * has left the video conference.
  282. * The listener will receive object with the following structure:
  283. * {{
  284. * roomName: room //the room name of the conference
  285. * }}
  286. * readyToClose - all hangup operations are completed and Jitsi Meet is
  287. * ready to be disposed.
  288. * @returns {void}
  289. *
  290. * @deprecated
  291. * NOTE: This method is not removed for backward comatability purposes.
  292. */
  293. addEventListeners(listeners) {
  294. for (const event in listeners) { // eslint-disable-line guard-for-in
  295. this.addEventListener(event, listeners[event]);
  296. }
  297. }
  298. /**
  299. * Removes the listeners and removes the Jitsi Meet frame.
  300. *
  301. * @returns {void}
  302. */
  303. dispose() {
  304. this._transport.dispose();
  305. this.removeAllListeners();
  306. if (this.iframeHolder) {
  307. this.iframeHolder.parentNode.removeChild(this.iframeHolder);
  308. }
  309. }
  310. /**
  311. * Executes command. The available commands are:
  312. * displayName - sets the display name of the local participant to the value
  313. * passed in the arguments array.
  314. * toggleAudio - mutes / unmutes audio with no arguments.
  315. * toggleVideo - mutes / unmutes video with no arguments.
  316. * toggleFilmStrip - hides / shows the filmstrip with no arguments.
  317. * If the command doesn't require any arguments the parameter should be set
  318. * to empty array or it may be omitted.
  319. *
  320. * @param {string} name - The name of the command.
  321. * @returns {void}
  322. */
  323. executeCommand(name, ...args) {
  324. if (!(name in commands)) {
  325. logger.error('Not supported command name.');
  326. return;
  327. }
  328. this._transport.sendEvent({
  329. data: args,
  330. name: commands[name]
  331. });
  332. }
  333. /**
  334. * Executes commands. The available commands are:
  335. * displayName - sets the display name of the local participant to the value
  336. * passed in the arguments array.
  337. * toggleAudio - mutes / unmutes audio. no arguments
  338. * toggleVideo - mutes / unmutes video. no arguments
  339. * toggleFilmStrip - hides / shows the filmstrip. no arguments
  340. * toggleChat - hides / shows chat. no arguments.
  341. * toggleContactList - hides / shows contact list. no arguments.
  342. * toggleShareScreen - starts / stops screen sharing. no arguments.
  343. *
  344. * @param {Object} commandList - The object with commands to be executed.
  345. * The keys of the object are the commands that will be executed and the
  346. * values are the arguments for the command.
  347. * @returns {void}
  348. */
  349. executeCommands(commandList) {
  350. for (const key in commandList) { // eslint-disable-line guard-for-in
  351. this.executeCommand(key, commandList[key]);
  352. }
  353. }
  354. /**
  355. * Returns the number of participants in the conference. The local
  356. * participant is included.
  357. *
  358. * @returns {int} The number of participants in the conference.
  359. */
  360. getNumberOfParticipants() {
  361. return this.numberOfParticipants;
  362. }
  363. /**
  364. * Removes event listener.
  365. *
  366. * @param {string} event - The name of the event.
  367. * @returns {void}
  368. *
  369. * @deprecated
  370. * NOTE: This method is not removed for backward comatability purposes.
  371. */
  372. removeEventListener(event) {
  373. this.removeAllListeners(event);
  374. }
  375. /**
  376. * Removes event listeners.
  377. *
  378. * @param {Array<string>} eventList - Array with the names of the events.
  379. * @returns {void}
  380. *
  381. * @deprecated
  382. * NOTE: This method is not removed for backward comatability purposes.
  383. */
  384. removeEventListeners(eventList) {
  385. eventList.forEach(event => this.removeEventListener(event));
  386. }
  387. }
  388. module.exports = JitsiMeetExternalAPI;