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

conference.js 67KB

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