You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

conference.js 67KB

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