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

conference.js 97KB

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