Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

conference.js 112KB

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