Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

conference.js 105KB

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