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

conference.js 67KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929
  1. /* global $, APP, JitsiMeetJS, config, interfaceConfig */
  2. const logger = require("jitsi-meet-logger").getLogger(__filename);
  3. import {openConnection} from './connection';
  4. import Invite from './modules/UI/invite/Invite';
  5. import ContactList from './modules/UI/side_pannels/contactlist/ContactList';
  6. import AuthHandler from './modules/UI/authentication/AuthHandler';
  7. import Recorder from './modules/recorder/Recorder';
  8. import mediaDeviceHelper from './modules/devices/mediaDeviceHelper';
  9. import { reload, reportError } from './modules/util/helpers';
  10. import UIEvents from './service/UI/UIEvents';
  11. import UIUtil from './modules/UI/util/UIUtil';
  12. import * as JitsiMeetConferenceEvents from './ConferenceEvents';
  13. import analytics from './modules/analytics/analytics';
  14. import EventEmitter from "events";
  15. import {
  16. conferenceJoined,
  17. conferenceFailed,
  18. conferenceLeft
  19. } from './react/features/base/conference';
  20. import {
  21. isFatalJitsiConnectionError
  22. } from './react/features/base/lib-jitsi-meet';
  23. import {
  24. changeParticipantAvatarID,
  25. changeParticipantAvatarURL,
  26. changeParticipantEmail,
  27. participantJoined,
  28. participantLeft,
  29. participantRoleChanged
  30. } from './react/features/base/participants';
  31. import {
  32. mediaPermissionPromptVisibilityChanged,
  33. suspendDetected
  34. } from './react/features/overlay';
  35. const ConnectionEvents = JitsiMeetJS.events.connection;
  36. const ConnectionErrors = JitsiMeetJS.errors.connection;
  37. const ConferenceEvents = JitsiMeetJS.events.conference;
  38. const ConferenceErrors = JitsiMeetJS.errors.conference;
  39. const TrackEvents = JitsiMeetJS.events.track;
  40. const TrackErrors = JitsiMeetJS.errors.track;
  41. const ConnectionQualityEvents = JitsiMeetJS.events.connectionQuality;
  42. const eventEmitter = new EventEmitter();
  43. let room, connection, localAudio, localVideo;
  44. /**
  45. * Indicates whether extension external installation is in progress or not.
  46. */
  47. let DSExternalInstallationInProgress = false;
  48. import {VIDEO_CONTAINER_TYPE} from "./modules/UI/videolayout/VideoContainer";
  49. /**
  50. * Known custom conference commands.
  51. */
  52. const commands = {
  53. EMAIL: "email",
  54. AVATAR_URL: "avatar-url",
  55. AVATAR_ID: "avatar-id",
  56. ETHERPAD: "etherpad",
  57. SHARED_VIDEO: "shared-video",
  58. CUSTOM_ROLE: "custom-role"
  59. };
  60. /**
  61. * Max length of the display names. If we receive longer display name the
  62. * additional chars are going to be cut.
  63. */
  64. const MAX_DISPLAY_NAME_LENGTH = 50;
  65. /**
  66. * Open Connection. When authentication failed it shows auth dialog.
  67. * @param roomName the room name to use
  68. * @returns Promise<JitsiConnection>
  69. */
  70. function connect(roomName) {
  71. return openConnection({retry: true, roomName: roomName})
  72. .catch(function (err) {
  73. if (err === ConnectionErrors.PASSWORD_REQUIRED) {
  74. APP.UI.notifyTokenAuthFailed();
  75. } else {
  76. APP.UI.notifyConnectionFailed(err);
  77. }
  78. throw err;
  79. });
  80. }
  81. /**
  82. * Creates local media tracks and connects to room. Will show error
  83. * dialogs in case if accessing local microphone and/or camera failed. Will
  84. * show guidance overlay for users on how to give access to camera and/or
  85. * microphone,
  86. * @param {string} roomName
  87. * @returns {Promise.<JitsiLocalTrack[], JitsiConnection>}
  88. */
  89. function createInitialLocalTracksAndConnect(roomName) {
  90. let audioAndVideoError,
  91. audioOnlyError;
  92. JitsiMeetJS.mediaDevices.addEventListener(
  93. JitsiMeetJS.events.mediaDevices.PERMISSION_PROMPT_IS_SHOWN,
  94. browser =>
  95. APP.store.dispatch(
  96. mediaPermissionPromptVisibilityChanged(true, browser))
  97. );
  98. // First try to retrieve both audio and video.
  99. let tryCreateLocalTracks = createLocalTracks(
  100. { devices: ['audio', 'video'] }, true)
  101. .catch(err => {
  102. // If failed then try to retrieve only audio.
  103. audioAndVideoError = err;
  104. return createLocalTracks({ devices: ['audio'] }, true);
  105. })
  106. .catch(err => {
  107. // If audio failed too then just return empty array for tracks.
  108. audioOnlyError = err;
  109. return [];
  110. });
  111. return Promise.all([ tryCreateLocalTracks, connect(roomName) ])
  112. .then(([tracks, con]) => {
  113. APP.store.dispatch(mediaPermissionPromptVisibilityChanged(false));
  114. if (audioAndVideoError) {
  115. if (audioOnlyError) {
  116. // If both requests for 'audio' + 'video' and 'audio' only
  117. // failed, we assume that there is some problems with user's
  118. // microphone and show corresponding dialog.
  119. APP.UI.showDeviceErrorDialog(audioOnlyError, null);
  120. } else {
  121. // If request for 'audio' + 'video' failed, but request for
  122. // 'audio' only was OK, we assume that we had problems with
  123. // camera and show corresponding dialog.
  124. APP.UI.showDeviceErrorDialog(null, audioAndVideoError);
  125. }
  126. }
  127. return [tracks, con];
  128. });
  129. }
  130. /**
  131. * Share data to other users.
  132. * @param command the command
  133. * @param {string} value new value
  134. */
  135. function sendData (command, value) {
  136. room.removeCommand(command);
  137. room.sendCommand(command, {value: value});
  138. }
  139. /**
  140. * Sets up initially the properties of the local participant - email, avatarID,
  141. * avatarURL, displayName, etc.
  142. */
  143. function _setupLocalParticipantProperties() {
  144. const email = APP.settings.getEmail();
  145. email && sendData(commands.EMAIL, email);
  146. const avatarUrl = APP.settings.getAvatarUrl();
  147. avatarUrl && sendData(commands.AVATAR_URL, avatarUrl);
  148. if (!email && !avatarUrl) {
  149. sendData(commands.AVATAR_ID, APP.settings.getAvatarId());
  150. }
  151. let nick = APP.settings.getDisplayName();
  152. if (config.useNicks && !nick) {
  153. nick = APP.UI.askForNickname();
  154. APP.settings.setDisplayName(nick);
  155. }
  156. nick && room.setDisplayName(nick);
  157. }
  158. /**
  159. * Get user nickname by user id.
  160. * @param {string} id user id
  161. * @returns {string?} user nickname or undefined if user is unknown.
  162. */
  163. function getDisplayName (id) {
  164. if (APP.conference.isLocalId(id)) {
  165. return APP.settings.getDisplayName();
  166. }
  167. let participant = room.getParticipantById(id);
  168. if (participant && participant.getDisplayName()) {
  169. return participant.getDisplayName();
  170. }
  171. }
  172. /**
  173. * Mute or unmute local audio stream if it exists.
  174. * @param {boolean} muted - if audio stream should be muted or unmuted.
  175. * @param {boolean} userInteraction - indicates if this local audio mute was a
  176. * result of user interaction
  177. */
  178. function muteLocalAudio (muted) {
  179. muteLocalMedia(localAudio, muted, 'Audio');
  180. }
  181. function muteLocalMedia(localMedia, muted, localMediaTypeString) {
  182. if (!localMedia) {
  183. return;
  184. }
  185. const method = muted ? 'mute' : 'unmute';
  186. localMedia[method]().catch(reason => {
  187. logger.warn(`${localMediaTypeString} ${method} was rejected:`, reason);
  188. });
  189. }
  190. /**
  191. * Mute or unmute local video stream if it exists.
  192. * @param {boolean} muted if video stream should be muted or unmuted.
  193. */
  194. function muteLocalVideo (muted) {
  195. muteLocalMedia(localVideo, muted, 'Video');
  196. }
  197. /**
  198. * Check if the welcome page is enabled and redirects to it.
  199. * If requested show a thank you dialog before that.
  200. * If we have a close page enabled, redirect to it without
  201. * showing any other dialog.
  202. *
  203. * @param {object} options used to decide which particular close page to show
  204. * or if close page is disabled, whether we should show the thankyou dialog
  205. * @param {boolean} options.thankYouDialogVisible - whether we should
  206. * show thank you dialog
  207. * @param {boolean} options.feedbackSubmitted - whether feedback was submitted
  208. */
  209. function maybeRedirectToWelcomePage(options) {
  210. // if close page is enabled redirect to it, without further action
  211. if (config.enableClosePage) {
  212. // save whether current user is guest or not, before navigating
  213. // to close page
  214. window.sessionStorage.setItem('guest', APP.tokenData.isGuest);
  215. assignWindowLocationPathname(
  216. options.feedbackSubmitted ? "close.html" : "close2.html");
  217. return;
  218. }
  219. // else: show thankYou dialog only if there is no feedback
  220. if (options.thankYouDialogVisible)
  221. APP.UI.messageHandler.openMessageDialog(
  222. null, "dialog.thankYou", {appName:interfaceConfig.APP_NAME});
  223. // if Welcome page is enabled redirect to welcome page after 3 sec.
  224. if (config.enableWelcomePage) {
  225. setTimeout(() => {
  226. APP.settings.setWelcomePageEnabled(true);
  227. assignWindowLocationPathname('./');
  228. }, 3000);
  229. }
  230. }
  231. /**
  232. * Assigns a specific pathname to window.location.pathname taking into account
  233. * the context root of the Web app.
  234. *
  235. * @param {string} pathname - The pathname to assign to
  236. * window.location.pathname. If the specified pathname is relative, the context
  237. * root of the Web app will be prepended to the specified pathname before
  238. * assigning it to window.location.pathname.
  239. * @return {void}
  240. */
  241. function assignWindowLocationPathname(pathname) {
  242. const windowLocation = window.location;
  243. if (!pathname.startsWith('/')) {
  244. // XXX To support a deployment in a sub-directory, assume that the room
  245. // (name) is the last non-directory component of the path (name).
  246. let contextRoot = windowLocation.pathname;
  247. contextRoot
  248. = contextRoot.substring(0, contextRoot.lastIndexOf('/') + 1);
  249. // A pathname equal to ./ specifies the current directory. It will be
  250. // fine but pointless to include it because contextRoot is the current
  251. // directory.
  252. pathname.startsWith('./') && (pathname = pathname.substring(2));
  253. pathname = contextRoot + pathname;
  254. }
  255. windowLocation.pathname = pathname;
  256. }
  257. /**
  258. * Create local tracks of specified types.
  259. * @param {Object} options
  260. * @param {string[]} options.devices - required track types
  261. * ('audio', 'video' etc.)
  262. * @param {string|null} (options.cameraDeviceId) - camera device id, if
  263. * undefined - one from settings will be used
  264. * @param {string|null} (options.micDeviceId) - microphone device id, if
  265. * undefined - one from settings will be used
  266. * @param {boolean} (checkForPermissionPrompt) - if lib-jitsi-meet should check
  267. * for gUM permission prompt
  268. * @returns {Promise<JitsiLocalTrack[]>}
  269. */
  270. function createLocalTracks (options, checkForPermissionPrompt) {
  271. options || (options = {});
  272. return JitsiMeetJS
  273. .createLocalTracks({
  274. // copy array to avoid mutations inside library
  275. devices: options.devices.slice(0),
  276. resolution: config.resolution,
  277. cameraDeviceId: typeof options.cameraDeviceId === 'undefined' ||
  278. options.cameraDeviceId === null
  279. ? APP.settings.getCameraDeviceId()
  280. : options.cameraDeviceId,
  281. micDeviceId: typeof options.micDeviceId === 'undefined' ||
  282. options.micDeviceId === null
  283. ? APP.settings.getMicDeviceId()
  284. : options.micDeviceId,
  285. // adds any ff fake device settings if any
  286. firefox_fake_device: config.firefox_fake_device,
  287. desktopSharingExtensionExternalInstallation:
  288. options.desktopSharingExtensionExternalInstallation
  289. }, checkForPermissionPrompt).then( (tracks) => {
  290. tracks.forEach((track) => {
  291. track.on(TrackEvents.NO_DATA_FROM_SOURCE,
  292. APP.UI.showTrackNotWorkingDialog.bind(null, track));
  293. });
  294. return tracks;
  295. }).catch(function (err) {
  296. logger.error(
  297. 'failed to create local tracks', options.devices, err);
  298. return Promise.reject(err);
  299. });
  300. }
  301. /**
  302. * Changes the display name for the local user
  303. * @param nickname {string} the new display name
  304. */
  305. function changeLocalDisplayName(nickname = '') {
  306. const formattedNickname
  307. = nickname.trim().substr(0, MAX_DISPLAY_NAME_LENGTH);
  308. if (formattedNickname === APP.settings.getDisplayName()) {
  309. return;
  310. }
  311. APP.settings.setDisplayName(formattedNickname);
  312. room.setDisplayName(formattedNickname);
  313. APP.UI.changeDisplayName(APP.conference.getMyUserId(), formattedNickname);
  314. }
  315. class ConferenceConnector {
  316. constructor(resolve, reject, invite) {
  317. this._resolve = resolve;
  318. this._reject = reject;
  319. this._invite = invite;
  320. this.reconnectTimeout = null;
  321. room.on(ConferenceEvents.CONFERENCE_JOINED,
  322. this._handleConferenceJoined.bind(this));
  323. room.on(ConferenceEvents.CONFERENCE_FAILED,
  324. this._onConferenceFailed.bind(this));
  325. room.on(ConferenceEvents.CONFERENCE_ERROR,
  326. this._onConferenceError.bind(this));
  327. }
  328. _handleConferenceFailed(err) {
  329. this._unsubscribe();
  330. this._reject(err);
  331. }
  332. _onConferenceFailed(err, ...params) {
  333. APP.store.dispatch(conferenceFailed(room, err, ...params));
  334. logger.error('CONFERENCE FAILED:', err, ...params);
  335. APP.UI.hideRingOverLay();
  336. switch (err) {
  337. // room is locked by the password
  338. case ConferenceErrors.PASSWORD_REQUIRED:
  339. APP.UI.emitEvent(UIEvents.PASSWORD_REQUIRED);
  340. break;
  341. case ConferenceErrors.CONNECTION_ERROR:
  342. {
  343. let [msg] = params;
  344. APP.UI.notifyConnectionFailed(msg);
  345. }
  346. break;
  347. case ConferenceErrors.NOT_ALLOWED_ERROR:
  348. {
  349. // let's show some auth not allowed page
  350. assignWindowLocationPathname('authError.html');
  351. }
  352. break;
  353. // not enough rights to create conference
  354. case ConferenceErrors.AUTHENTICATION_REQUIRED:
  355. // schedule reconnect to check if someone else created the room
  356. this.reconnectTimeout = setTimeout(function () {
  357. room.join();
  358. }, 5000);
  359. // notify user that auth is required
  360. AuthHandler.requireAuth(
  361. room, this._invite.getRoomLocker().password);
  362. break;
  363. case ConferenceErrors.RESERVATION_ERROR:
  364. {
  365. let [code, msg] = params;
  366. APP.UI.notifyReservationError(code, msg);
  367. }
  368. break;
  369. case ConferenceErrors.GRACEFUL_SHUTDOWN:
  370. APP.UI.notifyGracefulShutdown();
  371. break;
  372. case ConferenceErrors.JINGLE_FATAL_ERROR:
  373. APP.UI.notifyInternalError();
  374. break;
  375. case ConferenceErrors.CONFERENCE_DESTROYED:
  376. {
  377. let [reason] = params;
  378. APP.UI.hideStats();
  379. APP.UI.notifyConferenceDestroyed(reason);
  380. }
  381. break;
  382. // FIXME FOCUS_DISCONNECTED is confusing event name.
  383. // What really happens there is that the library is not ready yet,
  384. // because Jicofo is not available, but it is going to give
  385. // it another try.
  386. case ConferenceErrors.FOCUS_DISCONNECTED:
  387. {
  388. let [focus, retrySec] = params;
  389. APP.UI.notifyFocusDisconnected(focus, retrySec);
  390. }
  391. break;
  392. case ConferenceErrors.FOCUS_LEFT:
  393. case ConferenceErrors.VIDEOBRIDGE_NOT_AVAILABLE:
  394. // FIXME the conference should be stopped by the library and not by
  395. // the app. Both the errors above are unrecoverable from the library
  396. // perspective.
  397. room.leave().then(() => connection.disconnect());
  398. break;
  399. case ConferenceErrors.CONFERENCE_MAX_USERS:
  400. connection.disconnect();
  401. APP.UI.notifyMaxUsersLimitReached();
  402. break;
  403. case ConferenceErrors.INCOMPATIBLE_SERVER_VERSIONS:
  404. reload();
  405. break;
  406. default:
  407. this._handleConferenceFailed(err, ...params);
  408. }
  409. }
  410. _onConferenceError(err, ...params) {
  411. logger.error('CONFERENCE Error:', err, params);
  412. switch (err) {
  413. case ConferenceErrors.CHAT_ERROR:
  414. {
  415. let [code, msg] = params;
  416. APP.UI.showChatError(code, msg);
  417. }
  418. break;
  419. default:
  420. logger.error("Unknown error.", err);
  421. }
  422. }
  423. _unsubscribe() {
  424. room.off(
  425. ConferenceEvents.CONFERENCE_JOINED, this._handleConferenceJoined);
  426. room.off(
  427. ConferenceEvents.CONFERENCE_FAILED, this._onConferenceFailed);
  428. if (this.reconnectTimeout !== null) {
  429. clearTimeout(this.reconnectTimeout);
  430. }
  431. AuthHandler.closeAuth();
  432. }
  433. _handleConferenceJoined() {
  434. this._unsubscribe();
  435. this._resolve();
  436. }
  437. connect() {
  438. room.join();
  439. }
  440. }
  441. /**
  442. * Disconnects the connection.
  443. * @returns resolved Promise. We need this in order to make the Promise.all
  444. * call in hangup() to resolve when all operations are finished.
  445. */
  446. function disconnect() {
  447. connection.disconnect();
  448. APP.API.notifyConferenceLeft(APP.conference.roomName);
  449. return Promise.resolve();
  450. }
  451. /**
  452. * Handles CONNECTION_FAILED events from lib-jitsi-meet.
  453. *
  454. * @param {JitsiMeetJS.connection.error} error - The reported error.
  455. * @returns {void}
  456. * @private
  457. */
  458. function _connectionFailedHandler(error) {
  459. if (isFatalJitsiConnectionError(error)) {
  460. APP.connection.removeEventListener(
  461. ConnectionEvents.CONNECTION_FAILED,
  462. _connectionFailedHandler);
  463. if (room)
  464. room.leave();
  465. }
  466. }
  467. export default {
  468. isModerator: false,
  469. audioMuted: false,
  470. videoMuted: false,
  471. isSharingScreen: false,
  472. isDesktopSharingEnabled: false,
  473. /*
  474. * Whether the local "raisedHand" flag is on.
  475. */
  476. isHandRaised: false,
  477. /*
  478. * Whether the local participant is the dominant speaker in the conference.
  479. */
  480. isDominantSpeaker: false,
  481. /**
  482. * Open new connection and join to the conference.
  483. * @param {object} options
  484. * @param {string} roomName name of the conference
  485. * @returns {Promise}
  486. */
  487. init(options) {
  488. this.roomName = options.roomName;
  489. // attaches global error handler, if there is already one, respect it
  490. if(JitsiMeetJS.getGlobalOnErrorHandler){
  491. var oldOnErrorHandler = window.onerror;
  492. window.onerror = function (message, source, lineno, colno, error) {
  493. JitsiMeetJS.getGlobalOnErrorHandler(
  494. message, source, lineno, colno, error);
  495. if(oldOnErrorHandler)
  496. oldOnErrorHandler(message, source, lineno, colno, error);
  497. };
  498. var oldOnUnhandledRejection = window.onunhandledrejection;
  499. window.onunhandledrejection = function(event) {
  500. JitsiMeetJS.getGlobalOnErrorHandler(
  501. null, null, null, null, event.reason);
  502. if(oldOnUnhandledRejection)
  503. oldOnUnhandledRejection(event);
  504. };
  505. }
  506. return JitsiMeetJS.init(
  507. Object.assign(
  508. {enableAnalyticsLogging: analytics.isEnabled()}, config)
  509. ).then(() => {
  510. analytics.init();
  511. return createInitialLocalTracksAndConnect(options.roomName);
  512. }).then(([tracks, con]) => {
  513. logger.log('initialized with %s local tracks', tracks.length);
  514. con.addEventListener(
  515. ConnectionEvents.CONNECTION_FAILED,
  516. _connectionFailedHandler);
  517. APP.connection = connection = con;
  518. this.isDesktopSharingEnabled =
  519. JitsiMeetJS.isDesktopSharingEnabled();
  520. APP.remoteControl.init();
  521. this._createRoom(tracks);
  522. if (UIUtil.isButtonEnabled('contacts')
  523. && !interfaceConfig.filmStripOnly) {
  524. APP.UI.ContactList = new ContactList(room);
  525. }
  526. // if user didn't give access to mic or camera or doesn't have
  527. // them at all, we disable corresponding toolbar buttons
  528. if (!tracks.find((t) => t.isAudioTrack())) {
  529. APP.UI.setMicrophoneButtonEnabled(false);
  530. }
  531. if (!tracks.find((t) => t.isVideoTrack())) {
  532. APP.UI.setCameraButtonEnabled(false);
  533. }
  534. this._initDeviceList();
  535. if (config.iAmRecorder)
  536. this.recorder = new Recorder();
  537. // XXX The API will take care of disconnecting from the XMPP
  538. // server (and, thus, leaving the room) on unload.
  539. return new Promise((resolve, reject) => {
  540. (new ConferenceConnector(
  541. resolve, reject, this.invite)).connect();
  542. });
  543. });
  544. },
  545. /**
  546. * Check if id is id of the local user.
  547. * @param {string} id id to check
  548. * @returns {boolean}
  549. */
  550. isLocalId (id) {
  551. return this.getMyUserId() === id;
  552. },
  553. /**
  554. * Simulates toolbar button click for audio mute. Used by shortcuts and API.
  555. * @param mute true for mute and false for unmute.
  556. */
  557. muteAudio (mute) {
  558. muteLocalAudio(mute);
  559. },
  560. /**
  561. * Returns whether local audio is muted or not.
  562. * @returns {boolean}
  563. */
  564. isLocalAudioMuted() {
  565. return this.audioMuted;
  566. },
  567. /**
  568. * Simulates toolbar button click for audio mute. Used by shortcuts and API.
  569. */
  570. toggleAudioMuted () {
  571. this.muteAudio(!this.audioMuted);
  572. },
  573. /**
  574. * Simulates toolbar button click for video mute. Used by shortcuts and API.
  575. * @param mute true for mute and false for unmute.
  576. */
  577. muteVideo (mute) {
  578. muteLocalVideo(mute);
  579. },
  580. /**
  581. * Simulates toolbar button click for video mute. Used by shortcuts and API.
  582. */
  583. toggleVideoMuted () {
  584. this.muteVideo(!this.videoMuted);
  585. },
  586. /**
  587. * Retrieve list of conference participants (without local user).
  588. * @returns {JitsiParticipant[]}
  589. */
  590. listMembers () {
  591. return room.getParticipants();
  592. },
  593. /**
  594. * Retrieve list of ids of conference participants (without local user).
  595. * @returns {string[]}
  596. */
  597. listMembersIds () {
  598. return room.getParticipants().map(p => p.getId());
  599. },
  600. /**
  601. * Checks whether the participant identified by id is a moderator.
  602. * @id id to search for participant
  603. * @return {boolean} whether the participant is moderator
  604. */
  605. isParticipantModerator (id) {
  606. let user = room.getParticipantById(id);
  607. return user && user.isModerator();
  608. },
  609. /**
  610. * Check if SIP is supported.
  611. * @returns {boolean}
  612. */
  613. sipGatewayEnabled () {
  614. return room.isSIPCallingSupported();
  615. },
  616. get membersCount () {
  617. return room.getParticipants().length + 1;
  618. },
  619. /**
  620. * Returns true if the callstats integration is enabled, otherwise returns
  621. * false.
  622. *
  623. * @returns true if the callstats integration is enabled, otherwise returns
  624. * false.
  625. */
  626. isCallstatsEnabled () {
  627. return room && room.isCallstatsEnabled();
  628. },
  629. /**
  630. * Sends the given feedback through CallStats if enabled.
  631. *
  632. * @param overallFeedback an integer between 1 and 5 indicating the
  633. * user feedback
  634. * @param detailedFeedback detailed feedback from the user. Not yet used
  635. */
  636. sendFeedback (overallFeedback, detailedFeedback) {
  637. return room.sendFeedback (overallFeedback, detailedFeedback);
  638. },
  639. /**
  640. * Returns the connection times stored in the library.
  641. */
  642. getConnectionTimes () {
  643. return this._room.getConnectionTimes();
  644. },
  645. // used by torture currently
  646. isJoined () {
  647. return this._room
  648. && this._room.isJoined();
  649. },
  650. getConnectionState () {
  651. return this._room
  652. && this._room.getConnectionState();
  653. },
  654. /**
  655. * Checks whether or not our connection is currently in interrupted and
  656. * reconnect attempts are in progress.
  657. *
  658. * @returns {boolean} true if the connection is in interrupted state or
  659. * false otherwise.
  660. */
  661. isConnectionInterrupted () {
  662. return this._room.isConnectionInterrupted();
  663. },
  664. /**
  665. * Finds JitsiParticipant for given id.
  666. *
  667. * @param {string} id participant's identifier(MUC nickname).
  668. *
  669. * @returns {JitsiParticipant|null} participant instance for given id or
  670. * null if not found.
  671. */
  672. getParticipantById (id) {
  673. return room ? room.getParticipantById(id) : null;
  674. },
  675. /**
  676. * Checks whether the user identified by given id is currently connected.
  677. *
  678. * @param {string} id participant's identifier(MUC nickname)
  679. *
  680. * @returns {boolean|null} true if participant's connection is ok or false
  681. * if the user is having connectivity issues.
  682. */
  683. isParticipantConnectionActive (id) {
  684. let participant = this.getParticipantById(id);
  685. return participant ? participant.isConnectionActive() : null;
  686. },
  687. /**
  688. * Gets the display name foe the <tt>JitsiParticipant</tt> identified by
  689. * the given <tt>id</tt>.
  690. *
  691. * @param id {string} the participant's id(MUC nickname/JVB endpoint id)
  692. *
  693. * @return {string} the participant's display name or the default string if
  694. * absent.
  695. */
  696. getParticipantDisplayName (id) {
  697. let displayName = getDisplayName(id);
  698. if (displayName) {
  699. return displayName;
  700. } else {
  701. if (APP.conference.isLocalId(id)) {
  702. return APP.translation.generateTranslationHTML(
  703. interfaceConfig.DEFAULT_LOCAL_DISPLAY_NAME);
  704. } else {
  705. return interfaceConfig.DEFAULT_REMOTE_DISPLAY_NAME;
  706. }
  707. }
  708. },
  709. getMyUserId () {
  710. return this._room
  711. && this._room.myUserId();
  712. },
  713. /**
  714. * Indicates if recording is supported in this conference.
  715. */
  716. isRecordingSupported() {
  717. return this._room && this._room.isRecordingSupported();
  718. },
  719. /**
  720. * Returns the recording state or undefined if the room is not defined.
  721. */
  722. getRecordingState() {
  723. return (this._room) ? this._room.getRecordingState() : undefined;
  724. },
  725. /**
  726. * Will be filled with values only when config.debug is enabled.
  727. * Its used by torture to check audio levels.
  728. */
  729. audioLevelsMap: {},
  730. /**
  731. * Returns the stored audio level (stored only if config.debug is enabled)
  732. * @param id the id for the user audio level to return (the id value is
  733. * returned for the participant using getMyUserId() method)
  734. */
  735. getPeerSSRCAudioLevel (id) {
  736. return this.audioLevelsMap[id];
  737. },
  738. /**
  739. * @return {number} the number of participants in the conference with at
  740. * least one track.
  741. */
  742. getNumberOfParticipantsWithTracks() {
  743. return this._room.getParticipants()
  744. .filter((p) => p.getTracks().length > 0)
  745. .length;
  746. },
  747. /**
  748. * Returns the stats.
  749. */
  750. getStats() {
  751. return room.connectionQuality.getStats();
  752. },
  753. // end used by torture
  754. getLogs () {
  755. return room.getLogs();
  756. },
  757. /**
  758. * Download logs, a function that can be called from console while
  759. * debugging.
  760. * @param filename (optional) specify target filename
  761. */
  762. saveLogs (filename = 'meetlog.json') {
  763. // this can be called from console and will not have reference to this
  764. // that's why we reference the global var
  765. let logs = APP.conference.getLogs();
  766. let data = encodeURIComponent(JSON.stringify(logs, null, ' '));
  767. let elem = document.createElement('a');
  768. elem.download = filename;
  769. elem.href = 'data:application/json;charset=utf-8,\n' + data;
  770. elem.dataset.downloadurl
  771. = ['text/json', elem.download, elem.href].join(':');
  772. elem.dispatchEvent(new MouseEvent('click', {
  773. view: window,
  774. bubbles: true,
  775. cancelable: false
  776. }));
  777. },
  778. /**
  779. * Exposes a Command(s) API on this instance. It is necessitated by (1) the
  780. * desire to keep room private to this instance and (2) the need of other
  781. * modules to send and receive commands to and from participants.
  782. * Eventually, this instance remains in control with respect to the
  783. * decision whether the Command(s) API of room (i.e. lib-jitsi-meet's
  784. * JitsiConference) is to be used in the implementation of the Command(s)
  785. * API of this instance.
  786. */
  787. commands: {
  788. /**
  789. * Known custom conference commands.
  790. */
  791. defaults: commands,
  792. /**
  793. * Receives notifications from other participants about commands aka
  794. * custom events (sent by sendCommand or sendCommandOnce methods).
  795. * @param command {String} the name of the command
  796. * @param handler {Function} handler for the command
  797. */
  798. addCommandListener () {
  799. room.addCommandListener.apply(room, arguments);
  800. },
  801. /**
  802. * Removes command.
  803. * @param name {String} the name of the command.
  804. */
  805. removeCommand () {
  806. room.removeCommand.apply(room, arguments);
  807. },
  808. /**
  809. * Sends command.
  810. * @param name {String} the name of the command.
  811. * @param values {Object} with keys and values that will be sent.
  812. */
  813. sendCommand () {
  814. room.sendCommand.apply(room, arguments);
  815. },
  816. /**
  817. * Sends command one time.
  818. * @param name {String} the name of the command.
  819. * @param values {Object} with keys and values that will be sent.
  820. */
  821. sendCommandOnce () {
  822. room.sendCommandOnce.apply(room, arguments);
  823. }
  824. },
  825. _createRoom (localTracks) {
  826. room = connection.initJitsiConference(APP.conference.roomName,
  827. this._getConferenceOptions());
  828. this._setLocalAudioVideoStreams(localTracks);
  829. this.invite = new Invite(room);
  830. this._room = room; // FIXME do not use this
  831. _setupLocalParticipantProperties();
  832. this._setupListeners();
  833. },
  834. /**
  835. * Sets local video and audio streams.
  836. * @param {JitsiLocalTrack[]} tracks=[]
  837. * @returns {Promise[]}
  838. * @private
  839. */
  840. _setLocalAudioVideoStreams(tracks = []) {
  841. return tracks.map(track => {
  842. if (track.isAudioTrack()) {
  843. return this.useAudioStream(track);
  844. } else if (track.isVideoTrack()) {
  845. return this.useVideoStream(track);
  846. } else {
  847. logger.error(
  848. "Ignored not an audio nor a video track: ", track);
  849. return Promise.resolve();
  850. }
  851. });
  852. },
  853. _getConferenceOptions() {
  854. let options = config;
  855. if(config.enableRecording && !config.recordingType) {
  856. options.recordingType = (config.hosts &&
  857. (typeof config.hosts.jirecon != "undefined"))?
  858. "jirecon" : "colibri";
  859. }
  860. return options;
  861. },
  862. /**
  863. * Start using provided video stream.
  864. * Stops previous video stream.
  865. * @param {JitsiLocalTrack} [stream] new stream to use or null
  866. * @returns {Promise}
  867. */
  868. useVideoStream (newStream) {
  869. return room.replaceTrack(localVideo, newStream)
  870. .then(() => {
  871. // We call dispose after doing the replace because
  872. // dispose will try and do a new o/a after the
  873. // track removes itself. Doing it after means
  874. // the JitsiLocalTrack::conference member is already
  875. // cleared, so it won't try and do the o/a
  876. if (localVideo) {
  877. localVideo.dispose();
  878. }
  879. localVideo = newStream;
  880. if (newStream) {
  881. this.videoMuted = newStream.isMuted();
  882. this.isSharingScreen = newStream.videoType === 'desktop';
  883. APP.UI.addLocalStream(newStream);
  884. newStream.videoType === 'camera'
  885. && APP.UI.setCameraButtonEnabled(true);
  886. } else {
  887. this.videoMuted = false;
  888. this.isSharingScreen = false;
  889. }
  890. APP.UI.setVideoMuted(this.getMyUserId(), this.videoMuted);
  891. APP.UI.updateDesktopSharingButtons();
  892. });
  893. },
  894. /**
  895. * Start using provided audio stream.
  896. * Stops previous audio stream.
  897. * @param {JitsiLocalTrack} [stream] new stream to use or null
  898. * @returns {Promise}
  899. */
  900. useAudioStream (newStream) {
  901. return room.replaceTrack(localAudio, newStream)
  902. .then(() => {
  903. // We call dispose after doing the replace because
  904. // dispose will try and do a new o/a after the
  905. // track removes itself. Doing it after means
  906. // the JitsiLocalTrack::conference member is already
  907. // cleared, so it won't try and do the o/a
  908. if (localAudio) {
  909. localAudio.dispose();
  910. }
  911. localAudio = newStream;
  912. if (newStream) {
  913. this.audioMuted = newStream.isMuted();
  914. APP.UI.addLocalStream(newStream);
  915. } else {
  916. this.audioMuted = false;
  917. }
  918. APP.UI.setMicrophoneButtonEnabled(true);
  919. APP.UI.setAudioMuted(this.getMyUserId(), this.audioMuted);
  920. });
  921. },
  922. videoSwitchInProgress: false,
  923. toggleScreenSharing (shareScreen = !this.isSharingScreen) {
  924. if (this.videoSwitchInProgress) {
  925. logger.warn("Switch in progress.");
  926. return;
  927. }
  928. if (!this.isDesktopSharingEnabled) {
  929. logger.warn("Cannot toggle screen sharing: not supported.");
  930. return;
  931. }
  932. this.videoSwitchInProgress = true;
  933. let externalInstallation = false;
  934. if (shareScreen) {
  935. this.screenSharingPromise = createLocalTracks({
  936. devices: ['desktop'],
  937. desktopSharingExtensionExternalInstallation: {
  938. interval: 500,
  939. checkAgain: () => {
  940. return DSExternalInstallationInProgress;
  941. },
  942. listener: (status, url) => {
  943. switch(status) {
  944. case "waitingForExtension":
  945. DSExternalInstallationInProgress = true;
  946. externalInstallation = true;
  947. APP.UI.showExtensionExternalInstallationDialog(
  948. url);
  949. break;
  950. case "extensionFound":
  951. if(externalInstallation) //close the dialog
  952. $.prompt.close();
  953. break;
  954. default:
  955. //Unknown status
  956. }
  957. }
  958. }
  959. }).then(([stream]) => {
  960. DSExternalInstallationInProgress = false;
  961. // close external installation dialog on success.
  962. if(externalInstallation)
  963. $.prompt.close();
  964. stream.on(
  965. TrackEvents.LOCAL_TRACK_STOPPED,
  966. () => {
  967. // if stream was stopped during screensharing session
  968. // then we should switch to video
  969. // otherwise we stopped it because we already switched
  970. // to video, so nothing to do here
  971. if (this.isSharingScreen) {
  972. this.toggleScreenSharing(false);
  973. }
  974. }
  975. );
  976. return this.useVideoStream(stream);
  977. }).then(() => {
  978. this.videoSwitchInProgress = false;
  979. JitsiMeetJS.analytics.sendEvent(
  980. 'conference.sharingDesktop.start');
  981. logger.log('sharing local desktop');
  982. }).catch((err) => {
  983. // close external installation dialog to show the error.
  984. if(externalInstallation)
  985. $.prompt.close();
  986. this.videoSwitchInProgress = false;
  987. this.toggleScreenSharing(false);
  988. if (err.name === TrackErrors.CHROME_EXTENSION_USER_CANCELED) {
  989. return;
  990. }
  991. logger.error('failed to share local desktop', err);
  992. if (err.name === TrackErrors.FIREFOX_EXTENSION_NEEDED) {
  993. APP.UI.showExtensionRequiredDialog(
  994. config.desktopSharingFirefoxExtensionURL
  995. );
  996. return;
  997. }
  998. // Handling:
  999. // TrackErrors.PERMISSION_DENIED
  1000. // TrackErrors.CHROME_EXTENSION_INSTALLATION_ERROR
  1001. // TrackErrors.GENERAL
  1002. // and any other
  1003. let dialogTxt;
  1004. let dialogTitleKey;
  1005. if (err.name === TrackErrors.PERMISSION_DENIED) {
  1006. dialogTxt = APP.translation.generateTranslationHTML(
  1007. "dialog.screenSharingPermissionDeniedError");
  1008. dialogTitleKey = "dialog.error";
  1009. } else {
  1010. dialogTxt = APP.translation.generateTranslationHTML(
  1011. "dialog.failtoinstall");
  1012. dialogTitleKey = "dialog.permissionDenied";
  1013. }
  1014. APP.UI.messageHandler.openDialog(
  1015. dialogTitleKey, dialogTxt, false);
  1016. });
  1017. } else {
  1018. APP.remoteControl.receiver.stop();
  1019. this.screenSharingPromise = createLocalTracks(
  1020. { devices: ['video'] })
  1021. .then(
  1022. ([stream]) => this.useVideoStream(stream)
  1023. ).then(() => {
  1024. this.videoSwitchInProgress = false;
  1025. JitsiMeetJS.analytics.sendEvent(
  1026. 'conference.sharingDesktop.stop');
  1027. logger.log('sharing local video');
  1028. }).catch((err) => {
  1029. this.useVideoStream(null);
  1030. this.videoSwitchInProgress = false;
  1031. logger.error('failed to share local video', err);
  1032. });
  1033. }
  1034. },
  1035. /**
  1036. * Setup interaction between conference and UI.
  1037. */
  1038. _setupListeners () {
  1039. // add local streams when joined to the conference
  1040. room.on(ConferenceEvents.CONFERENCE_JOINED, () => {
  1041. APP.store.dispatch(conferenceJoined(room));
  1042. APP.UI.mucJoined();
  1043. APP.API.notifyConferenceJoined(APP.conference.roomName);
  1044. APP.UI.markVideoInterrupted(false);
  1045. });
  1046. room.on(
  1047. ConferenceEvents.CONFERENCE_LEFT,
  1048. (...args) => APP.store.dispatch(conferenceLeft(room, ...args)));
  1049. room.on(
  1050. ConferenceEvents.AUTH_STATUS_CHANGED,
  1051. function (authEnabled, authLogin) {
  1052. APP.UI.updateAuthInfo(authEnabled, authLogin);
  1053. }
  1054. );
  1055. room.on(ConferenceEvents.PARTCIPANT_FEATURES_CHANGED,
  1056. user => APP.UI.onUserFeaturesChanged(user));
  1057. room.on(ConferenceEvents.USER_JOINED, (id, user) => {
  1058. if (user.isHidden())
  1059. return;
  1060. APP.store.dispatch(participantJoined({
  1061. id,
  1062. name: user.getDisplayName(),
  1063. role: user.getRole()
  1064. }));
  1065. logger.log('USER %s connnected', id, user);
  1066. APP.API.notifyUserJoined(id);
  1067. APP.UI.addUser(user);
  1068. // check the roles for the new user and reflect them
  1069. APP.UI.updateUserRole(user);
  1070. });
  1071. room.on(ConferenceEvents.USER_LEFT, (id, user) => {
  1072. APP.store.dispatch(participantLeft(id, user));
  1073. logger.log('USER %s LEFT', id, user);
  1074. APP.API.notifyUserLeft(id);
  1075. APP.UI.removeUser(id, user.getDisplayName());
  1076. APP.UI.onSharedVideoStop(id);
  1077. });
  1078. room.on(ConferenceEvents.USER_ROLE_CHANGED, (id, role) => {
  1079. APP.store.dispatch(participantRoleChanged(id, role));
  1080. if (this.isLocalId(id)) {
  1081. logger.info(`My role changed, new role: ${role}`);
  1082. if (this.isModerator !== room.isModerator()) {
  1083. this.isModerator = room.isModerator();
  1084. APP.UI.updateLocalRole(room.isModerator());
  1085. }
  1086. } else {
  1087. let user = room.getParticipantById(id);
  1088. if (user) {
  1089. APP.UI.updateUserRole(user);
  1090. }
  1091. }
  1092. });
  1093. room.on(ConferenceEvents.TRACK_ADDED, (track) => {
  1094. if(!track || track.isLocal())
  1095. return;
  1096. track.on(TrackEvents.TRACK_VIDEOTYPE_CHANGED, (type) => {
  1097. APP.UI.onPeerVideoTypeChanged(track.getParticipantId(), type);
  1098. });
  1099. APP.UI.addRemoteStream(track);
  1100. });
  1101. room.on(ConferenceEvents.TRACK_REMOVED, (track) => {
  1102. if(!track || track.isLocal())
  1103. return;
  1104. APP.UI.removeRemoteStream(track);
  1105. });
  1106. room.on(ConferenceEvents.TRACK_MUTE_CHANGED, (track) => {
  1107. if(!track)
  1108. return;
  1109. const handler = (track.getType() === "audio")?
  1110. APP.UI.setAudioMuted : APP.UI.setVideoMuted;
  1111. let id;
  1112. const mute = track.isMuted();
  1113. if(track.isLocal()){
  1114. id = APP.conference.getMyUserId();
  1115. if(track.getType() === "audio") {
  1116. this.audioMuted = mute;
  1117. } else {
  1118. this.videoMuted = mute;
  1119. }
  1120. } else {
  1121. id = track.getParticipantId();
  1122. }
  1123. handler(id , mute);
  1124. });
  1125. room.on(ConferenceEvents.TRACK_AUDIO_LEVEL_CHANGED, (id, lvl) => {
  1126. if(this.isLocalId(id) && localAudio && localAudio.isMuted()) {
  1127. lvl = 0;
  1128. }
  1129. if(config.debug)
  1130. {
  1131. this.audioLevelsMap[id] = lvl;
  1132. if(config.debugAudioLevels)
  1133. logger.log("AudioLevel:" + id + "/" + lvl);
  1134. }
  1135. APP.UI.setAudioLevel(id, lvl);
  1136. });
  1137. room.on(ConferenceEvents.TALK_WHILE_MUTED, () => {
  1138. APP.UI.showToolbar(6000);
  1139. APP.UI.showCustomToolbarPopup('#talkWhileMutedPopup', true, 5000);
  1140. });
  1141. /*
  1142. room.on(ConferenceEvents.IN_LAST_N_CHANGED, (inLastN) => {
  1143. //FIXME
  1144. if (config.muteLocalVideoIfNotInLastN) {
  1145. // TODO mute or unmute if required
  1146. // mark video on UI
  1147. // APP.UI.markVideoMuted(true/false);
  1148. }
  1149. });
  1150. */
  1151. room.on(
  1152. ConferenceEvents.LAST_N_ENDPOINTS_CHANGED, (ids, enteringIds) => {
  1153. APP.UI.handleLastNEndpoints(ids, enteringIds);
  1154. });
  1155. room.on(
  1156. ConferenceEvents.PARTICIPANT_CONN_STATUS_CHANGED,
  1157. (id, isActive) => {
  1158. APP.UI.participantConnectionStatusChanged(id, isActive);
  1159. });
  1160. room.on(ConferenceEvents.DOMINANT_SPEAKER_CHANGED, (id) => {
  1161. if (this.isLocalId(id)) {
  1162. this.isDominantSpeaker = true;
  1163. this.setRaisedHand(false);
  1164. } else {
  1165. this.isDominantSpeaker = false;
  1166. var participant = room.getParticipantById(id);
  1167. if (participant) {
  1168. APP.UI.setRaisedHandStatus(participant, false);
  1169. }
  1170. }
  1171. APP.UI.markDominantSpeaker(id);
  1172. });
  1173. if (!interfaceConfig.filmStripOnly) {
  1174. room.on(ConferenceEvents.CONNECTION_INTERRUPTED, () => {
  1175. APP.UI.markVideoInterrupted(true);
  1176. });
  1177. room.on(ConferenceEvents.CONNECTION_RESTORED, () => {
  1178. APP.UI.markVideoInterrupted(false);
  1179. });
  1180. room.on(ConferenceEvents.MESSAGE_RECEIVED, (id, text, ts) => {
  1181. let nick = getDisplayName(id);
  1182. APP.API.notifyReceivedChatMessage(id, nick, text, ts);
  1183. APP.UI.addMessage(id, nick, text, ts);
  1184. });
  1185. APP.UI.addListener(UIEvents.MESSAGE_CREATED, (message) => {
  1186. APP.API.notifySendingChatMessage(message);
  1187. room.sendTextMessage(message);
  1188. });
  1189. APP.UI.addListener(UIEvents.SELECTED_ENDPOINT, (id) => {
  1190. try {
  1191. // do not try to select participant if there is none (we
  1192. // are alone in the room), otherwise an error will be
  1193. // thrown cause reporting mechanism is not available
  1194. // (datachannels currently)
  1195. if (room.getParticipants().length === 0)
  1196. return;
  1197. room.selectParticipant(id);
  1198. } catch (e) {
  1199. JitsiMeetJS.analytics.sendEvent(
  1200. 'selectParticipant.failed');
  1201. reportError(e);
  1202. }
  1203. });
  1204. APP.UI.addListener(UIEvents.PINNED_ENDPOINT,
  1205. (smallVideo, isPinned) => {
  1206. let smallVideoId = smallVideo.getId();
  1207. let isLocal = APP.conference.isLocalId(smallVideoId);
  1208. let eventName
  1209. = (isPinned ? "pinned" : "unpinned") + "." +
  1210. (isLocal ? "local" : "remote");
  1211. let participantCount = room.getParticipantCount();
  1212. JitsiMeetJS.analytics.sendEvent(
  1213. eventName,
  1214. { value: participantCount });
  1215. // FIXME why VIDEO_CONTAINER_TYPE instead of checking if
  1216. // the participant is on the large video ?
  1217. if (smallVideo.getVideoType() === VIDEO_CONTAINER_TYPE
  1218. && !isLocal) {
  1219. // When the library starts supporting multiple pins we
  1220. // would pass the isPinned parameter together with the
  1221. // identifier, but currently we send null to indicate that
  1222. // we unpin the last pinned.
  1223. try {
  1224. room.pinParticipant(isPinned ? smallVideoId : null);
  1225. } catch (e) {
  1226. reportError(e);
  1227. }
  1228. }
  1229. });
  1230. }
  1231. room.on(ConferenceEvents.CONNECTION_INTERRUPTED, () => {
  1232. APP.UI.showLocalConnectionInterrupted(true);
  1233. });
  1234. room.on(ConferenceEvents.CONNECTION_RESTORED, () => {
  1235. APP.UI.showLocalConnectionInterrupted(false);
  1236. });
  1237. room.on(ConferenceEvents.DISPLAY_NAME_CHANGED, (id, displayName) => {
  1238. const formattedDisplayName
  1239. = displayName.substr(0, MAX_DISPLAY_NAME_LENGTH);
  1240. APP.API.notifyDisplayNameChanged(id, formattedDisplayName);
  1241. APP.UI.changeDisplayName(id, formattedDisplayName);
  1242. });
  1243. room.on(ConferenceEvents.PARTICIPANT_PROPERTY_CHANGED,
  1244. (participant, name, oldValue, newValue) => {
  1245. if (name === "raisedHand") {
  1246. APP.UI.setRaisedHandStatus(participant, newValue);
  1247. }
  1248. });
  1249. room.on(ConferenceEvents.RECORDER_STATE_CHANGED, (status, error) => {
  1250. logger.log("Received recorder status change: ", status, error);
  1251. APP.UI.updateRecordingState(status);
  1252. });
  1253. room.on(ConferenceEvents.KICKED, () => {
  1254. APP.UI.hideStats();
  1255. APP.UI.notifyKicked();
  1256. // FIXME close
  1257. });
  1258. room.on(ConferenceEvents.SUSPEND_DETECTED, () => {
  1259. APP.store.dispatch(suspendDetected());
  1260. // After wake up, we will be in a state where conference is left
  1261. // there will be dialog shown to user.
  1262. // We do not want video/audio as we show an overlay and after it
  1263. // user need to rejoin or close, while waking up we can detect
  1264. // camera wakeup as a problem with device.
  1265. // We also do not care about device change, which happens
  1266. // on resume after suspending PC.
  1267. if (this.deviceChangeListener)
  1268. JitsiMeetJS.mediaDevices.removeEventListener(
  1269. JitsiMeetJS.events.mediaDevices.DEVICE_LIST_CHANGED,
  1270. this.deviceChangeListener);
  1271. // stop local video
  1272. if (localVideo) {
  1273. localVideo.dispose();
  1274. }
  1275. // stop local audio
  1276. if (localAudio) {
  1277. localAudio.dispose();
  1278. }
  1279. });
  1280. room.on(ConferenceEvents.DTMF_SUPPORT_CHANGED, (isDTMFSupported) => {
  1281. APP.UI.updateDTMFSupport(isDTMFSupported);
  1282. });
  1283. APP.UI.addListener(UIEvents.EXTERNAL_INSTALLATION_CANCELED, () => {
  1284. // Wait a little bit more just to be sure that we won't miss the
  1285. // extension installation
  1286. setTimeout(() => DSExternalInstallationInProgress = false, 500);
  1287. });
  1288. APP.UI.addListener(UIEvents.OPEN_EXTENSION_STORE, (url) => {
  1289. window.open(
  1290. url, "extension_store_window",
  1291. "resizable,scrollbars=yes,status=1");
  1292. });
  1293. APP.UI.addListener(UIEvents.AUDIO_MUTED, muteLocalAudio);
  1294. APP.UI.addListener(UIEvents.VIDEO_MUTED, muteLocalVideo);
  1295. room.on(ConnectionQualityEvents.LOCAL_STATS_UPDATED,
  1296. (stats) => {
  1297. APP.UI.updateLocalStats(stats.connectionQuality, stats);
  1298. });
  1299. room.on(ConnectionQualityEvents.REMOTE_STATS_UPDATED,
  1300. (id, stats) => {
  1301. APP.UI.updateRemoteStats(id, stats.connectionQuality, stats);
  1302. });
  1303. room.addCommandListener(this.commands.defaults.ETHERPAD, ({value}) => {
  1304. APP.UI.initEtherpad(value);
  1305. });
  1306. APP.UI.addListener(UIEvents.EMAIL_CHANGED, this.changeLocalEmail);
  1307. room.addCommandListener(this.commands.defaults.EMAIL, (data, from) => {
  1308. APP.store.dispatch(changeParticipantEmail(from, data.value));
  1309. APP.UI.setUserEmail(from, data.value);
  1310. });
  1311. room.addCommandListener(
  1312. this.commands.defaults.AVATAR_URL,
  1313. (data, from) => {
  1314. APP.store.dispatch(
  1315. changeParticipantAvatarURL(from, data.value));
  1316. APP.UI.setUserAvatarUrl(from, data.value);
  1317. });
  1318. room.addCommandListener(this.commands.defaults.AVATAR_ID,
  1319. (data, from) => {
  1320. APP.store.dispatch(
  1321. changeParticipantAvatarID(from, data.value));
  1322. APP.UI.setUserAvatarID(from, data.value);
  1323. });
  1324. APP.UI.addListener(UIEvents.NICKNAME_CHANGED, changeLocalDisplayName);
  1325. APP.UI.addListener(UIEvents.START_MUTED_CHANGED,
  1326. (startAudioMuted, startVideoMuted) => {
  1327. room.setStartMutedPolicy({
  1328. audio: startAudioMuted,
  1329. video: startVideoMuted
  1330. });
  1331. }
  1332. );
  1333. room.on(
  1334. ConferenceEvents.START_MUTED_POLICY_CHANGED,
  1335. ({ audio, video }) => {
  1336. APP.UI.onStartMutedChanged(audio, video);
  1337. }
  1338. );
  1339. room.on(ConferenceEvents.STARTED_MUTED, () => {
  1340. (room.isStartAudioMuted() || room.isStartVideoMuted())
  1341. && APP.UI.notifyInitiallyMuted();
  1342. });
  1343. room.on(
  1344. ConferenceEvents.AVAILABLE_DEVICES_CHANGED, function (id, devices) {
  1345. APP.UI.updateDevicesAvailability(id, devices);
  1346. }
  1347. );
  1348. // call hangup
  1349. APP.UI.addListener(UIEvents.HANGUP, () => {
  1350. this.hangup(true);
  1351. });
  1352. // logout
  1353. APP.UI.addListener(UIEvents.LOGOUT, () => {
  1354. AuthHandler.logout(room).then(url => {
  1355. if (url) {
  1356. UIUtil.redirect(url);
  1357. } else {
  1358. this.hangup(true);
  1359. }
  1360. });
  1361. });
  1362. APP.UI.addListener(UIEvents.SIP_DIAL, (sipNumber) => {
  1363. room.dial(sipNumber);
  1364. });
  1365. APP.UI.addListener(UIEvents.RESOLUTION_CHANGED,
  1366. (id, oldResolution, newResolution, delay) => {
  1367. var logObject = {
  1368. id: "resolution_change",
  1369. participant: id,
  1370. oldValue: oldResolution,
  1371. newValue: newResolution,
  1372. delay: delay
  1373. };
  1374. room.sendApplicationLog(JSON.stringify(logObject));
  1375. // We only care about the delay between simulcast streams.
  1376. // Longer delays will be caused by something else and will just
  1377. // poison the data.
  1378. if (delay < 2000) {
  1379. JitsiMeetJS.analytics.sendEvent('stream.switch.delay',
  1380. {value: delay});
  1381. }
  1382. });
  1383. // Starts or stops the recording for the conference.
  1384. APP.UI.addListener(UIEvents.RECORDING_TOGGLED, (options) => {
  1385. room.toggleRecording(options);
  1386. });
  1387. APP.UI.addListener(UIEvents.SUBJECT_CHANGED, (topic) => {
  1388. room.setSubject(topic);
  1389. });
  1390. room.on(ConferenceEvents.SUBJECT_CHANGED, function (subject) {
  1391. APP.UI.setSubject(subject);
  1392. });
  1393. APP.UI.addListener(UIEvents.USER_KICKED, (id) => {
  1394. room.kickParticipant(id);
  1395. });
  1396. APP.UI.addListener(UIEvents.REMOTE_AUDIO_MUTED, (id) => {
  1397. room.muteParticipant(id);
  1398. });
  1399. APP.UI.addListener(UIEvents.AUTH_CLICKED, () => {
  1400. AuthHandler.authenticate(room);
  1401. });
  1402. APP.UI.addListener(
  1403. UIEvents.VIDEO_DEVICE_CHANGED,
  1404. (cameraDeviceId) => {
  1405. JitsiMeetJS.analytics.sendEvent('settings.changeDevice.video');
  1406. createLocalTracks({
  1407. devices: ['video'],
  1408. cameraDeviceId: cameraDeviceId,
  1409. micDeviceId: null
  1410. })
  1411. .then(([stream]) => {
  1412. this.useVideoStream(stream);
  1413. logger.log('switched local video device');
  1414. APP.settings.setCameraDeviceId(cameraDeviceId, true);
  1415. })
  1416. .catch((err) => {
  1417. APP.UI.showDeviceErrorDialog(null, err);
  1418. APP.UI.setSelectedCameraFromSettings();
  1419. });
  1420. }
  1421. );
  1422. APP.UI.addListener(
  1423. UIEvents.AUDIO_DEVICE_CHANGED,
  1424. (micDeviceId) => {
  1425. JitsiMeetJS.analytics.sendEvent(
  1426. 'settings.changeDevice.audioIn');
  1427. createLocalTracks({
  1428. devices: ['audio'],
  1429. cameraDeviceId: null,
  1430. micDeviceId: micDeviceId
  1431. })
  1432. .then(([stream]) => {
  1433. this.useAudioStream(stream);
  1434. logger.log('switched local audio device');
  1435. APP.settings.setMicDeviceId(micDeviceId, true);
  1436. })
  1437. .catch((err) => {
  1438. APP.UI.showDeviceErrorDialog(err, null);
  1439. APP.UI.setSelectedMicFromSettings();
  1440. });
  1441. }
  1442. );
  1443. APP.UI.addListener(
  1444. UIEvents.AUDIO_OUTPUT_DEVICE_CHANGED,
  1445. (audioOutputDeviceId) => {
  1446. JitsiMeetJS.analytics.sendEvent(
  1447. 'settings.changeDevice.audioOut');
  1448. APP.settings.setAudioOutputDeviceId(audioOutputDeviceId)
  1449. .then(() => logger.log('changed audio output device'))
  1450. .catch((err) => {
  1451. logger.warn('Failed to change audio output device. ' +
  1452. 'Default or previously set audio output device ' +
  1453. 'will be used instead.', err);
  1454. APP.UI.setSelectedAudioOutputFromSettings();
  1455. });
  1456. }
  1457. );
  1458. APP.UI.addListener(
  1459. UIEvents.TOGGLE_SCREENSHARING, this.toggleScreenSharing.bind(this)
  1460. );
  1461. APP.UI.addListener(UIEvents.UPDATE_SHARED_VIDEO,
  1462. (url, state, time, isMuted, volume) => {
  1463. // send start and stop commands once, and remove any updates
  1464. // that had left
  1465. if (state === 'stop' || state === 'start' || state === 'playing') {
  1466. room.removeCommand(this.commands.defaults.SHARED_VIDEO);
  1467. room.sendCommandOnce(this.commands.defaults.SHARED_VIDEO, {
  1468. value: url,
  1469. attributes: {
  1470. state: state,
  1471. time: time,
  1472. muted: isMuted,
  1473. volume: volume
  1474. }
  1475. });
  1476. }
  1477. else {
  1478. // in case of paused, in order to allow late users to join
  1479. // paused
  1480. room.removeCommand(this.commands.defaults.SHARED_VIDEO);
  1481. room.sendCommand(this.commands.defaults.SHARED_VIDEO, {
  1482. value: url,
  1483. attributes: {
  1484. state: state,
  1485. time: time,
  1486. muted: isMuted,
  1487. volume: volume
  1488. }
  1489. });
  1490. }
  1491. });
  1492. room.addCommandListener(
  1493. this.commands.defaults.SHARED_VIDEO, ({value, attributes}, id) => {
  1494. if (attributes.state === 'stop') {
  1495. APP.UI.onSharedVideoStop(id, attributes);
  1496. }
  1497. else if (attributes.state === 'start') {
  1498. APP.UI.onSharedVideoStart(id, value, attributes);
  1499. }
  1500. else if (attributes.state === 'playing'
  1501. || attributes.state === 'pause') {
  1502. APP.UI.onSharedVideoUpdate(id, value, attributes);
  1503. }
  1504. });
  1505. },
  1506. /**
  1507. * Adds any room listener.
  1508. * @param {string} eventName one of the ConferenceEvents
  1509. * @param {Function} listener the function to be called when the event
  1510. * occurs
  1511. */
  1512. addConferenceListener(eventName, listener) {
  1513. room.on(eventName, listener);
  1514. },
  1515. /**
  1516. * Removes any room listener.
  1517. * @param {string} eventName one of the ConferenceEvents
  1518. * @param {Function} listener the listener to be removed.
  1519. */
  1520. removeConferenceListener(eventName, listener) {
  1521. room.off(eventName, listener);
  1522. },
  1523. /**
  1524. * Inits list of current devices and event listener for device change.
  1525. * @private
  1526. */
  1527. _initDeviceList() {
  1528. if (JitsiMeetJS.mediaDevices.isDeviceListAvailable() &&
  1529. JitsiMeetJS.mediaDevices.isDeviceChangeAvailable()) {
  1530. JitsiMeetJS.mediaDevices.enumerateDevices(devices => {
  1531. // Ugly way to synchronize real device IDs with local
  1532. // storage and settings menu. This is a workaround until
  1533. // getConstraints() method will be implemented in browsers.
  1534. if (localAudio) {
  1535. APP.settings.setMicDeviceId(
  1536. localAudio.getDeviceId(), false);
  1537. }
  1538. if (localVideo) {
  1539. APP.settings.setCameraDeviceId(
  1540. localVideo.getDeviceId(), false);
  1541. }
  1542. mediaDeviceHelper.setCurrentMediaDevices(devices);
  1543. APP.UI.onAvailableDevicesChanged(devices);
  1544. });
  1545. this.deviceChangeListener = (devices) =>
  1546. window.setTimeout(
  1547. () => this._onDeviceListChanged(devices), 0);
  1548. JitsiMeetJS.mediaDevices.addEventListener(
  1549. JitsiMeetJS.events.mediaDevices.DEVICE_LIST_CHANGED,
  1550. this.deviceChangeListener);
  1551. }
  1552. },
  1553. /**
  1554. * Event listener for JitsiMediaDevicesEvents.DEVICE_LIST_CHANGED to
  1555. * handle change of available media devices.
  1556. * @private
  1557. * @param {MediaDeviceInfo[]} devices
  1558. * @returns {Promise}
  1559. */
  1560. _onDeviceListChanged(devices) {
  1561. let currentDevices = mediaDeviceHelper.getCurrentMediaDevices();
  1562. // Event handler can be fired before direct
  1563. // enumerateDevices() call, so handle this situation here.
  1564. if (!currentDevices.audioinput &&
  1565. !currentDevices.videoinput &&
  1566. !currentDevices.audiooutput) {
  1567. mediaDeviceHelper.setCurrentMediaDevices(devices);
  1568. currentDevices = mediaDeviceHelper.getCurrentMediaDevices();
  1569. }
  1570. let newDevices =
  1571. mediaDeviceHelper.getNewMediaDevicesAfterDeviceListChanged(
  1572. devices, this.isSharingScreen, localVideo, localAudio);
  1573. let promises = [];
  1574. let audioWasMuted = this.audioMuted;
  1575. let videoWasMuted = this.videoMuted;
  1576. let availableAudioInputDevices =
  1577. mediaDeviceHelper.getDevicesFromListByKind(devices, 'audioinput');
  1578. let availableVideoInputDevices =
  1579. mediaDeviceHelper.getDevicesFromListByKind(devices, 'videoinput');
  1580. if (typeof newDevices.audiooutput !== 'undefined') {
  1581. // Just ignore any errors in catch block.
  1582. promises.push(APP.settings
  1583. .setAudioOutputDeviceId(newDevices.audiooutput)
  1584. .catch());
  1585. }
  1586. promises.push(
  1587. mediaDeviceHelper.createLocalTracksAfterDeviceListChanged(
  1588. createLocalTracks,
  1589. newDevices.videoinput,
  1590. newDevices.audioinput)
  1591. .then(tracks =>
  1592. Promise.all(this._setLocalAudioVideoStreams(tracks)))
  1593. .then(() => {
  1594. // If audio was muted before, or we unplugged current device
  1595. // and selected new one, then mute new audio track.
  1596. if (audioWasMuted ||
  1597. currentDevices.audioinput.length >
  1598. availableAudioInputDevices.length) {
  1599. muteLocalAudio(true);
  1600. }
  1601. // If video was muted before, or we unplugged current device
  1602. // and selected new one, then mute new video track.
  1603. if (videoWasMuted ||
  1604. currentDevices.videoinput.length >
  1605. availableVideoInputDevices.length) {
  1606. muteLocalVideo(true);
  1607. }
  1608. }));
  1609. return Promise.all(promises)
  1610. .then(() => {
  1611. mediaDeviceHelper.setCurrentMediaDevices(devices);
  1612. APP.UI.onAvailableDevicesChanged(devices);
  1613. });
  1614. },
  1615. /**
  1616. * Toggles the local "raised hand" status.
  1617. */
  1618. maybeToggleRaisedHand() {
  1619. this.setRaisedHand(!this.isHandRaised);
  1620. },
  1621. /**
  1622. * Sets the local "raised hand" status to a particular value.
  1623. */
  1624. setRaisedHand(raisedHand) {
  1625. if (raisedHand !== this.isHandRaised)
  1626. {
  1627. APP.UI.onLocalRaiseHandChanged(raisedHand);
  1628. this.isHandRaised = raisedHand;
  1629. // Advertise the updated status
  1630. room.setLocalParticipantProperty("raisedHand", raisedHand);
  1631. // Update the view
  1632. APP.UI.setLocalRaisedHandStatus(raisedHand);
  1633. }
  1634. },
  1635. /**
  1636. * Log event to callstats and analytics.
  1637. * @param {string} name the event name
  1638. * @param {int} value the value (it's int because google analytics supports
  1639. * only int).
  1640. * @param {string} label short text which provides more info about the event
  1641. * which allows to distinguish between few event cases of the same name
  1642. * NOTE: Should be used after conference.init
  1643. */
  1644. logEvent(name, value, label) {
  1645. if(JitsiMeetJS.analytics) {
  1646. JitsiMeetJS.analytics.sendEvent(name, {value, label});
  1647. }
  1648. if(room) {
  1649. room.sendApplicationLog(JSON.stringify({name, value, label}));
  1650. }
  1651. },
  1652. /**
  1653. * Methods logs an application event given in the JSON format.
  1654. * @param {string} logJSON an event to be logged in JSON format
  1655. */
  1656. logJSON(logJSON) {
  1657. if (room) {
  1658. room.sendApplicationLog(logJSON);
  1659. }
  1660. },
  1661. /**
  1662. * Disconnect from the conference and optionally request user feedback.
  1663. * @param {boolean} [requestFeedback=false] if user feedback should be
  1664. * requested
  1665. */
  1666. hangup (requestFeedback = false) {
  1667. eventEmitter.emit(JitsiMeetConferenceEvents.BEFORE_HANGUP);
  1668. APP.UI.hideRingOverLay();
  1669. let requestFeedbackPromise = requestFeedback
  1670. ? APP.UI.requestFeedbackOnHangup()
  1671. // false - because the thank you dialog shouldn't be displayed
  1672. .catch(() => Promise.resolve(false))
  1673. : Promise.resolve(true);// true - because the thank you dialog
  1674. //should be displayed
  1675. // All promises are returning Promise.resolve to make Promise.all to
  1676. // be resolved when both Promises are finished. Otherwise Promise.all
  1677. // will reject on first rejected Promise and we can redirect the page
  1678. // before all operations are done.
  1679. Promise.all([
  1680. requestFeedbackPromise,
  1681. room.leave().then(disconnect, disconnect)
  1682. ]).then(values => {
  1683. APP.API.notifyReadyToClose();
  1684. maybeRedirectToWelcomePage(values[0]);
  1685. });
  1686. },
  1687. /**
  1688. * Changes the email for the local user
  1689. * @param email {string} the new email
  1690. */
  1691. changeLocalEmail(email = '') {
  1692. email = email.trim();
  1693. if (email === APP.settings.getEmail()) {
  1694. return;
  1695. }
  1696. APP.store.dispatch(changeParticipantEmail(room.myUserId(), email));
  1697. APP.settings.setEmail(email);
  1698. APP.UI.setUserEmail(room.myUserId(), email);
  1699. sendData(commands.EMAIL, email);
  1700. },
  1701. /**
  1702. * Changes the avatar url for the local user
  1703. * @param url {string} the new url
  1704. */
  1705. changeLocalAvatarUrl(url = '') {
  1706. url = url.trim();
  1707. if (url === APP.settings.getAvatarUrl()) {
  1708. return;
  1709. }
  1710. APP.store.dispatch(changeParticipantAvatarURL(room.myUserId(), url));
  1711. APP.settings.setAvatarUrl(url);
  1712. APP.UI.setUserAvatarUrl(room.myUserId(), url);
  1713. sendData(commands.AVATAR_URL, url);
  1714. },
  1715. /**
  1716. * Sends a message via the data channel.
  1717. * @param {string} to the id of the endpoint that should receive the
  1718. * message. If "" - the message will be sent to all participants.
  1719. * @param {object} payload the payload of the message.
  1720. * @throws NetworkError or InvalidStateError or Error if the operation
  1721. * fails.
  1722. */
  1723. sendEndpointMessage (to, payload) {
  1724. room.sendEndpointMessage(to, payload);
  1725. },
  1726. /**
  1727. * Adds new listener.
  1728. * @param {String} eventName the name of the event
  1729. * @param {Function} listener the listener.
  1730. */
  1731. addListener (eventName, listener) {
  1732. eventEmitter.addListener(eventName, listener);
  1733. },
  1734. /**
  1735. * Removes listener.
  1736. * @param {String} eventName the name of the event that triggers the
  1737. * listener
  1738. * @param {Function} listener the listener.
  1739. */
  1740. removeListener (eventName, listener) {
  1741. eventEmitter.removeListener(eventName, listener);
  1742. }
  1743. };