You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

conference.js 110KB

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