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

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