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

conference.js 67KB

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