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

conference.js 107KB

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