You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

conference.js 101KB

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