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

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