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

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