Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

conference.js 70KB

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