Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

conference.js 90KB

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