Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

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