選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

conference.js 110KB

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