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

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