Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

conference.js 67KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931
  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. CONFERENCE_JOINED,
  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. mediaPermissionPromptVisibilityChanged,
  25. suspendDetected
  26. } from './react/features/overlay';
  27. import {
  28. changeParticipantAvatarID,
  29. changeParticipantAvatarURL,
  30. changeParticipantEmail,
  31. participantJoined,
  32. participantLeft,
  33. participantRoleChanged
  34. } from './react/features/base/participants';
  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. * Setups initially the properties for 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({
  1042. type: CONFERENCE_JOINED,
  1043. conference: room
  1044. });
  1045. APP.UI.mucJoined();
  1046. APP.API.notifyConferenceJoined(APP.conference.roomName);
  1047. APP.UI.markVideoInterrupted(false);
  1048. });
  1049. room.on(ConferenceEvents.CONFERENCE_LEFT,
  1050. (...args) => APP.store.dispatch(conferenceLeft(room, ...args)));
  1051. room.on(
  1052. ConferenceEvents.AUTH_STATUS_CHANGED,
  1053. function (authEnabled, authLogin) {
  1054. APP.UI.updateAuthInfo(authEnabled, authLogin);
  1055. }
  1056. );
  1057. room.on(ConferenceEvents.PARTCIPANT_FEATURES_CHANGED,
  1058. user => APP.UI.onUserFeaturesChanged(user));
  1059. room.on(ConferenceEvents.USER_JOINED, (id, user) => {
  1060. if (user.isHidden())
  1061. return;
  1062. APP.store.dispatch(participantJoined({
  1063. id,
  1064. name: user.getDisplayName(),
  1065. role: user.getRole()
  1066. }));
  1067. logger.log('USER %s connnected', id, user);
  1068. APP.API.notifyUserJoined(id);
  1069. APP.UI.addUser(user);
  1070. // check the roles for the new user and reflect them
  1071. APP.UI.updateUserRole(user);
  1072. });
  1073. room.on(ConferenceEvents.USER_LEFT, (id, user) => {
  1074. APP.store.dispatch(participantLeft(id, user));
  1075. logger.log('USER %s LEFT', id, user);
  1076. APP.API.notifyUserLeft(id);
  1077. APP.UI.removeUser(id, user.getDisplayName());
  1078. APP.UI.onSharedVideoStop(id);
  1079. });
  1080. room.on(ConferenceEvents.USER_ROLE_CHANGED, (id, role) => {
  1081. APP.store.dispatch(participantRoleChanged(id, role));
  1082. if (this.isLocalId(id)) {
  1083. logger.info(`My role changed, new role: ${role}`);
  1084. if (this.isModerator !== room.isModerator()) {
  1085. this.isModerator = room.isModerator();
  1086. APP.UI.updateLocalRole(room.isModerator());
  1087. }
  1088. } else {
  1089. let user = room.getParticipantById(id);
  1090. if (user) {
  1091. APP.UI.updateUserRole(user);
  1092. }
  1093. }
  1094. });
  1095. room.on(ConferenceEvents.TRACK_ADDED, (track) => {
  1096. if(!track || track.isLocal())
  1097. return;
  1098. track.on(TrackEvents.TRACK_VIDEOTYPE_CHANGED, (type) => {
  1099. APP.UI.onPeerVideoTypeChanged(track.getParticipantId(), type);
  1100. });
  1101. APP.UI.addRemoteStream(track);
  1102. });
  1103. room.on(ConferenceEvents.TRACK_REMOVED, (track) => {
  1104. if(!track || track.isLocal())
  1105. return;
  1106. APP.UI.removeRemoteStream(track);
  1107. });
  1108. room.on(ConferenceEvents.TRACK_MUTE_CHANGED, (track) => {
  1109. if(!track)
  1110. return;
  1111. const handler = (track.getType() === "audio")?
  1112. APP.UI.setAudioMuted : APP.UI.setVideoMuted;
  1113. let id;
  1114. const mute = track.isMuted();
  1115. if(track.isLocal()){
  1116. id = APP.conference.getMyUserId();
  1117. if(track.getType() === "audio") {
  1118. this.audioMuted = mute;
  1119. } else {
  1120. this.videoMuted = mute;
  1121. }
  1122. } else {
  1123. id = track.getParticipantId();
  1124. }
  1125. handler(id , mute);
  1126. });
  1127. room.on(ConferenceEvents.TRACK_AUDIO_LEVEL_CHANGED, (id, lvl) => {
  1128. if(this.isLocalId(id) && localAudio && localAudio.isMuted()) {
  1129. lvl = 0;
  1130. }
  1131. if(config.debug)
  1132. {
  1133. this.audioLevelsMap[id] = lvl;
  1134. if(config.debugAudioLevels)
  1135. logger.log("AudioLevel:" + id + "/" + lvl);
  1136. }
  1137. APP.UI.setAudioLevel(id, lvl);
  1138. });
  1139. room.on(ConferenceEvents.TALK_WHILE_MUTED, () => {
  1140. APP.UI.showToolbar(6000);
  1141. APP.UI.showCustomToolbarPopup('#talkWhileMutedPopup', true, 5000);
  1142. });
  1143. /*
  1144. room.on(ConferenceEvents.IN_LAST_N_CHANGED, (inLastN) => {
  1145. //FIXME
  1146. if (config.muteLocalVideoIfNotInLastN) {
  1147. // TODO mute or unmute if required
  1148. // mark video on UI
  1149. // APP.UI.markVideoMuted(true/false);
  1150. }
  1151. });
  1152. */
  1153. room.on(
  1154. ConferenceEvents.LAST_N_ENDPOINTS_CHANGED, (ids, enteringIds) => {
  1155. APP.UI.handleLastNEndpoints(ids, enteringIds);
  1156. });
  1157. room.on(
  1158. ConferenceEvents.PARTICIPANT_CONN_STATUS_CHANGED,
  1159. (id, isActive) => {
  1160. APP.UI.participantConnectionStatusChanged(id, isActive);
  1161. });
  1162. room.on(ConferenceEvents.DOMINANT_SPEAKER_CHANGED, (id) => {
  1163. if (this.isLocalId(id)) {
  1164. this.isDominantSpeaker = true;
  1165. this.setRaisedHand(false);
  1166. } else {
  1167. this.isDominantSpeaker = false;
  1168. var participant = room.getParticipantById(id);
  1169. if (participant) {
  1170. APP.UI.setRaisedHandStatus(participant, false);
  1171. }
  1172. }
  1173. APP.UI.markDominantSpeaker(id);
  1174. });
  1175. if (!interfaceConfig.filmStripOnly) {
  1176. room.on(ConferenceEvents.CONNECTION_INTERRUPTED, () => {
  1177. APP.UI.markVideoInterrupted(true);
  1178. });
  1179. room.on(ConferenceEvents.CONNECTION_RESTORED, () => {
  1180. APP.UI.markVideoInterrupted(false);
  1181. });
  1182. room.on(ConferenceEvents.MESSAGE_RECEIVED, (id, text, ts) => {
  1183. let nick = getDisplayName(id);
  1184. APP.API.notifyReceivedChatMessage(id, nick, text, ts);
  1185. APP.UI.addMessage(id, nick, text, ts);
  1186. });
  1187. APP.UI.addListener(UIEvents.MESSAGE_CREATED, (message) => {
  1188. APP.API.notifySendingChatMessage(message);
  1189. room.sendTextMessage(message);
  1190. });
  1191. APP.UI.addListener(UIEvents.SELECTED_ENDPOINT, (id) => {
  1192. try {
  1193. // do not try to select participant if there is none (we
  1194. // are alone in the room), otherwise an error will be
  1195. // thrown cause reporting mechanism is not available
  1196. // (datachannels currently)
  1197. if (room.getParticipants().length === 0)
  1198. return;
  1199. room.selectParticipant(id);
  1200. } catch (e) {
  1201. JitsiMeetJS.analytics.sendEvent(
  1202. 'selectParticipant.failed');
  1203. reportError(e);
  1204. }
  1205. });
  1206. APP.UI.addListener(UIEvents.PINNED_ENDPOINT,
  1207. (smallVideo, isPinned) => {
  1208. let smallVideoId = smallVideo.getId();
  1209. let isLocal = APP.conference.isLocalId(smallVideoId);
  1210. let eventName
  1211. = (isPinned ? "pinned" : "unpinned") + "." +
  1212. (isLocal ? "local" : "remote");
  1213. let participantCount = room.getParticipantCount();
  1214. JitsiMeetJS.analytics.sendEvent(
  1215. eventName,
  1216. { value: participantCount });
  1217. // FIXME why VIDEO_CONTAINER_TYPE instead of checking if
  1218. // the participant is on the large video ?
  1219. if (smallVideo.getVideoType() === VIDEO_CONTAINER_TYPE
  1220. && !isLocal) {
  1221. // When the library starts supporting multiple pins we
  1222. // would pass the isPinned parameter together with the
  1223. // identifier, but currently we send null to indicate that
  1224. // we unpin the last pinned.
  1225. try {
  1226. room.pinParticipant(isPinned ? smallVideoId : null);
  1227. } catch (e) {
  1228. reportError(e);
  1229. }
  1230. }
  1231. });
  1232. }
  1233. room.on(ConferenceEvents.CONNECTION_INTERRUPTED, () => {
  1234. APP.UI.showLocalConnectionInterrupted(true);
  1235. });
  1236. room.on(ConferenceEvents.CONNECTION_RESTORED, () => {
  1237. APP.UI.showLocalConnectionInterrupted(false);
  1238. });
  1239. room.on(ConferenceEvents.DISPLAY_NAME_CHANGED, (id, displayName) => {
  1240. const formattedDisplayName
  1241. = displayName.substr(0, MAX_DISPLAY_NAME_LENGTH);
  1242. APP.API.notifyDisplayNameChanged(id, formattedDisplayName);
  1243. APP.UI.changeDisplayName(id, formattedDisplayName);
  1244. });
  1245. room.on(ConferenceEvents.PARTICIPANT_PROPERTY_CHANGED,
  1246. (participant, name, oldValue, newValue) => {
  1247. if (name === "raisedHand") {
  1248. APP.UI.setRaisedHandStatus(participant, newValue);
  1249. }
  1250. });
  1251. room.on(ConferenceEvents.RECORDER_STATE_CHANGED, (status, error) => {
  1252. logger.log("Received recorder status change: ", status, error);
  1253. APP.UI.updateRecordingState(status);
  1254. });
  1255. room.on(ConferenceEvents.KICKED, () => {
  1256. APP.UI.hideStats();
  1257. APP.UI.notifyKicked();
  1258. // FIXME close
  1259. });
  1260. room.on(ConferenceEvents.SUSPEND_DETECTED, () => {
  1261. APP.store.dispatch(suspendDetected());
  1262. // After wake up, we will be in a state where conference is left
  1263. // there will be dialog shown to user.
  1264. // We do not want video/audio as we show an overlay and after it
  1265. // user need to rejoin or close, while waking up we can detect
  1266. // camera wakeup as a problem with device.
  1267. // We also do not care about device change, which happens
  1268. // on resume after suspending PC.
  1269. if (this.deviceChangeListener)
  1270. JitsiMeetJS.mediaDevices.removeEventListener(
  1271. JitsiMeetJS.events.mediaDevices.DEVICE_LIST_CHANGED,
  1272. this.deviceChangeListener);
  1273. // stop local video
  1274. if (localVideo) {
  1275. localVideo.dispose();
  1276. }
  1277. // stop local audio
  1278. if (localAudio) {
  1279. localAudio.dispose();
  1280. }
  1281. });
  1282. room.on(ConferenceEvents.DTMF_SUPPORT_CHANGED, (isDTMFSupported) => {
  1283. APP.UI.updateDTMFSupport(isDTMFSupported);
  1284. });
  1285. APP.UI.addListener(UIEvents.EXTERNAL_INSTALLATION_CANCELED, () => {
  1286. // Wait a little bit more just to be sure that we won't miss the
  1287. // extension installation
  1288. setTimeout(() => DSExternalInstallationInProgress = false, 500);
  1289. });
  1290. APP.UI.addListener(UIEvents.OPEN_EXTENSION_STORE, (url) => {
  1291. window.open(
  1292. url, "extension_store_window",
  1293. "resizable,scrollbars=yes,status=1");
  1294. });
  1295. APP.UI.addListener(UIEvents.AUDIO_MUTED, muteLocalAudio);
  1296. APP.UI.addListener(UIEvents.VIDEO_MUTED, muteLocalVideo);
  1297. room.on(ConnectionQualityEvents.LOCAL_STATS_UPDATED,
  1298. (stats) => {
  1299. APP.UI.updateLocalStats(stats.connectionQuality, stats);
  1300. });
  1301. room.on(ConnectionQualityEvents.REMOTE_STATS_UPDATED,
  1302. (id, stats) => {
  1303. APP.UI.updateRemoteStats(id, stats.connectionQuality, stats);
  1304. });
  1305. room.addCommandListener(this.commands.defaults.ETHERPAD, ({value}) => {
  1306. APP.UI.initEtherpad(value);
  1307. });
  1308. APP.UI.addListener(UIEvents.EMAIL_CHANGED, this.changeLocalEmail);
  1309. room.addCommandListener(this.commands.defaults.EMAIL, (data, from) => {
  1310. APP.store.dispatch(changeParticipantEmail(from, data.value));
  1311. APP.UI.setUserEmail(from, data.value);
  1312. });
  1313. room.addCommandListener(
  1314. this.commands.defaults.AVATAR_URL,
  1315. (data, from) => {
  1316. APP.store.dispatch(
  1317. changeParticipantAvatarURL(from, data.value));
  1318. APP.UI.setUserAvatarUrl(from, data.value);
  1319. });
  1320. room.addCommandListener(this.commands.defaults.AVATAR_ID,
  1321. (data, from) => {
  1322. APP.store.dispatch(
  1323. changeParticipantAvatarID(from, data.value));
  1324. APP.UI.setUserAvatarID(from, data.value);
  1325. });
  1326. APP.UI.addListener(UIEvents.NICKNAME_CHANGED, changeLocalDisplayName);
  1327. APP.UI.addListener(UIEvents.START_MUTED_CHANGED,
  1328. (startAudioMuted, startVideoMuted) => {
  1329. room.setStartMutedPolicy({
  1330. audio: startAudioMuted,
  1331. video: startVideoMuted
  1332. });
  1333. }
  1334. );
  1335. room.on(
  1336. ConferenceEvents.START_MUTED_POLICY_CHANGED,
  1337. ({ audio, video }) => {
  1338. APP.UI.onStartMutedChanged(audio, video);
  1339. }
  1340. );
  1341. room.on(ConferenceEvents.STARTED_MUTED, () => {
  1342. (room.isStartAudioMuted() || room.isStartVideoMuted())
  1343. && APP.UI.notifyInitiallyMuted();
  1344. });
  1345. room.on(
  1346. ConferenceEvents.AVAILABLE_DEVICES_CHANGED, function (id, devices) {
  1347. APP.UI.updateDevicesAvailability(id, devices);
  1348. }
  1349. );
  1350. // call hangup
  1351. APP.UI.addListener(UIEvents.HANGUP, () => {
  1352. this.hangup(true);
  1353. });
  1354. // logout
  1355. APP.UI.addListener(UIEvents.LOGOUT, () => {
  1356. AuthHandler.logout(room).then(url => {
  1357. if (url) {
  1358. UIUtil.redirect(url);
  1359. } else {
  1360. this.hangup(true);
  1361. }
  1362. });
  1363. });
  1364. APP.UI.addListener(UIEvents.SIP_DIAL, (sipNumber) => {
  1365. room.dial(sipNumber);
  1366. });
  1367. APP.UI.addListener(UIEvents.RESOLUTION_CHANGED,
  1368. (id, oldResolution, newResolution, delay) => {
  1369. var logObject = {
  1370. id: "resolution_change",
  1371. participant: id,
  1372. oldValue: oldResolution,
  1373. newValue: newResolution,
  1374. delay: delay
  1375. };
  1376. room.sendApplicationLog(JSON.stringify(logObject));
  1377. // We only care about the delay between simulcast streams.
  1378. // Longer delays will be caused by something else and will just
  1379. // poison the data.
  1380. if (delay < 2000) {
  1381. JitsiMeetJS.analytics.sendEvent('stream.switch.delay',
  1382. {value: delay});
  1383. }
  1384. });
  1385. // Starts or stops the recording for the conference.
  1386. APP.UI.addListener(UIEvents.RECORDING_TOGGLED, (options) => {
  1387. room.toggleRecording(options);
  1388. });
  1389. APP.UI.addListener(UIEvents.SUBJECT_CHANGED, (topic) => {
  1390. room.setSubject(topic);
  1391. });
  1392. room.on(ConferenceEvents.SUBJECT_CHANGED, function (subject) {
  1393. APP.UI.setSubject(subject);
  1394. });
  1395. APP.UI.addListener(UIEvents.USER_KICKED, (id) => {
  1396. room.kickParticipant(id);
  1397. });
  1398. APP.UI.addListener(UIEvents.REMOTE_AUDIO_MUTED, (id) => {
  1399. room.muteParticipant(id);
  1400. });
  1401. APP.UI.addListener(UIEvents.AUTH_CLICKED, () => {
  1402. AuthHandler.authenticate(room);
  1403. });
  1404. APP.UI.addListener(
  1405. UIEvents.VIDEO_DEVICE_CHANGED,
  1406. (cameraDeviceId) => {
  1407. JitsiMeetJS.analytics.sendEvent('settings.changeDevice.video');
  1408. createLocalTracks({
  1409. devices: ['video'],
  1410. cameraDeviceId: cameraDeviceId,
  1411. micDeviceId: null
  1412. })
  1413. .then(([stream]) => {
  1414. this.useVideoStream(stream);
  1415. logger.log('switched local video device');
  1416. APP.settings.setCameraDeviceId(cameraDeviceId, true);
  1417. })
  1418. .catch((err) => {
  1419. APP.UI.showDeviceErrorDialog(null, err);
  1420. APP.UI.setSelectedCameraFromSettings();
  1421. });
  1422. }
  1423. );
  1424. APP.UI.addListener(
  1425. UIEvents.AUDIO_DEVICE_CHANGED,
  1426. (micDeviceId) => {
  1427. JitsiMeetJS.analytics.sendEvent(
  1428. 'settings.changeDevice.audioIn');
  1429. createLocalTracks({
  1430. devices: ['audio'],
  1431. cameraDeviceId: null,
  1432. micDeviceId: micDeviceId
  1433. })
  1434. .then(([stream]) => {
  1435. this.useAudioStream(stream);
  1436. logger.log('switched local audio device');
  1437. APP.settings.setMicDeviceId(micDeviceId, true);
  1438. })
  1439. .catch((err) => {
  1440. APP.UI.showDeviceErrorDialog(err, null);
  1441. APP.UI.setSelectedMicFromSettings();
  1442. });
  1443. }
  1444. );
  1445. APP.UI.addListener(
  1446. UIEvents.AUDIO_OUTPUT_DEVICE_CHANGED,
  1447. (audioOutputDeviceId) => {
  1448. JitsiMeetJS.analytics.sendEvent(
  1449. 'settings.changeDevice.audioOut');
  1450. APP.settings.setAudioOutputDeviceId(audioOutputDeviceId)
  1451. .then(() => logger.log('changed audio output device'))
  1452. .catch((err) => {
  1453. logger.warn('Failed to change audio output device. ' +
  1454. 'Default or previously set audio output device ' +
  1455. 'will be used instead.', err);
  1456. APP.UI.setSelectedAudioOutputFromSettings();
  1457. });
  1458. }
  1459. );
  1460. APP.UI.addListener(
  1461. UIEvents.TOGGLE_SCREENSHARING, this.toggleScreenSharing.bind(this)
  1462. );
  1463. APP.UI.addListener(UIEvents.UPDATE_SHARED_VIDEO,
  1464. (url, state, time, isMuted, volume) => {
  1465. // send start and stop commands once, and remove any updates
  1466. // that had left
  1467. if (state === 'stop' || state === 'start' || state === 'playing') {
  1468. room.removeCommand(this.commands.defaults.SHARED_VIDEO);
  1469. room.sendCommandOnce(this.commands.defaults.SHARED_VIDEO, {
  1470. value: url,
  1471. attributes: {
  1472. state: state,
  1473. time: time,
  1474. muted: isMuted,
  1475. volume: volume
  1476. }
  1477. });
  1478. }
  1479. else {
  1480. // in case of paused, in order to allow late users to join
  1481. // paused
  1482. room.removeCommand(this.commands.defaults.SHARED_VIDEO);
  1483. room.sendCommand(this.commands.defaults.SHARED_VIDEO, {
  1484. value: url,
  1485. attributes: {
  1486. state: state,
  1487. time: time,
  1488. muted: isMuted,
  1489. volume: volume
  1490. }
  1491. });
  1492. }
  1493. });
  1494. room.addCommandListener(
  1495. this.commands.defaults.SHARED_VIDEO, ({value, attributes}, id) => {
  1496. if (attributes.state === 'stop') {
  1497. APP.UI.onSharedVideoStop(id, attributes);
  1498. }
  1499. else if (attributes.state === 'start') {
  1500. APP.UI.onSharedVideoStart(id, value, attributes);
  1501. }
  1502. else if (attributes.state === 'playing'
  1503. || attributes.state === 'pause') {
  1504. APP.UI.onSharedVideoUpdate(id, value, attributes);
  1505. }
  1506. });
  1507. },
  1508. /**
  1509. * Adds any room listener.
  1510. * @param {string} eventName one of the ConferenceEvents
  1511. * @param {Function} listener the function to be called when the event
  1512. * occurs
  1513. */
  1514. addConferenceListener(eventName, listener) {
  1515. room.on(eventName, listener);
  1516. },
  1517. /**
  1518. * Removes any room listener.
  1519. * @param {string} eventName one of the ConferenceEvents
  1520. * @param {Function} listener the listener to be removed.
  1521. */
  1522. removeConferenceListener(eventName, listener) {
  1523. room.off(eventName, listener);
  1524. },
  1525. /**
  1526. * Inits list of current devices and event listener for device change.
  1527. * @private
  1528. */
  1529. _initDeviceList() {
  1530. if (JitsiMeetJS.mediaDevices.isDeviceListAvailable() &&
  1531. JitsiMeetJS.mediaDevices.isDeviceChangeAvailable()) {
  1532. JitsiMeetJS.mediaDevices.enumerateDevices(devices => {
  1533. // Ugly way to synchronize real device IDs with local
  1534. // storage and settings menu. This is a workaround until
  1535. // getConstraints() method will be implemented in browsers.
  1536. if (localAudio) {
  1537. APP.settings.setMicDeviceId(
  1538. localAudio.getDeviceId(), false);
  1539. }
  1540. if (localVideo) {
  1541. APP.settings.setCameraDeviceId(
  1542. localVideo.getDeviceId(), false);
  1543. }
  1544. mediaDeviceHelper.setCurrentMediaDevices(devices);
  1545. APP.UI.onAvailableDevicesChanged(devices);
  1546. });
  1547. this.deviceChangeListener = (devices) =>
  1548. window.setTimeout(
  1549. () => this._onDeviceListChanged(devices), 0);
  1550. JitsiMeetJS.mediaDevices.addEventListener(
  1551. JitsiMeetJS.events.mediaDevices.DEVICE_LIST_CHANGED,
  1552. this.deviceChangeListener);
  1553. }
  1554. },
  1555. /**
  1556. * Event listener for JitsiMediaDevicesEvents.DEVICE_LIST_CHANGED to
  1557. * handle change of available media devices.
  1558. * @private
  1559. * @param {MediaDeviceInfo[]} devices
  1560. * @returns {Promise}
  1561. */
  1562. _onDeviceListChanged(devices) {
  1563. let currentDevices = mediaDeviceHelper.getCurrentMediaDevices();
  1564. // Event handler can be fired before direct
  1565. // enumerateDevices() call, so handle this situation here.
  1566. if (!currentDevices.audioinput &&
  1567. !currentDevices.videoinput &&
  1568. !currentDevices.audiooutput) {
  1569. mediaDeviceHelper.setCurrentMediaDevices(devices);
  1570. currentDevices = mediaDeviceHelper.getCurrentMediaDevices();
  1571. }
  1572. let newDevices =
  1573. mediaDeviceHelper.getNewMediaDevicesAfterDeviceListChanged(
  1574. devices, this.isSharingScreen, localVideo, localAudio);
  1575. let promises = [];
  1576. let audioWasMuted = this.audioMuted;
  1577. let videoWasMuted = this.videoMuted;
  1578. let availableAudioInputDevices =
  1579. mediaDeviceHelper.getDevicesFromListByKind(devices, 'audioinput');
  1580. let availableVideoInputDevices =
  1581. mediaDeviceHelper.getDevicesFromListByKind(devices, 'videoinput');
  1582. if (typeof newDevices.audiooutput !== 'undefined') {
  1583. // Just ignore any errors in catch block.
  1584. promises.push(APP.settings
  1585. .setAudioOutputDeviceId(newDevices.audiooutput)
  1586. .catch());
  1587. }
  1588. promises.push(
  1589. mediaDeviceHelper.createLocalTracksAfterDeviceListChanged(
  1590. createLocalTracks,
  1591. newDevices.videoinput,
  1592. newDevices.audioinput)
  1593. .then(tracks =>
  1594. Promise.all(this._setLocalAudioVideoStreams(tracks)))
  1595. .then(() => {
  1596. // If audio was muted before, or we unplugged current device
  1597. // and selected new one, then mute new audio track.
  1598. if (audioWasMuted ||
  1599. currentDevices.audioinput.length >
  1600. availableAudioInputDevices.length) {
  1601. muteLocalAudio(true);
  1602. }
  1603. // If video was muted before, or we unplugged current device
  1604. // and selected new one, then mute new video track.
  1605. if (videoWasMuted ||
  1606. currentDevices.videoinput.length >
  1607. availableVideoInputDevices.length) {
  1608. muteLocalVideo(true);
  1609. }
  1610. }));
  1611. return Promise.all(promises)
  1612. .then(() => {
  1613. mediaDeviceHelper.setCurrentMediaDevices(devices);
  1614. APP.UI.onAvailableDevicesChanged(devices);
  1615. });
  1616. },
  1617. /**
  1618. * Toggles the local "raised hand" status.
  1619. */
  1620. maybeToggleRaisedHand() {
  1621. this.setRaisedHand(!this.isHandRaised);
  1622. },
  1623. /**
  1624. * Sets the local "raised hand" status to a particular value.
  1625. */
  1626. setRaisedHand(raisedHand) {
  1627. if (raisedHand !== this.isHandRaised)
  1628. {
  1629. APP.UI.onLocalRaiseHandChanged(raisedHand);
  1630. this.isHandRaised = raisedHand;
  1631. // Advertise the updated status
  1632. room.setLocalParticipantProperty("raisedHand", raisedHand);
  1633. // Update the view
  1634. APP.UI.setLocalRaisedHandStatus(raisedHand);
  1635. }
  1636. },
  1637. /**
  1638. * Log event to callstats and analytics.
  1639. * @param {string} name the event name
  1640. * @param {int} value the value (it's int because google analytics supports
  1641. * only int).
  1642. * @param {string} label short text which provides more info about the event
  1643. * which allows to distinguish between few event cases of the same name
  1644. * NOTE: Should be used after conference.init
  1645. */
  1646. logEvent(name, value, label) {
  1647. if(JitsiMeetJS.analytics) {
  1648. JitsiMeetJS.analytics.sendEvent(name, {value, label});
  1649. }
  1650. if(room) {
  1651. room.sendApplicationLog(JSON.stringify({name, value, label}));
  1652. }
  1653. },
  1654. /**
  1655. * Methods logs an application event given in the JSON format.
  1656. * @param {string} logJSON an event to be logged in JSON format
  1657. */
  1658. logJSON(logJSON) {
  1659. if (room) {
  1660. room.sendApplicationLog(logJSON);
  1661. }
  1662. },
  1663. /**
  1664. * Disconnect from the conference and optionally request user feedback.
  1665. * @param {boolean} [requestFeedback=false] if user feedback should be
  1666. * requested
  1667. */
  1668. hangup (requestFeedback = false) {
  1669. eventEmitter.emit(JitsiMeetConferenceEvents.BEFORE_HANGUP);
  1670. APP.UI.hideRingOverLay();
  1671. let requestFeedbackPromise = requestFeedback
  1672. ? APP.UI.requestFeedbackOnHangup()
  1673. // false - because the thank you dialog shouldn't be displayed
  1674. .catch(() => Promise.resolve(false))
  1675. : Promise.resolve(true);// true - because the thank you dialog
  1676. //should be displayed
  1677. // All promises are returning Promise.resolve to make Promise.all to
  1678. // be resolved when both Promises are finished. Otherwise Promise.all
  1679. // will reject on first rejected Promise and we can redirect the page
  1680. // before all operations are done.
  1681. Promise.all([
  1682. requestFeedbackPromise,
  1683. room.leave().then(disconnect, disconnect)
  1684. ]).then(values => {
  1685. APP.API.notifyReadyToClose();
  1686. maybeRedirectToWelcomePage(values[0]);
  1687. });
  1688. },
  1689. /**
  1690. * Changes the email for the local user
  1691. * @param email {string} the new email
  1692. */
  1693. changeLocalEmail(email = '') {
  1694. email = email.trim();
  1695. if (email === APP.settings.getEmail()) {
  1696. return;
  1697. }
  1698. APP.store.dispatch(changeParticipantEmail(room.myUserId(), email));
  1699. APP.settings.setEmail(email);
  1700. APP.UI.setUserEmail(room.myUserId(), email);
  1701. sendData(commands.EMAIL, email);
  1702. },
  1703. /**
  1704. * Changes the avatar url for the local user
  1705. * @param url {string} the new url
  1706. */
  1707. changeLocalAvatarUrl(url = '') {
  1708. url = url.trim();
  1709. if (url === APP.settings.getAvatarUrl()) {
  1710. return;
  1711. }
  1712. APP.store.dispatch(changeParticipantAvatarURL(room.myUserId(), url));
  1713. APP.settings.setAvatarUrl(url);
  1714. APP.UI.setUserAvatarUrl(room.myUserId(), url);
  1715. sendData(commands.AVATAR_URL, url);
  1716. },
  1717. /**
  1718. * Sends a message via the data channel.
  1719. * @param {string} to the id of the endpoint that should receive the
  1720. * message. If "" - the message will be sent to all participants.
  1721. * @param {object} payload the payload of the message.
  1722. * @throws NetworkError or InvalidStateError or Error if the operation
  1723. * fails.
  1724. */
  1725. sendEndpointMessage (to, payload) {
  1726. room.sendEndpointMessage(to, payload);
  1727. },
  1728. /**
  1729. * Adds new listener.
  1730. * @param {String} eventName the name of the event
  1731. * @param {Function} listener the listener.
  1732. */
  1733. addListener (eventName, listener) {
  1734. eventEmitter.addListener(eventName, listener);
  1735. },
  1736. /**
  1737. * Removes listener.
  1738. * @param {String} eventName the name of the event that triggers the
  1739. * listener
  1740. * @param {Function} listener the listener.
  1741. */
  1742. removeListener (eventName, listener) {
  1743. eventEmitter.removeListener(eventName, listener);
  1744. }
  1745. };