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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704
  1. /* global APP, JitsiMeetJS, config, interfaceConfig */
  2. import { jitsiLocalStorage } from '@jitsi/js-utils';
  3. import Logger from '@jitsi/logger';
  4. import EventEmitter from 'events';
  5. import { ENDPOINT_TEXT_MESSAGE_NAME } from './modules/API/constants';
  6. import { AUDIO_ONLY_SCREEN_SHARE_NO_TRACK } from './modules/UI/UIErrors';
  7. import mediaDeviceHelper from './modules/devices/mediaDeviceHelper';
  8. import Recorder from './modules/recorder/Recorder';
  9. import { createTaskQueue } from './modules/util/helpers';
  10. import {
  11. createDeviceChangedEvent,
  12. createScreenSharingEvent,
  13. createStartSilentEvent,
  14. createTrackMutedEvent
  15. } from './react/features/analytics/AnalyticsEvents';
  16. import { sendAnalytics } from './react/features/analytics/functions';
  17. import {
  18. maybeRedirectToWelcomePage,
  19. redirectToStaticPage,
  20. reloadWithStoredParams
  21. } from './react/features/app/actions';
  22. import { showModeratedNotification } from './react/features/av-moderation/actions';
  23. import { shouldShowModeratedNotification } from './react/features/av-moderation/functions';
  24. import {
  25. _conferenceWillJoin,
  26. authStatusChanged,
  27. conferenceFailed,
  28. conferenceJoinInProgress,
  29. conferenceJoined,
  30. conferenceLeft,
  31. conferenceSubjectChanged,
  32. conferenceTimestampChanged,
  33. conferenceUniqueIdSet,
  34. conferenceWillInit,
  35. conferenceWillLeave,
  36. dataChannelClosed,
  37. dataChannelOpened,
  38. e2eRttChanged,
  39. kickedOut,
  40. lockStateChanged,
  41. nonParticipantMessageReceived,
  42. onStartMutedPolicyChanged,
  43. p2pStatusChanged
  44. } from './react/features/base/conference/actions';
  45. import {
  46. AVATAR_URL_COMMAND,
  47. CONFERENCE_LEAVE_REASONS,
  48. EMAIL_COMMAND
  49. } from './react/features/base/conference/constants';
  50. import {
  51. commonUserJoinedHandling,
  52. commonUserLeftHandling,
  53. getConferenceOptions,
  54. sendLocalParticipant
  55. } from './react/features/base/conference/functions';
  56. import { getReplaceParticipant } from './react/features/base/config/functions';
  57. import { connect } from './react/features/base/connection/actions.web';
  58. import {
  59. checkAndNotifyForNewDevice,
  60. getAvailableDevices,
  61. notifyCameraError,
  62. notifyMicError,
  63. updateDeviceList
  64. } from './react/features/base/devices/actions.web';
  65. import {
  66. getDefaultDeviceId,
  67. setAudioOutputDeviceId
  68. } from './react/features/base/devices/functions.web';
  69. import {
  70. JitsiConferenceErrors,
  71. JitsiConferenceEvents,
  72. JitsiE2ePingEvents,
  73. JitsiMediaDevicesEvents,
  74. JitsiTrackErrors,
  75. JitsiTrackEvents,
  76. browser
  77. } from './react/features/base/lib-jitsi-meet';
  78. import {
  79. gumPending,
  80. setAudioAvailable,
  81. setAudioMuted,
  82. setAudioUnmutePermissions,
  83. setVideoAvailable,
  84. setVideoMuted,
  85. setVideoUnmutePermissions
  86. } from './react/features/base/media/actions';
  87. import { MEDIA_TYPE } from './react/features/base/media/constants';
  88. import {
  89. getStartWithAudioMuted,
  90. getStartWithVideoMuted,
  91. isVideoMutedByUser
  92. } from './react/features/base/media/functions';
  93. import { IGUMPendingState } from './react/features/base/media/types';
  94. import {
  95. dominantSpeakerChanged,
  96. localParticipantAudioLevelChanged,
  97. localParticipantRoleChanged,
  98. participantKicked,
  99. participantMutedUs,
  100. participantPresenceChanged,
  101. participantRoleChanged,
  102. participantSourcesUpdated,
  103. participantUpdated,
  104. screenshareParticipantDisplayNameChanged,
  105. updateRemoteParticipantFeatures
  106. } from './react/features/base/participants/actions';
  107. import {
  108. getLocalParticipant,
  109. getNormalizedDisplayName,
  110. getVirtualScreenshareParticipantByOwnerId
  111. } from './react/features/base/participants/functions';
  112. import { updateSettings } from './react/features/base/settings/actions';
  113. import {
  114. addLocalTrack,
  115. destroyLocalTracks,
  116. replaceLocalTrack,
  117. toggleScreensharing as toggleScreensharingA,
  118. trackAdded,
  119. trackRemoved
  120. } from './react/features/base/tracks/actions';
  121. import {
  122. createLocalTracksF,
  123. getLocalJitsiAudioTrack,
  124. getLocalJitsiVideoTrack,
  125. getLocalTracks,
  126. getLocalVideoTrack,
  127. isLocalTrackMuted,
  128. isUserInteractionRequiredForUnmute
  129. } from './react/features/base/tracks/functions';
  130. import { downloadJSON } from './react/features/base/util/downloadJSON';
  131. import { showDesktopPicker } from './react/features/desktop-picker/actions';
  132. import { appendSuffix } from './react/features/display-name/functions';
  133. import { maybeOpenFeedbackDialog, submitFeedback } from './react/features/feedback/actions';
  134. import { initKeyboardShortcuts } from './react/features/keyboard-shortcuts/actions';
  135. import { maybeSetLobbyChatMessageListener } from './react/features/lobby/actions.any';
  136. import { setNoiseSuppressionEnabled } from './react/features/noise-suppression/actions';
  137. import {
  138. hideNotification,
  139. showErrorNotification,
  140. showNotification,
  141. showWarningNotification
  142. } from './react/features/notifications/actions';
  143. import {
  144. DATA_CHANNEL_CLOSED_NOTIFICATION_ID,
  145. NOTIFICATION_TIMEOUT_TYPE
  146. } from './react/features/notifications/constants';
  147. import { isModerationNotificationDisplayed } from './react/features/notifications/functions';
  148. import { mediaPermissionPromptVisibilityChanged } from './react/features/overlay/actions';
  149. import { suspendDetected } from './react/features/power-monitor/actions';
  150. import { initPrejoin, makePrecallTest } from './react/features/prejoin/actions';
  151. import { isPrejoinPageVisible } from './react/features/prejoin/functions';
  152. import { disableReceiver, stopReceiver } from './react/features/remote-control/actions';
  153. import { setScreenAudioShareState } from './react/features/screen-share/actions.web';
  154. import { isScreenAudioShared } from './react/features/screen-share/functions';
  155. import { toggleScreenshotCaptureSummary } from './react/features/screenshot-capture/actions';
  156. import { AudioMixerEffect } from './react/features/stream-effects/audio-mixer/AudioMixerEffect';
  157. import { createRnnoiseProcessor } from './react/features/stream-effects/rnnoise';
  158. import { endpointMessageReceived } from './react/features/subtitles/actions.any';
  159. import { handleToggleVideoMuted } from './react/features/toolbox/actions.any';
  160. import { muteLocal } from './react/features/video-menu/actions.any';
  161. import { iAmVisitor } from './react/features/visitors/functions';
  162. import UIEvents from './service/UI/UIEvents';
  163. const logger = Logger.getLogger(__filename);
  164. const eventEmitter = new EventEmitter();
  165. let room;
  166. /*
  167. * Logic to open a desktop picker put on the window global for
  168. * lib-jitsi-meet to detect and invoke
  169. */
  170. window.JitsiMeetScreenObtainer = {
  171. openDesktopPicker(options, onSourceChoose) {
  172. APP.store.dispatch(showDesktopPicker(options, onSourceChoose));
  173. }
  174. };
  175. /**
  176. * Known custom conference commands.
  177. */
  178. const commands = {
  179. AVATAR_URL: AVATAR_URL_COMMAND,
  180. CUSTOM_ROLE: 'custom-role',
  181. EMAIL: EMAIL_COMMAND,
  182. ETHERPAD: 'etherpad'
  183. };
  184. /**
  185. * Share data to other users.
  186. * @param command the command
  187. * @param {string} value new value
  188. */
  189. function sendData(command, value) {
  190. if (!room) {
  191. return;
  192. }
  193. room.removeCommand(command);
  194. room.sendCommand(command, { value });
  195. }
  196. /**
  197. * Mute or unmute local audio stream if it exists.
  198. * @param {boolean} muted - if audio stream should be muted or unmuted.
  199. */
  200. function muteLocalAudio(muted) {
  201. APP.store.dispatch(setAudioMuted(muted));
  202. }
  203. /**
  204. * Mute or unmute local video stream if it exists.
  205. * @param {boolean} muted if video stream should be muted or unmuted.
  206. *
  207. */
  208. function muteLocalVideo(muted) {
  209. APP.store.dispatch(setVideoMuted(muted));
  210. }
  211. /**
  212. * A queue for the async replaceLocalTrack action so that multiple audio
  213. * replacements cannot happen simultaneously. This solves the issue where
  214. * replaceLocalTrack is called multiple times with an oldTrack of null, causing
  215. * multiple local tracks of the same type to be used.
  216. *
  217. * @private
  218. * @type {Object}
  219. */
  220. const _replaceLocalAudioTrackQueue = createTaskQueue();
  221. /**
  222. * A task queue for replacement local video tracks. This separate queue exists
  223. * so video replacement is not blocked by audio replacement tasks in the queue
  224. * {@link _replaceLocalAudioTrackQueue}.
  225. *
  226. * @private
  227. * @type {Object}
  228. */
  229. const _replaceLocalVideoTrackQueue = createTaskQueue();
  230. /**
  231. *
  232. */
  233. class ConferenceConnector {
  234. /**
  235. *
  236. */
  237. constructor(resolve, reject, conference) {
  238. this._conference = conference;
  239. this._resolve = resolve;
  240. this._reject = reject;
  241. this.reconnectTimeout = null;
  242. room.on(JitsiConferenceEvents.CONFERENCE_JOINED,
  243. this._handleConferenceJoined.bind(this));
  244. room.on(JitsiConferenceEvents.CONFERENCE_FAILED,
  245. this._onConferenceFailed.bind(this));
  246. }
  247. /**
  248. *
  249. */
  250. _handleConferenceFailed(err) {
  251. this._unsubscribe();
  252. this._reject(err);
  253. }
  254. /**
  255. *
  256. */
  257. _onConferenceFailed(err, ...params) {
  258. APP.store.dispatch(conferenceFailed(room, err, ...params));
  259. logger.error('CONFERENCE FAILED:', err, ...params);
  260. switch (err) {
  261. case JitsiConferenceErrors.NOT_ALLOWED_ERROR: {
  262. // let's show some auth not allowed page
  263. APP.store.dispatch(redirectToStaticPage('static/authError.html'));
  264. break;
  265. }
  266. case JitsiConferenceErrors.RESERVATION_ERROR: {
  267. const [ code, msg ] = params;
  268. APP.store.dispatch(showErrorNotification({
  269. descriptionArguments: {
  270. code,
  271. msg
  272. },
  273. descriptionKey: 'dialog.reservationErrorMsg',
  274. titleKey: 'dialog.reservationError'
  275. }, NOTIFICATION_TIMEOUT_TYPE.LONG));
  276. break;
  277. }
  278. case JitsiConferenceErrors.GRACEFUL_SHUTDOWN:
  279. APP.store.dispatch(showErrorNotification({
  280. descriptionKey: 'dialog.gracefulShutdown',
  281. titleKey: 'dialog.serviceUnavailable'
  282. }, NOTIFICATION_TIMEOUT_TYPE.LONG));
  283. break;
  284. // FIXME FOCUS_DISCONNECTED is a confusing event name.
  285. // What really happens there is that the library is not ready yet,
  286. // because Jicofo is not available, but it is going to give it another
  287. // try.
  288. case JitsiConferenceErrors.FOCUS_DISCONNECTED: {
  289. const [ focus, retrySec ] = params;
  290. APP.store.dispatch(showNotification({
  291. descriptionKey: focus,
  292. titleKey: retrySec
  293. }, NOTIFICATION_TIMEOUT_TYPE.SHORT));
  294. break;
  295. }
  296. case JitsiConferenceErrors.FOCUS_LEFT:
  297. case JitsiConferenceErrors.ICE_FAILED:
  298. case JitsiConferenceErrors.VIDEOBRIDGE_NOT_AVAILABLE:
  299. case JitsiConferenceErrors.OFFER_ANSWER_FAILED:
  300. APP.store.dispatch(conferenceWillLeave(room));
  301. // FIXME the conference should be stopped by the library and not by
  302. // the app. Both the errors above are unrecoverable from the library
  303. // perspective.
  304. room.leave(CONFERENCE_LEAVE_REASONS.UNRECOVERABLE_ERROR).then(() => APP.connection.disconnect());
  305. break;
  306. case JitsiConferenceErrors.INCOMPATIBLE_SERVER_VERSIONS:
  307. APP.store.dispatch(reloadWithStoredParams());
  308. break;
  309. default:
  310. this._handleConferenceFailed(err, ...params);
  311. }
  312. }
  313. /**
  314. *
  315. */
  316. _unsubscribe() {
  317. room.off(
  318. JitsiConferenceEvents.CONFERENCE_JOINED,
  319. this._handleConferenceJoined);
  320. room.off(
  321. JitsiConferenceEvents.CONFERENCE_FAILED,
  322. this._onConferenceFailed);
  323. if (this.reconnectTimeout !== null) {
  324. clearTimeout(this.reconnectTimeout);
  325. }
  326. }
  327. /**
  328. *
  329. */
  330. _handleConferenceJoined() {
  331. this._unsubscribe();
  332. this._resolve();
  333. }
  334. /**
  335. *
  336. */
  337. connect() {
  338. const replaceParticipant = getReplaceParticipant(APP.store.getState());
  339. // the local storage overrides here and in connection.js can be used by jibri
  340. room.join(jitsiLocalStorage.getItem('xmpp_conference_password_override'), replaceParticipant);
  341. }
  342. }
  343. /**
  344. * Disconnects the connection.
  345. * @returns resolved Promise. We need this in order to make the Promise.all
  346. * call in hangup() to resolve when all operations are finished.
  347. */
  348. function disconnect() {
  349. const onDisconnected = () => {
  350. APP.API.notifyConferenceLeft(APP.conference.roomName);
  351. return Promise.resolve();
  352. };
  353. if (!APP.connection) {
  354. return onDisconnected();
  355. }
  356. return APP.connection.disconnect().then(onDisconnected, onDisconnected);
  357. }
  358. /**
  359. * Sets the GUM pending state for the tracks that have failed.
  360. *
  361. * NOTE: Some of the track that we will be setting to GUM pending state NONE may not have failed but they may have
  362. * been requested. This won't be a problem because their current GUM pending state will be NONE anyway.
  363. * @param {JitsiLocalTrack} tracks - The tracks that have been created.
  364. * @returns {void}
  365. */
  366. function setGUMPendingStateOnFailedTracks(tracks) {
  367. const tracksTypes = tracks.map(track => track.getType());
  368. const nonPendingTracks = [ MEDIA_TYPE.AUDIO, MEDIA_TYPE.VIDEO ].filter(type => !tracksTypes.includes(type));
  369. APP.store.dispatch(gumPending(nonPendingTracks, IGUMPendingState.NONE));
  370. }
  371. export default {
  372. /**
  373. * Flag used to delay modification of the muted status of local media tracks
  374. * until those are created (or not, but at that point it's certain that
  375. * the tracks won't exist).
  376. */
  377. _localTracksInitialized: false,
  378. /**
  379. * Flag used to prevent the creation of another local video track in this.muteVideo if one is already in progress.
  380. */
  381. isCreatingLocalTrack: false,
  382. isSharingScreen: false,
  383. /**
  384. * Returns an object containing a promise which resolves with the created tracks &
  385. * the errors resulting from that process.
  386. * @param {object} options
  387. * @param {boolean} options.startAudioOnly=false - if <tt>true</tt> then
  388. * only audio track will be created and the audio only mode will be turned
  389. * on.
  390. * @param {boolean} options.startScreenSharing=false - if <tt>true</tt>
  391. * should start with screensharing instead of camera video.
  392. * @param {boolean} options.startWithAudioMuted - will start the conference
  393. * without any audio tracks.
  394. * @param {boolean} options.startWithVideoMuted - will start the conference
  395. * without any video tracks.
  396. * @returns {Promise<JitsiLocalTrack[]>, Object}
  397. */
  398. createInitialLocalTracks(options = {}) {
  399. const errors = {};
  400. // Always get a handle on the audio input device so that we have statistics (such as "No audio input" or
  401. // "Are you trying to speak?" ) even if the user joins the conference muted.
  402. const initialDevices = config.disableInitialGUM ? [] : [ MEDIA_TYPE.AUDIO ];
  403. const requestedAudio = !config.disableInitialGUM;
  404. let requestedVideo = false;
  405. if (!config.disableInitialGUM
  406. && !options.startWithVideoMuted
  407. && !options.startAudioOnly
  408. && !options.startScreenSharing) {
  409. initialDevices.push(MEDIA_TYPE.VIDEO);
  410. requestedVideo = true;
  411. }
  412. if (!config.disableInitialGUM) {
  413. JitsiMeetJS.mediaDevices.addEventListener(
  414. JitsiMediaDevicesEvents.PERMISSION_PROMPT_IS_SHOWN,
  415. browserName =>
  416. APP.store.dispatch(
  417. mediaPermissionPromptVisibilityChanged(true, browserName))
  418. );
  419. }
  420. let tryCreateLocalTracks = Promise.resolve([]);
  421. // On Electron there is no permission prompt for granting permissions. That's why we don't need to
  422. // spend much time displaying the overlay screen. If GUM is not resolved within 15 seconds it will
  423. // probably never resolve.
  424. const timeout = browser.isElectron() ? 15000 : 60000;
  425. const audioOptions = {
  426. devices: [ MEDIA_TYPE.AUDIO ],
  427. timeout,
  428. firePermissionPromptIsShownEvent: true
  429. };
  430. // Spot uses the _desktopSharingSourceDevice config option to use an external video input device label as
  431. // screenshare and calls getUserMedia instead of getDisplayMedia for capturing the media.
  432. if (options.startScreenSharing && config._desktopSharingSourceDevice) {
  433. tryCreateLocalTracks = this._createDesktopTrack()
  434. .then(([ desktopStream ]) => {
  435. if (!requestedAudio) {
  436. return [ desktopStream ];
  437. }
  438. return createLocalTracksF(audioOptions)
  439. .then(([ audioStream ]) =>
  440. [ desktopStream, audioStream ])
  441. .catch(error => {
  442. errors.audioOnlyError = error;
  443. return [ desktopStream ];
  444. });
  445. })
  446. .catch(error => {
  447. logger.error('Failed to obtain desktop stream', error);
  448. errors.screenSharingError = error;
  449. return requestedAudio ? createLocalTracksF(audioOptions) : [];
  450. })
  451. .catch(error => {
  452. errors.audioOnlyError = error;
  453. return [];
  454. });
  455. } else if (requestedAudio || requestedVideo) {
  456. APP.store.dispatch(gumPending(initialDevices, IGUMPendingState.PENDING_UNMUTE));
  457. tryCreateLocalTracks = createLocalTracksF({
  458. devices: initialDevices,
  459. timeout,
  460. firePermissionPromptIsShownEvent: true
  461. })
  462. .catch(async error => {
  463. if (error.name === JitsiTrackErrors.TIMEOUT && !browser.isElectron()) {
  464. errors.audioAndVideoError = error;
  465. return [];
  466. }
  467. // Retry with separate gUM calls.
  468. const gUMPromises = [];
  469. const tracks = [];
  470. if (requestedAudio) {
  471. gUMPromises.push(createLocalTracksF(audioOptions));
  472. }
  473. if (requestedVideo) {
  474. gUMPromises.push(createLocalTracksF({
  475. devices: [ MEDIA_TYPE.VIDEO ],
  476. timeout,
  477. firePermissionPromptIsShownEvent: true
  478. }));
  479. }
  480. const results = await Promise.allSettled(gUMPromises);
  481. let errorMsg;
  482. results.forEach((result, idx) => {
  483. if (result.status === 'fulfilled') {
  484. tracks.push(result.value[0]);
  485. } else {
  486. errorMsg = result.reason;
  487. const isAudio = idx === 0;
  488. logger.error(`${isAudio ? 'Audio' : 'Video'} track creation failed with error ${errorMsg}`);
  489. if (isAudio) {
  490. errors.audioOnlyError = errorMsg;
  491. } else {
  492. errors.videoOnlyError = errorMsg;
  493. }
  494. }
  495. });
  496. if (errors.audioOnlyError && errors.videoOnlyError) {
  497. errors.audioAndVideoError = errorMsg;
  498. }
  499. return tracks;
  500. });
  501. }
  502. // Hide the permissions prompt/overlay as soon as the tracks are created. Don't wait for the connection to
  503. // be established, as in some cases like when auth is required, connection won't be established until the user
  504. // inputs their credentials, but the dialog would be overshadowed by the overlay.
  505. tryCreateLocalTracks.then(tracks => {
  506. APP.store.dispatch(mediaPermissionPromptVisibilityChanged(false));
  507. return tracks;
  508. });
  509. return {
  510. tryCreateLocalTracks,
  511. errors
  512. };
  513. },
  514. /**
  515. * Displays error notifications according to the state carried by {@code errors} object returned
  516. * by {@link createInitialLocalTracks}.
  517. * @param {Object} errors - the errors (if any) returned by {@link createInitialLocalTracks}.
  518. *
  519. * @returns {void}
  520. * @private
  521. */
  522. _displayErrorsForCreateInitialLocalTracks(errors) {
  523. const {
  524. audioAndVideoError,
  525. audioOnlyError,
  526. screenSharingError,
  527. videoOnlyError
  528. } = errors;
  529. // FIXME If there will be microphone error it will cover any screensharing dialog, but it's still better than in
  530. // the reverse order where the screensharing dialog will sometimes be closing the microphone alert
  531. // ($.prompt.close(); is called). Need to figure out dialogs chaining to fix that.
  532. if (screenSharingError) {
  533. this._handleScreenSharingError(screenSharingError);
  534. }
  535. if (audioAndVideoError || audioOnlyError) {
  536. if (audioOnlyError || videoOnlyError) {
  537. // If both requests for 'audio' + 'video' and 'audio' only failed, we assume that there are some
  538. // problems with user's microphone and show corresponding dialog.
  539. APP.store.dispatch(notifyMicError(audioOnlyError));
  540. APP.store.dispatch(notifyCameraError(videoOnlyError));
  541. } else {
  542. // If request for 'audio' + 'video' failed, but request for 'audio' only was OK, we assume that we had
  543. // problems with camera and show corresponding dialog.
  544. APP.store.dispatch(notifyCameraError(audioAndVideoError));
  545. }
  546. }
  547. },
  548. startConference(tracks) {
  549. tracks.forEach(track => {
  550. if ((track.isAudioTrack() && this.isLocalAudioMuted())
  551. || (track.isVideoTrack() && this.isLocalVideoMuted())) {
  552. const mediaType = track.getType();
  553. sendAnalytics(
  554. createTrackMutedEvent(mediaType, 'initial mute'));
  555. logger.log(`${mediaType} mute: initially muted.`);
  556. track.mute();
  557. }
  558. });
  559. this._createRoom(tracks);
  560. // if user didn't give access to mic or camera or doesn't have
  561. // them at all, we mark corresponding toolbar buttons as muted,
  562. // so that the user can try unmute later on and add audio/video
  563. // to the conference
  564. if (!tracks.find(t => t.isAudioTrack())) {
  565. this.setAudioMuteStatus(true);
  566. }
  567. if (!tracks.find(t => t.isVideoTrack())) {
  568. this.setVideoMuteStatus();
  569. }
  570. if (config.iAmRecorder) {
  571. this.recorder = new Recorder();
  572. }
  573. if (config.startSilent) {
  574. sendAnalytics(createStartSilentEvent());
  575. APP.store.dispatch(showNotification({
  576. descriptionKey: 'notify.startSilentDescription',
  577. titleKey: 'notify.startSilentTitle'
  578. }, NOTIFICATION_TIMEOUT_TYPE.LONG));
  579. }
  580. // XXX The API will take care of disconnecting from the XMPP
  581. // server (and, thus, leaving the room) on unload.
  582. return new Promise((resolve, reject) => {
  583. new ConferenceConnector(resolve, reject, this).connect();
  584. });
  585. },
  586. /**
  587. * Open new connection and join the conference when prejoin page is not enabled.
  588. * If prejoin page is enabled open an new connection in the background
  589. * and create local tracks.
  590. *
  591. * @param {{ roomName: string }} options
  592. * @returns {Promise}
  593. */
  594. async init({ roomName }) {
  595. const state = APP.store.getState();
  596. const initialOptions = {
  597. startAudioOnly: config.startAudioOnly,
  598. startScreenSharing: config.startScreenSharing,
  599. startWithAudioMuted: getStartWithAudioMuted(state) || isUserInteractionRequiredForUnmute(state),
  600. startWithVideoMuted: getStartWithVideoMuted(state) || isUserInteractionRequiredForUnmute(state)
  601. };
  602. this.roomName = roomName;
  603. try {
  604. // Initialize the device list first. This way, when creating tracks based on preferred devices, loose label
  605. // matching can be done in cases where the exact ID match is no longer available, such as -
  606. // 1. When the camera device has switched USB ports.
  607. // 2. When in startSilent mode we want to start with audio muted
  608. await this._initDeviceList();
  609. } catch (error) {
  610. logger.warn('initial device list initialization failed', error);
  611. }
  612. // Filter out the local tracks based on various config options, i.e., when user joins muted or is muted by
  613. // focus. However, audio track will always be created even though it is not added to the conference since we
  614. // want audio related features (noisy mic, talk while muted, etc.) to work even if the mic is muted.
  615. const handleInitialTracks = (options, tracks) => {
  616. let localTracks = tracks;
  617. // No local tracks are added when user joins as a visitor.
  618. if (iAmVisitor(state)) {
  619. return [];
  620. }
  621. if (options.startWithAudioMuted || room?.isStartAudioMuted()) {
  622. // Always add the track on Safari because of a known issue where audio playout doesn't happen
  623. // if the user joins audio and video muted, i.e., if there is no local media capture.
  624. if (browser.isWebKitBased()) {
  625. this.muteAudio(true, true);
  626. } else {
  627. localTracks = localTracks.filter(track => track.getType() !== MEDIA_TYPE.AUDIO);
  628. }
  629. }
  630. if (room?.isStartVideoMuted()) {
  631. localTracks = localTracks.filter(track => track.getType() !== MEDIA_TYPE.VIDEO);
  632. }
  633. return localTracks;
  634. };
  635. if (isPrejoinPageVisible(state)) {
  636. APP.store.dispatch(makePrecallTest(this._getConferenceOptions()));
  637. const { tryCreateLocalTracks, errors } = this.createInitialLocalTracks(initialOptions);
  638. const localTracks = await tryCreateLocalTracks;
  639. // Initialize device list a second time to ensure device labels get populated in case of an initial gUM
  640. // acceptance; otherwise they may remain as empty strings.
  641. this._initDeviceList(true);
  642. if (isPrejoinPageVisible(state)) {
  643. APP.store.dispatch(gumPending([ MEDIA_TYPE.AUDIO, MEDIA_TYPE.VIDEO ], IGUMPendingState.NONE));
  644. return APP.store.dispatch(initPrejoin(localTracks, errors));
  645. }
  646. logger.debug('Prejoin screen no longer displayed at the time when tracks were created');
  647. this._displayErrorsForCreateInitialLocalTracks(errors);
  648. const tracks = handleInitialTracks(initialOptions, localTracks);
  649. setGUMPendingStateOnFailedTracks(tracks);
  650. return this._setLocalAudioVideoStreams(tracks);
  651. }
  652. const { tryCreateLocalTracks, errors } = this.createInitialLocalTracks(initialOptions);
  653. return Promise.all([
  654. tryCreateLocalTracks.then(tr => {
  655. this._displayErrorsForCreateInitialLocalTracks(errors);
  656. return tr;
  657. }).then(tr => {
  658. this._initDeviceList(true);
  659. const filteredTracks = handleInitialTracks(initialOptions, tr);
  660. setGUMPendingStateOnFailedTracks(filteredTracks);
  661. return filteredTracks;
  662. }),
  663. APP.store.dispatch(connect())
  664. ]).then(([ tracks, _ ]) => {
  665. this.startConference(tracks).catch(logger.error);
  666. });
  667. },
  668. /**
  669. * Check if id is id of the local user.
  670. * @param {string} id id to check
  671. * @returns {boolean}
  672. */
  673. isLocalId(id) {
  674. return this.getMyUserId() === id;
  675. },
  676. /**
  677. * Tells whether the local video is muted or not.
  678. * @return {boolean}
  679. */
  680. isLocalVideoMuted() {
  681. // If the tracks are not ready, read from base/media state
  682. return this._localTracksInitialized
  683. ? isLocalTrackMuted(APP.store.getState()['features/base/tracks'], MEDIA_TYPE.VIDEO)
  684. : isVideoMutedByUser(APP.store);
  685. },
  686. /**
  687. * Verify if there is an ongoing system audio sharing session and apply to the provided track
  688. * as a AudioMixer effect.
  689. *
  690. * @param {*} localAudioTrack - track to which system audio track will be applied as an effect, most likely
  691. * microphone local audio track.
  692. */
  693. async _maybeApplyAudioMixerEffect(localAudioTrack) {
  694. // At the time of writing this comment there were two separate flows for toggling screen-sharing
  695. // and system audio sharing, the first is the legacy method using the functionality from conference.js
  696. // the second is used when both sendMultipleVideoStreams and sourceNameSignaling flags are set to true.
  697. // The second flow uses functionality from base/conference/middleware.web.js.
  698. // We check if system audio sharing was done using the first flow by verifying this._desktopAudioStream and
  699. // for the second by checking 'features/screen-share' state.
  700. const { desktopAudioTrack } = APP.store.getState()['features/screen-share'];
  701. const currentDesktopAudioTrack = this._desktopAudioStream || desktopAudioTrack;
  702. // If system audio is already being sent, mix it with the provided audio track.
  703. if (currentDesktopAudioTrack) {
  704. // In case system audio sharing was done in the absence of an initial mic audio track, there is no
  705. // AudioMixerEffect so we have to remove system audio track from the room before setting it as an effect.
  706. await room.replaceTrack(currentDesktopAudioTrack, null);
  707. this._mixerEffect = new AudioMixerEffect(currentDesktopAudioTrack);
  708. logger.debug('Mixing new audio track with existing screen audio track.');
  709. await localAudioTrack.setEffect(this._mixerEffect);
  710. }
  711. },
  712. /**
  713. * Simulates toolbar button click for audio mute. Used by shortcuts and API.
  714. * @param {boolean} mute true for mute and false for unmute.
  715. * @param {boolean} [showUI] when set to false will not display any error
  716. * dialogs in case of media permissions error.
  717. */
  718. muteAudio(mute, showUI = true) {
  719. const state = APP.store.getState();
  720. if (!mute
  721. && isUserInteractionRequiredForUnmute(state)) {
  722. logger.error('Unmuting audio requires user interaction');
  723. return;
  724. }
  725. // check for A/V Moderation when trying to unmute
  726. if (!mute && shouldShowModeratedNotification(MEDIA_TYPE.AUDIO, state)) {
  727. if (!isModerationNotificationDisplayed(MEDIA_TYPE.AUDIO, state)) {
  728. APP.store.dispatch(showModeratedNotification(MEDIA_TYPE.AUDIO));
  729. }
  730. return;
  731. }
  732. // Not ready to modify track's state yet
  733. if (!this._localTracksInitialized) {
  734. // This will only modify base/media.audio.muted which is then synced
  735. // up with the track at the end of local tracks initialization.
  736. muteLocalAudio(mute);
  737. this.setAudioMuteStatus(mute);
  738. return;
  739. } else if (this.isLocalAudioMuted() === mute) {
  740. // NO-OP
  741. return;
  742. }
  743. const localAudio = getLocalJitsiAudioTrack(APP.store.getState());
  744. if (!localAudio && !mute) {
  745. const maybeShowErrorDialog = error => {
  746. showUI && APP.store.dispatch(notifyMicError(error));
  747. };
  748. APP.store.dispatch(gumPending([ MEDIA_TYPE.AUDIO ], IGUMPendingState.PENDING_UNMUTE));
  749. createLocalTracksF({ devices: [ 'audio' ] })
  750. .then(([ audioTrack ]) => audioTrack)
  751. .catch(error => {
  752. maybeShowErrorDialog(error);
  753. // Rollback the audio muted status by using null track
  754. return null;
  755. })
  756. .then(async audioTrack => {
  757. await this._maybeApplyAudioMixerEffect(audioTrack);
  758. return this.useAudioStream(audioTrack);
  759. })
  760. .finally(() => {
  761. APP.store.dispatch(gumPending([ MEDIA_TYPE.AUDIO ], IGUMPendingState.NONE));
  762. });
  763. } else {
  764. muteLocalAudio(mute);
  765. }
  766. },
  767. /**
  768. * Returns whether local audio is muted or not.
  769. * @returns {boolean}
  770. */
  771. isLocalAudioMuted() {
  772. // If the tracks are not ready, read from base/media state
  773. return this._localTracksInitialized
  774. ? isLocalTrackMuted(
  775. APP.store.getState()['features/base/tracks'],
  776. MEDIA_TYPE.AUDIO)
  777. : Boolean(
  778. APP.store.getState()['features/base/media'].audio.muted);
  779. },
  780. /**
  781. * Simulates toolbar button click for audio mute. Used by shortcuts
  782. * and API.
  783. * @param {boolean} [showUI] when set to false will not display any error
  784. * dialogs in case of media permissions error.
  785. */
  786. toggleAudioMuted(showUI = true) {
  787. this.muteAudio(!this.isLocalAudioMuted(), showUI);
  788. },
  789. /**
  790. * Simulates toolbar button click for video mute. Used by shortcuts and API.
  791. * @param mute true for mute and false for unmute.
  792. * @param {boolean} [showUI] when set to false will not display any error
  793. * dialogs in case of media permissions error.
  794. */
  795. muteVideo(mute, showUI = true) {
  796. if (this.videoSwitchInProgress) {
  797. logger.warn('muteVideo - unable to perform operations while video switch is in progress');
  798. return;
  799. }
  800. const state = APP.store.getState();
  801. if (!mute
  802. && isUserInteractionRequiredForUnmute(state)) {
  803. logger.error('Unmuting video requires user interaction');
  804. return;
  805. }
  806. // check for A/V Moderation when trying to unmute and return early
  807. if (!mute && shouldShowModeratedNotification(MEDIA_TYPE.VIDEO, state)) {
  808. return;
  809. }
  810. // If not ready to modify track's state yet adjust the base/media
  811. if (!this._localTracksInitialized) {
  812. // This will only modify base/media.video.muted which is then synced
  813. // up with the track at the end of local tracks initialization.
  814. muteLocalVideo(mute);
  815. this.setVideoMuteStatus();
  816. return;
  817. } else if (this.isLocalVideoMuted() === mute) {
  818. // NO-OP
  819. return;
  820. }
  821. const localVideo = getLocalJitsiVideoTrack(state);
  822. if (!localVideo && !mute && !this.isCreatingLocalTrack) {
  823. const maybeShowErrorDialog = error => {
  824. showUI && APP.store.dispatch(notifyCameraError(error));
  825. };
  826. this.isCreatingLocalTrack = true;
  827. APP.store.dispatch(gumPending([ MEDIA_TYPE.VIDEO ], IGUMPendingState.PENDING_UNMUTE));
  828. // Try to create local video if there wasn't any.
  829. // This handles the case when user joined with no video
  830. // (dismissed screen sharing screen or in audio only mode), but
  831. // decided to add it later on by clicking on muted video icon or
  832. // turning off the audio only mode.
  833. //
  834. // FIXME when local track creation is moved to react/redux
  835. // it should take care of the use case described above
  836. createLocalTracksF({ devices: [ 'video' ] })
  837. .then(([ videoTrack ]) => videoTrack)
  838. .catch(error => {
  839. // FIXME should send some feedback to the API on error ?
  840. maybeShowErrorDialog(error);
  841. // Rollback the video muted status by using null track
  842. return null;
  843. })
  844. .then(videoTrack => {
  845. logger.debug(`muteVideo: calling useVideoStream for track: ${videoTrack}`);
  846. return this.useVideoStream(videoTrack);
  847. })
  848. .finally(() => {
  849. this.isCreatingLocalTrack = false;
  850. APP.store.dispatch(gumPending([ MEDIA_TYPE.VIDEO ], IGUMPendingState.NONE));
  851. });
  852. } else {
  853. // FIXME show error dialog if it fails (should be handled by react)
  854. muteLocalVideo(mute);
  855. }
  856. },
  857. /**
  858. * Simulates toolbar button click for video mute. Used by shortcuts and API.
  859. * @param {boolean} [showUI] when set to false will not display any error
  860. * dialogs in case of media permissions error.
  861. * @param {boolean} ensureTrack - True if we want to ensure that a new track is
  862. * created if missing.
  863. */
  864. toggleVideoMuted(showUI = true, ensureTrack = false) {
  865. const mute = !this.isLocalVideoMuted();
  866. APP.store.dispatch(handleToggleVideoMuted(mute, showUI, ensureTrack));
  867. },
  868. /**
  869. * Retrieve list of ids of conference participants (without local user).
  870. * @returns {string[]}
  871. */
  872. listMembersIds() {
  873. return room.getParticipants().map(p => p.getId());
  874. },
  875. /**
  876. * Checks whether the participant identified by id is a moderator.
  877. * @id id to search for participant
  878. * @return {boolean} whether the participant is moderator
  879. */
  880. isParticipantModerator(id) {
  881. const user = room.getParticipantById(id);
  882. return user && user.isModerator();
  883. },
  884. /**
  885. * Retrieve list of conference participants (without local user).
  886. * @returns {JitsiParticipant[]}
  887. *
  888. * NOTE: Used by jitsi-meet-torture!
  889. */
  890. listMembers() {
  891. return room.getParticipants();
  892. },
  893. /**
  894. * Used by Jibri to detect when it's alone and the meeting should be terminated.
  895. */
  896. get membersCount() {
  897. return room.getParticipants()
  898. .filter(p => !p.isHidden() || !(config.iAmRecorder && p.isHiddenFromRecorder())).length + 1;
  899. },
  900. /**
  901. * Returns true if the callstats integration is enabled, otherwise returns
  902. * false.
  903. *
  904. * @returns true if the callstats integration is enabled, otherwise returns
  905. * false.
  906. */
  907. isCallstatsEnabled() {
  908. return room && room.isCallstatsEnabled();
  909. },
  910. /**
  911. * Get speaker stats that track total dominant speaker time.
  912. *
  913. * @returns {object} A hash with keys being user ids and values being the
  914. * library's SpeakerStats model used for calculating time as dominant
  915. * speaker.
  916. */
  917. getSpeakerStats() {
  918. return room.getSpeakerStats();
  919. },
  920. /**
  921. * Returns the connection times stored in the library.
  922. */
  923. getConnectionTimes() {
  924. return room.getConnectionTimes();
  925. },
  926. // used by torture currently
  927. isJoined() {
  928. return room && room.isJoined();
  929. },
  930. getConnectionState() {
  931. return room && room.getConnectionState();
  932. },
  933. /**
  934. * Obtains current P2P ICE connection state.
  935. * @return {string|null} ICE connection state or <tt>null</tt> if there's no
  936. * P2P connection
  937. */
  938. getP2PConnectionState() {
  939. return room && room.getP2PConnectionState();
  940. },
  941. /**
  942. * Starts P2P (for tests only)
  943. * @private
  944. */
  945. _startP2P() {
  946. try {
  947. room && room.startP2PSession();
  948. } catch (error) {
  949. logger.error('Start P2P failed', error);
  950. throw error;
  951. }
  952. },
  953. /**
  954. * Stops P2P (for tests only)
  955. * @private
  956. */
  957. _stopP2P() {
  958. try {
  959. room && room.stopP2PSession();
  960. } catch (error) {
  961. logger.error('Stop P2P failed', error);
  962. throw error;
  963. }
  964. },
  965. /**
  966. * Checks whether or not our connection is currently in interrupted and
  967. * reconnect attempts are in progress.
  968. *
  969. * @returns {boolean} true if the connection is in interrupted state or
  970. * false otherwise.
  971. */
  972. isConnectionInterrupted() {
  973. return room.isConnectionInterrupted();
  974. },
  975. /**
  976. * Finds JitsiParticipant for given id.
  977. *
  978. * @param {string} id participant's identifier(MUC nickname).
  979. *
  980. * @returns {JitsiParticipant|null} participant instance for given id or
  981. * null if not found.
  982. */
  983. getParticipantById(id) {
  984. return room ? room.getParticipantById(id) : null;
  985. },
  986. getMyUserId() {
  987. return room && room.myUserId();
  988. },
  989. /**
  990. * Will be filled with values only when config.debug is enabled.
  991. * Its used by torture to check audio levels.
  992. */
  993. audioLevelsMap: {},
  994. /**
  995. * Returns the stored audio level (stored only if config.debug is enabled)
  996. * @param id the id for the user audio level to return (the id value is
  997. * returned for the participant using getMyUserId() method)
  998. */
  999. getPeerSSRCAudioLevel(id) {
  1000. return this.audioLevelsMap[id];
  1001. },
  1002. /**
  1003. * @return {number} the number of participants in the conference with at
  1004. * least one track.
  1005. */
  1006. getNumberOfParticipantsWithTracks() {
  1007. return room.getParticipants()
  1008. .filter(p => p.getTracks().length > 0)
  1009. .length;
  1010. },
  1011. /**
  1012. * Returns the stats.
  1013. */
  1014. getStats() {
  1015. return room.connectionQuality.getStats();
  1016. },
  1017. // end used by torture
  1018. /**
  1019. * Download logs, a function that can be called from console while
  1020. * debugging.
  1021. * @param filename (optional) specify target filename
  1022. */
  1023. saveLogs(filename = 'meetlog.json') {
  1024. // this can be called from console and will not have reference to this
  1025. // that's why we reference the global var
  1026. const logs = APP.connection.getLogs();
  1027. downloadJSON(logs, filename);
  1028. },
  1029. /**
  1030. * Exposes a Command(s) API on this instance. It is necessitated by (1) the
  1031. * desire to keep room private to this instance and (2) the need of other
  1032. * modules to send and receive commands to and from participants.
  1033. * Eventually, this instance remains in control with respect to the
  1034. * decision whether the Command(s) API of room (i.e. lib-jitsi-meet's
  1035. * JitsiConference) is to be used in the implementation of the Command(s)
  1036. * API of this instance.
  1037. */
  1038. commands: {
  1039. /**
  1040. * Known custom conference commands.
  1041. */
  1042. defaults: commands,
  1043. /**
  1044. * Receives notifications from other participants about commands aka
  1045. * custom events (sent by sendCommand or sendCommandOnce methods).
  1046. * @param command {String} the name of the command
  1047. * @param handler {Function} handler for the command
  1048. */
  1049. addCommandListener() {
  1050. // eslint-disable-next-line prefer-rest-params
  1051. room.addCommandListener(...arguments);
  1052. },
  1053. /**
  1054. * Removes command.
  1055. * @param name {String} the name of the command.
  1056. */
  1057. removeCommand() {
  1058. // eslint-disable-next-line prefer-rest-params
  1059. room.removeCommand(...arguments);
  1060. },
  1061. /**
  1062. * Sends command.
  1063. * @param name {String} the name of the command.
  1064. * @param values {Object} with keys and values that will be sent.
  1065. */
  1066. sendCommand() {
  1067. // eslint-disable-next-line prefer-rest-params
  1068. room.sendCommand(...arguments);
  1069. },
  1070. /**
  1071. * Sends command one time.
  1072. * @param name {String} the name of the command.
  1073. * @param values {Object} with keys and values that will be sent.
  1074. */
  1075. sendCommandOnce() {
  1076. // eslint-disable-next-line prefer-rest-params
  1077. room.sendCommandOnce(...arguments);
  1078. }
  1079. },
  1080. /**
  1081. * Used by the Breakout Rooms feature to join a breakout room or go back to the main room.
  1082. */
  1083. async joinRoom(roomName, options) {
  1084. APP.store.dispatch(conferenceWillInit());
  1085. // Restore initial state.
  1086. this._localTracksInitialized = false;
  1087. this.isSharingScreen = false;
  1088. this.roomName = roomName;
  1089. const { tryCreateLocalTracks, errors } = this.createInitialLocalTracks(options);
  1090. const localTracks = await tryCreateLocalTracks;
  1091. this._displayErrorsForCreateInitialLocalTracks(errors);
  1092. localTracks.forEach(track => {
  1093. if ((track.isAudioTrack() && this.isLocalAudioMuted())
  1094. || (track.isVideoTrack() && this.isLocalVideoMuted())) {
  1095. track.mute();
  1096. }
  1097. });
  1098. this._createRoom(localTracks);
  1099. return new Promise((resolve, reject) => {
  1100. new ConferenceConnector(resolve, reject, this).connect();
  1101. });
  1102. },
  1103. _createRoom(localTracks) {
  1104. room = APP.connection.initJitsiConference(APP.conference.roomName, this._getConferenceOptions());
  1105. // Filter out the tracks that are muted (except on Safari).
  1106. const tracks = browser.isWebKitBased() ? localTracks : localTracks.filter(track => !track.isMuted());
  1107. this._setLocalAudioVideoStreams(tracks);
  1108. this._room = room; // FIXME do not use this
  1109. APP.store.dispatch(_conferenceWillJoin(room));
  1110. sendLocalParticipant(APP.store, room);
  1111. this._setupListeners();
  1112. },
  1113. /**
  1114. * Sets local video and audio streams.
  1115. * @param {JitsiLocalTrack[]} tracks=[]
  1116. * @returns {Promise[]}
  1117. * @private
  1118. */
  1119. _setLocalAudioVideoStreams(tracks = []) {
  1120. const { dispatch } = APP.store;
  1121. const pendingGUMDevicesToRemove = [];
  1122. const promises = tracks.map(track => {
  1123. if (track.isAudioTrack()) {
  1124. pendingGUMDevicesToRemove.push(MEDIA_TYPE.AUDIO);
  1125. return this.useAudioStream(track);
  1126. } else if (track.isVideoTrack()) {
  1127. logger.debug(`_setLocalAudioVideoStreams is calling useVideoStream with track: ${track}`);
  1128. pendingGUMDevicesToRemove.push(MEDIA_TYPE.VIDEO);
  1129. return this.useVideoStream(track);
  1130. }
  1131. logger.error('Ignored not an audio nor a video track: ', track);
  1132. return Promise.resolve();
  1133. });
  1134. return Promise.allSettled(promises).then(() => {
  1135. if (pendingGUMDevicesToRemove.length > 0) {
  1136. dispatch(gumPending(pendingGUMDevicesToRemove, IGUMPendingState.NONE));
  1137. }
  1138. this._localTracksInitialized = true;
  1139. logger.log(`Initialized with ${tracks.length} local tracks`);
  1140. });
  1141. },
  1142. _getConferenceOptions() {
  1143. const options = getConferenceOptions(APP.store.getState());
  1144. options.createVADProcessor = createRnnoiseProcessor;
  1145. return options;
  1146. },
  1147. /**
  1148. * Start using provided video stream.
  1149. * Stops previous video stream.
  1150. * @param {JitsiLocalTrack} newTrack - new track to use or null
  1151. * @returns {Promise}
  1152. */
  1153. useVideoStream(newTrack) {
  1154. const state = APP.store.getState();
  1155. logger.debug(`useVideoStream: ${newTrack}`);
  1156. return new Promise((resolve, reject) => {
  1157. _replaceLocalVideoTrackQueue.enqueue(onFinish => {
  1158. const oldTrack = getLocalJitsiVideoTrack(state);
  1159. logger.debug(`useVideoStream: Replacing ${oldTrack} with ${newTrack}`);
  1160. if (oldTrack === newTrack || (!oldTrack && !newTrack)) {
  1161. resolve();
  1162. onFinish();
  1163. return;
  1164. }
  1165. // Add the track to the conference if there is no existing track, replace it otherwise.
  1166. const trackAction = oldTrack
  1167. ? replaceLocalTrack(oldTrack, newTrack, room)
  1168. : addLocalTrack(newTrack);
  1169. APP.store.dispatch(trackAction)
  1170. .then(() => {
  1171. this.setVideoMuteStatus();
  1172. })
  1173. .then(resolve)
  1174. .catch(error => {
  1175. logger.error(`useVideoStream failed: ${error}`);
  1176. reject(error);
  1177. })
  1178. .then(onFinish);
  1179. });
  1180. });
  1181. },
  1182. /**
  1183. * Start using provided audio stream.
  1184. * Stops previous audio stream.
  1185. * @param {JitsiLocalTrack} newTrack - new track to use or null
  1186. * @returns {Promise}
  1187. */
  1188. useAudioStream(newTrack) {
  1189. return new Promise((resolve, reject) => {
  1190. _replaceLocalAudioTrackQueue.enqueue(onFinish => {
  1191. const oldTrack = getLocalJitsiAudioTrack(APP.store.getState());
  1192. if (oldTrack === newTrack) {
  1193. resolve();
  1194. onFinish();
  1195. return;
  1196. }
  1197. APP.store.dispatch(
  1198. replaceLocalTrack(oldTrack, newTrack, room))
  1199. .then(() => {
  1200. this.setAudioMuteStatus(this.isLocalAudioMuted());
  1201. })
  1202. .then(resolve)
  1203. .catch(reject)
  1204. .then(onFinish);
  1205. });
  1206. });
  1207. },
  1208. /**
  1209. * Returns whether or not the conference is currently in audio only mode.
  1210. *
  1211. * @returns {boolean}
  1212. */
  1213. isAudioOnly() {
  1214. return Boolean(APP.store.getState()['features/base/audio-only'].enabled);
  1215. },
  1216. videoSwitchInProgress: false,
  1217. /**
  1218. * This fields stores a handler which will create a Promise which turns off
  1219. * the screen sharing and restores the previous video state (was there
  1220. * any video, before switching to screen sharing ? was it muted ?).
  1221. *
  1222. * Once called this fields is cleared to <tt>null</tt>.
  1223. * @type {Function|null}
  1224. */
  1225. _untoggleScreenSharing: null,
  1226. /**
  1227. * Creates a Promise which turns off the screen sharing and restores
  1228. * the previous state described by the arguments.
  1229. *
  1230. * This method is bound to the appropriate values, after switching to screen
  1231. * sharing and stored in {@link _untoggleScreenSharing}.
  1232. *
  1233. * @param {boolean} didHaveVideo indicates if there was a camera video being
  1234. * used, before switching to screen sharing.
  1235. * @param {boolean} ignoreDidHaveVideo indicates if the camera video should be
  1236. * ignored when switching screen sharing off.
  1237. * @return {Promise} resolved after the screen sharing is turned off, or
  1238. * rejected with some error (no idea what kind of error, possible GUM error)
  1239. * in case it fails.
  1240. * @private
  1241. */
  1242. async _turnScreenSharingOff(didHaveVideo, ignoreDidHaveVideo) {
  1243. this._untoggleScreenSharing = null;
  1244. this.videoSwitchInProgress = true;
  1245. APP.store.dispatch(stopReceiver());
  1246. this._stopProxyConnection();
  1247. APP.store.dispatch(toggleScreenshotCaptureSummary(false));
  1248. const tracks = APP.store.getState()['features/base/tracks'];
  1249. const duration = getLocalVideoTrack(tracks)?.jitsiTrack.getDuration() ?? 0;
  1250. // If system audio was also shared stop the AudioMixerEffect and dispose of the desktop audio track.
  1251. if (this._mixerEffect) {
  1252. const localAudio = getLocalJitsiAudioTrack(APP.store.getState());
  1253. await localAudio.setEffect(undefined);
  1254. await this._desktopAudioStream.dispose();
  1255. this._mixerEffect = undefined;
  1256. this._desktopAudioStream = undefined;
  1257. // In case there was no local audio when screen sharing was started the fact that we set the audio stream to
  1258. // null will take care of the desktop audio stream cleanup.
  1259. } else if (this._desktopAudioStream) {
  1260. await room.replaceTrack(this._desktopAudioStream, null);
  1261. this._desktopAudioStream.dispose();
  1262. this._desktopAudioStream = undefined;
  1263. }
  1264. APP.store.dispatch(setScreenAudioShareState(false));
  1265. let promise;
  1266. if (didHaveVideo && !ignoreDidHaveVideo) {
  1267. promise = createLocalTracksF({ devices: [ 'video' ] })
  1268. .then(([ stream ]) => {
  1269. logger.debug(`_turnScreenSharingOff using ${stream} for useVideoStream`);
  1270. return this.useVideoStream(stream);
  1271. })
  1272. .catch(error => {
  1273. logger.error('failed to switch back to local video', error);
  1274. return this.useVideoStream(null).then(() =>
  1275. // Still fail with the original err
  1276. Promise.reject(error)
  1277. );
  1278. });
  1279. } else {
  1280. promise = this.useVideoStream(null);
  1281. }
  1282. return promise.then(
  1283. () => {
  1284. this.videoSwitchInProgress = false;
  1285. sendAnalytics(createScreenSharingEvent('stopped',
  1286. duration === 0 ? null : duration));
  1287. logger.info('Screen sharing stopped.');
  1288. },
  1289. error => {
  1290. this.videoSwitchInProgress = false;
  1291. logger.error(`_turnScreenSharingOff failed: ${error}`);
  1292. throw error;
  1293. });
  1294. },
  1295. /**
  1296. * Creates desktop (screensharing) {@link JitsiLocalTrack}
  1297. *
  1298. * @param {Object} [options] - Screen sharing options that will be passed to
  1299. * createLocalTracks.
  1300. * @param {Object} [options.desktopSharing]
  1301. * @param {Object} [options.desktopStream] - An existing desktop stream to
  1302. * use instead of creating a new desktop stream.
  1303. * @return {Promise.<JitsiLocalTrack>} - A Promise resolved with
  1304. * {@link JitsiLocalTrack} for the screensharing or rejected with
  1305. * {@link JitsiTrackError}.
  1306. *
  1307. * @private
  1308. */
  1309. _createDesktopTrack(options = {}) {
  1310. const didHaveVideo = !this.isLocalVideoMuted();
  1311. const getDesktopStreamPromise = options.desktopStream
  1312. ? Promise.resolve([ options.desktopStream ])
  1313. : createLocalTracksF({
  1314. desktopSharingSourceDevice: options.desktopSharingSources
  1315. ? null : config._desktopSharingSourceDevice,
  1316. desktopSharingSources: options.desktopSharingSources,
  1317. devices: [ 'desktop' ]
  1318. });
  1319. return getDesktopStreamPromise.then(desktopStreams => {
  1320. // Stores the "untoggle" handler which remembers whether was
  1321. // there any video before and whether was it muted.
  1322. this._untoggleScreenSharing
  1323. = this._turnScreenSharingOff.bind(this, didHaveVideo);
  1324. const desktopVideoStream = desktopStreams.find(stream => stream.getType() === MEDIA_TYPE.VIDEO);
  1325. const desktopAudioStream = desktopStreams.find(stream => stream.getType() === MEDIA_TYPE.AUDIO);
  1326. if (desktopAudioStream) {
  1327. desktopAudioStream.on(
  1328. JitsiTrackEvents.LOCAL_TRACK_STOPPED,
  1329. () => {
  1330. logger.debug(`Local screensharing audio track stopped. ${this.isSharingScreen}`);
  1331. // Handle case where screen share was stopped from the browsers 'screen share in progress'
  1332. // window. If audio screen sharing is stopped via the normal UX flow this point shouldn't
  1333. // be reached.
  1334. isScreenAudioShared(APP.store.getState())
  1335. && this._untoggleScreenSharing
  1336. && this._untoggleScreenSharing();
  1337. }
  1338. );
  1339. }
  1340. if (desktopVideoStream) {
  1341. desktopVideoStream.on(
  1342. JitsiTrackEvents.LOCAL_TRACK_STOPPED,
  1343. () => {
  1344. logger.debug(`Local screensharing track stopped. ${this.isSharingScreen}`);
  1345. // If the stream was stopped during screen sharing
  1346. // session then we should switch back to video.
  1347. this.isSharingScreen
  1348. && this._untoggleScreenSharing
  1349. && this._untoggleScreenSharing();
  1350. }
  1351. );
  1352. }
  1353. return desktopStreams;
  1354. }, error => {
  1355. throw error;
  1356. });
  1357. },
  1358. /**
  1359. * Handles {@link JitsiTrackError} returned by the lib-jitsi-meet when
  1360. * trying to create screensharing track. It will either do nothing if
  1361. * the dialog was canceled on user's request or display an error if
  1362. * screensharing couldn't be started.
  1363. * @param {JitsiTrackError} error - The error returned by
  1364. * {@link _createDesktopTrack} Promise.
  1365. * @private
  1366. */
  1367. _handleScreenSharingError(error) {
  1368. if (error.name === JitsiTrackErrors.SCREENSHARING_USER_CANCELED) {
  1369. return;
  1370. }
  1371. logger.error('failed to share local desktop', error);
  1372. // Handling:
  1373. // JitsiTrackErrors.CONSTRAINT_FAILED
  1374. // JitsiTrackErrors.PERMISSION_DENIED
  1375. // JitsiTrackErrors.SCREENSHARING_GENERIC_ERROR
  1376. // and any other
  1377. let descriptionKey;
  1378. let titleKey;
  1379. if (error.name === JitsiTrackErrors.PERMISSION_DENIED) {
  1380. descriptionKey = 'dialog.screenSharingPermissionDeniedError';
  1381. titleKey = 'dialog.screenSharingFailedTitle';
  1382. } else if (error.name === JitsiTrackErrors.CONSTRAINT_FAILED) {
  1383. descriptionKey = 'dialog.cameraConstraintFailedError';
  1384. titleKey = 'deviceError.cameraError';
  1385. } else if (error.name === JitsiTrackErrors.SCREENSHARING_GENERIC_ERROR) {
  1386. descriptionKey = 'dialog.screenSharingFailed';
  1387. titleKey = 'dialog.screenSharingFailedTitle';
  1388. } else if (error === AUDIO_ONLY_SCREEN_SHARE_NO_TRACK) {
  1389. descriptionKey = 'notify.screenShareNoAudio';
  1390. titleKey = 'notify.screenShareNoAudioTitle';
  1391. }
  1392. APP.store.dispatch(showErrorNotification({
  1393. descriptionKey,
  1394. titleKey
  1395. }, NOTIFICATION_TIMEOUT_TYPE.LONG));
  1396. },
  1397. /**
  1398. * Setup interaction between conference and UI.
  1399. */
  1400. _setupListeners() {
  1401. // add local streams when joined to the conference
  1402. room.on(JitsiConferenceEvents.CONFERENCE_JOINED, () => {
  1403. this._onConferenceJoined();
  1404. });
  1405. room.on(
  1406. JitsiConferenceEvents.CONFERENCE_JOIN_IN_PROGRESS,
  1407. () => APP.store.dispatch(conferenceJoinInProgress(room)));
  1408. room.on(
  1409. JitsiConferenceEvents.CONFERENCE_LEFT,
  1410. (...args) => {
  1411. APP.store.dispatch(conferenceTimestampChanged(0));
  1412. APP.store.dispatch(conferenceLeft(room, ...args));
  1413. });
  1414. room.on(
  1415. JitsiConferenceEvents.CONFERENCE_UNIQUE_ID_SET,
  1416. (...args) => {
  1417. // Preserve the sessionId so that the value is accessible even after room
  1418. // is disconnected.
  1419. room.sessionId = room.getMeetingUniqueId();
  1420. APP.store.dispatch(conferenceUniqueIdSet(room, ...args));
  1421. });
  1422. // we want to ignore this event in case of tokenAuthUrl config
  1423. // we are deprecating this and at some point will get rid of it
  1424. if (!config.tokenAuthUrl) {
  1425. room.on(
  1426. JitsiConferenceEvents.AUTH_STATUS_CHANGED,
  1427. (authEnabled, authLogin) =>
  1428. APP.store.dispatch(authStatusChanged(authEnabled, authLogin)));
  1429. }
  1430. room.on(JitsiConferenceEvents.PARTCIPANT_FEATURES_CHANGED, user => {
  1431. APP.store.dispatch(updateRemoteParticipantFeatures(user));
  1432. });
  1433. room.on(JitsiConferenceEvents.USER_JOINED, (id, user) => {
  1434. if (config.iAmRecorder && user.isHiddenFromRecorder()) {
  1435. return;
  1436. }
  1437. // The logic shared between RN and web.
  1438. commonUserJoinedHandling(APP.store, room, user);
  1439. if (user.isHidden()) {
  1440. return;
  1441. }
  1442. APP.store.dispatch(updateRemoteParticipantFeatures(user));
  1443. logger.log(`USER ${id} connected:`, user);
  1444. APP.UI.addUser(user);
  1445. });
  1446. room.on(JitsiConferenceEvents.USER_LEFT, (id, user) => {
  1447. // The logic shared between RN and web.
  1448. commonUserLeftHandling(APP.store, room, user);
  1449. if (user.isHidden()) {
  1450. return;
  1451. }
  1452. logger.log(`USER ${id} LEFT:`, user);
  1453. });
  1454. room.on(JitsiConferenceEvents.USER_STATUS_CHANGED, (id, status) => {
  1455. APP.store.dispatch(participantPresenceChanged(id, status));
  1456. const user = room.getParticipantById(id);
  1457. if (user) {
  1458. APP.UI.updateUserStatus(user, status);
  1459. }
  1460. });
  1461. room.on(JitsiConferenceEvents.USER_ROLE_CHANGED, (id, role) => {
  1462. if (this.isLocalId(id)) {
  1463. logger.info(`My role changed, new role: ${role}`);
  1464. if (role === 'moderator') {
  1465. APP.store.dispatch(maybeSetLobbyChatMessageListener());
  1466. }
  1467. APP.store.dispatch(localParticipantRoleChanged(role));
  1468. APP.API.notifyUserRoleChanged(id, role);
  1469. } else {
  1470. APP.store.dispatch(participantRoleChanged(id, role));
  1471. }
  1472. });
  1473. room.on(JitsiConferenceEvents.TRACK_ADDED, track => {
  1474. if (!track || track.isLocal()) {
  1475. return;
  1476. }
  1477. if (config.iAmRecorder) {
  1478. const participant = room.getParticipantById(track.getParticipantId());
  1479. if (participant.isHiddenFromRecorder()) {
  1480. return;
  1481. }
  1482. }
  1483. APP.store.dispatch(trackAdded(track));
  1484. });
  1485. room.on(JitsiConferenceEvents.TRACK_REMOVED, track => {
  1486. if (!track || track.isLocal()) {
  1487. return;
  1488. }
  1489. APP.store.dispatch(trackRemoved(track));
  1490. });
  1491. room.on(JitsiConferenceEvents.TRACK_AUDIO_LEVEL_CHANGED, (id, lvl) => {
  1492. const localAudio = getLocalJitsiAudioTrack(APP.store.getState());
  1493. let newLvl = lvl;
  1494. if (this.isLocalId(id)) {
  1495. APP.store.dispatch(localParticipantAudioLevelChanged(lvl));
  1496. }
  1497. if (this.isLocalId(id) && localAudio?.isMuted()) {
  1498. newLvl = 0;
  1499. }
  1500. if (config.debug) {
  1501. this.audioLevelsMap[id] = newLvl;
  1502. if (config.debugAudioLevels) {
  1503. logger.log(`AudioLevel:${id}/${newLvl}`);
  1504. }
  1505. }
  1506. APP.UI.setAudioLevel(id, newLvl);
  1507. });
  1508. room.on(JitsiConferenceEvents.TRACK_MUTE_CHANGED, (track, participantThatMutedUs) => {
  1509. if (participantThatMutedUs) {
  1510. APP.store.dispatch(participantMutedUs(participantThatMutedUs, track));
  1511. if (this.isSharingScreen && track.isVideoTrack()) {
  1512. logger.debug('TRACK_MUTE_CHANGED while screen sharing');
  1513. this._turnScreenSharingOff(false);
  1514. }
  1515. }
  1516. });
  1517. room.on(JitsiConferenceEvents.TRACK_UNMUTE_REJECTED, track => APP.store.dispatch(destroyLocalTracks(track)));
  1518. room.on(JitsiConferenceEvents.SUBJECT_CHANGED,
  1519. subject => APP.store.dispatch(conferenceSubjectChanged(subject)));
  1520. room.on(
  1521. JitsiConferenceEvents.LAST_N_ENDPOINTS_CHANGED,
  1522. (leavingIds, enteringIds) =>
  1523. APP.UI.handleLastNEndpoints(leavingIds, enteringIds));
  1524. room.on(
  1525. JitsiConferenceEvents.P2P_STATUS,
  1526. (jitsiConference, p2p) =>
  1527. APP.store.dispatch(p2pStatusChanged(p2p)));
  1528. room.on(
  1529. JitsiConferenceEvents.DOMINANT_SPEAKER_CHANGED,
  1530. (dominant, previous, silence) => {
  1531. APP.store.dispatch(dominantSpeakerChanged(dominant, previous, Boolean(silence), room));
  1532. });
  1533. room.on(
  1534. JitsiConferenceEvents.CONFERENCE_CREATED_TIMESTAMP,
  1535. conferenceTimestamp => APP.store.dispatch(conferenceTimestampChanged(conferenceTimestamp)));
  1536. room.on(
  1537. JitsiConferenceEvents.DISPLAY_NAME_CHANGED,
  1538. (id, displayName) => {
  1539. const formattedDisplayName
  1540. = getNormalizedDisplayName(displayName);
  1541. const state = APP.store.getState();
  1542. const {
  1543. defaultRemoteDisplayName
  1544. } = state['features/base/config'];
  1545. APP.store.dispatch(participantUpdated({
  1546. conference: room,
  1547. id,
  1548. name: formattedDisplayName
  1549. }));
  1550. const virtualScreenshareParticipantId = getVirtualScreenshareParticipantByOwnerId(state, id)?.id;
  1551. if (virtualScreenshareParticipantId) {
  1552. APP.store.dispatch(
  1553. screenshareParticipantDisplayNameChanged(virtualScreenshareParticipantId, formattedDisplayName)
  1554. );
  1555. }
  1556. APP.API.notifyDisplayNameChanged(id, {
  1557. displayName: formattedDisplayName,
  1558. formattedDisplayName:
  1559. appendSuffix(
  1560. formattedDisplayName
  1561. || defaultRemoteDisplayName)
  1562. });
  1563. }
  1564. );
  1565. room.on(
  1566. JitsiConferenceEvents.BOT_TYPE_CHANGED,
  1567. (id, botType) => {
  1568. APP.store.dispatch(participantUpdated({
  1569. conference: room,
  1570. id,
  1571. botType
  1572. }));
  1573. }
  1574. );
  1575. room.on(
  1576. JitsiConferenceEvents.ENDPOINT_MESSAGE_RECEIVED,
  1577. (...args) => {
  1578. APP.store.dispatch(endpointMessageReceived(...args));
  1579. if (args && args.length >= 2) {
  1580. const [ sender, eventData ] = args;
  1581. if (eventData.name === ENDPOINT_TEXT_MESSAGE_NAME) {
  1582. APP.API.notifyEndpointTextMessageReceived({
  1583. senderInfo: {
  1584. jid: sender._jid,
  1585. id: sender._id
  1586. },
  1587. eventData
  1588. });
  1589. }
  1590. }
  1591. });
  1592. room.on(
  1593. JitsiConferenceEvents.NON_PARTICIPANT_MESSAGE_RECEIVED,
  1594. (...args) => {
  1595. APP.store.dispatch(nonParticipantMessageReceived(...args));
  1596. APP.API.notifyNonParticipantMessageReceived(...args);
  1597. });
  1598. room.on(
  1599. JitsiConferenceEvents.LOCK_STATE_CHANGED,
  1600. (...args) => APP.store.dispatch(lockStateChanged(room, ...args)));
  1601. room.on(JitsiConferenceEvents.KICKED, (participant, reason, isReplaced) => {
  1602. if (isReplaced) {
  1603. // this event triggers when the local participant is kicked, `participant`
  1604. // is the kicker. In replace participant case, kicker is undefined,
  1605. // as the server initiated it. We mark in store the local participant
  1606. // as being replaced based on jwt.
  1607. const localParticipant = getLocalParticipant(APP.store.getState());
  1608. APP.store.dispatch(participantUpdated({
  1609. conference: room,
  1610. id: localParticipant.id,
  1611. isReplaced
  1612. }));
  1613. // we send readyToClose when kicked participant is replace so that
  1614. // embedding app can choose to dispose the iframe API on the handler.
  1615. APP.API.notifyReadyToClose();
  1616. }
  1617. APP.store.dispatch(kickedOut(room, participant));
  1618. });
  1619. room.on(JitsiConferenceEvents.PARTICIPANT_KICKED, (kicker, kicked) => {
  1620. APP.store.dispatch(participantKicked(kicker, kicked));
  1621. });
  1622. room.on(JitsiConferenceEvents.PARTICIPANT_SOURCE_UPDATED,
  1623. jitsiParticipant => {
  1624. APP.store.dispatch(participantSourcesUpdated(jitsiParticipant));
  1625. });
  1626. room.on(JitsiConferenceEvents.SUSPEND_DETECTED, () => {
  1627. APP.store.dispatch(suspendDetected());
  1628. });
  1629. room.on(
  1630. JitsiConferenceEvents.AUDIO_UNMUTE_PERMISSIONS_CHANGED,
  1631. disableAudioMuteChange => {
  1632. APP.store.dispatch(setAudioUnmutePermissions(disableAudioMuteChange));
  1633. });
  1634. room.on(
  1635. JitsiConferenceEvents.VIDEO_UNMUTE_PERMISSIONS_CHANGED,
  1636. disableVideoMuteChange => {
  1637. APP.store.dispatch(setVideoUnmutePermissions(disableVideoMuteChange));
  1638. });
  1639. room.on(
  1640. JitsiE2ePingEvents.E2E_RTT_CHANGED,
  1641. (...args) => APP.store.dispatch(e2eRttChanged(...args)));
  1642. APP.UI.addListener(UIEvents.AUDIO_MUTED, muted => {
  1643. this.muteAudio(muted);
  1644. });
  1645. APP.UI.addListener(UIEvents.VIDEO_MUTED, (muted, showUI = false) => {
  1646. this.muteVideo(muted, showUI);
  1647. });
  1648. room.addCommandListener(this.commands.defaults.ETHERPAD,
  1649. ({ value }) => {
  1650. APP.UI.initEtherpad(value);
  1651. }
  1652. );
  1653. APP.UI.addListener(UIEvents.EMAIL_CHANGED,
  1654. this.changeLocalEmail.bind(this));
  1655. room.addCommandListener(this.commands.defaults.EMAIL, (data, from) => {
  1656. APP.store.dispatch(participantUpdated({
  1657. conference: room,
  1658. id: from,
  1659. email: data.value
  1660. }));
  1661. });
  1662. room.addCommandListener(
  1663. this.commands.defaults.AVATAR_URL,
  1664. (data, from) => {
  1665. APP.store.dispatch(
  1666. participantUpdated({
  1667. conference: room,
  1668. id: from,
  1669. avatarURL: data.value
  1670. }));
  1671. });
  1672. APP.UI.addListener(UIEvents.NICKNAME_CHANGED,
  1673. this.changeLocalDisplayName.bind(this));
  1674. room.on(
  1675. JitsiConferenceEvents.START_MUTED_POLICY_CHANGED,
  1676. ({ audio, video }) => {
  1677. APP.store.dispatch(
  1678. onStartMutedPolicyChanged(audio, video));
  1679. }
  1680. );
  1681. room.on(JitsiConferenceEvents.STARTED_MUTED, () => {
  1682. const audioMuted = room.isStartAudioMuted();
  1683. const videoMuted = room.isStartVideoMuted();
  1684. const localTracks = getLocalTracks(APP.store.getState()['features/base/tracks']);
  1685. const promises = [];
  1686. APP.store.dispatch(setAudioMuted(audioMuted));
  1687. APP.store.dispatch(setVideoMuted(videoMuted));
  1688. // Remove the tracks from the peerconnection.
  1689. for (const track of localTracks) {
  1690. // Always add the track on Safari because of a known issue where audio playout doesn't happen
  1691. // if the user joins audio and video muted, i.e., if there is no local media capture.
  1692. if (audioMuted && track.jitsiTrack?.getType() === MEDIA_TYPE.AUDIO && !browser.isWebKitBased()) {
  1693. promises.push(this.useAudioStream(null));
  1694. }
  1695. if (videoMuted && track.jitsiTrack?.getType() === MEDIA_TYPE.VIDEO) {
  1696. promises.push(this.useVideoStream(null));
  1697. }
  1698. }
  1699. Promise.allSettled(promises)
  1700. .then(() => {
  1701. APP.store.dispatch(showNotification({
  1702. titleKey: 'notify.mutedTitle',
  1703. descriptionKey: 'notify.muted'
  1704. }, NOTIFICATION_TIMEOUT_TYPE.SHORT));
  1705. });
  1706. });
  1707. room.on(
  1708. JitsiConferenceEvents.DATA_CHANNEL_OPENED, () => {
  1709. APP.store.dispatch(dataChannelOpened());
  1710. APP.store.dispatch(hideNotification(DATA_CHANNEL_CLOSED_NOTIFICATION_ID));
  1711. }
  1712. );
  1713. room.on(
  1714. JitsiConferenceEvents.DATA_CHANNEL_CLOSED, ev => {
  1715. APP.store.dispatch(dataChannelClosed(ev.code, ev.reason));
  1716. APP.store.dispatch(showWarningNotification({
  1717. descriptionKey: 'notify.dataChannelClosedDescription',
  1718. titleKey: 'notify.dataChannelClosed',
  1719. uid: DATA_CHANNEL_CLOSED_NOTIFICATION_ID
  1720. }, NOTIFICATION_TIMEOUT_TYPE.STICKY));
  1721. }
  1722. );
  1723. // call hangup
  1724. APP.UI.addListener(UIEvents.HANGUP, () => {
  1725. this.hangup(true);
  1726. });
  1727. APP.UI.addListener(
  1728. UIEvents.VIDEO_DEVICE_CHANGED,
  1729. cameraDeviceId => {
  1730. const videoWasMuted = this.isLocalVideoMuted();
  1731. const localVideoTrack = getLocalJitsiVideoTrack(APP.store.getState());
  1732. if (localVideoTrack?.getDeviceId() === cameraDeviceId) {
  1733. return;
  1734. }
  1735. sendAnalytics(createDeviceChangedEvent('video', 'input'));
  1736. createLocalTracksF({
  1737. devices: [ 'video' ],
  1738. cameraDeviceId
  1739. })
  1740. .then(([ stream ]) => {
  1741. // if we are in audio only mode or video was muted before
  1742. // changing device, then mute
  1743. if (this.isAudioOnly() || videoWasMuted) {
  1744. return stream.mute()
  1745. .then(() => stream);
  1746. }
  1747. return stream;
  1748. })
  1749. .then(stream => {
  1750. logger.info(`Switching the local video device to ${cameraDeviceId}.`);
  1751. return this.useVideoStream(stream);
  1752. })
  1753. .then(() => {
  1754. logger.info(`Switched local video device to ${cameraDeviceId}.`);
  1755. this._updateVideoDeviceId();
  1756. })
  1757. .catch(error => {
  1758. logger.error(`Failed to switch to selected camera:${cameraDeviceId}, error:${error}`);
  1759. return APP.store.dispatch(notifyCameraError(error));
  1760. });
  1761. }
  1762. );
  1763. APP.UI.addListener(
  1764. UIEvents.AUDIO_DEVICE_CHANGED,
  1765. async micDeviceId => {
  1766. const audioWasMuted = this.isLocalAudioMuted();
  1767. // Disable noise suppression if it was enabled on the previous track.
  1768. await APP.store.dispatch(setNoiseSuppressionEnabled(false));
  1769. // When the 'default' mic needs to be selected, we need to pass the real device id to gUM instead of
  1770. // 'default' in order to get the correct MediaStreamTrack from chrome because of the following bug.
  1771. // https://bugs.chromium.org/p/chromium/issues/detail?id=997689.
  1772. const isDefaultMicSelected = micDeviceId === 'default';
  1773. const selectedDeviceId = isDefaultMicSelected
  1774. ? getDefaultDeviceId(APP.store.getState(), 'audioInput')
  1775. : micDeviceId;
  1776. logger.info(`Switching audio input device to ${selectedDeviceId}`);
  1777. sendAnalytics(createDeviceChangedEvent('audio', 'input'));
  1778. createLocalTracksF({
  1779. devices: [ 'audio' ],
  1780. micDeviceId: selectedDeviceId
  1781. })
  1782. .then(([ stream ]) => {
  1783. // if audio was muted before changing the device, mute
  1784. // with the new device
  1785. if (audioWasMuted) {
  1786. return stream.mute()
  1787. .then(() => stream);
  1788. }
  1789. return stream;
  1790. })
  1791. .then(async stream => {
  1792. await this._maybeApplyAudioMixerEffect(stream);
  1793. return this.useAudioStream(stream);
  1794. })
  1795. .then(() => {
  1796. const localAudio = getLocalJitsiAudioTrack(APP.store.getState());
  1797. if (localAudio && isDefaultMicSelected) {
  1798. // workaround for the default device to be shown as selected in the
  1799. // settings even when the real device id was passed to gUM because of the
  1800. // above mentioned chrome bug.
  1801. localAudio._realDeviceId = localAudio.deviceId = 'default';
  1802. }
  1803. logger.info(`switched local audio input device to: ${selectedDeviceId}`);
  1804. this._updateAudioDeviceId();
  1805. })
  1806. .catch(err => {
  1807. logger.error(`Failed to switch to selected audio input device ${selectedDeviceId}, error=${err}`);
  1808. APP.store.dispatch(notifyMicError(err));
  1809. });
  1810. }
  1811. );
  1812. APP.UI.addListener(UIEvents.TOGGLE_AUDIO_ONLY, () => {
  1813. // Immediately update the UI by having remote videos and the large video update themselves.
  1814. const displayedUserId = APP.UI.getLargeVideoID();
  1815. if (displayedUserId) {
  1816. APP.UI.updateLargeVideo(displayedUserId, true);
  1817. }
  1818. });
  1819. },
  1820. /**
  1821. * Cleanups local conference on suspend.
  1822. */
  1823. onSuspendDetected() {
  1824. // After wake up, we will be in a state where conference is left
  1825. // there will be dialog shown to user.
  1826. // We do not want video/audio as we show an overlay and after it
  1827. // user need to rejoin or close, while waking up we can detect
  1828. // camera wakeup as a problem with device.
  1829. // We also do not care about device change, which happens
  1830. // on resume after suspending PC.
  1831. if (this.deviceChangeListener) {
  1832. JitsiMeetJS.mediaDevices.removeEventListener(
  1833. JitsiMediaDevicesEvents.DEVICE_LIST_CHANGED,
  1834. this.deviceChangeListener);
  1835. }
  1836. },
  1837. /**
  1838. * Callback invoked when the conference has been successfully joined.
  1839. * Initializes the UI and various other features.
  1840. *
  1841. * @private
  1842. * @returns {void}
  1843. */
  1844. _onConferenceJoined() {
  1845. const { dispatch } = APP.store;
  1846. APP.UI.initConference();
  1847. dispatch(initKeyboardShortcuts());
  1848. dispatch(conferenceJoined(room));
  1849. const jwt = APP.store.getState()['features/base/jwt'];
  1850. if (jwt?.user?.hiddenFromRecorder) {
  1851. dispatch(muteLocal(true, MEDIA_TYPE.AUDIO));
  1852. dispatch(muteLocal(true, MEDIA_TYPE.VIDEO));
  1853. dispatch(setAudioUnmutePermissions(true, true));
  1854. dispatch(setVideoUnmutePermissions(true, true));
  1855. }
  1856. },
  1857. /**
  1858. * Updates the list of current devices.
  1859. * @param {boolean} setDeviceListChangeHandler - Whether to add the deviceList change handlers.
  1860. * @private
  1861. * @returns {Promise}
  1862. */
  1863. _initDeviceList(setDeviceListChangeHandler = false) {
  1864. const { mediaDevices } = JitsiMeetJS;
  1865. if (mediaDevices.isDeviceListAvailable()
  1866. && mediaDevices.isDeviceChangeAvailable()) {
  1867. if (setDeviceListChangeHandler) {
  1868. this.deviceChangeListener = devices =>
  1869. window.setTimeout(() => this._onDeviceListChanged(devices), 0);
  1870. mediaDevices.addEventListener(
  1871. JitsiMediaDevicesEvents.DEVICE_LIST_CHANGED,
  1872. this.deviceChangeListener);
  1873. }
  1874. const { dispatch } = APP.store;
  1875. return dispatch(getAvailableDevices())
  1876. .then(devices => {
  1877. // Ugly way to synchronize real device IDs with local
  1878. // storage and settings menu. This is a workaround until
  1879. // getConstraints() method will be implemented in browsers.
  1880. this._updateAudioDeviceId();
  1881. this._updateVideoDeviceId();
  1882. APP.UI.onAvailableDevicesChanged(devices);
  1883. });
  1884. }
  1885. return Promise.resolve();
  1886. },
  1887. /**
  1888. * Updates the settings for the currently used video device, extracting
  1889. * the device id from the used track.
  1890. * @private
  1891. */
  1892. _updateVideoDeviceId() {
  1893. const localVideo = getLocalJitsiVideoTrack(APP.store.getState());
  1894. if (localVideo && localVideo.videoType === 'camera') {
  1895. APP.store.dispatch(updateSettings({
  1896. cameraDeviceId: localVideo.getDeviceId()
  1897. }));
  1898. }
  1899. },
  1900. /**
  1901. * Updates the settings for the currently used audio device, extracting
  1902. * the device id from the used track.
  1903. * @private
  1904. */
  1905. _updateAudioDeviceId() {
  1906. const localAudio = getLocalJitsiAudioTrack(APP.store.getState());
  1907. if (localAudio) {
  1908. APP.store.dispatch(updateSettings({
  1909. micDeviceId: localAudio.getDeviceId()
  1910. }));
  1911. }
  1912. },
  1913. /**
  1914. * Event listener for JitsiMediaDevicesEvents.DEVICE_LIST_CHANGED to
  1915. * handle change of available media devices.
  1916. * @private
  1917. * @param {MediaDeviceInfo[]} devices
  1918. * @returns {Promise}
  1919. */
  1920. async _onDeviceListChanged(devices) {
  1921. const oldDevices = APP.store.getState()['features/base/devices'].availableDevices;
  1922. const localAudio = getLocalJitsiAudioTrack(APP.store.getState());
  1923. const localVideo = getLocalJitsiVideoTrack(APP.store.getState());
  1924. APP.store.dispatch(updateDeviceList(devices));
  1925. // Firefox users can choose their preferred device in the gUM prompt. In that case
  1926. // we should respect that and not attempt to switch to the preferred device from
  1927. // our settings.
  1928. const newLabelsOnly = mediaDeviceHelper.newDeviceListAddedLabelsOnly(oldDevices, devices);
  1929. const newDevices
  1930. = mediaDeviceHelper.getNewMediaDevicesAfterDeviceListChanged(
  1931. devices,
  1932. localVideo,
  1933. localAudio,
  1934. newLabelsOnly);
  1935. const promises = [];
  1936. const requestedInput = {
  1937. audio: Boolean(newDevices.audioinput),
  1938. video: Boolean(newDevices.videoinput)
  1939. };
  1940. if (typeof newDevices.audiooutput !== 'undefined') {
  1941. const { dispatch } = APP.store;
  1942. const setAudioOutputPromise
  1943. = setAudioOutputDeviceId(newDevices.audiooutput, dispatch)
  1944. .catch(err => {
  1945. logger.error(`Failed to set the audio output device to ${newDevices.audiooutput} - ${err}`);
  1946. });
  1947. promises.push(setAudioOutputPromise);
  1948. }
  1949. // Handles the use case when the default device is changed (we are always stopping the streams because it's
  1950. // simpler):
  1951. // If the default device is changed we need to first stop the local streams and then call GUM. Otherwise GUM
  1952. // will return a stream using the old default device.
  1953. if (requestedInput.audio && localAudio) {
  1954. localAudio.stopStream();
  1955. }
  1956. if (requestedInput.video && localVideo) {
  1957. localVideo.stopStream();
  1958. }
  1959. // Let's handle unknown/non-preferred devices
  1960. const newAvailDevices = APP.store.getState()['features/base/devices'].availableDevices;
  1961. let newAudioDevices = [];
  1962. let oldAudioDevices = [];
  1963. if (typeof newDevices.audiooutput === 'undefined') {
  1964. newAudioDevices = newAvailDevices.audioOutput;
  1965. oldAudioDevices = oldDevices.audioOutput;
  1966. }
  1967. if (!requestedInput.audio) {
  1968. newAudioDevices = newAudioDevices.concat(newAvailDevices.audioInput);
  1969. oldAudioDevices = oldAudioDevices.concat(oldDevices.audioInput);
  1970. }
  1971. // check for audio
  1972. if (newAudioDevices.length > 0) {
  1973. APP.store.dispatch(checkAndNotifyForNewDevice(newAudioDevices, oldAudioDevices));
  1974. }
  1975. // check for video
  1976. if (requestedInput.video) {
  1977. APP.store.dispatch(checkAndNotifyForNewDevice(newAvailDevices.videoInput, oldDevices.videoInput));
  1978. }
  1979. // When the 'default' mic needs to be selected, we need to pass the real device id to gUM instead of 'default'
  1980. // in order to get the correct MediaStreamTrack from chrome because of the following bug.
  1981. // https://bugs.chromium.org/p/chromium/issues/detail?id=997689
  1982. const hasDefaultMicChanged = newDevices.audioinput === 'default';
  1983. // When the local video is muted and a preferred device is connected, update the settings and remove the track
  1984. // from the conference. A new track will be created and replaced when the user unmutes their camera.
  1985. if (requestedInput.video && this.isLocalVideoMuted()) {
  1986. APP.store.dispatch(updateSettings({
  1987. cameraDeviceId: newDevices.videoinput
  1988. }));
  1989. requestedInput.video = false;
  1990. delete newDevices.videoinput;
  1991. // Remove the track from the conference.
  1992. if (localVideo) {
  1993. await this.useVideoStream(null);
  1994. logger.debug('_onDeviceListChanged: Removed the current video track.');
  1995. }
  1996. }
  1997. // When the local audio is muted and a preferred device is connected, update the settings and remove the track
  1998. // from the conference. A new track will be created and replaced when the user unmutes their mic.
  1999. if (requestedInput.audio && this.isLocalAudioMuted()) {
  2000. APP.store.dispatch(updateSettings({
  2001. micDeviceId: newDevices.audioinput
  2002. }));
  2003. requestedInput.audio = false;
  2004. delete newDevices.audioinput;
  2005. // Remove the track from the conference.
  2006. if (localAudio) {
  2007. await this.useAudioStream(null);
  2008. logger.debug('_onDeviceListChanged: Removed the current audio track.');
  2009. }
  2010. }
  2011. // Create the tracks and replace them only if the user is unmuted.
  2012. if (requestedInput.audio || requestedInput.video) {
  2013. let tracks = [];
  2014. const realAudioDeviceId = hasDefaultMicChanged
  2015. ? getDefaultDeviceId(APP.store.getState(), 'audioInput') : newDevices.audioinput;
  2016. try {
  2017. tracks = await mediaDeviceHelper.createLocalTracksAfterDeviceListChanged(
  2018. createLocalTracksF,
  2019. requestedInput.video ? newDevices.videoinput : null,
  2020. requestedInput.audio ? realAudioDeviceId : null
  2021. );
  2022. } catch (error) {
  2023. logger.error(`Track creation failed on device change, ${error}`);
  2024. return Promise.reject(error);
  2025. }
  2026. for (const track of tracks) {
  2027. if (track.isAudioTrack()) {
  2028. promises.push(
  2029. this.useAudioStream(track)
  2030. .then(() => {
  2031. hasDefaultMicChanged && (track._realDeviceId = track.deviceId = 'default');
  2032. this._updateAudioDeviceId();
  2033. }));
  2034. } else {
  2035. promises.push(
  2036. this.useVideoStream(track)
  2037. .then(() => {
  2038. this._updateVideoDeviceId();
  2039. }));
  2040. }
  2041. }
  2042. }
  2043. return Promise.all(promises)
  2044. .then(() => {
  2045. APP.UI.onAvailableDevicesChanged(devices);
  2046. });
  2047. },
  2048. /**
  2049. * Determines whether or not the audio button should be enabled.
  2050. */
  2051. updateAudioIconEnabled() {
  2052. const localAudio = getLocalJitsiAudioTrack(APP.store.getState());
  2053. const audioMediaDevices = APP.store.getState()['features/base/devices'].availableDevices.audioInput;
  2054. const audioDeviceCount = audioMediaDevices ? audioMediaDevices.length : 0;
  2055. // The audio functionality is considered available if there are any
  2056. // audio devices detected or if the local audio stream already exists.
  2057. const available = audioDeviceCount > 0 || Boolean(localAudio);
  2058. APP.store.dispatch(setAudioAvailable(available));
  2059. },
  2060. /**
  2061. * Determines whether or not the video button should be enabled.
  2062. */
  2063. updateVideoIconEnabled() {
  2064. const videoMediaDevices
  2065. = APP.store.getState()['features/base/devices'].availableDevices.videoInput;
  2066. const videoDeviceCount
  2067. = videoMediaDevices ? videoMediaDevices.length : 0;
  2068. const localVideo = getLocalJitsiVideoTrack(APP.store.getState());
  2069. // The video functionality is considered available if there are any
  2070. // video devices detected or if there is local video stream already
  2071. // active which could be either screensharing stream or a video track
  2072. // created before the permissions were rejected (through browser
  2073. // config).
  2074. const available = videoDeviceCount > 0 || Boolean(localVideo);
  2075. APP.store.dispatch(setVideoAvailable(available));
  2076. APP.API.notifyVideoAvailabilityChanged(available);
  2077. },
  2078. /**
  2079. * Disconnect from the conference and optionally request user feedback.
  2080. * @param {boolean} [requestFeedback=false] if user feedback should be
  2081. * requested
  2082. */
  2083. hangup(requestFeedback = false) {
  2084. APP.store.dispatch(disableReceiver());
  2085. this._stopProxyConnection();
  2086. APP.store.dispatch(destroyLocalTracks());
  2087. this._localTracksInitialized = false;
  2088. // Remove unnecessary event listeners from firing callbacks.
  2089. if (this.deviceChangeListener) {
  2090. JitsiMeetJS.mediaDevices.removeEventListener(
  2091. JitsiMediaDevicesEvents.DEVICE_LIST_CHANGED,
  2092. this.deviceChangeListener);
  2093. }
  2094. APP.UI.removeAllListeners();
  2095. let requestFeedbackPromise;
  2096. if (requestFeedback) {
  2097. requestFeedbackPromise
  2098. = APP.store.dispatch(maybeOpenFeedbackDialog(room))
  2099. // false because the thank you dialog shouldn't be displayed
  2100. .catch(() => Promise.resolve(false));
  2101. } else {
  2102. requestFeedbackPromise = Promise.resolve(true);
  2103. }
  2104. Promise.all([
  2105. requestFeedbackPromise,
  2106. this.leaveRoom()
  2107. ])
  2108. .then(values => {
  2109. this._room = undefined;
  2110. room = undefined;
  2111. /**
  2112. * Don't call {@code notifyReadyToClose} if the promotional page flag is set
  2113. * and let the page take care of sending the message, since there will be
  2114. * a redirect to the page regardlessly.
  2115. */
  2116. if (!interfaceConfig.SHOW_PROMOTIONAL_CLOSE_PAGE) {
  2117. APP.API.notifyReadyToClose();
  2118. }
  2119. APP.store.dispatch(maybeRedirectToWelcomePage(values[0]));
  2120. });
  2121. },
  2122. /**
  2123. * Leaves the room.
  2124. *
  2125. * @param {boolean} doDisconnect - Whether leaving the room should also terminate the connection.
  2126. * @param {string} reason - reason for leaving the room.
  2127. * @returns {Promise}
  2128. */
  2129. async leaveRoom(doDisconnect = true, reason = '') {
  2130. APP.store.dispatch(conferenceWillLeave(room));
  2131. const maybeDisconnect = () => {
  2132. if (doDisconnect) {
  2133. return disconnect();
  2134. }
  2135. };
  2136. if (room && room.isJoined()) {
  2137. return room.leave(reason).then(() => maybeDisconnect())
  2138. .catch(e => {
  2139. logger.error(e);
  2140. return maybeDisconnect();
  2141. });
  2142. }
  2143. return maybeDisconnect();
  2144. },
  2145. /**
  2146. * Changes the email for the local user
  2147. * @param email {string} the new email
  2148. */
  2149. changeLocalEmail(email = '') {
  2150. const formattedEmail = String(email).trim();
  2151. APP.store.dispatch(updateSettings({
  2152. email: formattedEmail
  2153. }));
  2154. sendData(commands.EMAIL, formattedEmail);
  2155. },
  2156. /**
  2157. * Changes the avatar url for the local user
  2158. * @param url {string} the new url
  2159. */
  2160. changeLocalAvatarUrl(url = '') {
  2161. const formattedUrl = String(url).trim();
  2162. APP.store.dispatch(updateSettings({
  2163. avatarURL: formattedUrl
  2164. }));
  2165. sendData(commands.AVATAR_URL, url);
  2166. },
  2167. /**
  2168. * Sends a message via the data channel.
  2169. * @param {string} to the id of the endpoint that should receive the
  2170. * message. If "" - the message will be sent to all participants.
  2171. * @param {object} payload the payload of the message.
  2172. * @throws NetworkError or InvalidStateError or Error if the operation
  2173. * fails.
  2174. */
  2175. sendEndpointMessage(to, payload) {
  2176. room.sendEndpointMessage(to, payload);
  2177. },
  2178. /**
  2179. * Adds new listener.
  2180. * @param {String} eventName the name of the event
  2181. * @param {Function} listener the listener.
  2182. */
  2183. addListener(eventName, listener) {
  2184. eventEmitter.addListener(eventName, listener);
  2185. },
  2186. /**
  2187. * Removes listener.
  2188. * @param {String} eventName the name of the event that triggers the
  2189. * listener
  2190. * @param {Function} listener the listener.
  2191. */
  2192. removeListener(eventName, listener) {
  2193. eventEmitter.removeListener(eventName, listener);
  2194. },
  2195. /**
  2196. * Changes the display name for the local user
  2197. * @param nickname {string} the new display name
  2198. */
  2199. changeLocalDisplayName(nickname = '') {
  2200. const formattedNickname = getNormalizedDisplayName(nickname);
  2201. APP.store.dispatch(updateSettings({
  2202. displayName: formattedNickname
  2203. }));
  2204. },
  2205. /**
  2206. * Callback invoked by the external api create or update a direct connection
  2207. * from the local client to an external client.
  2208. *
  2209. * @param {Object} event - The object containing information that should be
  2210. * passed to the {@code ProxyConnectionService}.
  2211. * @returns {void}
  2212. */
  2213. onProxyConnectionEvent(event) {
  2214. if (!this._proxyConnection) {
  2215. this._proxyConnection = new JitsiMeetJS.ProxyConnectionService({
  2216. /**
  2217. * Pass the {@code JitsiConnection} instance which will be used
  2218. * to fetch TURN credentials.
  2219. */
  2220. jitsiConnection: APP.connection,
  2221. /**
  2222. * The proxy connection feature is currently tailored towards
  2223. * taking a proxied video stream and showing it as a local
  2224. * desktop screen.
  2225. */
  2226. convertVideoToDesktop: true,
  2227. /**
  2228. * Callback invoked when the connection has been closed
  2229. * automatically. Triggers cleanup of screensharing if active.
  2230. *
  2231. * @returns {void}
  2232. */
  2233. onConnectionClosed: () => {
  2234. if (this._untoggleScreenSharing) {
  2235. this._untoggleScreenSharing();
  2236. }
  2237. },
  2238. /**
  2239. * Callback invoked to pass messages from the local client back
  2240. * out to the external client.
  2241. *
  2242. * @param {string} peerJid - The jid of the intended recipient
  2243. * of the message.
  2244. * @param {Object} data - The message that should be sent. For
  2245. * screensharing this is an iq.
  2246. * @returns {void}
  2247. */
  2248. onSendMessage: (peerJid, data) =>
  2249. APP.API.sendProxyConnectionEvent({
  2250. data,
  2251. to: peerJid
  2252. }),
  2253. /**
  2254. * Callback invoked when the remote peer of the proxy connection
  2255. * has provided a video stream, intended to be used as a local
  2256. * desktop stream.
  2257. *
  2258. * @param {JitsiLocalTrack} remoteProxyStream - The media
  2259. * stream to use as a local desktop stream.
  2260. * @returns {void}
  2261. */
  2262. onRemoteStream: desktopStream => {
  2263. if (desktopStream.videoType !== 'desktop') {
  2264. logger.warn('Received a non-desktop stream to proxy.');
  2265. desktopStream.dispose();
  2266. return;
  2267. }
  2268. APP.store.dispatch(toggleScreensharingA(undefined, false, { desktopStream }));
  2269. }
  2270. });
  2271. }
  2272. this._proxyConnection.processMessage(event);
  2273. },
  2274. /**
  2275. * Sets the video muted status.
  2276. */
  2277. setVideoMuteStatus() {
  2278. APP.UI.setVideoMuted(this.getMyUserId());
  2279. },
  2280. /**
  2281. * Sets the audio muted status.
  2282. *
  2283. * @param {boolean} muted - New muted status.
  2284. */
  2285. setAudioMuteStatus(muted) {
  2286. APP.UI.setAudioMuted(this.getMyUserId(), muted);
  2287. },
  2288. /**
  2289. * Dispatches the passed in feedback for submission. The submitted score
  2290. * should be a number inclusively between 1 through 5, or -1 for no score.
  2291. *
  2292. * @param {number} score - a number between 1 and 5 (inclusive) or -1 for no
  2293. * score.
  2294. * @param {string} message - An optional message to attach to the feedback
  2295. * in addition to the score.
  2296. * @returns {void}
  2297. */
  2298. submitFeedback(score = -1, message = '') {
  2299. if (score === -1 || (score >= 1 && score <= 5)) {
  2300. APP.store.dispatch(submitFeedback(score, message, room));
  2301. }
  2302. },
  2303. /**
  2304. * Terminates any proxy screensharing connection that is active.
  2305. *
  2306. * @private
  2307. * @returns {void}
  2308. */
  2309. _stopProxyConnection() {
  2310. if (this._proxyConnection) {
  2311. this._proxyConnection.stop();
  2312. }
  2313. this._proxyConnection = null;
  2314. }
  2315. };