Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

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