您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

conference.js 111KB

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