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

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