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

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