Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

conference.js 109KB

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