您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

external_api.js 21KB

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