Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

external_api.js 23KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729
  1. import EventEmitter from 'events';
  2. import { urlObjectToString } from '../../../react/features/base/util/uri';
  3. import {
  4. PostMessageTransportBackend,
  5. Transport
  6. } from '../../transport';
  7. import electronPopupsConfig from './electronPopupsConfig.json';
  8. const logger = require('jitsi-meet-logger').getLogger(__filename);
  9. const ALWAYS_ON_TOP_FILENAMES = [
  10. 'css/all.css', 'libs/alwaysontop.min.js'
  11. ];
  12. /**
  13. * Maps the names of the commands expected by the API with the name of the
  14. * commands expected by jitsi-meet
  15. */
  16. const commands = {
  17. avatarUrl: 'avatar-url',
  18. displayName: 'display-name',
  19. email: 'email',
  20. hangup: 'video-hangup',
  21. submitFeedback: 'submit-feedback',
  22. toggleAudio: 'toggle-audio',
  23. toggleChat: 'toggle-chat',
  24. toggleFilmStrip: 'toggle-film-strip',
  25. toggleShareScreen: 'toggle-share-screen',
  26. toggleVideo: 'toggle-video'
  27. };
  28. /**
  29. * Maps the names of the events expected by the API with the name of the
  30. * events expected by jitsi-meet
  31. */
  32. const events = {
  33. 'avatar-changed': 'avatarChanged',
  34. 'audio-availability-changed': 'audioAvailabilityChanged',
  35. 'audio-mute-status-changed': 'audioMuteStatusChanged',
  36. 'display-name-change': 'displayNameChange',
  37. 'feedback-submitted': 'feedbackSubmitted',
  38. 'incoming-message': 'incomingMessage',
  39. 'outgoing-message': 'outgoingMessage',
  40. 'participant-joined': 'participantJoined',
  41. 'participant-left': 'participantLeft',
  42. 'video-ready-to-close': 'readyToClose',
  43. 'video-conference-joined': 'videoConferenceJoined',
  44. 'video-conference-left': 'videoConferenceLeft',
  45. 'video-availability-changed': 'videoAvailabilityChanged',
  46. 'video-mute-status-changed': 'videoMuteStatusChanged',
  47. 'screen-sharing-status-changed': 'screenSharingStatusChanged'
  48. };
  49. /**
  50. * Last id of api object
  51. * @type {number}
  52. */
  53. let id = 0;
  54. /**
  55. * Adds given number to the numberOfParticipants property of given APIInstance.
  56. *
  57. * @param {JitsiMeetExternalAPI} APIInstance - The instance of the API.
  58. * @param {int} number - The number of participants to be added to
  59. * numberOfParticipants property (this parameter can be negative number if the
  60. * numberOfParticipants should be decreased).
  61. * @returns {void}
  62. */
  63. function changeParticipantNumber(APIInstance, number) {
  64. APIInstance._numberOfParticipants += number;
  65. }
  66. /**
  67. * Generates the URL for the iframe.
  68. *
  69. * @param {string} domain - The domain name of the server that hosts the
  70. * conference.
  71. * @param {string} [options] - Another optional parameters.
  72. * @param {Object} [options.configOverwrite] - Object containing configuration
  73. * options defined in config.js to be overridden.
  74. * @param {Object} [options.interfaceConfigOverwrite] - Object containing
  75. * configuration options defined in interface_config.js to be overridden.
  76. * @param {string} [options.jwt] - The JWT token if needed by jitsi-meet for
  77. * authentication.
  78. * @param {boolean} [options.noSSL] - If the value is true https won't be used.
  79. * @param {string} [options.roomName] - The name of the room to join.
  80. * @returns {string} The URL.
  81. */
  82. function generateURL(domain, options = {}) {
  83. return urlObjectToString({
  84. ...options,
  85. url:
  86. `${options.noSSL ? 'http' : 'https'}://${
  87. domain}/#jitsi_meet_external_api_id=${id}`
  88. });
  89. }
  90. /**
  91. * Parses the arguments passed to the constructor. If the old format is used
  92. * the function translates the arguments to the new format.
  93. *
  94. * @param {Array} args - The arguments to be parsed.
  95. * @returns {Object} JS object with properties.
  96. */
  97. function parseArguments(args) {
  98. if (!args.length) {
  99. return {};
  100. }
  101. const firstArg = args[0];
  102. switch (typeof firstArg) {
  103. case 'string': // old arguments format
  104. case undefined: // eslint-disable-line no-case-declarations
  105. // not sure which format but we are trying to parse the old
  106. // format because if the new format is used everything will be undefined
  107. // anyway.
  108. const [
  109. roomName,
  110. width,
  111. height,
  112. parentNode,
  113. configOverwrite,
  114. interfaceConfigOverwrite,
  115. noSSL,
  116. jwt,
  117. onload
  118. ] = args;
  119. return {
  120. roomName,
  121. width,
  122. height,
  123. parentNode,
  124. configOverwrite,
  125. interfaceConfigOverwrite,
  126. noSSL,
  127. jwt,
  128. onload
  129. };
  130. case 'object': // new arguments format
  131. return args[0];
  132. default:
  133. throw new Error('Can\'t parse the arguments!');
  134. }
  135. }
  136. /**
  137. * Compute valid values for height and width. If a number is specified it's
  138. * treated as pixel units. If the value is expressed in px, em, pt or
  139. * percentage, it's used as is.
  140. *
  141. * @param {any} value - The value to be parsed.
  142. * @returns {string|undefined} The parsed value that can be used for setting
  143. * sizes through the style property. If invalid value is passed the method
  144. * retuns undefined.
  145. */
  146. function parseSizeParam(value) {
  147. let parsedValue;
  148. // This regex parses values of the form 100px, 100em, 100pt or 100%.
  149. // Values like 100 or 100px are handled outside of the regex, and
  150. // invalid values will be ignored and the minimum will be used.
  151. const re = /([0-9]*\.?[0-9]+)(em|pt|px|%)$/;
  152. if (typeof value === 'string' && String(value).match(re) !== null) {
  153. parsedValue = value;
  154. } else if (typeof value === 'number') {
  155. parsedValue = `${value}px`;
  156. }
  157. return parsedValue;
  158. }
  159. /**
  160. * The IFrame API interface class.
  161. */
  162. export default class JitsiMeetExternalAPI extends EventEmitter {
  163. /**
  164. * Constructs new API instance. Creates iframe and loads Jitsi Meet in it.
  165. *
  166. * @param {string} domain - The domain name of the server that hosts the
  167. * conference.
  168. * @param {Object} [options] - Optional arguments.
  169. * @param {string} [options.roomName] - The name of the room to join.
  170. * @param {number|string} [options.width] - Width of the iframe. Check
  171. * parseSizeParam for format details.
  172. * @param {number|string} [options.height] - Height of the iframe. Check
  173. * parseSizeParam for format details.
  174. * @param {DOMElement} [options.parentNode] - The node that will contain the
  175. * iframe.
  176. * @param {Object} [options.configOverwrite] - Object containing
  177. * configuration options defined in config.js to be overridden.
  178. * @param {Object} [options.interfaceConfigOverwrite] - Object containing
  179. * configuration options defined in interface_config.js to be overridden.
  180. * @param {boolean} [options.noSSL] - If the value is true https won't be
  181. * used.
  182. * @param {string} [options.jwt] - The JWT token if needed by jitsi-meet for
  183. * authentication.
  184. * @param {string} [options.onload] - The onload function that will listen
  185. * for iframe onload event.
  186. * @param {Array<Object>} [options.invitees] - Array of objects containing
  187. * information about new participants that will be invited in the call.
  188. */
  189. constructor(domain, ...args) {
  190. super();
  191. const {
  192. roomName = '',
  193. width = '100%',
  194. height = '100%',
  195. parentNode = document.body,
  196. configOverwrite = {},
  197. interfaceConfigOverwrite = {},
  198. noSSL = false,
  199. jwt = undefined,
  200. onload = undefined,
  201. invitees
  202. } = parseArguments(args);
  203. this._parentNode = parentNode;
  204. this._url = generateURL(domain, {
  205. configOverwrite,
  206. interfaceConfigOverwrite,
  207. jwt,
  208. noSSL,
  209. roomName
  210. });
  211. this._createIFrame(height, width, onload);
  212. this._transport = new Transport({
  213. backend: new PostMessageTransportBackend({
  214. postisOptions: {
  215. scope: `jitsi_meet_external_api_${id}`,
  216. window: this._frame.contentWindow
  217. }
  218. })
  219. });
  220. this._invitees = invitees;
  221. this._isLargeVideoVisible = true;
  222. this._numberOfParticipants = 0;
  223. this._participants = {};
  224. this._myUserID = undefined;
  225. this._onStageParticipant = undefined;
  226. this._setupListeners();
  227. id++;
  228. }
  229. /**
  230. * Creates the iframe element.
  231. *
  232. * @param {number|string} height - The height of the iframe. Check
  233. * parseSizeParam for format details.
  234. * @param {number|string} width - The with of the iframe. Check
  235. * parseSizeParam for format details.
  236. * @param {Function} onload - The function that will listen
  237. * for onload event.
  238. * @returns {void}
  239. *
  240. * @private
  241. */
  242. _createIFrame(height, width, onload) {
  243. const frameName = `jitsiConferenceFrame${id}`;
  244. this._frame = document.createElement('iframe');
  245. this._frame.allow = 'camera; microphone';
  246. this._frame.src = this._url;
  247. this._frame.name = frameName;
  248. this._frame.id = frameName;
  249. this._setSize(height, width);
  250. this._frame.setAttribute('allowFullScreen', 'true');
  251. this._frame.style.border = 0;
  252. if (onload) {
  253. // waits for iframe resources to load
  254. // and fires event when it is done
  255. this._frame.onload = onload;
  256. }
  257. this._frame = this._parentNode.appendChild(this._frame);
  258. }
  259. /**
  260. * Returns arrays with the all resources for the always on top feature.
  261. *
  262. * @returns {Array<string>}
  263. */
  264. _getAlwaysOnTopResources() {
  265. const iframeWindow = this._frame.contentWindow;
  266. const iframeDocument = iframeWindow.document;
  267. let baseURL = '';
  268. const base = iframeDocument.querySelector('base');
  269. if (base && base.href) {
  270. baseURL = base.href;
  271. } else {
  272. const { protocol, host } = iframeWindow.location;
  273. baseURL = `${protocol}//${host}`;
  274. }
  275. return ALWAYS_ON_TOP_FILENAMES.map(
  276. filename => (new URL(filename, baseURL)).href
  277. );
  278. }
  279. /**
  280. * Returns the id of the on stage participant.
  281. *
  282. * @returns {string} - The id of the on stage participant.
  283. */
  284. _getOnStageParticipant() {
  285. return this._onStageParticipant;
  286. }
  287. /**
  288. * Getter for the large video element in Jitsi Meet.
  289. *
  290. * @returns {HTMLElement|undefined} - The large video.
  291. */
  292. _getLargeVideo() {
  293. const iframe = this.getIFrame();
  294. if (!this._isLargeVideoVisible
  295. || !iframe
  296. || !iframe.contentWindow
  297. || !iframe.contentWindow.document) {
  298. return;
  299. }
  300. return iframe.contentWindow.document.getElementById('largeVideo');
  301. }
  302. /**
  303. * Sets the size of the iframe element.
  304. *
  305. * @param {number|string} height - The height of the iframe.
  306. * @param {number|string} width - The with of the iframe.
  307. * @returns {void}
  308. *
  309. * @private
  310. */
  311. _setSize(height, width) {
  312. const parsedHeight = parseSizeParam(height);
  313. const parsedWidth = parseSizeParam(width);
  314. if (parsedHeight !== undefined) {
  315. this._frame.style.height = parsedHeight;
  316. }
  317. if (parsedWidth !== undefined) {
  318. this._frame.style.width = parsedWidth;
  319. }
  320. }
  321. /**
  322. * Setups listeners that are used internally for JitsiMeetExternalAPI.
  323. *
  324. * @returns {void}
  325. *
  326. * @private
  327. */
  328. _setupListeners() {
  329. this._transport.on('event', ({ name, ...data }) => {
  330. const userID = data.id;
  331. switch (name) {
  332. case 'video-conference-joined':
  333. if (this._invitees) {
  334. this.invite(this._invitees);
  335. }
  336. this._myUserID = userID;
  337. this._participants[userID] = {
  338. avatarURL: data.avatarURL
  339. };
  340. // eslint-disable-next-line no-fallthrough
  341. case 'participant-joined': {
  342. this._participants[userID] = this._participants[userID] || {};
  343. this._participants[userID].displayName = data.displayName;
  344. this._participants[userID].formattedDisplayName
  345. = data.formattedDisplayName;
  346. changeParticipantNumber(this, 1);
  347. break;
  348. }
  349. case 'participant-left':
  350. changeParticipantNumber(this, -1);
  351. delete this._participants[userID];
  352. break;
  353. case 'display-name-change': {
  354. const user = this._participants[userID];
  355. if (user) {
  356. user.displayName = data.displayname;
  357. user.formattedDisplayName = data.formattedDisplayName;
  358. }
  359. break;
  360. }
  361. case 'avatar-changed': {
  362. const user = this._participants[userID];
  363. if (user) {
  364. user.avatarURL = data.avatarURL;
  365. }
  366. break;
  367. }
  368. case 'on-stage-participant-changed':
  369. this._onStageParticipant = userID;
  370. this.emit('largeVideoChanged');
  371. break;
  372. case 'large-video-visibility-changed':
  373. this._isLargeVideoVisible = data.isVisible;
  374. this.emit('largeVideoChanged');
  375. break;
  376. case 'video-conference-left':
  377. changeParticipantNumber(this, -1);
  378. delete this._participants[this._myUserID];
  379. break;
  380. }
  381. const eventName = events[name];
  382. if (eventName) {
  383. this.emit(eventName, data);
  384. return true;
  385. }
  386. return false;
  387. });
  388. }
  389. /**
  390. * Adds event listener to Meet Jitsi.
  391. *
  392. * @param {string} event - The name of the event.
  393. * @param {Function} listener - The listener.
  394. * @returns {void}
  395. *
  396. * @deprecated
  397. * NOTE: This method is not removed for backward comatability purposes.
  398. */
  399. addEventListener(event, listener) {
  400. this.on(event, listener);
  401. }
  402. /**
  403. * Adds event listeners to Meet Jitsi.
  404. *
  405. * @param {Object} listeners - The object key should be the name of
  406. * the event and value - the listener.
  407. * Currently we support the following
  408. * events:
  409. * incomingMessage - receives event notifications about incoming
  410. * messages. The listener will receive object with the following structure:
  411. * {{
  412. * 'from': from,//JID of the user that sent the message
  413. * 'nick': nick,//the nickname of the user that sent the message
  414. * 'message': txt//the text of the message
  415. * }}
  416. * outgoingMessage - receives event notifications about outgoing
  417. * messages. The listener will receive object with the following structure:
  418. * {{
  419. * 'message': txt//the text of the message
  420. * }}
  421. * displayNameChanged - receives event notifications about display name
  422. * change. The listener will receive object with the following structure:
  423. * {{
  424. * jid: jid,//the JID of the participant that changed his display name
  425. * displayname: displayName //the new display name
  426. * }}
  427. * participantJoined - receives event notifications about new participant.
  428. * The listener will receive object with the following structure:
  429. * {{
  430. * jid: jid //the jid of the participant
  431. * }}
  432. * participantLeft - receives event notifications about the participant that
  433. * left the room.
  434. * The listener will receive object with the following structure:
  435. * {{
  436. * jid: jid //the jid of the participant
  437. * }}
  438. * video-conference-joined - receives event notifications about the local
  439. * user has successfully joined the video conference.
  440. * The listener will receive object with the following structure:
  441. * {{
  442. * roomName: room //the room name of the conference
  443. * }}
  444. * video-conference-left - receives event notifications about the local user
  445. * has left the video conference.
  446. * The listener will receive object with the following structure:
  447. * {{
  448. * roomName: room //the room name of the conference
  449. * }}
  450. * screenSharingStatusChanged - receives event notifications about
  451. * turning on/off the local user screen sharing.
  452. * The listener will receive object with the following structure:
  453. * {{
  454. * on: on //whether screen sharing is on
  455. * }}
  456. * readyToClose - all hangup operations are completed and Jitsi Meet is
  457. * ready to be disposed.
  458. * @returns {void}
  459. *
  460. * @deprecated
  461. * NOTE: This method is not removed for backward comatability purposes.
  462. */
  463. addEventListeners(listeners) {
  464. for (const event in listeners) { // eslint-disable-line guard-for-in
  465. this.addEventListener(event, listeners[event]);
  466. }
  467. }
  468. /**
  469. * Removes the listeners and removes the Jitsi Meet frame.
  470. *
  471. * @returns {void}
  472. */
  473. dispose() {
  474. this._transport.dispose();
  475. this.removeAllListeners();
  476. if (this._frame) {
  477. this._frame.parentNode.removeChild(this._frame);
  478. }
  479. }
  480. /**
  481. * Executes command. The available commands are:
  482. * displayName - sets the display name of the local participant to the value
  483. * passed in the arguments array.
  484. * toggleAudio - mutes / unmutes audio with no arguments.
  485. * toggleVideo - mutes / unmutes video with no arguments.
  486. * toggleFilmStrip - hides / shows the filmstrip with no arguments.
  487. * If the command doesn't require any arguments the parameter should be set
  488. * to empty array or it may be omitted.
  489. *
  490. * @param {string} name - The name of the command.
  491. * @returns {void}
  492. */
  493. executeCommand(name, ...args) {
  494. if (!(name in commands)) {
  495. logger.error('Not supported command name.');
  496. return;
  497. }
  498. this._transport.sendEvent({
  499. data: args,
  500. name: commands[name]
  501. });
  502. }
  503. /**
  504. * Executes commands. The available commands are:
  505. * displayName - sets the display name of the local participant to the value
  506. * passed in the arguments array.
  507. * toggleAudio - mutes / unmutes audio. no arguments
  508. * toggleVideo - mutes / unmutes video. no arguments
  509. * toggleFilmStrip - hides / shows the filmstrip. no arguments
  510. * toggleChat - hides / shows chat. no arguments.
  511. * toggleShareScreen - starts / stops screen sharing. no arguments.
  512. *
  513. * @param {Object} commandList - The object with commands to be executed.
  514. * The keys of the object are the commands that will be executed and the
  515. * values are the arguments for the command.
  516. * @returns {void}
  517. */
  518. executeCommands(commandList) {
  519. for (const key in commandList) { // eslint-disable-line guard-for-in
  520. this.executeCommand(key, commandList[key]);
  521. }
  522. }
  523. /**
  524. * Check if the audio is available.
  525. *
  526. * @returns {Promise} - Resolves with true if the audio available, with
  527. * false if not and rejects on failure.
  528. */
  529. isAudioAvailable() {
  530. return this._transport.sendRequest({
  531. name: 'is-audio-available'
  532. });
  533. }
  534. /**
  535. * Invite people to the call.
  536. *
  537. * @param {Array<Object>} invitees - The invitees.
  538. * @returns {Promise} - Resolves on success and rejects on failure.
  539. */
  540. invite(invitees) {
  541. return this._transport.sendRequest({
  542. name: 'invite',
  543. invitees
  544. });
  545. }
  546. /**
  547. * Returns the audio mute status.
  548. *
  549. * @returns {Promise} - Resolves with the audio mute status and rejects on
  550. * failure.
  551. */
  552. isAudioMuted() {
  553. return this._transport.sendRequest({
  554. name: 'is-audio-muted'
  555. });
  556. }
  557. /**
  558. * Returns the avatar URL of a participant.
  559. *
  560. * @param {string} participantId - The id of the participant.
  561. * @returns {string} The avatar URL.
  562. */
  563. getAvatarURL(participantId) {
  564. const { avatarURL } = this._participants[participantId] || {};
  565. return avatarURL;
  566. }
  567. /**
  568. * Returns the display name of a participant.
  569. *
  570. * @param {string} participantId - The id of the participant.
  571. * @returns {string} The display name.
  572. */
  573. getDisplayName(participantId) {
  574. const { displayName } = this._participants[participantId] || {};
  575. return displayName;
  576. }
  577. /**
  578. * Returns the formatted display name of a participant.
  579. *
  580. * @param {string} participantId - The id of the participant.
  581. * @returns {string} The formatted display name.
  582. */
  583. _getFormattedDisplayName(participantId) {
  584. const { formattedDisplayName }
  585. = this._participants[participantId] || {};
  586. return formattedDisplayName;
  587. }
  588. /**
  589. * Returns the iframe that loads Jitsi Meet.
  590. *
  591. * @returns {HTMLElement} The iframe.
  592. */
  593. getIFrame() {
  594. return this._frame;
  595. }
  596. /**
  597. * Returns the number of participants in the conference. The local
  598. * participant is included.
  599. *
  600. * @returns {int} The number of participants in the conference.
  601. */
  602. getNumberOfParticipants() {
  603. return this._numberOfParticipants;
  604. }
  605. /**
  606. * Check if the video is available.
  607. *
  608. * @returns {Promise} - Resolves with true if the video available, with
  609. * false if not and rejects on failure.
  610. */
  611. isVideoAvailable() {
  612. return this._transport.sendRequest({
  613. name: 'is-video-available'
  614. });
  615. }
  616. /**
  617. * Returns the audio mute status.
  618. *
  619. * @returns {Promise} - Resolves with the audio mute status and rejects on
  620. * failure.
  621. */
  622. isVideoMuted() {
  623. return this._transport.sendRequest({
  624. name: 'is-video-muted'
  625. });
  626. }
  627. /**
  628. * Removes event listener.
  629. *
  630. * @param {string} event - The name of the event.
  631. * @returns {void}
  632. *
  633. * @deprecated
  634. * NOTE: This method is not removed for backward comatability purposes.
  635. */
  636. removeEventListener(event) {
  637. this.removeAllListeners(event);
  638. }
  639. /**
  640. * Removes event listeners.
  641. *
  642. * @param {Array<string>} eventList - Array with the names of the events.
  643. * @returns {void}
  644. *
  645. * @deprecated
  646. * NOTE: This method is not removed for backward comatability purposes.
  647. */
  648. removeEventListeners(eventList) {
  649. eventList.forEach(event => this.removeEventListener(event));
  650. }
  651. /**
  652. * Returns the configuration for electron for the windows that are open
  653. * from Jitsi Meet.
  654. *
  655. * @returns {Promise<Object>}
  656. *
  657. * NOTE: For internal use only.
  658. */
  659. _getElectronPopupsConfig() {
  660. return Promise.resolve(electronPopupsConfig);
  661. }
  662. }