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

conference.js 113KB

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