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

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