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

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