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

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