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

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