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

conference.js 89KB

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