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 108KB

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