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 68KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981
  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. * Obtains current P2P ICE connection state.
  669. * @return {string|null} ICE connection state or <tt>null</tt> if there's no
  670. * P2P connection
  671. */
  672. getP2PConnectionState () {
  673. return this._room
  674. && this._room.getP2PConnectionState();
  675. },
  676. /**
  677. * Starts P2P (for tests only)
  678. * @private
  679. */
  680. _startP2P () {
  681. try {
  682. this._room && this._room.startP2PSession();
  683. } catch (error) {
  684. logger.error("Start P2P failed", error);
  685. throw error;
  686. }
  687. },
  688. /**
  689. * Stops P2P (for tests only)
  690. * @private
  691. */
  692. _stopP2P () {
  693. try {
  694. this._room && this._room.stopP2PSession();
  695. } catch (error) {
  696. logger.error("Stop P2P failed", error);
  697. throw error;
  698. }
  699. },
  700. /**
  701. * Checks whether or not our connection is currently in interrupted and
  702. * reconnect attempts are in progress.
  703. *
  704. * @returns {boolean} true if the connection is in interrupted state or
  705. * false otherwise.
  706. */
  707. isConnectionInterrupted () {
  708. return this._room.isConnectionInterrupted();
  709. },
  710. /**
  711. * Finds JitsiParticipant for given id.
  712. *
  713. * @param {string} id participant's identifier(MUC nickname).
  714. *
  715. * @returns {JitsiParticipant|null} participant instance for given id or
  716. * null if not found.
  717. */
  718. getParticipantById (id) {
  719. return room ? room.getParticipantById(id) : null;
  720. },
  721. /**
  722. * Checks whether the user identified by given id is currently connected.
  723. *
  724. * @param {string} id participant's identifier(MUC nickname)
  725. *
  726. * @returns {boolean|null} true if participant's connection is ok or false
  727. * if the user is having connectivity issues.
  728. */
  729. isParticipantConnectionActive (id) {
  730. let participant = this.getParticipantById(id);
  731. return participant ? participant.isConnectionActive() : null;
  732. },
  733. /**
  734. * Gets the display name foe the <tt>JitsiParticipant</tt> identified by
  735. * the given <tt>id</tt>.
  736. *
  737. * @param id {string} the participant's id(MUC nickname/JVB endpoint id)
  738. *
  739. * @return {string} the participant's display name or the default string if
  740. * absent.
  741. */
  742. getParticipantDisplayName (id) {
  743. let displayName = getDisplayName(id);
  744. if (displayName) {
  745. return displayName;
  746. } else {
  747. if (APP.conference.isLocalId(id)) {
  748. return APP.translation.generateTranslationHTML(
  749. interfaceConfig.DEFAULT_LOCAL_DISPLAY_NAME);
  750. } else {
  751. return interfaceConfig.DEFAULT_REMOTE_DISPLAY_NAME;
  752. }
  753. }
  754. },
  755. getMyUserId () {
  756. return this._room
  757. && this._room.myUserId();
  758. },
  759. /**
  760. * Indicates if recording is supported in this conference.
  761. */
  762. isRecordingSupported() {
  763. return this._room && this._room.isRecordingSupported();
  764. },
  765. /**
  766. * Returns the recording state or undefined if the room is not defined.
  767. */
  768. getRecordingState() {
  769. return (this._room) ? this._room.getRecordingState() : undefined;
  770. },
  771. /**
  772. * Will be filled with values only when config.debug is enabled.
  773. * Its used by torture to check audio levels.
  774. */
  775. audioLevelsMap: {},
  776. /**
  777. * Returns the stored audio level (stored only if config.debug is enabled)
  778. * @param id the id for the user audio level to return (the id value is
  779. * returned for the participant using getMyUserId() method)
  780. */
  781. getPeerSSRCAudioLevel (id) {
  782. return this.audioLevelsMap[id];
  783. },
  784. /**
  785. * @return {number} the number of participants in the conference with at
  786. * least one track.
  787. */
  788. getNumberOfParticipantsWithTracks() {
  789. return this._room.getParticipants()
  790. .filter((p) => p.getTracks().length > 0)
  791. .length;
  792. },
  793. /**
  794. * Returns the stats.
  795. */
  796. getStats() {
  797. return room.connectionQuality.getStats();
  798. },
  799. // end used by torture
  800. getLogs () {
  801. return room.getLogs();
  802. },
  803. /**
  804. * Download logs, a function that can be called from console while
  805. * debugging.
  806. * @param filename (optional) specify target filename
  807. */
  808. saveLogs (filename = 'meetlog.json') {
  809. // this can be called from console and will not have reference to this
  810. // that's why we reference the global var
  811. let logs = APP.conference.getLogs();
  812. let data = encodeURIComponent(JSON.stringify(logs, null, ' '));
  813. let elem = document.createElement('a');
  814. elem.download = filename;
  815. elem.href = 'data:application/json;charset=utf-8,\n' + data;
  816. elem.dataset.downloadurl
  817. = ['text/json', elem.download, elem.href].join(':');
  818. elem.dispatchEvent(new MouseEvent('click', {
  819. view: window,
  820. bubbles: true,
  821. cancelable: false
  822. }));
  823. },
  824. /**
  825. * Exposes a Command(s) API on this instance. It is necessitated by (1) the
  826. * desire to keep room private to this instance and (2) the need of other
  827. * modules to send and receive commands to and from participants.
  828. * Eventually, this instance remains in control with respect to the
  829. * decision whether the Command(s) API of room (i.e. lib-jitsi-meet's
  830. * JitsiConference) is to be used in the implementation of the Command(s)
  831. * API of this instance.
  832. */
  833. commands: {
  834. /**
  835. * Known custom conference commands.
  836. */
  837. defaults: commands,
  838. /**
  839. * Receives notifications from other participants about commands aka
  840. * custom events (sent by sendCommand or sendCommandOnce methods).
  841. * @param command {String} the name of the command
  842. * @param handler {Function} handler for the command
  843. */
  844. addCommandListener () {
  845. room.addCommandListener.apply(room, arguments);
  846. },
  847. /**
  848. * Removes command.
  849. * @param name {String} the name of the command.
  850. */
  851. removeCommand () {
  852. room.removeCommand.apply(room, arguments);
  853. },
  854. /**
  855. * Sends command.
  856. * @param name {String} the name of the command.
  857. * @param values {Object} with keys and values that will be sent.
  858. */
  859. sendCommand () {
  860. room.sendCommand.apply(room, arguments);
  861. },
  862. /**
  863. * Sends command one time.
  864. * @param name {String} the name of the command.
  865. * @param values {Object} with keys and values that will be sent.
  866. */
  867. sendCommandOnce () {
  868. room.sendCommandOnce.apply(room, arguments);
  869. }
  870. },
  871. _createRoom (localTracks) {
  872. room = connection.initJitsiConference(APP.conference.roomName,
  873. this._getConferenceOptions());
  874. this._setLocalAudioVideoStreams(localTracks);
  875. this.invite = new Invite(room);
  876. this._room = room; // FIXME do not use this
  877. _setupLocalParticipantProperties();
  878. this._setupListeners();
  879. },
  880. /**
  881. * Sets local video and audio streams.
  882. * @param {JitsiLocalTrack[]} tracks=[]
  883. * @returns {Promise[]}
  884. * @private
  885. */
  886. _setLocalAudioVideoStreams(tracks = []) {
  887. return tracks.map(track => {
  888. if (track.isAudioTrack()) {
  889. return this.useAudioStream(track);
  890. } else if (track.isVideoTrack()) {
  891. return this.useVideoStream(track);
  892. } else {
  893. logger.error(
  894. "Ignored not an audio nor a video track: ", track);
  895. return Promise.resolve();
  896. }
  897. });
  898. },
  899. _getConferenceOptions() {
  900. let options = config;
  901. if(config.enableRecording && !config.recordingType) {
  902. options.recordingType = (config.hosts &&
  903. (typeof config.hosts.jirecon != "undefined"))?
  904. "jirecon" : "colibri";
  905. }
  906. return options;
  907. },
  908. /**
  909. * Start using provided video stream.
  910. * Stops previous video stream.
  911. * @param {JitsiLocalTrack} [stream] new stream to use or null
  912. * @returns {Promise}
  913. */
  914. useVideoStream (newStream) {
  915. return room.replaceTrack(localVideo, newStream)
  916. .then(() => {
  917. // We call dispose after doing the replace because
  918. // dispose will try and do a new o/a after the
  919. // track removes itself. Doing it after means
  920. // the JitsiLocalTrack::conference member is already
  921. // cleared, so it won't try and do the o/a
  922. if (localVideo) {
  923. localVideo.dispose();
  924. }
  925. localVideo = newStream;
  926. if (newStream) {
  927. this.videoMuted = newStream.isMuted();
  928. this.isSharingScreen = newStream.videoType === 'desktop';
  929. APP.UI.addLocalStream(newStream);
  930. newStream.videoType === 'camera'
  931. && APP.UI.setCameraButtonEnabled(true);
  932. } else {
  933. this.videoMuted = false;
  934. this.isSharingScreen = false;
  935. }
  936. APP.UI.setVideoMuted(this.getMyUserId(), this.videoMuted);
  937. APP.UI.updateDesktopSharingButtons();
  938. });
  939. },
  940. /**
  941. * Start using provided audio stream.
  942. * Stops previous audio stream.
  943. * @param {JitsiLocalTrack} [stream] new stream to use or null
  944. * @returns {Promise}
  945. */
  946. useAudioStream (newStream) {
  947. return room.replaceTrack(localAudio, newStream)
  948. .then(() => {
  949. // We call dispose after doing the replace because
  950. // dispose will try and do a new o/a after the
  951. // track removes itself. Doing it after means
  952. // the JitsiLocalTrack::conference member is already
  953. // cleared, so it won't try and do the o/a
  954. if (localAudio) {
  955. localAudio.dispose();
  956. }
  957. localAudio = newStream;
  958. if (newStream) {
  959. this.audioMuted = newStream.isMuted();
  960. APP.UI.addLocalStream(newStream);
  961. } else {
  962. this.audioMuted = false;
  963. }
  964. APP.UI.setMicrophoneButtonEnabled(true);
  965. APP.UI.setAudioMuted(this.getMyUserId(), this.audioMuted);
  966. });
  967. },
  968. videoSwitchInProgress: false,
  969. toggleScreenSharing (shareScreen = !this.isSharingScreen) {
  970. if (this.videoSwitchInProgress) {
  971. logger.warn("Switch in progress.");
  972. return;
  973. }
  974. if (!this.isDesktopSharingEnabled) {
  975. logger.warn("Cannot toggle screen sharing: not supported.");
  976. return;
  977. }
  978. this.videoSwitchInProgress = true;
  979. let externalInstallation = false;
  980. if (shareScreen) {
  981. this.screenSharingPromise = createLocalTracks({
  982. devices: ['desktop'],
  983. desktopSharingExtensionExternalInstallation: {
  984. interval: 500,
  985. checkAgain: () => {
  986. return DSExternalInstallationInProgress;
  987. },
  988. listener: (status, url) => {
  989. switch(status) {
  990. case "waitingForExtension":
  991. DSExternalInstallationInProgress = true;
  992. externalInstallation = true;
  993. APP.UI.showExtensionExternalInstallationDialog(
  994. url);
  995. break;
  996. case "extensionFound":
  997. if(externalInstallation) //close the dialog
  998. $.prompt.close();
  999. break;
  1000. default:
  1001. //Unknown status
  1002. }
  1003. }
  1004. }
  1005. }).then(([stream]) => {
  1006. DSExternalInstallationInProgress = false;
  1007. // close external installation dialog on success.
  1008. if(externalInstallation)
  1009. $.prompt.close();
  1010. stream.on(
  1011. TrackEvents.LOCAL_TRACK_STOPPED,
  1012. () => {
  1013. // if stream was stopped during screensharing session
  1014. // then we should switch to video
  1015. // otherwise we stopped it because we already switched
  1016. // to video, so nothing to do here
  1017. if (this.isSharingScreen) {
  1018. this.toggleScreenSharing(false);
  1019. }
  1020. }
  1021. );
  1022. return this.useVideoStream(stream);
  1023. }).then(() => {
  1024. this.videoSwitchInProgress = false;
  1025. JitsiMeetJS.analytics.sendEvent(
  1026. 'conference.sharingDesktop.start');
  1027. logger.log('sharing local desktop');
  1028. }).catch((err) => {
  1029. // close external installation dialog to show the error.
  1030. if(externalInstallation)
  1031. $.prompt.close();
  1032. this.videoSwitchInProgress = false;
  1033. this.toggleScreenSharing(false);
  1034. if (err.name === TrackErrors.CHROME_EXTENSION_USER_CANCELED) {
  1035. return;
  1036. }
  1037. logger.error('failed to share local desktop', err);
  1038. if (err.name === TrackErrors.FIREFOX_EXTENSION_NEEDED) {
  1039. APP.UI.showExtensionRequiredDialog(
  1040. config.desktopSharingFirefoxExtensionURL
  1041. );
  1042. return;
  1043. }
  1044. // Handling:
  1045. // TrackErrors.PERMISSION_DENIED
  1046. // TrackErrors.CHROME_EXTENSION_INSTALLATION_ERROR
  1047. // TrackErrors.GENERAL
  1048. // and any other
  1049. let dialogTxt;
  1050. let dialogTitleKey;
  1051. if (err.name === TrackErrors.PERMISSION_DENIED) {
  1052. dialogTxt = APP.translation.generateTranslationHTML(
  1053. "dialog.screenSharingPermissionDeniedError");
  1054. dialogTitleKey = "dialog.error";
  1055. } else {
  1056. dialogTxt = APP.translation.generateTranslationHTML(
  1057. "dialog.failtoinstall");
  1058. dialogTitleKey = "dialog.permissionDenied";
  1059. }
  1060. APP.UI.messageHandler.openDialog(
  1061. dialogTitleKey, dialogTxt, false);
  1062. });
  1063. } else {
  1064. APP.remoteControl.receiver.stop();
  1065. this.screenSharingPromise = createLocalTracks(
  1066. { devices: ['video'] })
  1067. .then(
  1068. ([stream]) => this.useVideoStream(stream)
  1069. ).then(() => {
  1070. this.videoSwitchInProgress = false;
  1071. JitsiMeetJS.analytics.sendEvent(
  1072. 'conference.sharingDesktop.stop');
  1073. logger.log('sharing local video');
  1074. }).catch((err) => {
  1075. this.useVideoStream(null);
  1076. this.videoSwitchInProgress = false;
  1077. logger.error('failed to share local video', err);
  1078. });
  1079. }
  1080. },
  1081. /**
  1082. * Setup interaction between conference and UI.
  1083. */
  1084. _setupListeners () {
  1085. // add local streams when joined to the conference
  1086. room.on(ConferenceEvents.CONFERENCE_JOINED, () => {
  1087. APP.store.dispatch(conferenceJoined(room));
  1088. APP.UI.mucJoined();
  1089. APP.API.notifyConferenceJoined(APP.conference.roomName);
  1090. APP.UI.markVideoInterrupted(false);
  1091. });
  1092. room.on(
  1093. ConferenceEvents.CONFERENCE_LEFT,
  1094. (...args) => APP.store.dispatch(conferenceLeft(room, ...args)));
  1095. room.on(
  1096. ConferenceEvents.AUTH_STATUS_CHANGED,
  1097. function (authEnabled, authLogin) {
  1098. APP.UI.updateAuthInfo(authEnabled, authLogin);
  1099. }
  1100. );
  1101. room.on(ConferenceEvents.PARTCIPANT_FEATURES_CHANGED,
  1102. user => APP.UI.onUserFeaturesChanged(user));
  1103. room.on(ConferenceEvents.USER_JOINED, (id, user) => {
  1104. if (user.isHidden())
  1105. return;
  1106. APP.store.dispatch(participantJoined({
  1107. id,
  1108. name: user.getDisplayName(),
  1109. role: user.getRole()
  1110. }));
  1111. logger.log('USER %s connnected', id, user);
  1112. APP.API.notifyUserJoined(id);
  1113. APP.UI.addUser(user);
  1114. // check the roles for the new user and reflect them
  1115. APP.UI.updateUserRole(user);
  1116. });
  1117. room.on(ConferenceEvents.USER_LEFT, (id, user) => {
  1118. APP.store.dispatch(participantLeft(id, user));
  1119. logger.log('USER %s LEFT', id, user);
  1120. APP.API.notifyUserLeft(id);
  1121. APP.UI.removeUser(id, user.getDisplayName());
  1122. APP.UI.onSharedVideoStop(id);
  1123. });
  1124. room.on(ConferenceEvents.USER_ROLE_CHANGED, (id, role) => {
  1125. APP.store.dispatch(participantRoleChanged(id, role));
  1126. if (this.isLocalId(id)) {
  1127. logger.info(`My role changed, new role: ${role}`);
  1128. if (this.isModerator !== room.isModerator()) {
  1129. this.isModerator = room.isModerator();
  1130. APP.UI.updateLocalRole(room.isModerator());
  1131. }
  1132. } else {
  1133. let user = room.getParticipantById(id);
  1134. if (user) {
  1135. APP.UI.updateUserRole(user);
  1136. }
  1137. }
  1138. });
  1139. room.on(ConferenceEvents.TRACK_ADDED, (track) => {
  1140. if(!track || track.isLocal())
  1141. return;
  1142. track.on(TrackEvents.TRACK_VIDEOTYPE_CHANGED, (type) => {
  1143. APP.UI.onPeerVideoTypeChanged(track.getParticipantId(), type);
  1144. });
  1145. APP.UI.addRemoteStream(track);
  1146. });
  1147. room.on(ConferenceEvents.TRACK_REMOVED, (track) => {
  1148. if(!track || track.isLocal())
  1149. return;
  1150. APP.UI.removeRemoteStream(track);
  1151. });
  1152. room.on(ConferenceEvents.TRACK_MUTE_CHANGED, (track) => {
  1153. if(!track)
  1154. return;
  1155. const handler = (track.getType() === "audio")?
  1156. APP.UI.setAudioMuted : APP.UI.setVideoMuted;
  1157. let id;
  1158. const mute = track.isMuted();
  1159. if(track.isLocal()){
  1160. id = APP.conference.getMyUserId();
  1161. if(track.getType() === "audio") {
  1162. this.audioMuted = mute;
  1163. } else {
  1164. this.videoMuted = mute;
  1165. }
  1166. } else {
  1167. id = track.getParticipantId();
  1168. }
  1169. handler(id , mute);
  1170. });
  1171. room.on(ConferenceEvents.TRACK_AUDIO_LEVEL_CHANGED, (id, lvl) => {
  1172. if(this.isLocalId(id) && localAudio && localAudio.isMuted()) {
  1173. lvl = 0;
  1174. }
  1175. if(config.debug)
  1176. {
  1177. this.audioLevelsMap[id] = lvl;
  1178. if(config.debugAudioLevels)
  1179. logger.log("AudioLevel:" + id + "/" + lvl);
  1180. }
  1181. APP.UI.setAudioLevel(id, lvl);
  1182. });
  1183. room.on(ConferenceEvents.TALK_WHILE_MUTED, () => {
  1184. APP.UI.showToolbar(6000);
  1185. APP.UI.showCustomToolbarPopup('#talkWhileMutedPopup', true, 5000);
  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. /**
  1780. * Checks if the participant given by participantId is currently in the
  1781. * last N set if there's one supported.
  1782. *
  1783. * @param participantId the identifier of the participant
  1784. * @returns {boolean} {true} if the participant given by the participantId
  1785. * is currently in the last N set or if there's no last N set at this point
  1786. * and {false} otherwise
  1787. */
  1788. isInLastN (participantId) {
  1789. return room.isInLastN(participantId);
  1790. }
  1791. };