Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

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