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 17KB

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