您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

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