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 110KB

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