You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

conference.js 105KB

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