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

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