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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427
  1. import EventEmitter from 'events';
  2. import PostMessageTransportBackend
  3. from '../../transport/PostMessageTransportBackend';
  4. import Transport from '../../transport/Transport';
  5. const logger = require('jitsi-meet-logger').getLogger(__filename);
  6. /**
  7. * Maps the names of the commands expected by the API with the name of the
  8. * commands expected by jitsi-meet
  9. */
  10. const commands = {
  11. avatarUrl: 'avatar-url',
  12. displayName: 'display-name',
  13. email: 'email',
  14. hangup: 'video-hangup',
  15. toggleAudio: 'toggle-audio',
  16. toggleChat: 'toggle-chat',
  17. toggleContactList: 'toggle-contact-list',
  18. toggleFilmStrip: 'toggle-film-strip',
  19. toggleShareScreen: 'toggle-share-screen',
  20. toggleVideo: 'toggle-video'
  21. };
  22. /**
  23. * Maps the names of the events expected by the API with the name of the
  24. * events expected by jitsi-meet
  25. */
  26. const events = {
  27. 'display-name-change': 'displayNameChange',
  28. 'incoming-message': 'incomingMessage',
  29. 'outgoing-message': 'outgoingMessage',
  30. 'participant-joined': 'participantJoined',
  31. 'participant-left': 'participantLeft',
  32. 'video-ready-to-close': 'readyToClose',
  33. 'video-conference-joined': 'videoConferenceJoined',
  34. 'video-conference-left': 'videoConferenceLeft'
  35. };
  36. /**
  37. * Last id of api object
  38. * @type {number}
  39. */
  40. let id = 0;
  41. /**
  42. * The minimum height for the Jitsi Meet frame
  43. * @type {number}
  44. */
  45. const MIN_HEIGHT = 300;
  46. /**
  47. * The minimum width for the Jitsi Meet frame
  48. * @type {number}
  49. */
  50. const MIN_WIDTH = 790;
  51. /**
  52. * Adds given number to the numberOfParticipants property of given APIInstance.
  53. *
  54. * @param {JitsiMeetExternalAPI} APIInstance - The instance of the API.
  55. * @param {int} number - The number of participants to be added to
  56. * numberOfParticipants property (this parameter can be negative number if the
  57. * numberOfParticipants should be decreased).
  58. * @returns {void}
  59. */
  60. function changeParticipantNumber(APIInstance, number) {
  61. APIInstance.numberOfParticipants += number;
  62. }
  63. /**
  64. * Generates array with URL params based on the passed config object that will
  65. * be used for the Jitsi Meet URL generation.
  66. *
  67. * @param {Object} config - The config object.
  68. * @returns {Array<string>} The array with URL param strings.
  69. */
  70. function configToURLParamsArray(config = {}) {
  71. const params = [];
  72. for (const key in config) { // eslint-disable-line guard-for-in
  73. try {
  74. params.push(
  75. `${key}=${encodeURIComponent(JSON.stringify(config[key]))}`);
  76. } catch (e) {
  77. console.warn(`Error encoding ${key}: ${e}`);
  78. }
  79. }
  80. return params;
  81. }
  82. /**
  83. * Generates the URL for the iframe.
  84. *
  85. * @param {string} domain - The domain name of the server that hosts the
  86. * conference.
  87. * @param {string} [options] - Another optional parameters.
  88. * @param {Object} [options.configOverwrite] - Object containing configuration
  89. * options defined in config.js to be overridden.
  90. * @param {Object} [options.interfaceConfigOverwrite] - Object containing
  91. * configuration options defined in interface_config.js to be overridden.
  92. * @param {string} [options.jwt] - The JWT token if needed by jitsi-meet for
  93. * authentication.
  94. * @param {boolean} [options.noSsl] - If the value is true https won't be used.
  95. * @param {string} [options.roomName] - The name of the room to join.
  96. * @returns {string} The URL.
  97. */
  98. function generateURL(domain, options = {}) {
  99. const {
  100. configOverwrite,
  101. interfaceConfigOverwrite,
  102. jwt,
  103. noSSL,
  104. roomName
  105. } = options;
  106. let url = `${noSSL ? 'http' : 'https'}://${domain}/${roomName || ''}`;
  107. if (jwt) {
  108. url += `?jwt=${jwt}`;
  109. }
  110. url += `#jitsi_meet_external_api_id=${id}`;
  111. const configURLParams = configToURLParamsArray(configOverwrite);
  112. if (configURLParams.length) {
  113. url += `&config.${configURLParams.join('&config.')}`;
  114. }
  115. const interfaceConfigURLParams
  116. = configToURLParamsArray(interfaceConfigOverwrite);
  117. if (interfaceConfigURLParams.length) {
  118. url += `&interfaceConfig.${
  119. interfaceConfigURLParams.join('&interfaceConfig.')}`;
  120. }
  121. return url;
  122. }
  123. /**
  124. * The IFrame API interface class.
  125. */
  126. class JitsiMeetExternalAPI extends EventEmitter {
  127. /**
  128. * Constructs new API instance. Creates iframe and loads Jitsi Meet in it.
  129. *
  130. * @param {string} domain - The domain name of the server that hosts the
  131. * conference.
  132. * @param {string} [roomName] - The name of the room to join.
  133. * @param {number} [width] - Width of the iframe.
  134. * @param {number} [height] - Height of the iframe.
  135. * @param {DOMElement} [parentNode] - The node that will contain the
  136. * iframe.
  137. * @param {Object} [configOverwrite] - Object containing configuration
  138. * options defined in config.js to be overridden.
  139. * @param {Object} [interfaceConfigOverwrite] - Object containing
  140. * configuration options defined in interface_config.js to be overridden.
  141. * @param {boolean} [noSSL] - If the value is true https won't be used.
  142. * @param {string} [jwt] - The JWT token if needed by jitsi-meet for
  143. * authentication.
  144. */
  145. constructor(domain, // eslint-disable-line max-params
  146. roomName = '',
  147. width = MIN_WIDTH,
  148. height = MIN_HEIGHT,
  149. parentNode = document.body,
  150. configOverwrite = {},
  151. interfaceConfigOverwrite = {},
  152. noSSL = false,
  153. jwt = undefined) {
  154. super();
  155. this.parentNode = parentNode;
  156. this.url = generateURL(domain, {
  157. configOverwrite,
  158. interfaceConfigOverwrite,
  159. jwt,
  160. noSSL,
  161. roomName
  162. });
  163. this._createIFrame(Math.max(height, MIN_HEIGHT),
  164. Math.max(width, MIN_WIDTH));
  165. this._transport = new Transport({
  166. transport: 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. this.iframeHolder
  188. = this.parentNode.appendChild(document.createElement('div'));
  189. this.iframeHolder.id = `jitsiConference${id}`;
  190. this.iframeHolder.style.width = `${width}px`;
  191. this.iframeHolder.style.height = `${height}px`;
  192. this.frameName = `jitsiConferenceFrame${id}`;
  193. this.frame = document.createElement('iframe');
  194. this.frame.src = this.url;
  195. this.frame.name = this.frameName;
  196. this.frame.id = this.frameName;
  197. this.frame.width = '100%';
  198. this.frame.height = '100%';
  199. this.frame.setAttribute('allowFullScreen', 'true');
  200. this.frame = this.iframeHolder.appendChild(this.frame);
  201. }
  202. /**
  203. * Setups listeners that are used internally for JitsiMeetExternalAPI.
  204. *
  205. * @returns {void}
  206. *
  207. * @private
  208. */
  209. _setupListeners() {
  210. this._transport.on('event', ({ data, name }) => {
  211. if (name === 'participant-joined') {
  212. changeParticipantNumber(this, 1);
  213. } else if (name === 'participant-left') {
  214. changeParticipantNumber(this, -1);
  215. }
  216. const eventName = events[name];
  217. if (eventName) {
  218. this.emit(eventName, data);
  219. return true;
  220. }
  221. return false;
  222. });
  223. }
  224. /**
  225. * Adds event listener to Meet Jitsi.
  226. *
  227. * @param {string} event - The name of the event.
  228. * @param {Function} listener - The listener.
  229. * @returns {void}
  230. *
  231. * @deprecated
  232. * NOTE: This method is not removed for backward comatability purposes.
  233. */
  234. addEventListener(event, listener) {
  235. this.on(event, listener);
  236. }
  237. /**
  238. * Adds event listeners to Meet Jitsi.
  239. *
  240. * @param {Object} listeners - The object key should be the name of
  241. * the event and value - the listener.
  242. * Currently we support the following
  243. * events:
  244. * incomingMessage - receives event notifications about incoming
  245. * messages. The listener will receive object with the following structure:
  246. * {{
  247. * 'from': from,//JID of the user that sent the message
  248. * 'nick': nick,//the nickname of the user that sent the message
  249. * 'message': txt//the text of the message
  250. * }}
  251. * outgoingMessage - receives event notifications about outgoing
  252. * messages. The listener will receive object with the following structure:
  253. * {{
  254. * 'message': txt//the text of the message
  255. * }}
  256. * displayNameChanged - receives event notifications about display name
  257. * change. The listener will receive object with the following structure:
  258. * {{
  259. * jid: jid,//the JID of the participant that changed his display name
  260. * displayname: displayName //the new display name
  261. * }}
  262. * participantJoined - receives event notifications about new participant.
  263. * The listener will receive object with the following structure:
  264. * {{
  265. * jid: jid //the jid of the participant
  266. * }}
  267. * participantLeft - receives event notifications about the participant that
  268. * left the room.
  269. * The listener will receive object with the following structure:
  270. * {{
  271. * jid: jid //the jid of the participant
  272. * }}
  273. * video-conference-joined - receives event notifications about the local
  274. * user has successfully joined the video conference.
  275. * The listener will receive object with the following structure:
  276. * {{
  277. * roomName: room //the room name of the conference
  278. * }}
  279. * video-conference-left - receives event notifications about the local user
  280. * has left the video conference.
  281. * The listener will receive object with the following structure:
  282. * {{
  283. * roomName: room //the room name of the conference
  284. * }}
  285. * readyToClose - all hangup operations are completed and Jitsi Meet is
  286. * ready to be disposed.
  287. * @returns {void}
  288. *
  289. * @deprecated
  290. * NOTE: This method is not removed for backward comatability purposes.
  291. */
  292. addEventListeners(listeners) {
  293. for (const event in listeners) { // eslint-disable-line guard-for-in
  294. this.addEventListener(event, listeners[event]);
  295. }
  296. }
  297. /**
  298. * Removes the listeners and removes the Jitsi Meet frame.
  299. *
  300. * @returns {void}
  301. */
  302. dispose() {
  303. this._transport.dispose();
  304. this.removeAllListeners();
  305. if (this.iframeHolder) {
  306. this.iframeHolder.parentNode.removeChild(this.iframeHolder);
  307. }
  308. }
  309. /**
  310. * Executes command. The available commands are:
  311. * displayName - sets the display name of the local participant to the value
  312. * passed in the arguments array.
  313. * toggleAudio - mutes / unmutes audio with no arguments.
  314. * toggleVideo - mutes / unmutes video with no arguments.
  315. * toggleFilmStrip - hides / shows the filmstrip with no arguments.
  316. * If the command doesn't require any arguments the parameter should be set
  317. * to empty array or it may be omitted.
  318. *
  319. * @param {string} name - The name of the command.
  320. * @returns {void}
  321. */
  322. executeCommand(name, ...args) {
  323. if (!(name in commands)) {
  324. logger.error('Not supported command name.');
  325. return;
  326. }
  327. this._transport.sendEvent({
  328. data: args,
  329. name: commands[name]
  330. });
  331. }
  332. /**
  333. * Executes commands. The available commands are:
  334. * displayName - sets the display name of the local participant to the value
  335. * passed in the arguments array.
  336. * toggleAudio - mutes / unmutes audio. no arguments
  337. * toggleVideo - mutes / unmutes video. no arguments
  338. * toggleFilmStrip - hides / shows the filmstrip. no arguments
  339. * toggleChat - hides / shows chat. no arguments.
  340. * toggleContactList - hides / shows contact list. no arguments.
  341. * toggleShareScreen - starts / stops screen sharing. no arguments.
  342. *
  343. * @param {Object} commandList - The object with commands to be executed.
  344. * The keys of the object are the commands that will be executed and the
  345. * values are the arguments for the command.
  346. * @returns {void}
  347. */
  348. executeCommands(commandList) {
  349. for (const key in commandList) { // eslint-disable-line guard-for-in
  350. this.executeCommand(key, commandList[key]);
  351. }
  352. }
  353. /**
  354. * Returns the number of participants in the conference. The local
  355. * participant is included.
  356. *
  357. * @returns {int} The number of participants in the conference.
  358. */
  359. getNumberOfParticipants() {
  360. return this.numberOfParticipants;
  361. }
  362. /**
  363. * Removes event listener.
  364. *
  365. * @param {string} event - The name of the event.
  366. * @returns {void}
  367. *
  368. * @deprecated
  369. * NOTE: This method is not removed for backward comatability purposes.
  370. */
  371. removeEventListener(event) {
  372. this.removeAllListeners(event);
  373. }
  374. /**
  375. * Removes event listeners.
  376. *
  377. * @param {Array<string>} eventList - Array with the names of the events.
  378. * @returns {void}
  379. *
  380. * @deprecated
  381. * NOTE: This method is not removed for backward comatability purposes.
  382. */
  383. removeEventListeners(eventList) {
  384. eventList.forEach(event => this.removeEventListener(event));
  385. }
  386. }
  387. module.exports = JitsiMeetExternalAPI;