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

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