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.

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