Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

external_api.js 21KB

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