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

external_api.js 15KB

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