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

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