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

external_api.js 41KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265
  1. import { jitsiLocalStorage } from '@jitsi/js-utils/jitsi-local-storage';
  2. import EventEmitter from 'events';
  3. import { urlObjectToString } from '../../../react/features/base/util/uri';
  4. import {
  5. PostMessageTransportBackend,
  6. Transport
  7. } from '../../transport';
  8. import {
  9. getAvailableDevices,
  10. getCurrentDevices,
  11. isDeviceChangeAvailable,
  12. isDeviceListAvailable,
  13. isMultipleAudioInputSupported,
  14. setAudioInputDevice,
  15. setAudioOutputDevice,
  16. setVideoInputDevice
  17. } from './functions';
  18. const ALWAYS_ON_TOP_FILENAMES = [
  19. 'css/all.css', 'libs/alwaysontop.min.js'
  20. ];
  21. /**
  22. * Maps the names of the commands expected by the API with the name of the
  23. * commands expected by jitsi-meet.
  24. */
  25. const commands = {
  26. addBreakoutRoom: 'add-breakout-room',
  27. answerKnockingParticipant: 'answer-knocking-participant',
  28. approveVideo: 'approve-video',
  29. askToUnmute: 'ask-to-unmute',
  30. autoAssignToBreakoutRooms: 'auto-assign-to-breakout-rooms',
  31. avatarUrl: 'avatar-url',
  32. cancelPrivateChat: 'cancel-private-chat',
  33. closeBreakoutRoom: 'close-breakout-room',
  34. displayName: 'display-name',
  35. e2eeKey: 'e2ee-key',
  36. email: 'email',
  37. grantModerator: 'grant-moderator',
  38. hangup: 'video-hangup',
  39. initiatePrivateChat: 'initiate-private-chat',
  40. joinBreakoutRoom: 'join-breakout-room',
  41. localSubject: 'local-subject',
  42. kickParticipant: 'kick-participant',
  43. muteEveryone: 'mute-everyone',
  44. overwriteConfig: 'overwrite-config',
  45. password: 'password',
  46. pinParticipant: 'pin-participant',
  47. rejectParticipant: 'reject-participant',
  48. removeBreakoutRoom: 'remove-breakout-room',
  49. resizeLargeVideo: 'resize-large-video',
  50. sendChatMessage: 'send-chat-message',
  51. sendEndpointTextMessage: 'send-endpoint-text-message',
  52. sendParticipantToRoom: 'send-participant-to-room',
  53. sendTones: 'send-tones',
  54. setFollowMe: 'set-follow-me',
  55. setLargeVideoParticipant: 'set-large-video-participant',
  56. setMediaEncryptionKey: 'set-media-encryption-key',
  57. setParticipantVolume: 'set-participant-volume',
  58. setTileView: 'set-tile-view',
  59. setVideoQuality: 'set-video-quality',
  60. startRecording: 'start-recording',
  61. startShareVideo: 'start-share-video',
  62. stopRecording: 'stop-recording',
  63. stopShareVideo: 'stop-share-video',
  64. subject: 'subject',
  65. submitFeedback: 'submit-feedback',
  66. toggleAudio: 'toggle-audio',
  67. toggleCamera: 'toggle-camera',
  68. toggleCameraMirror: 'toggle-camera-mirror',
  69. toggleChat: 'toggle-chat',
  70. toggleE2EE: 'toggle-e2ee',
  71. toggleFilmStrip: 'toggle-film-strip',
  72. toggleLobby: 'toggle-lobby',
  73. toggleModeration: 'toggle-moderation',
  74. toggleParticipantsPane: 'toggle-participants-pane',
  75. toggleRaiseHand: 'toggle-raise-hand',
  76. toggleShareAudio: 'toggle-share-audio',
  77. toggleShareScreen: 'toggle-share-screen',
  78. toggleTileView: 'toggle-tile-view',
  79. toggleVirtualBackgroundDialog: 'toggle-virtual-background',
  80. toggleVideo: 'toggle-video'
  81. };
  82. /**
  83. * Maps the names of the events expected by the API with the name of the
  84. * events expected by jitsi-meet.
  85. */
  86. const events = {
  87. 'avatar-changed': 'avatarChanged',
  88. 'audio-availability-changed': 'audioAvailabilityChanged',
  89. 'audio-mute-status-changed': 'audioMuteStatusChanged',
  90. 'browser-support': 'browserSupport',
  91. 'camera-error': 'cameraError',
  92. 'chat-updated': 'chatUpdated',
  93. 'content-sharing-participants-changed': 'contentSharingParticipantsChanged',
  94. 'data-channel-opened': 'dataChannelOpened',
  95. 'device-list-changed': 'deviceListChanged',
  96. 'display-name-change': 'displayNameChange',
  97. 'email-change': 'emailChange',
  98. 'error-occurred': 'errorOccurred',
  99. 'endpoint-text-message-received': 'endpointTextMessageReceived',
  100. 'face-landmark-detected': 'faceLandmarkDetected',
  101. 'feedback-submitted': 'feedbackSubmitted',
  102. 'feedback-prompt-displayed': 'feedbackPromptDisplayed',
  103. 'filmstrip-display-changed': 'filmstripDisplayChanged',
  104. 'incoming-message': 'incomingMessage',
  105. 'knocking-participant': 'knockingParticipant',
  106. 'log': 'log',
  107. 'mic-error': 'micError',
  108. 'moderation-participant-approved': 'moderationParticipantApproved',
  109. 'moderation-participant-rejected': 'moderationParticipantRejected',
  110. 'moderation-status-changed': 'moderationStatusChanged',
  111. 'mouse-enter': 'mouseEnter',
  112. 'mouse-leave': 'mouseLeave',
  113. 'mouse-move': 'mouseMove',
  114. 'outgoing-message': 'outgoingMessage',
  115. 'participant-joined': 'participantJoined',
  116. 'participant-kicked-out': 'participantKickedOut',
  117. 'participant-left': 'participantLeft',
  118. 'participant-role-changed': 'participantRoleChanged',
  119. 'password-required': 'passwordRequired',
  120. 'proxy-connection-event': 'proxyConnectionEvent',
  121. 'raise-hand-updated': 'raiseHandUpdated',
  122. 'recording-link-available': 'recordingLinkAvailable',
  123. 'recording-status-changed': 'recordingStatusChanged',
  124. 'video-ready-to-close': 'readyToClose',
  125. 'video-conference-joined': 'videoConferenceJoined',
  126. 'video-conference-left': 'videoConferenceLeft',
  127. 'video-availability-changed': 'videoAvailabilityChanged',
  128. 'video-mute-status-changed': 'videoMuteStatusChanged',
  129. 'video-quality-changed': 'videoQualityChanged',
  130. 'screen-sharing-status-changed': 'screenSharingStatusChanged',
  131. 'dominant-speaker-changed': 'dominantSpeakerChanged',
  132. 'subject-change': 'subjectChange',
  133. 'suspend-detected': 'suspendDetected',
  134. 'tile-view-changed': 'tileViewChanged',
  135. 'toolbar-button-clicked': 'toolbarButtonClicked'
  136. };
  137. /**
  138. * Last id of api object.
  139. *
  140. * @type {number}
  141. */
  142. let id = 0;
  143. /**
  144. * Adds given number to the numberOfParticipants property of given APIInstance.
  145. *
  146. * @param {JitsiMeetExternalAPI} APIInstance - The instance of the API.
  147. * @param {int} number - The number of participants to be added to
  148. * numberOfParticipants property (this parameter can be negative number if the
  149. * numberOfParticipants should be decreased).
  150. * @returns {void}
  151. */
  152. function changeParticipantNumber(APIInstance, number) {
  153. APIInstance._numberOfParticipants += number;
  154. }
  155. /**
  156. * Generates the URL for the iframe.
  157. *
  158. * @param {string} domain - The domain name of the server that hosts the
  159. * conference.
  160. * @param {string} [options] - Another optional parameters.
  161. * @param {Object} [options.configOverwrite] - Object containing configuration
  162. * options defined in config.js to be overridden.
  163. * @param {Object} [options.interfaceConfigOverwrite] - Object containing
  164. * configuration options defined in interface_config.js to be overridden.
  165. * @param {string} [options.jwt] - The JWT token if needed by jitsi-meet for
  166. * authentication.
  167. * @param {string} [options.lang] - The meeting's default language.
  168. * @param {string} [options.roomName] - The name of the room to join.
  169. * @returns {string} The URL.
  170. */
  171. function generateURL(domain, options = {}) {
  172. return urlObjectToString({
  173. ...options,
  174. url: `https://${domain}/#jitsi_meet_external_api_id=${id}`
  175. });
  176. }
  177. /**
  178. * Parses the arguments passed to the constructor. If the old format is used
  179. * the function translates the arguments to the new format.
  180. *
  181. * @param {Array} args - The arguments to be parsed.
  182. * @returns {Object} JS object with properties.
  183. */
  184. function parseArguments(args) {
  185. if (!args.length) {
  186. return {};
  187. }
  188. const firstArg = args[0];
  189. switch (typeof firstArg) {
  190. case 'string': // old arguments format
  191. case 'undefined': {
  192. // Not sure which format but we are trying to parse the old
  193. // format because if the new format is used everything will be undefined
  194. // anyway.
  195. const [
  196. roomName,
  197. width,
  198. height,
  199. parentNode,
  200. configOverwrite,
  201. interfaceConfigOverwrite,
  202. jwt,
  203. onload,
  204. lang
  205. ] = args;
  206. return {
  207. roomName,
  208. width,
  209. height,
  210. parentNode,
  211. configOverwrite,
  212. interfaceConfigOverwrite,
  213. jwt,
  214. onload,
  215. lang
  216. };
  217. }
  218. case 'object': // new arguments format
  219. return args[0];
  220. default:
  221. throw new Error('Can\'t parse the arguments!');
  222. }
  223. }
  224. /**
  225. * Compute valid values for height and width. If a number is specified it's
  226. * treated as pixel units. If the value is expressed in px, em, pt or
  227. * percentage, it's used as is.
  228. *
  229. * @param {any} value - The value to be parsed.
  230. * @returns {string|undefined} The parsed value that can be used for setting
  231. * sizes through the style property. If invalid value is passed the method
  232. * returns undefined.
  233. */
  234. function parseSizeParam(value) {
  235. let parsedValue;
  236. // This regex parses values of the form 100px, 100em, 100pt or 100%.
  237. // Values like 100 or 100px are handled outside of the regex, and
  238. // invalid values will be ignored and the minimum will be used.
  239. const re = /([0-9]*\.?[0-9]+)(em|pt|px|%)$/;
  240. if (typeof value === 'string' && String(value).match(re) !== null) {
  241. parsedValue = value;
  242. } else if (typeof value === 'number') {
  243. parsedValue = `${value}px`;
  244. }
  245. return parsedValue;
  246. }
  247. /**
  248. * The IFrame API interface class.
  249. */
  250. export default class JitsiMeetExternalAPI extends EventEmitter {
  251. /**
  252. * Constructs new API instance. Creates iframe and loads Jitsi Meet in it.
  253. *
  254. * @param {string} domain - The domain name of the server that hosts the
  255. * conference.
  256. * @param {Object} [options] - Optional arguments.
  257. * @param {string} [options.roomName] - The name of the room to join.
  258. * @param {number|string} [options.width] - Width of the iframe. Check
  259. * parseSizeParam for format details.
  260. * @param {number|string} [options.height] - Height of the iframe. Check
  261. * parseSizeParam for format details.
  262. * @param {DOMElement} [options.parentNode] - The node that will contain the
  263. * iframe.
  264. * @param {Object} [options.configOverwrite] - Object containing
  265. * configuration options defined in config.js to be overridden.
  266. * @param {Object} [options.interfaceConfigOverwrite] - Object containing
  267. * configuration options defined in interface_config.js to be overridden.
  268. * @param {string} [options.jwt] - The JWT token if needed by jitsi-meet for
  269. * authentication.
  270. * @param {string} [options.lang] - The meeting's default language.
  271. * @param {string} [options.onload] - The onload function that will listen
  272. * for iframe onload event.
  273. * @param {Array<Object>} [options.invitees] - Array of objects containing
  274. * information about new participants that will be invited in the call.
  275. * @param {Array<Object>} [options.devices] - Array of objects containing
  276. * information about the initial devices that will be used in the call.
  277. * @param {Object} [options.userInfo] - Object containing information about
  278. * the participant opening the meeting.
  279. * @param {string} [options.e2eeKey] - The key used for End-to-End encryption.
  280. * THIS IS EXPERIMENTAL.
  281. */
  282. constructor(domain, ...args) {
  283. super();
  284. const {
  285. roomName = '',
  286. width = '100%',
  287. height = '100%',
  288. parentNode = document.body,
  289. configOverwrite = {},
  290. interfaceConfigOverwrite = {},
  291. jwt = undefined,
  292. lang = undefined,
  293. onload = undefined,
  294. invitees,
  295. devices,
  296. userInfo,
  297. e2eeKey
  298. } = parseArguments(args);
  299. const localStorageContent = jitsiLocalStorage.getItem('jitsiLocalStorage');
  300. this._parentNode = parentNode;
  301. this._url = generateURL(domain, {
  302. configOverwrite,
  303. interfaceConfigOverwrite,
  304. jwt,
  305. lang,
  306. roomName,
  307. devices,
  308. userInfo,
  309. appData: {
  310. localStorageContent
  311. }
  312. });
  313. this._createIFrame(height, width, onload);
  314. this._transport = new Transport({
  315. backend: new PostMessageTransportBackend({
  316. postisOptions: {
  317. allowedOrigin: new URL(this._url).origin,
  318. scope: `jitsi_meet_external_api_${id}`,
  319. window: this._frame.contentWindow
  320. }
  321. })
  322. });
  323. if (Array.isArray(invitees) && invitees.length > 0) {
  324. this.invite(invitees);
  325. }
  326. this._tmpE2EEKey = e2eeKey;
  327. this._isLargeVideoVisible = true;
  328. this._numberOfParticipants = 0;
  329. this._participants = {};
  330. this._myUserID = undefined;
  331. this._onStageParticipant = undefined;
  332. this._setupListeners();
  333. id++;
  334. }
  335. /**
  336. * Creates the iframe element.
  337. *
  338. * @param {number|string} height - The height of the iframe. Check
  339. * parseSizeParam for format details.
  340. * @param {number|string} width - The with of the iframe. Check
  341. * parseSizeParam for format details.
  342. * @param {Function} onload - The function that will listen
  343. * for onload event.
  344. * @returns {void}
  345. *
  346. * @private
  347. */
  348. _createIFrame(height, width, onload) {
  349. const frameName = `jitsiConferenceFrame${id}`;
  350. this._frame = document.createElement('iframe');
  351. this._frame.allow = 'camera; microphone; display-capture; autoplay; clipboard-write';
  352. this._frame.src = this._url;
  353. this._frame.name = frameName;
  354. this._frame.id = frameName;
  355. this._setSize(height, width);
  356. this._frame.setAttribute('allowFullScreen', 'true');
  357. this._frame.style.border = 0;
  358. if (onload) {
  359. // waits for iframe resources to load
  360. // and fires event when it is done
  361. this._frame.onload = onload;
  362. }
  363. this._frame = this._parentNode.appendChild(this._frame);
  364. }
  365. /**
  366. * Returns arrays with the all resources for the always on top feature.
  367. *
  368. * @returns {Array<string>}
  369. */
  370. _getAlwaysOnTopResources() {
  371. const iframeWindow = this._frame.contentWindow;
  372. const iframeDocument = iframeWindow.document;
  373. let baseURL = '';
  374. const base = iframeDocument.querySelector('base');
  375. if (base && base.href) {
  376. baseURL = base.href;
  377. } else {
  378. const { protocol, host } = iframeWindow.location;
  379. baseURL = `${protocol}//${host}`;
  380. }
  381. return ALWAYS_ON_TOP_FILENAMES.map(
  382. filename => new URL(filename, baseURL).href
  383. );
  384. }
  385. /**
  386. * Returns the formatted display name of a participant.
  387. *
  388. * @param {string} participantId - The id of the participant.
  389. * @returns {string} The formatted display name.
  390. */
  391. _getFormattedDisplayName(participantId) {
  392. const { formattedDisplayName }
  393. = this._participants[participantId] || {};
  394. return formattedDisplayName;
  395. }
  396. /**
  397. * Returns the id of the on stage participant.
  398. *
  399. * @returns {string} - The id of the on stage participant.
  400. */
  401. _getOnStageParticipant() {
  402. return this._onStageParticipant;
  403. }
  404. /**
  405. * Getter for the large video element in Jitsi Meet.
  406. *
  407. * @returns {HTMLElement|undefined} - The large video.
  408. */
  409. _getLargeVideo() {
  410. const iframe = this.getIFrame();
  411. if (!this._isLargeVideoVisible
  412. || !iframe
  413. || !iframe.contentWindow
  414. || !iframe.contentWindow.document) {
  415. return;
  416. }
  417. return iframe.contentWindow.document.getElementById('largeVideo');
  418. }
  419. /**
  420. * Getter for participant specific video element in Jitsi Meet.
  421. *
  422. * @param {string|undefined} participantId - Id of participant to return the video for.
  423. *
  424. * @returns {HTMLElement|undefined} - The requested video. Will return the local video
  425. * by default if participantId is undefined.
  426. */
  427. _getParticipantVideo(participantId) {
  428. const iframe = this.getIFrame();
  429. if (!iframe
  430. || !iframe.contentWindow
  431. || !iframe.contentWindow.document) {
  432. return;
  433. }
  434. if (typeof participantId === 'undefined' || participantId === this._myUserID) {
  435. return iframe.contentWindow.document.getElementById('localVideo_container');
  436. }
  437. return iframe.contentWindow.document.querySelector(`#participant_${participantId} video`);
  438. }
  439. /**
  440. * Sets the size of the iframe element.
  441. *
  442. * @param {number|string} height - The height of the iframe.
  443. * @param {number|string} width - The with of the iframe.
  444. * @returns {void}
  445. *
  446. * @private
  447. */
  448. _setSize(height, width) {
  449. const parsedHeight = parseSizeParam(height);
  450. const parsedWidth = parseSizeParam(width);
  451. if (parsedHeight !== undefined) {
  452. this._height = height;
  453. this._frame.style.height = parsedHeight;
  454. }
  455. if (parsedWidth !== undefined) {
  456. this._width = width;
  457. this._frame.style.width = parsedWidth;
  458. }
  459. }
  460. /**
  461. * Setups listeners that are used internally for JitsiMeetExternalAPI.
  462. *
  463. * @returns {void}
  464. *
  465. * @private
  466. */
  467. _setupListeners() {
  468. this._transport.on('event', ({ name, ...data }) => {
  469. const userID = data.id;
  470. switch (name) {
  471. case 'video-conference-joined': {
  472. if (typeof this._tmpE2EEKey !== 'undefined') {
  473. this.executeCommand(commands.e2eeKey, this._tmpE2EEKey);
  474. this._tmpE2EEKey = undefined;
  475. }
  476. this._myUserID = userID;
  477. this._participants[userID] = {
  478. avatarURL: data.avatarURL
  479. };
  480. }
  481. // eslint-disable-next-line no-fallthrough
  482. case 'participant-joined': {
  483. this._participants[userID] = this._participants[userID] || {};
  484. this._participants[userID].displayName = data.displayName;
  485. this._participants[userID].formattedDisplayName
  486. = data.formattedDisplayName;
  487. changeParticipantNumber(this, 1);
  488. break;
  489. }
  490. case 'participant-left':
  491. changeParticipantNumber(this, -1);
  492. delete this._participants[userID];
  493. break;
  494. case 'display-name-change': {
  495. const user = this._participants[userID];
  496. if (user) {
  497. user.displayName = data.displayname;
  498. user.formattedDisplayName = data.formattedDisplayName;
  499. }
  500. break;
  501. }
  502. case 'email-change': {
  503. const user = this._participants[userID];
  504. if (user) {
  505. user.email = data.email;
  506. }
  507. break;
  508. }
  509. case 'avatar-changed': {
  510. const user = this._participants[userID];
  511. if (user) {
  512. user.avatarURL = data.avatarURL;
  513. }
  514. break;
  515. }
  516. case 'on-stage-participant-changed':
  517. this._onStageParticipant = userID;
  518. this.emit('largeVideoChanged');
  519. break;
  520. case 'large-video-visibility-changed':
  521. this._isLargeVideoVisible = data.isVisible;
  522. this.emit('largeVideoChanged');
  523. break;
  524. case 'video-conference-left':
  525. changeParticipantNumber(this, -1);
  526. delete this._participants[this._myUserID];
  527. break;
  528. case 'video-quality-changed':
  529. this._videoQuality = data.videoQuality;
  530. break;
  531. case 'local-storage-changed':
  532. jitsiLocalStorage.setItem('jitsiLocalStorage', data.localStorageContent);
  533. // Since this is internal event we don't need to emit it to the consumer of the API.
  534. return true;
  535. }
  536. const eventName = events[name];
  537. if (eventName) {
  538. this.emit(eventName, data);
  539. return true;
  540. }
  541. return false;
  542. });
  543. }
  544. /**
  545. * Adds event listener to Meet Jitsi.
  546. *
  547. * @param {string} event - The name of the event.
  548. * @param {Function} listener - The listener.
  549. * @returns {void}
  550. *
  551. * @deprecated
  552. * NOTE: This method is not removed for backward comatability purposes.
  553. */
  554. addEventListener(event, listener) {
  555. this.on(event, listener);
  556. }
  557. /**
  558. * Adds event listeners to Meet Jitsi.
  559. *
  560. * @param {Object} listeners - The object key should be the name of
  561. * the event and value - the listener.
  562. * Currently we support the following
  563. * events:
  564. * {@code log} - receives event notifications whenever information has
  565. * been logged and has a log level specified within {@code config.apiLogLevels}.
  566. * The listener will receive object with the following structure:
  567. * {{
  568. * logLevel: the message log level
  569. * arguments: an array of strings that compose the actual log message
  570. * }}
  571. * {@code chatUpdated} - receives event notifications about chat state being
  572. * updated. The listener will receive object with the following structure:
  573. * {{
  574. * 'unreadCount': unreadCounter, // the unread message(s) counter,
  575. * 'isOpen': isOpen, // whether the chat panel is open or not
  576. * }}
  577. * {@code incomingMessage} - receives event notifications about incoming
  578. * messages. The listener will receive object with the following structure:
  579. * {{
  580. * 'from': from,//JID of the user that sent the message
  581. * 'nick': nick,//the nickname of the user that sent the message
  582. * 'message': txt//the text of the message
  583. * }}
  584. * {@code outgoingMessage} - receives event notifications about outgoing
  585. * messages. The listener will receive object with the following structure:
  586. * {{
  587. * 'message': txt//the text of the message
  588. * }}
  589. * {@code displayNameChanged} - receives event notifications about display
  590. * name change. The listener will receive object with the following
  591. * structure:
  592. * {{
  593. * jid: jid,//the JID of the participant that changed his display name
  594. * displayname: displayName //the new display name
  595. * }}
  596. * {@code participantJoined} - receives event notifications about new
  597. * participant.
  598. * The listener will receive object with the following structure:
  599. * {{
  600. * jid: jid //the jid of the participant
  601. * }}
  602. * {@code participantLeft} - receives event notifications about the
  603. * participant that left the room.
  604. * The listener will receive object with the following structure:
  605. * {{
  606. * jid: jid //the jid of the participant
  607. * }}
  608. * {@code videoConferenceJoined} - receives event notifications about the
  609. * local user has successfully joined the video conference.
  610. * The listener will receive object with the following structure:
  611. * {{
  612. * roomName: room //the room name of the conference
  613. * }}
  614. * {@code videoConferenceLeft} - receives event notifications about the
  615. * local user has left the video conference.
  616. * The listener will receive object with the following structure:
  617. * {{
  618. * roomName: room //the room name of the conference
  619. * }}
  620. * {@code screenSharingStatusChanged} - receives event notifications about
  621. * turning on/off the local user screen sharing.
  622. * The listener will receive object with the following structure:
  623. * {{
  624. * on: on //whether screen sharing is on
  625. * }}
  626. * {@code dominantSpeakerChanged} - receives event notifications about
  627. * change in the dominant speaker.
  628. * The listener will receive object with the following structure:
  629. * {{
  630. * id: participantId //participantId of the new dominant speaker
  631. * }}
  632. * {@code suspendDetected} - receives event notifications about detecting suspend event in host computer.
  633. * {@code readyToClose} - all hangup operations are completed and Jitsi Meet
  634. * is ready to be disposed.
  635. * @returns {void}
  636. *
  637. * @deprecated
  638. * NOTE: This method is not removed for backward comatability purposes.
  639. */
  640. addEventListeners(listeners) {
  641. for (const event in listeners) { // eslint-disable-line guard-for-in
  642. this.addEventListener(event, listeners[event]);
  643. }
  644. }
  645. /**
  646. * Captures the screenshot of the large video.
  647. *
  648. * @returns {Promise<string>} - Resolves with a base64 encoded image data of the screenshot
  649. * if large video is detected, an error otherwise.
  650. */
  651. captureLargeVideoScreenshot() {
  652. return this._transport.sendRequest({
  653. name: 'capture-largevideo-screenshot'
  654. });
  655. }
  656. /**
  657. * Removes the listeners and removes the Jitsi Meet frame.
  658. *
  659. * @returns {void}
  660. */
  661. dispose() {
  662. this.emit('_willDispose');
  663. this._transport.dispose();
  664. this.removeAllListeners();
  665. if (this._frame && this._frame.parentNode) {
  666. this._frame.parentNode.removeChild(this._frame);
  667. }
  668. }
  669. /**
  670. * Executes command. The available commands are:
  671. * {@code displayName} - Sets the display name of the local participant to
  672. * the value passed in the arguments array.
  673. * {@code subject} - Sets the subject of the conference, the value passed
  674. * in the arguments array. Note: Available only for moderator.
  675. *
  676. * {@code toggleAudio} - Mutes / unmutes audio with no arguments.
  677. * {@code toggleVideo} - Mutes / unmutes video with no arguments.
  678. * {@code toggleFilmStrip} - Hides / shows the filmstrip with no arguments.
  679. *
  680. * If the command doesn't require any arguments the parameter should be set
  681. * to empty array or it may be omitted.
  682. *
  683. * @param {string} name - The name of the command.
  684. * @returns {void}
  685. */
  686. executeCommand(name, ...args) {
  687. if (!(name in commands)) {
  688. console.error('Not supported command name.');
  689. return;
  690. }
  691. this._transport.sendEvent({
  692. data: args,
  693. name: commands[name]
  694. });
  695. }
  696. /**
  697. * Executes commands. The available commands are:
  698. * {@code displayName} - Sets the display name of the local participant to
  699. * the value passed in the arguments array.
  700. * {@code toggleAudio} - Mutes / unmutes audio. No arguments.
  701. * {@code toggleVideo} - Mutes / unmutes video. No arguments.
  702. * {@code toggleFilmStrip} - Hides / shows the filmstrip. No arguments.
  703. * {@code toggleChat} - Hides / shows chat. No arguments.
  704. * {@code toggleShareScreen} - Starts / stops screen sharing. No arguments.
  705. *
  706. * @param {Object} commandList - The object with commands to be executed.
  707. * The keys of the object are the commands that will be executed and the
  708. * values are the arguments for the command.
  709. * @returns {void}
  710. */
  711. executeCommands(commandList) {
  712. for (const key in commandList) { // eslint-disable-line guard-for-in
  713. this.executeCommand(key, commandList[key]);
  714. }
  715. }
  716. /**
  717. * Returns Promise that resolves with a list of available devices.
  718. *
  719. * @returns {Promise}
  720. */
  721. getAvailableDevices() {
  722. return getAvailableDevices(this._transport);
  723. }
  724. /**
  725. * Gets a list of the currently sharing participant id's.
  726. *
  727. * @returns {Promise} - Resolves with the list of participant id's currently sharing.
  728. */
  729. getContentSharingParticipants() {
  730. return this._transport.sendRequest({
  731. name: 'get-content-sharing-participants'
  732. });
  733. }
  734. /**
  735. * Returns Promise that resolves with current selected devices.
  736. *
  737. * @returns {Promise}
  738. */
  739. getCurrentDevices() {
  740. return getCurrentDevices(this._transport);
  741. }
  742. /**
  743. * Returns any custom avatars backgrounds.
  744. *
  745. * @returns {Promise} - Resolves with the list of custom avatar backgrounds.
  746. */
  747. getCustomAvatarBackgrounds() {
  748. return this._transport.sendRequest({
  749. name: 'get-custom-avatar-backgrounds'
  750. });
  751. }
  752. /**
  753. * Returns the current livestream url.
  754. *
  755. * @returns {Promise} - Resolves with the current livestream URL if exists, with
  756. * undefined if not and rejects on failure.
  757. */
  758. getLivestreamUrl() {
  759. return this._transport.sendRequest({
  760. name: 'get-livestream-url'
  761. });
  762. }
  763. /**
  764. * Returns the conference participants information.
  765. *
  766. * @returns {Array<Object>} - Returns an array containing participants
  767. * information like participant id, display name, avatar URL and email.
  768. */
  769. getParticipantsInfo() {
  770. const participantIds = Object.keys(this._participants);
  771. const participantsInfo = Object.values(this._participants);
  772. participantsInfo.forEach((participant, idx) => {
  773. participant.participantId = participantIds[idx];
  774. });
  775. return participantsInfo;
  776. }
  777. /**
  778. * Returns the current video quality setting.
  779. *
  780. * @returns {number}
  781. */
  782. getVideoQuality() {
  783. return this._videoQuality;
  784. }
  785. /**
  786. * Check if the audio is available.
  787. *
  788. * @returns {Promise} - Resolves with true if the audio available, with
  789. * false if not and rejects on failure.
  790. */
  791. isAudioAvailable() {
  792. return this._transport.sendRequest({
  793. name: 'is-audio-available'
  794. });
  795. }
  796. /**
  797. * Returns Promise that resolves with true if the device change is available
  798. * and with false if not.
  799. *
  800. * @param {string} [deviceType] - Values - 'output', 'input' or undefined.
  801. * Default - 'input'.
  802. * @returns {Promise}
  803. */
  804. isDeviceChangeAvailable(deviceType) {
  805. return isDeviceChangeAvailable(this._transport, deviceType);
  806. }
  807. /**
  808. * Returns Promise that resolves with true if the device list is available
  809. * and with false if not.
  810. *
  811. * @returns {Promise}
  812. */
  813. isDeviceListAvailable() {
  814. return isDeviceListAvailable(this._transport);
  815. }
  816. /**
  817. * Returns Promise that resolves with true if multiple audio input is supported
  818. * and with false if not.
  819. *
  820. * @returns {Promise}
  821. */
  822. isMultipleAudioInputSupported() {
  823. return isMultipleAudioInputSupported(this._transport);
  824. }
  825. /**
  826. * Invite people to the call.
  827. *
  828. * @param {Array<Object>} invitees - The invitees.
  829. * @returns {Promise} - Resolves on success and rejects on failure.
  830. */
  831. invite(invitees) {
  832. if (!Array.isArray(invitees) || invitees.length === 0) {
  833. return Promise.reject(new TypeError('Invalid Argument'));
  834. }
  835. return this._transport.sendRequest({
  836. name: 'invite',
  837. invitees
  838. });
  839. }
  840. /**
  841. * Returns the audio mute status.
  842. *
  843. * @returns {Promise} - Resolves with the audio mute status and rejects on
  844. * failure.
  845. */
  846. isAudioMuted() {
  847. return this._transport.sendRequest({
  848. name: 'is-audio-muted'
  849. });
  850. }
  851. /**
  852. * Returns the moderation on status on the given mediaType.
  853. *
  854. * @param {string} mediaType - The media type for which to check moderation.
  855. * @returns {Promise} - Resolves with the moderation on status and rejects on
  856. * failure.
  857. */
  858. isModerationOn(mediaType) {
  859. return this._transport.sendRequest({
  860. name: 'is-moderation-on',
  861. mediaType
  862. });
  863. }
  864. /**
  865. * Returns force muted status of the given participant id for the given media type.
  866. *
  867. * @param {string} participantId - The id of the participant to check.
  868. * @param {string} mediaType - The media type for which to check.
  869. * @returns {Promise} - Resolves with the force muted status and rejects on
  870. * failure.
  871. */
  872. isParticipantForceMuted(participantId, mediaType) {
  873. return this._transport.sendRequest({
  874. name: 'is-participant-force-muted',
  875. participantId,
  876. mediaType
  877. });
  878. }
  879. /**
  880. * Returns whether the participants pane is open.
  881. *
  882. * @returns {Promise} - Resolves with true if the participants pane is open
  883. * and with false if not.
  884. */
  885. isParticipantsPaneOpen() {
  886. return this._transport.sendRequest({
  887. name: 'is-participants-pane-open'
  888. });
  889. }
  890. /**
  891. * Returns screen sharing status.
  892. *
  893. * @returns {Promise} - Resolves with screensharing status and rejects on failure.
  894. */
  895. isSharingScreen() {
  896. return this._transport.sendRequest({
  897. name: 'is-sharing-screen'
  898. });
  899. }
  900. /**
  901. * Returns the avatar URL of a participant.
  902. *
  903. * @param {string} participantId - The id of the participant.
  904. * @returns {string} The avatar URL.
  905. */
  906. getAvatarURL(participantId) {
  907. const { avatarURL } = this._participants[participantId] || {};
  908. return avatarURL;
  909. }
  910. /**
  911. * Gets the deployment info.
  912. *
  913. * @returns {Promise} - Resolves with the deployment info object.
  914. */
  915. getDeploymentInfo() {
  916. return this._transport.sendRequest({
  917. name: 'deployment-info'
  918. });
  919. }
  920. /**
  921. * Returns the display name of a participant.
  922. *
  923. * @param {string} participantId - The id of the participant.
  924. * @returns {string} The display name.
  925. */
  926. getDisplayName(participantId) {
  927. const { displayName } = this._participants[participantId] || {};
  928. return displayName;
  929. }
  930. /**
  931. * Returns the email of a participant.
  932. *
  933. * @param {string} participantId - The id of the participant.
  934. * @returns {string} The email.
  935. */
  936. getEmail(participantId) {
  937. const { email } = this._participants[participantId] || {};
  938. return email;
  939. }
  940. /**
  941. * Returns the iframe that loads Jitsi Meet.
  942. *
  943. * @returns {HTMLElement} The iframe.
  944. */
  945. getIFrame() {
  946. return this._frame;
  947. }
  948. /**
  949. * Returns the number of participants in the conference. The local
  950. * participant is included.
  951. *
  952. * @returns {int} The number of participants in the conference.
  953. */
  954. getNumberOfParticipants() {
  955. return this._numberOfParticipants;
  956. }
  957. /**
  958. * Check if the video is available.
  959. *
  960. * @returns {Promise} - Resolves with true if the video available, with
  961. * false if not and rejects on failure.
  962. */
  963. isVideoAvailable() {
  964. return this._transport.sendRequest({
  965. name: 'is-video-available'
  966. });
  967. }
  968. /**
  969. * Returns the audio mute status.
  970. *
  971. * @returns {Promise} - Resolves with the audio mute status and rejects on
  972. * failure.
  973. */
  974. isVideoMuted() {
  975. return this._transport.sendRequest({
  976. name: 'is-video-muted'
  977. });
  978. }
  979. /**
  980. * Returns the list of breakout rooms.
  981. *
  982. * @returns {Promise} Resolves with the list of breakout rooms.
  983. */
  984. listBreakoutRooms() {
  985. return this._transport.sendRequest({
  986. name: 'list-breakout-rooms'
  987. });
  988. }
  989. /**
  990. * Pins a participant's video on to the stage view.
  991. *
  992. * @param {string} participantId - Participant id (JID) of the participant
  993. * that needs to be pinned on the stage view.
  994. * @returns {void}
  995. */
  996. pinParticipant(participantId) {
  997. this.executeCommand('pinParticipant', participantId);
  998. }
  999. /**
  1000. * Removes event listener.
  1001. *
  1002. * @param {string} event - The name of the event.
  1003. * @returns {void}
  1004. *
  1005. * @deprecated
  1006. * NOTE: This method is not removed for backward comatability purposes.
  1007. */
  1008. removeEventListener(event) {
  1009. this.removeAllListeners(event);
  1010. }
  1011. /**
  1012. * Removes event listeners.
  1013. *
  1014. * @param {Array<string>} eventList - Array with the names of the events.
  1015. * @returns {void}
  1016. *
  1017. * @deprecated
  1018. * NOTE: This method is not removed for backward comatability purposes.
  1019. */
  1020. removeEventListeners(eventList) {
  1021. eventList.forEach(event => this.removeEventListener(event));
  1022. }
  1023. /**
  1024. * Resizes the large video container as per the dimensions provided.
  1025. *
  1026. * @param {number} width - Width that needs to be applied on the large video container.
  1027. * @param {number} height - Height that needs to be applied on the large video container.
  1028. * @returns {void}
  1029. */
  1030. resizeLargeVideo(width, height) {
  1031. if (width <= this._width && height <= this._height) {
  1032. this.executeCommand('resizeLargeVideo', width, height);
  1033. }
  1034. }
  1035. /**
  1036. * Passes an event along to the local conference participant to establish
  1037. * or update a direct peer connection. This is currently used for developing
  1038. * wireless screensharing with room integration and it is advised against to
  1039. * use as its api may change.
  1040. *
  1041. * @param {Object} event - An object with information to pass along.
  1042. * @param {Object} event.data - The payload of the event.
  1043. * @param {string} event.from - The jid of the sender of the event. Needed
  1044. * when a reply is to be sent regarding the event.
  1045. * @returns {void}
  1046. */
  1047. sendProxyConnectionEvent(event) {
  1048. this._transport.sendEvent({
  1049. data: [ event ],
  1050. name: 'proxy-connection-event'
  1051. });
  1052. }
  1053. /**
  1054. * Sets the audio input device to the one with the label or id that is
  1055. * passed.
  1056. *
  1057. * @param {string} label - The label of the new device.
  1058. * @param {string} deviceId - The id of the new device.
  1059. * @returns {Promise}
  1060. */
  1061. setAudioInputDevice(label, deviceId) {
  1062. return setAudioInputDevice(this._transport, label, deviceId);
  1063. }
  1064. /**
  1065. * Sets the audio output device to the one with the label or id that is
  1066. * passed.
  1067. *
  1068. * @param {string} label - The label of the new device.
  1069. * @param {string} deviceId - The id of the new device.
  1070. * @returns {Promise}
  1071. */
  1072. setAudioOutputDevice(label, deviceId) {
  1073. return setAudioOutputDevice(this._transport, label, deviceId);
  1074. }
  1075. /**
  1076. * Displays the given participant on the large video. If no participant id is specified,
  1077. * dominant and pinned speakers will be taken into consideration while selecting the
  1078. * the large video participant.
  1079. *
  1080. * @param {string} participantId - Jid of the participant to be displayed on the large video.
  1081. * @returns {void}
  1082. */
  1083. setLargeVideoParticipant(participantId) {
  1084. this.executeCommand('setLargeVideoParticipant', participantId);
  1085. }
  1086. /**
  1087. * Sets the video input device to the one with the label or id that is
  1088. * passed.
  1089. *
  1090. * @param {string} label - The label of the new device.
  1091. * @param {string} deviceId - The id of the new device.
  1092. * @returns {Promise}
  1093. */
  1094. setVideoInputDevice(label, deviceId) {
  1095. return setVideoInputDevice(this._transport, label, deviceId);
  1096. }
  1097. /**
  1098. * Starts a file recording or streaming session depending on the passed on params.
  1099. * For RTMP streams, `rtmpStreamKey` must be passed on. `rtmpBroadcastID` is optional.
  1100. * For youtube streams, `youtubeStreamKey` must be passed on. `youtubeBroadcastID` is optional.
  1101. * For dropbox recording, recording `mode` should be `file` and a dropbox oauth2 token must be provided.
  1102. * For file recording, recording `mode` should be `file` and optionally `shouldShare` could be passed on.
  1103. * No other params should be passed.
  1104. *
  1105. * @param {Object} options - An object with config options to pass along.
  1106. * @param { string } options.mode - Recording mode, either `file` or `stream`.
  1107. * @param { string } options.dropboxToken - Dropbox oauth2 token.
  1108. * @param { boolean } options.shouldShare - Whether the recording should be shared with the participants or not.
  1109. * Only applies to certain jitsi meet deploys.
  1110. * @param { string } options.rtmpStreamKey - The RTMP stream key.
  1111. * @param { string } options.rtmpBroadcastID - The RTMP broacast ID.
  1112. * @param { string } options.youtubeStreamKey - The youtube stream key.
  1113. * @param { string } options.youtubeBroadcastID - The youtube broacast ID.
  1114. * @returns {void}
  1115. */
  1116. startRecording(options) {
  1117. this.executeCommand('startRecording', options);
  1118. }
  1119. /**
  1120. * Stops a recording or streaming session that is in progress.
  1121. *
  1122. * @param {string} mode - `file` or `stream`.
  1123. * @returns {void}
  1124. */
  1125. stopRecording(mode) {
  1126. this.executeCommand('stopRecording', mode);
  1127. }
  1128. /**
  1129. * Sets e2ee enabled/disabled.
  1130. *
  1131. * @param {boolean} enabled - The new value for e2ee enabled.
  1132. * @returns {void}
  1133. */
  1134. toggleE2EE(enabled) {
  1135. this.executeCommand('toggleE2EE', enabled);
  1136. }
  1137. /**
  1138. * Sets the key and keyIndex for e2ee.
  1139. *
  1140. * @param {Object} keyInfo - Json containing key information.
  1141. * @param {CryptoKey} [keyInfo.encryptionKey] - The encryption key.
  1142. * @param {number} [keyInfo.index] - The index of the encryption key.
  1143. * @returns {void}
  1144. */
  1145. async setMediaEncryptionKey(keyInfo) {
  1146. const { key, index } = keyInfo;
  1147. if (key) {
  1148. const exportedKey = await crypto.subtle.exportKey('raw', key);
  1149. this.executeCommand('setMediaEncryptionKey', JSON.stringify({
  1150. exportedKey: Array.from(new Uint8Array(exportedKey)),
  1151. index }));
  1152. } else {
  1153. this.executeCommand('setMediaEncryptionKey', JSON.stringify({
  1154. exportedKey: false,
  1155. index }));
  1156. }
  1157. }
  1158. }