Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

conference.js 117KB

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