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

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