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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700
  1. /* global APP, JitsiMeetJS, config, interfaceConfig */
  2. import { jitsiLocalStorage } from '@jitsi/js-utils';
  3. import Logger from '@jitsi/logger';
  4. import EventEmitter from 'events';
  5. import { ENDPOINT_TEXT_MESSAGE_NAME } from './modules/API/constants';
  6. import { AUDIO_ONLY_SCREEN_SHARE_NO_TRACK } from './modules/UI/UIErrors';
  7. import mediaDeviceHelper from './modules/devices/mediaDeviceHelper';
  8. import Recorder from './modules/recorder/Recorder';
  9. import { createTaskQueue } from './modules/util/helpers';
  10. import {
  11. createDeviceChangedEvent,
  12. createScreenSharingEvent,
  13. createStartSilentEvent,
  14. createTrackMutedEvent
  15. } from './react/features/analytics/AnalyticsEvents';
  16. import { sendAnalytics } from './react/features/analytics/functions';
  17. import {
  18. maybeRedirectToWelcomePage,
  19. redirectToStaticPage,
  20. reloadWithStoredParams
  21. } from './react/features/app/actions';
  22. import { showModeratedNotification } from './react/features/av-moderation/actions';
  23. import { shouldShowModeratedNotification } from './react/features/av-moderation/functions';
  24. import {
  25. _conferenceWillJoin,
  26. authStatusChanged,
  27. conferenceFailed,
  28. conferenceJoinInProgress,
  29. conferenceJoined,
  30. conferenceLeft,
  31. conferenceSubjectChanged,
  32. conferenceTimestampChanged,
  33. conferenceUniqueIdSet,
  34. conferenceWillInit,
  35. conferenceWillLeave,
  36. dataChannelClosed,
  37. dataChannelOpened,
  38. e2eRttChanged,
  39. kickedOut,
  40. lockStateChanged,
  41. nonParticipantMessageReceived,
  42. onStartMutedPolicyChanged,
  43. p2pStatusChanged
  44. } from './react/features/base/conference/actions';
  45. import {
  46. AVATAR_URL_COMMAND,
  47. CONFERENCE_LEAVE_REASONS,
  48. EMAIL_COMMAND
  49. } from './react/features/base/conference/constants';
  50. import {
  51. commonUserJoinedHandling,
  52. commonUserLeftHandling,
  53. getConferenceOptions,
  54. sendLocalParticipant
  55. } from './react/features/base/conference/functions';
  56. import { getReplaceParticipant } from './react/features/base/config/functions';
  57. import { connect } from './react/features/base/connection/actions.web';
  58. import {
  59. checkAndNotifyForNewDevice,
  60. getAvailableDevices,
  61. notifyCameraError,
  62. notifyMicError,
  63. updateDeviceList
  64. } from './react/features/base/devices/actions.web';
  65. import {
  66. getDefaultDeviceId,
  67. setAudioOutputDeviceId
  68. } from './react/features/base/devices/functions.web';
  69. import {
  70. JitsiConferenceErrors,
  71. JitsiConferenceEvents,
  72. JitsiE2ePingEvents,
  73. JitsiMediaDevicesEvents,
  74. JitsiTrackErrors,
  75. JitsiTrackEvents,
  76. browser
  77. } from './react/features/base/lib-jitsi-meet';
  78. import {
  79. gumPending,
  80. setAudioAvailable,
  81. setAudioMuted,
  82. setAudioUnmutePermissions,
  83. setVideoAvailable,
  84. setVideoMuted,
  85. setVideoUnmutePermissions
  86. } from './react/features/base/media/actions';
  87. import { MEDIA_TYPE } from './react/features/base/media/constants';
  88. import {
  89. getStartWithAudioMuted,
  90. getStartWithVideoMuted,
  91. isVideoMutedByUser
  92. } from './react/features/base/media/functions';
  93. import { IGUMPendingState } from './react/features/base/media/types';
  94. import {
  95. dominantSpeakerChanged,
  96. localParticipantAudioLevelChanged,
  97. localParticipantRoleChanged,
  98. participantKicked,
  99. participantMutedUs,
  100. participantPresenceChanged,
  101. participantRoleChanged,
  102. participantSourcesUpdated,
  103. participantUpdated,
  104. screenshareParticipantDisplayNameChanged,
  105. updateRemoteParticipantFeatures
  106. } from './react/features/base/participants/actions';
  107. import {
  108. getLocalParticipant,
  109. getNormalizedDisplayName,
  110. getVirtualScreenshareParticipantByOwnerId
  111. } from './react/features/base/participants/functions';
  112. import { updateSettings } from './react/features/base/settings/actions';
  113. import {
  114. addLocalTrack,
  115. destroyLocalTracks,
  116. replaceLocalTrack,
  117. toggleScreensharing as toggleScreensharingA,
  118. trackAdded,
  119. trackRemoved
  120. } from './react/features/base/tracks/actions';
  121. import {
  122. createLocalTracksF,
  123. getLocalJitsiAudioTrack,
  124. getLocalJitsiVideoTrack,
  125. getLocalTracks,
  126. getLocalVideoTrack,
  127. isLocalTrackMuted,
  128. isUserInteractionRequiredForUnmute
  129. } from './react/features/base/tracks/functions';
  130. import { downloadJSON } from './react/features/base/util/downloadJSON';
  131. import { showDesktopPicker } from './react/features/desktop-picker/actions';
  132. import { appendSuffix } from './react/features/display-name/functions';
  133. import { maybeOpenFeedbackDialog, submitFeedback } from './react/features/feedback/actions';
  134. import { initKeyboardShortcuts } from './react/features/keyboard-shortcuts/actions';
  135. import { maybeSetLobbyChatMessageListener } from './react/features/lobby/actions.any';
  136. import { setNoiseSuppressionEnabled } from './react/features/noise-suppression/actions';
  137. import {
  138. hideNotification,
  139. showErrorNotification,
  140. showNotification,
  141. showWarningNotification
  142. } from './react/features/notifications/actions';
  143. import {
  144. DATA_CHANNEL_CLOSED_NOTIFICATION_ID,
  145. NOTIFICATION_TIMEOUT_TYPE
  146. } from './react/features/notifications/constants';
  147. import { isModerationNotificationDisplayed } from './react/features/notifications/functions';
  148. import { mediaPermissionPromptVisibilityChanged } from './react/features/overlay/actions';
  149. import { suspendDetected } from './react/features/power-monitor/actions';
  150. import { initPrejoin, makePrecallTest } from './react/features/prejoin/actions';
  151. import { isPrejoinPageVisible } from './react/features/prejoin/functions';
  152. import { disableReceiver, stopReceiver } from './react/features/remote-control/actions';
  153. import { setScreenAudioShareState } from './react/features/screen-share/actions.web';
  154. import { isScreenAudioShared } from './react/features/screen-share/functions';
  155. import { toggleScreenshotCaptureSummary } from './react/features/screenshot-capture/actions';
  156. import { AudioMixerEffect } from './react/features/stream-effects/audio-mixer/AudioMixerEffect';
  157. import { createRnnoiseProcessor } from './react/features/stream-effects/rnnoise';
  158. import { endpointMessageReceived } from './react/features/subtitles/actions.any';
  159. import { handleToggleVideoMuted } from './react/features/toolbox/actions.any';
  160. import { muteLocal } from './react/features/video-menu/actions.any';
  161. import { iAmVisitor } from './react/features/visitors/functions';
  162. import UIEvents from './service/UI/UIEvents';
  163. const logger = Logger.getLogger(__filename);
  164. const eventEmitter = new EventEmitter();
  165. let room;
  166. /*
  167. * Logic to open a desktop picker put on the window global for
  168. * lib-jitsi-meet to detect and invoke
  169. */
  170. window.JitsiMeetScreenObtainer = {
  171. openDesktopPicker(options, onSourceChoose) {
  172. APP.store.dispatch(showDesktopPicker(options, onSourceChoose));
  173. }
  174. };
  175. /**
  176. * Known custom conference commands.
  177. */
  178. const commands = {
  179. AVATAR_URL: AVATAR_URL_COMMAND,
  180. CUSTOM_ROLE: 'custom-role',
  181. EMAIL: EMAIL_COMMAND,
  182. ETHERPAD: 'etherpad'
  183. };
  184. /**
  185. * Share data to other users.
  186. * @param command the command
  187. * @param {string} value new value
  188. */
  189. function sendData(command, value) {
  190. if (!room) {
  191. return;
  192. }
  193. room.removeCommand(command);
  194. room.sendCommand(command, { value });
  195. }
  196. /**
  197. * Mute or unmute local audio stream if it exists.
  198. * @param {boolean} muted - if audio stream should be muted or unmuted.
  199. */
  200. function muteLocalAudio(muted) {
  201. APP.store.dispatch(setAudioMuted(muted));
  202. }
  203. /**
  204. * Mute or unmute local video stream if it exists.
  205. * @param {boolean} muted if video stream should be muted or unmuted.
  206. *
  207. */
  208. function muteLocalVideo(muted) {
  209. APP.store.dispatch(setVideoMuted(muted));
  210. }
  211. /**
  212. * A queue for the async replaceLocalTrack action so that multiple audio
  213. * replacements cannot happen simultaneously. This solves the issue where
  214. * replaceLocalTrack is called multiple times with an oldTrack of null, causing
  215. * multiple local tracks of the same type to be used.
  216. *
  217. * @private
  218. * @type {Object}
  219. */
  220. const _replaceLocalAudioTrackQueue = createTaskQueue();
  221. /**
  222. * A task queue for replacement local video tracks. This separate queue exists
  223. * so video replacement is not blocked by audio replacement tasks in the queue
  224. * {@link _replaceLocalAudioTrackQueue}.
  225. *
  226. * @private
  227. * @type {Object}
  228. */
  229. const _replaceLocalVideoTrackQueue = createTaskQueue();
  230. /**
  231. *
  232. */
  233. class ConferenceConnector {
  234. /**
  235. *
  236. */
  237. constructor(resolve, reject, conference) {
  238. this._conference = conference;
  239. this._resolve = resolve;
  240. this._reject = reject;
  241. this.reconnectTimeout = null;
  242. room.on(JitsiConferenceEvents.CONFERENCE_JOINED,
  243. this._handleConferenceJoined.bind(this));
  244. room.on(JitsiConferenceEvents.CONFERENCE_FAILED,
  245. this._onConferenceFailed.bind(this));
  246. }
  247. /**
  248. *
  249. */
  250. _handleConferenceFailed(err) {
  251. this._unsubscribe();
  252. this._reject(err);
  253. }
  254. /**
  255. *
  256. */
  257. _onConferenceFailed(err, ...params) {
  258. APP.store.dispatch(conferenceFailed(room, err, ...params));
  259. logger.error('CONFERENCE FAILED:', err, ...params);
  260. switch (err) {
  261. case JitsiConferenceErrors.NOT_ALLOWED_ERROR: {
  262. // let's show some auth not allowed page
  263. APP.store.dispatch(redirectToStaticPage('static/authError.html'));
  264. break;
  265. }
  266. case JitsiConferenceErrors.RESERVATION_ERROR: {
  267. const [ code, msg ] = params;
  268. APP.store.dispatch(showErrorNotification({
  269. descriptionArguments: {
  270. code,
  271. msg
  272. },
  273. descriptionKey: 'dialog.reservationErrorMsg',
  274. titleKey: 'dialog.reservationError'
  275. }, NOTIFICATION_TIMEOUT_TYPE.LONG));
  276. break;
  277. }
  278. case JitsiConferenceErrors.GRACEFUL_SHUTDOWN:
  279. APP.store.dispatch(showErrorNotification({
  280. descriptionKey: 'dialog.gracefulShutdown',
  281. titleKey: 'dialog.serviceUnavailable'
  282. }, NOTIFICATION_TIMEOUT_TYPE.LONG));
  283. break;
  284. // FIXME FOCUS_DISCONNECTED is a confusing event name.
  285. // What really happens there is that the library is not ready yet,
  286. // because Jicofo is not available, but it is going to give it another
  287. // try.
  288. case JitsiConferenceErrors.FOCUS_DISCONNECTED: {
  289. const [ focus, retrySec ] = params;
  290. APP.store.dispatch(showNotification({
  291. descriptionKey: focus,
  292. titleKey: retrySec
  293. }, NOTIFICATION_TIMEOUT_TYPE.SHORT));
  294. break;
  295. }
  296. case JitsiConferenceErrors.FOCUS_LEFT:
  297. case JitsiConferenceErrors.ICE_FAILED:
  298. case JitsiConferenceErrors.VIDEOBRIDGE_NOT_AVAILABLE:
  299. case JitsiConferenceErrors.OFFER_ANSWER_FAILED:
  300. APP.store.dispatch(conferenceWillLeave(room));
  301. // FIXME the conference should be stopped by the library and not by
  302. // the app. Both the errors above are unrecoverable from the library
  303. // perspective.
  304. room.leave(CONFERENCE_LEAVE_REASONS.UNRECOVERABLE_ERROR).then(() => APP.connection.disconnect());
  305. break;
  306. case JitsiConferenceErrors.INCOMPATIBLE_SERVER_VERSIONS:
  307. APP.store.dispatch(reloadWithStoredParams());
  308. break;
  309. default:
  310. this._handleConferenceFailed(err, ...params);
  311. }
  312. }
  313. /**
  314. *
  315. */
  316. _unsubscribe() {
  317. room.off(
  318. JitsiConferenceEvents.CONFERENCE_JOINED,
  319. this._handleConferenceJoined);
  320. room.off(
  321. JitsiConferenceEvents.CONFERENCE_FAILED,
  322. this._onConferenceFailed);
  323. if (this.reconnectTimeout !== null) {
  324. clearTimeout(this.reconnectTimeout);
  325. }
  326. }
  327. /**
  328. *
  329. */
  330. _handleConferenceJoined() {
  331. this._unsubscribe();
  332. this._resolve();
  333. }
  334. /**
  335. *
  336. */
  337. connect() {
  338. const replaceParticipant = getReplaceParticipant(APP.store.getState());
  339. // the local storage overrides here and in connection.js can be used by jibri
  340. room.join(jitsiLocalStorage.getItem('xmpp_conference_password_override'), replaceParticipant);
  341. }
  342. }
  343. /**
  344. * Disconnects the connection.
  345. * @returns resolved Promise. We need this in order to make the Promise.all
  346. * call in hangup() to resolve when all operations are finished.
  347. */
  348. function disconnect() {
  349. const onDisconnected = () => {
  350. APP.API.notifyConferenceLeft(APP.conference.roomName);
  351. return Promise.resolve();
  352. };
  353. if (!APP.connection) {
  354. return onDisconnected();
  355. }
  356. return APP.connection.disconnect().then(onDisconnected, onDisconnected);
  357. }
  358. /**
  359. * Sets the GUM pending state for the tracks that have failed.
  360. *
  361. * NOTE: Some of the track that we will be setting to GUM pending state NONE may not have failed but they may have
  362. * been requested. This won't be a problem because their current GUM pending state will be NONE anyway.
  363. * @param {JitsiLocalTrack} tracks - The tracks that have been created.
  364. * @returns {void}
  365. */
  366. function setGUMPendingStateOnFailedTracks(tracks) {
  367. const tracksTypes = tracks.map(track => track.getType());
  368. const nonPendingTracks = [ MEDIA_TYPE.AUDIO, MEDIA_TYPE.VIDEO ].filter(type => !tracksTypes.includes(type));
  369. APP.store.dispatch(gumPending(nonPendingTracks, IGUMPendingState.NONE));
  370. }
  371. export default {
  372. /**
  373. * Flag used to delay modification of the muted status of local media tracks
  374. * until those are created (or not, but at that point it's certain that
  375. * the tracks won't exist).
  376. */
  377. _localTracksInitialized: false,
  378. /**
  379. * Flag used to prevent the creation of another local video track in this.muteVideo if one is already in progress.
  380. */
  381. isCreatingLocalTrack: false,
  382. isSharingScreen: false,
  383. /**
  384. * Returns an object containing a promise which resolves with the created tracks &
  385. * the errors resulting from that process.
  386. * @param {object} options
  387. * @param {boolean} options.startAudioOnly=false - if <tt>true</tt> then
  388. * only audio track will be created and the audio only mode will be turned
  389. * on.
  390. * @param {boolean} options.startScreenSharing=false - if <tt>true</tt>
  391. * should start with screensharing instead of camera video.
  392. * @param {boolean} options.startWithAudioMuted - will start the conference
  393. * without any audio tracks.
  394. * @param {boolean} options.startWithVideoMuted - will start the conference
  395. * without any video tracks.
  396. * @returns {Promise<JitsiLocalTrack[]>, Object}
  397. */
  398. createInitialLocalTracks(options = {}) {
  399. const errors = {};
  400. // Always get a handle on the audio input device so that we have statistics (such as "No audio input" or
  401. // "Are you trying to speak?" ) even if the user joins the conference muted.
  402. const initialDevices = config.disableInitialGUM ? [] : [ MEDIA_TYPE.AUDIO ];
  403. const requestedAudio = !config.disableInitialGUM;
  404. let requestedVideo = false;
  405. if (!config.disableInitialGUM
  406. && !options.startWithVideoMuted
  407. && !options.startAudioOnly
  408. && !options.startScreenSharing) {
  409. initialDevices.push(MEDIA_TYPE.VIDEO);
  410. requestedVideo = true;
  411. }
  412. if (!config.disableInitialGUM) {
  413. JitsiMeetJS.mediaDevices.addEventListener(
  414. JitsiMediaDevicesEvents.PERMISSION_PROMPT_IS_SHOWN,
  415. browserName =>
  416. APP.store.dispatch(
  417. mediaPermissionPromptVisibilityChanged(true, browserName))
  418. );
  419. }
  420. let tryCreateLocalTracks = Promise.resolve([]);
  421. // On Electron there is no permission prompt for granting permissions. That's why we don't need to
  422. // spend much time displaying the overlay screen. If GUM is not resolved within 15 seconds it will
  423. // probably never resolve.
  424. const timeout = browser.isElectron() ? 15000 : 60000;
  425. const audioOptions = {
  426. devices: [ MEDIA_TYPE.AUDIO ],
  427. timeout,
  428. firePermissionPromptIsShownEvent: true
  429. };
  430. // Spot uses the _desktopSharingSourceDevice config option to use an external video input device label as
  431. // screenshare and calls getUserMedia instead of getDisplayMedia for capturing the media.
  432. if (options.startScreenSharing && config._desktopSharingSourceDevice) {
  433. tryCreateLocalTracks = this._createDesktopTrack()
  434. .then(([ desktopStream ]) => {
  435. if (!requestedAudio) {
  436. return [ desktopStream ];
  437. }
  438. return createLocalTracksF(audioOptions)
  439. .then(([ audioStream ]) =>
  440. [ desktopStream, audioStream ])
  441. .catch(error => {
  442. errors.audioOnlyError = error;
  443. return [ desktopStream ];
  444. });
  445. })
  446. .catch(error => {
  447. logger.error('Failed to obtain desktop stream', error);
  448. errors.screenSharingError = error;
  449. return requestedAudio ? createLocalTracksF(audioOptions) : [];
  450. })
  451. .catch(error => {
  452. errors.audioOnlyError = error;
  453. return [];
  454. });
  455. } else if (requestedAudio || requestedVideo) {
  456. APP.store.dispatch(gumPending(initialDevices, IGUMPendingState.PENDING_UNMUTE));
  457. tryCreateLocalTracks = createLocalTracksF({
  458. devices: initialDevices,
  459. timeout,
  460. firePermissionPromptIsShownEvent: true
  461. })
  462. .catch(async error => {
  463. if (error.name === JitsiTrackErrors.TIMEOUT && !browser.isElectron()) {
  464. errors.audioAndVideoError = error;
  465. return [];
  466. }
  467. // Retry with separate gUM calls.
  468. const gUMPromises = [];
  469. const tracks = [];
  470. if (requestedAudio) {
  471. gUMPromises.push(createLocalTracksF(audioOptions));
  472. }
  473. if (requestedVideo) {
  474. gUMPromises.push(createLocalTracksF({
  475. devices: [ MEDIA_TYPE.VIDEO ],
  476. timeout,
  477. firePermissionPromptIsShownEvent: true
  478. }));
  479. }
  480. const results = await Promise.allSettled(gUMPromises);
  481. let errorMsg;
  482. results.forEach((result, idx) => {
  483. if (result.status === 'fulfilled') {
  484. tracks.push(result.value[0]);
  485. } else {
  486. errorMsg = result.reason;
  487. const isAudio = idx === 0;
  488. logger.error(`${isAudio ? 'Audio' : 'Video'} track creation failed with error ${errorMsg}`);
  489. if (isAudio) {
  490. errors.audioOnlyError = errorMsg;
  491. } else {
  492. errors.videoOnlyError = errorMsg;
  493. }
  494. }
  495. });
  496. if (errors.audioOnlyError && errors.videoOnlyError) {
  497. errors.audioAndVideoError = errorMsg;
  498. }
  499. return tracks;
  500. });
  501. }
  502. // Hide the permissions prompt/overlay as soon as the tracks are created. Don't wait for the connection to
  503. // be established, as in some cases like when auth is required, connection won't be established until the user
  504. // inputs their credentials, but the dialog would be overshadowed by the overlay.
  505. tryCreateLocalTracks.then(tracks => {
  506. APP.store.dispatch(mediaPermissionPromptVisibilityChanged(false));
  507. return tracks;
  508. });
  509. return {
  510. tryCreateLocalTracks,
  511. errors
  512. };
  513. },
  514. /**
  515. * Displays error notifications according to the state carried by {@code errors} object returned
  516. * by {@link createInitialLocalTracks}.
  517. * @param {Object} errors - the errors (if any) returned by {@link createInitialLocalTracks}.
  518. *
  519. * @returns {void}
  520. * @private
  521. */
  522. _displayErrorsForCreateInitialLocalTracks(errors) {
  523. const {
  524. audioAndVideoError,
  525. audioOnlyError,
  526. screenSharingError,
  527. videoOnlyError
  528. } = errors;
  529. // FIXME If there will be microphone error it will cover any screensharing dialog, but it's still better than in
  530. // the reverse order where the screensharing dialog will sometimes be closing the microphone alert
  531. // ($.prompt.close(); is called). Need to figure out dialogs chaining to fix that.
  532. if (screenSharingError) {
  533. this._handleScreenSharingError(screenSharingError);
  534. }
  535. if (audioAndVideoError || audioOnlyError) {
  536. if (audioOnlyError || videoOnlyError) {
  537. // If both requests for 'audio' + 'video' and 'audio' only failed, we assume that there are some
  538. // problems with user's microphone and show corresponding dialog.
  539. APP.store.dispatch(notifyMicError(audioOnlyError));
  540. APP.store.dispatch(notifyCameraError(videoOnlyError));
  541. } else {
  542. // If request for 'audio' + 'video' failed, but request for 'audio' only was OK, we assume that we had
  543. // problems with camera and show corresponding dialog.
  544. APP.store.dispatch(notifyCameraError(audioAndVideoError));
  545. }
  546. }
  547. },
  548. startConference(tracks) {
  549. tracks.forEach(track => {
  550. if ((track.isAudioTrack() && this.isLocalAudioMuted())
  551. || (track.isVideoTrack() && this.isLocalVideoMuted())) {
  552. const mediaType = track.getType();
  553. sendAnalytics(
  554. createTrackMutedEvent(mediaType, 'initial mute'));
  555. logger.log(`${mediaType} mute: initially muted.`);
  556. track.mute();
  557. }
  558. });
  559. this._createRoom(tracks);
  560. // if user didn't give access to mic or camera or doesn't have
  561. // them at all, we mark corresponding toolbar buttons as muted,
  562. // so that the user can try unmute later on and add audio/video
  563. // to the conference
  564. if (!tracks.find(t => t.isAudioTrack())) {
  565. this.setAudioMuteStatus(true);
  566. }
  567. if (!tracks.find(t => t.isVideoTrack())) {
  568. this.setVideoMuteStatus();
  569. }
  570. if (config.iAmRecorder) {
  571. this.recorder = new Recorder();
  572. }
  573. if (config.startSilent) {
  574. sendAnalytics(createStartSilentEvent());
  575. APP.store.dispatch(showNotification({
  576. descriptionKey: 'notify.startSilentDescription',
  577. titleKey: 'notify.startSilentTitle'
  578. }, NOTIFICATION_TIMEOUT_TYPE.LONG));
  579. }
  580. // XXX The API will take care of disconnecting from the XMPP
  581. // server (and, thus, leaving the room) on unload.
  582. return new Promise((resolve, reject) => {
  583. new ConferenceConnector(resolve, reject, this).connect();
  584. });
  585. },
  586. /**
  587. * Open new connection and join the conference when prejoin page is not enabled.
  588. * If prejoin page is enabled open an new connection in the background
  589. * and create local tracks.
  590. *
  591. * @param {{ roomName: string }} options
  592. * @returns {Promise}
  593. */
  594. async init({ roomName }) {
  595. const state = APP.store.getState();
  596. const initialOptions = {
  597. startAudioOnly: config.startAudioOnly,
  598. startScreenSharing: config.startScreenSharing,
  599. startWithAudioMuted: getStartWithAudioMuted(state) || isUserInteractionRequiredForUnmute(state),
  600. startWithVideoMuted: getStartWithVideoMuted(state) || isUserInteractionRequiredForUnmute(state)
  601. };
  602. this.roomName = roomName;
  603. try {
  604. // Initialize the device list first. This way, when creating tracks based on preferred devices, loose label
  605. // matching can be done in cases where the exact ID match is no longer available, such as -
  606. // 1. When the camera device has switched USB ports.
  607. // 2. When in startSilent mode we want to start with audio muted
  608. await this._initDeviceList();
  609. } catch (error) {
  610. logger.warn('initial device list initialization failed', error);
  611. }
  612. // Filter out the local tracks based on various config options, i.e., when user joins muted or is muted by
  613. // focus. However, audio track will always be created even though it is not added to the conference since we
  614. // want audio related features (noisy mic, talk while muted, etc.) to work even if the mic is muted.
  615. const handleInitialTracks = (options, tracks) => {
  616. let localTracks = tracks;
  617. // No local tracks are added when user joins as a visitor.
  618. if (iAmVisitor(state)) {
  619. return [];
  620. }
  621. if (options.startWithAudioMuted || room?.isStartAudioMuted()) {
  622. // Always add the track on Safari because of a known issue where audio playout doesn't happen
  623. // if the user joins audio and video muted, i.e., if there is no local media capture.
  624. if (browser.isWebKitBased()) {
  625. this.muteAudio(true, true);
  626. } else {
  627. localTracks = localTracks.filter(track => track.getType() !== MEDIA_TYPE.AUDIO);
  628. }
  629. }
  630. if (room?.isStartVideoMuted()) {
  631. localTracks = localTracks.filter(track => track.getType() !== MEDIA_TYPE.VIDEO);
  632. }
  633. return localTracks;
  634. };
  635. if (isPrejoinPageVisible(state)) {
  636. APP.store.dispatch(makePrecallTest(this._getConferenceOptions()));
  637. const { tryCreateLocalTracks, errors } = this.createInitialLocalTracks(initialOptions);
  638. const localTracks = await tryCreateLocalTracks;
  639. // Initialize device list a second time to ensure device labels get populated in case of an initial gUM
  640. // acceptance; otherwise they may remain as empty strings.
  641. this._initDeviceList(true);
  642. if (isPrejoinPageVisible(state)) {
  643. APP.store.dispatch(gumPending([ MEDIA_TYPE.AUDIO, MEDIA_TYPE.VIDEO ], IGUMPendingState.NONE));
  644. return APP.store.dispatch(initPrejoin(localTracks, errors));
  645. }
  646. logger.debug('Prejoin screen no longer displayed at the time when tracks were created');
  647. this._displayErrorsForCreateInitialLocalTracks(errors);
  648. const tracks = handleInitialTracks(initialOptions, localTracks);
  649. setGUMPendingStateOnFailedTracks(tracks);
  650. return this._setLocalAudioVideoStreams(tracks);
  651. }
  652. const { tryCreateLocalTracks, errors } = this.createInitialLocalTracks(initialOptions);
  653. return Promise.all([
  654. tryCreateLocalTracks.then(tr => {
  655. this._displayErrorsForCreateInitialLocalTracks(errors);
  656. return tr;
  657. }).then(tr => {
  658. this._initDeviceList(true);
  659. const filteredTracks = handleInitialTracks(initialOptions, tr);
  660. setGUMPendingStateOnFailedTracks(filteredTracks);
  661. return filteredTracks;
  662. }),
  663. APP.store.dispatch(connect())
  664. ]).then(([ tracks, _ ]) => {
  665. this.startConference(tracks).catch(logger.error);
  666. });
  667. },
  668. /**
  669. * Check if id is id of the local user.
  670. * @param {string} id id to check
  671. * @returns {boolean}
  672. */
  673. isLocalId(id) {
  674. return this.getMyUserId() === id;
  675. },
  676. /**
  677. * Tells whether the local video is muted or not.
  678. * @return {boolean}
  679. */
  680. isLocalVideoMuted() {
  681. // If the tracks are not ready, read from base/media state
  682. return this._localTracksInitialized
  683. ? isLocalTrackMuted(APP.store.getState()['features/base/tracks'], MEDIA_TYPE.VIDEO)
  684. : isVideoMutedByUser(APP.store);
  685. },
  686. /**
  687. * Verify if there is an ongoing system audio sharing session and apply to the provided track
  688. * as a AudioMixer effect.
  689. *
  690. * @param {*} localAudioTrack - track to which system audio track will be applied as an effect, most likely
  691. * microphone local audio track.
  692. */
  693. async _maybeApplyAudioMixerEffect(localAudioTrack) {
  694. // At the time of writing this comment there were two separate flows for toggling screen-sharing
  695. // and system audio sharing, the first is the legacy method using the functionality from conference.js
  696. // the second is used when both sendMultipleVideoStreams and sourceNameSignaling flags are set to true.
  697. // The second flow uses functionality from base/conference/middleware.web.js.
  698. // We check if system audio sharing was done using the first flow by verifying this._desktopAudioStream and
  699. // for the second by checking 'features/screen-share' state.
  700. const { desktopAudioTrack } = APP.store.getState()['features/screen-share'];
  701. const currentDesktopAudioTrack = this._desktopAudioStream || desktopAudioTrack;
  702. // If system audio is already being sent, mix it with the provided audio track.
  703. if (currentDesktopAudioTrack) {
  704. // In case system audio sharing was done in the absence of an initial mic audio track, there is no
  705. // AudioMixerEffect so we have to remove system audio track from the room before setting it as an effect.
  706. await room.replaceTrack(currentDesktopAudioTrack, null);
  707. this._mixerEffect = new AudioMixerEffect(currentDesktopAudioTrack);
  708. logger.debug('Mixing new audio track with existing screen audio track.');
  709. await localAudioTrack.setEffect(this._mixerEffect);
  710. }
  711. },
  712. /**
  713. * Simulates toolbar button click for audio mute. Used by shortcuts and API.
  714. * @param {boolean} mute true for mute and false for unmute.
  715. * @param {boolean} [showUI] when set to false will not display any error
  716. * dialogs in case of media permissions error.
  717. */
  718. muteAudio(mute, showUI = true) {
  719. const state = APP.store.getState();
  720. if (!mute
  721. && isUserInteractionRequiredForUnmute(state)) {
  722. logger.error('Unmuting audio requires user interaction');
  723. return;
  724. }
  725. // check for A/V Moderation when trying to unmute
  726. if (!mute && shouldShowModeratedNotification(MEDIA_TYPE.AUDIO, state)) {
  727. if (!isModerationNotificationDisplayed(MEDIA_TYPE.AUDIO, state)) {
  728. APP.store.dispatch(showModeratedNotification(MEDIA_TYPE.AUDIO));
  729. }
  730. return;
  731. }
  732. // Not ready to modify track's state yet
  733. if (!this._localTracksInitialized) {
  734. // This will only modify base/media.audio.muted which is then synced
  735. // up with the track at the end of local tracks initialization.
  736. muteLocalAudio(mute);
  737. this.setAudioMuteStatus(mute);
  738. return;
  739. } else if (this.isLocalAudioMuted() === mute) {
  740. // NO-OP
  741. return;
  742. }
  743. const localAudio = getLocalJitsiAudioTrack(APP.store.getState());
  744. if (!localAudio && !mute) {
  745. const maybeShowErrorDialog = error => {
  746. showUI && APP.store.dispatch(notifyMicError(error));
  747. };
  748. APP.store.dispatch(gumPending([ MEDIA_TYPE.AUDIO ], IGUMPendingState.PENDING_UNMUTE));
  749. createLocalTracksF({ devices: [ 'audio' ] })
  750. .then(([ audioTrack ]) => audioTrack)
  751. .catch(error => {
  752. maybeShowErrorDialog(error);
  753. // Rollback the audio muted status by using null track
  754. return null;
  755. })
  756. .then(async audioTrack => {
  757. await this._maybeApplyAudioMixerEffect(audioTrack);
  758. return this.useAudioStream(audioTrack);
  759. })
  760. .finally(() => {
  761. APP.store.dispatch(gumPending([ MEDIA_TYPE.AUDIO ], IGUMPendingState.NONE));
  762. });
  763. } else {
  764. muteLocalAudio(mute);
  765. }
  766. },
  767. /**
  768. * Returns whether local audio is muted or not.
  769. * @returns {boolean}
  770. */
  771. isLocalAudioMuted() {
  772. // If the tracks are not ready, read from base/media state
  773. return this._localTracksInitialized
  774. ? isLocalTrackMuted(
  775. APP.store.getState()['features/base/tracks'],
  776. MEDIA_TYPE.AUDIO)
  777. : Boolean(
  778. APP.store.getState()['features/base/media'].audio.muted);
  779. },
  780. /**
  781. * Simulates toolbar button click for audio mute. Used by shortcuts
  782. * and API.
  783. * @param {boolean} [showUI] when set to false will not display any error
  784. * dialogs in case of media permissions error.
  785. */
  786. toggleAudioMuted(showUI = true) {
  787. this.muteAudio(!this.isLocalAudioMuted(), showUI);
  788. },
  789. /**
  790. * Simulates toolbar button click for video mute. Used by shortcuts and API.
  791. * @param mute true for mute and false for unmute.
  792. * @param {boolean} [showUI] when set to false will not display any error
  793. * dialogs in case of media permissions error.
  794. */
  795. muteVideo(mute, showUI = true) {
  796. if (this.videoSwitchInProgress) {
  797. logger.warn('muteVideo - unable to perform operations while video switch is in progress');
  798. return;
  799. }
  800. const state = APP.store.getState();
  801. if (!mute
  802. && isUserInteractionRequiredForUnmute(state)) {
  803. logger.error('Unmuting video requires user interaction');
  804. return;
  805. }
  806. // check for A/V Moderation when trying to unmute and return early
  807. if (!mute && shouldShowModeratedNotification(MEDIA_TYPE.VIDEO, state)) {
  808. return;
  809. }
  810. // If not ready to modify track's state yet adjust the base/media
  811. if (!this._localTracksInitialized) {
  812. // This will only modify base/media.video.muted which is then synced
  813. // up with the track at the end of local tracks initialization.
  814. muteLocalVideo(mute);
  815. this.setVideoMuteStatus();
  816. return;
  817. } else if (this.isLocalVideoMuted() === mute) {
  818. // NO-OP
  819. return;
  820. }
  821. const localVideo = getLocalJitsiVideoTrack(state);
  822. if (!localVideo && !mute && !this.isCreatingLocalTrack) {
  823. const maybeShowErrorDialog = error => {
  824. showUI && APP.store.dispatch(notifyCameraError(error));
  825. };
  826. this.isCreatingLocalTrack = true;
  827. APP.store.dispatch(gumPending([ MEDIA_TYPE.VIDEO ], IGUMPendingState.PENDING_UNMUTE));
  828. // Try to create local video if there wasn't any.
  829. // This handles the case when user joined with no video
  830. // (dismissed screen sharing screen or in audio only mode), but
  831. // decided to add it later on by clicking on muted video icon or
  832. // turning off the audio only mode.
  833. //
  834. // FIXME when local track creation is moved to react/redux
  835. // it should take care of the use case described above
  836. createLocalTracksF({ devices: [ 'video' ] })
  837. .then(([ videoTrack ]) => videoTrack)
  838. .catch(error => {
  839. // FIXME should send some feedback to the API on error ?
  840. maybeShowErrorDialog(error);
  841. // Rollback the video muted status by using null track
  842. return null;
  843. })
  844. .then(videoTrack => {
  845. logger.debug(`muteVideo: calling useVideoStream for track: ${videoTrack}`);
  846. return this.useVideoStream(videoTrack);
  847. })
  848. .finally(() => {
  849. this.isCreatingLocalTrack = false;
  850. APP.store.dispatch(gumPending([ MEDIA_TYPE.VIDEO ], IGUMPendingState.NONE));
  851. });
  852. } else {
  853. // FIXME show error dialog if it fails (should be handled by react)
  854. muteLocalVideo(mute);
  855. }
  856. },
  857. /**
  858. * Simulates toolbar button click for video mute. Used by shortcuts and API.
  859. * @param {boolean} [showUI] when set to false will not display any error
  860. * dialogs in case of media permissions error.
  861. * @param {boolean} ensureTrack - True if we want to ensure that a new track is
  862. * created if missing.
  863. */
  864. toggleVideoMuted(showUI = true, ensureTrack = false) {
  865. const mute = !this.isLocalVideoMuted();
  866. APP.store.dispatch(handleToggleVideoMuted(mute, showUI, ensureTrack));
  867. },
  868. /**
  869. * Retrieve list of ids of conference participants (without local user).
  870. * @returns {string[]}
  871. */
  872. listMembersIds() {
  873. return room.getParticipants().map(p => p.getId());
  874. },
  875. /**
  876. * Checks whether the participant identified by id is a moderator.
  877. * @id id to search for participant
  878. * @return {boolean} whether the participant is moderator
  879. */
  880. isParticipantModerator(id) {
  881. const user = room.getParticipantById(id);
  882. return user && user.isModerator();
  883. },
  884. /**
  885. * Retrieve list of conference participants (without local user).
  886. * @returns {JitsiParticipant[]}
  887. *
  888. * NOTE: Used by jitsi-meet-torture!
  889. */
  890. listMembers() {
  891. return room.getParticipants();
  892. },
  893. /**
  894. * Used by Jibri to detect when it's alone and the meeting should be terminated.
  895. */
  896. get membersCount() {
  897. return room.getParticipants()
  898. .filter(p => !p.isHidden() || !(config.iAmRecorder && p.isHiddenFromRecorder())).length + 1;
  899. },
  900. /**
  901. * Returns true if the callstats integration is enabled, otherwise returns
  902. * false.
  903. *
  904. * @returns true if the callstats integration is enabled, otherwise returns
  905. * false.
  906. */
  907. isCallstatsEnabled() {
  908. return room && room.isCallstatsEnabled();
  909. },
  910. /**
  911. * Get speaker stats that track total dominant speaker time.
  912. *
  913. * @returns {object} A hash with keys being user ids and values being the
  914. * library's SpeakerStats model used for calculating time as dominant
  915. * speaker.
  916. */
  917. getSpeakerStats() {
  918. return room.getSpeakerStats();
  919. },
  920. /**
  921. * Returns the connection times stored in the library.
  922. */
  923. getConnectionTimes() {
  924. return room.getConnectionTimes();
  925. },
  926. // used by torture currently
  927. isJoined() {
  928. return room && room.isJoined();
  929. },
  930. getConnectionState() {
  931. return room && room.getConnectionState();
  932. },
  933. /**
  934. * Obtains current P2P ICE connection state.
  935. * @return {string|null} ICE connection state or <tt>null</tt> if there's no
  936. * P2P connection
  937. */
  938. getP2PConnectionState() {
  939. return room && room.getP2PConnectionState();
  940. },
  941. /**
  942. * Starts P2P (for tests only)
  943. * @private
  944. */
  945. _startP2P() {
  946. try {
  947. room && room.startP2PSession();
  948. } catch (error) {
  949. logger.error('Start P2P failed', error);
  950. throw error;
  951. }
  952. },
  953. /**
  954. * Stops P2P (for tests only)
  955. * @private
  956. */
  957. _stopP2P() {
  958. try {
  959. room && room.stopP2PSession();
  960. } catch (error) {
  961. logger.error('Stop P2P failed', error);
  962. throw error;
  963. }
  964. },
  965. /**
  966. * Checks whether or not our connection is currently in interrupted and
  967. * reconnect attempts are in progress.
  968. *
  969. * @returns {boolean} true if the connection is in interrupted state or
  970. * false otherwise.
  971. */
  972. isConnectionInterrupted() {
  973. return room.isConnectionInterrupted();
  974. },
  975. /**
  976. * Finds JitsiParticipant for given id.
  977. *
  978. * @param {string} id participant's identifier(MUC nickname).
  979. *
  980. * @returns {JitsiParticipant|null} participant instance for given id or
  981. * null if not found.
  982. */
  983. getParticipantById(id) {
  984. return room ? room.getParticipantById(id) : null;
  985. },
  986. getMyUserId() {
  987. return room && room.myUserId();
  988. },
  989. /**
  990. * Will be filled with values only when config.debug is enabled.
  991. * Its used by torture to check audio levels.
  992. */
  993. audioLevelsMap: {},
  994. /**
  995. * Returns the stored audio level (stored only if config.debug is enabled)
  996. * @param id the id for the user audio level to return (the id value is
  997. * returned for the participant using getMyUserId() method)
  998. */
  999. getPeerSSRCAudioLevel(id) {
  1000. return this.audioLevelsMap[id];
  1001. },
  1002. /**
  1003. * @return {number} the number of participants in the conference with at
  1004. * least one track.
  1005. */
  1006. getNumberOfParticipantsWithTracks() {
  1007. return room.getParticipants()
  1008. .filter(p => p.getTracks().length > 0)
  1009. .length;
  1010. },
  1011. /**
  1012. * Returns the stats.
  1013. */
  1014. getStats() {
  1015. return room.connectionQuality.getStats();
  1016. },
  1017. // end used by torture
  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.connection.getLogs();
  1027. downloadJSON(logs, filename);
  1028. },
  1029. /**
  1030. * Exposes a Command(s) API on this instance. It is necessitated by (1) the
  1031. * desire to keep room private to this instance and (2) the need of other
  1032. * modules to send and receive commands to and from participants.
  1033. * Eventually, this instance remains in control with respect to the
  1034. * decision whether the Command(s) API of room (i.e. lib-jitsi-meet's
  1035. * JitsiConference) is to be used in the implementation of the Command(s)
  1036. * API of this instance.
  1037. */
  1038. commands: {
  1039. /**
  1040. * Known custom conference commands.
  1041. */
  1042. defaults: commands,
  1043. /**
  1044. * Receives notifications from other participants about commands aka
  1045. * custom events (sent by sendCommand or sendCommandOnce methods).
  1046. * @param command {String} the name of the command
  1047. * @param handler {Function} handler for the command
  1048. */
  1049. addCommandListener() {
  1050. // eslint-disable-next-line prefer-rest-params
  1051. room.addCommandListener(...arguments);
  1052. },
  1053. /**
  1054. * Removes command.
  1055. * @param name {String} the name of the command.
  1056. */
  1057. removeCommand() {
  1058. // eslint-disable-next-line prefer-rest-params
  1059. room.removeCommand(...arguments);
  1060. },
  1061. /**
  1062. * Sends command.
  1063. * @param name {String} the name of the command.
  1064. * @param values {Object} with keys and values that will be sent.
  1065. */
  1066. sendCommand() {
  1067. // eslint-disable-next-line prefer-rest-params
  1068. room.sendCommand(...arguments);
  1069. },
  1070. /**
  1071. * Sends command one time.
  1072. * @param name {String} the name of the command.
  1073. * @param values {Object} with keys and values that will be sent.
  1074. */
  1075. sendCommandOnce() {
  1076. // eslint-disable-next-line prefer-rest-params
  1077. room.sendCommandOnce(...arguments);
  1078. }
  1079. },
  1080. /**
  1081. * Used by the Breakout Rooms feature to join a breakout room or go back to the main room.
  1082. */
  1083. async joinRoom(roomName, options) {
  1084. APP.store.dispatch(conferenceWillInit());
  1085. // Restore initial state.
  1086. this._localTracksInitialized = false;
  1087. this.isSharingScreen = false;
  1088. this.roomName = roomName;
  1089. const { tryCreateLocalTracks, errors } = this.createInitialLocalTracks(options);
  1090. const localTracks = await tryCreateLocalTracks;
  1091. this._displayErrorsForCreateInitialLocalTracks(errors);
  1092. localTracks.forEach(track => {
  1093. if ((track.isAudioTrack() && this.isLocalAudioMuted())
  1094. || (track.isVideoTrack() && this.isLocalVideoMuted())) {
  1095. track.mute();
  1096. }
  1097. });
  1098. this._createRoom(localTracks);
  1099. return new Promise((resolve, reject) => {
  1100. new ConferenceConnector(resolve, reject, this).connect();
  1101. });
  1102. },
  1103. _createRoom(localTracks) {
  1104. room = APP.connection.initJitsiConference(APP.conference.roomName, this._getConferenceOptions());
  1105. // Filter out the tracks that are muted (except on Safari).
  1106. const tracks = browser.isWebKitBased() ? localTracks : localTracks.filter(track => !track.isMuted());
  1107. this._setLocalAudioVideoStreams(tracks);
  1108. this._room = room; // FIXME do not use this
  1109. APP.store.dispatch(_conferenceWillJoin(room));
  1110. sendLocalParticipant(APP.store, room);
  1111. this._setupListeners();
  1112. },
  1113. /**
  1114. * Sets local video and audio streams.
  1115. * @param {JitsiLocalTrack[]} tracks=[]
  1116. * @returns {Promise[]}
  1117. * @private
  1118. */
  1119. _setLocalAudioVideoStreams(tracks = []) {
  1120. const { dispatch } = APP.store;
  1121. const pendingGUMDevicesToRemove = [];
  1122. const promises = tracks.map(track => {
  1123. if (track.isAudioTrack()) {
  1124. pendingGUMDevicesToRemove.push(MEDIA_TYPE.AUDIO);
  1125. return this.useAudioStream(track);
  1126. } else if (track.isVideoTrack()) {
  1127. logger.debug(`_setLocalAudioVideoStreams is calling useVideoStream with track: ${track}`);
  1128. pendingGUMDevicesToRemove.push(MEDIA_TYPE.VIDEO);
  1129. return this.useVideoStream(track);
  1130. }
  1131. logger.error('Ignored not an audio nor a video track: ', track);
  1132. return Promise.resolve();
  1133. });
  1134. return Promise.allSettled(promises).then(() => {
  1135. if (pendingGUMDevicesToRemove.length > 0) {
  1136. dispatch(gumPending(pendingGUMDevicesToRemove, IGUMPendingState.NONE));
  1137. }
  1138. this._localTracksInitialized = true;
  1139. logger.log(`Initialized with ${tracks.length} local tracks`);
  1140. });
  1141. },
  1142. _getConferenceOptions() {
  1143. const options = getConferenceOptions(APP.store.getState());
  1144. options.createVADProcessor = createRnnoiseProcessor;
  1145. return options;
  1146. },
  1147. /**
  1148. * Start using provided video stream.
  1149. * Stops previous video stream.
  1150. * @param {JitsiLocalTrack} newTrack - new track to use or null
  1151. * @returns {Promise}
  1152. */
  1153. useVideoStream(newTrack) {
  1154. const state = APP.store.getState();
  1155. logger.debug(`useVideoStream: ${newTrack}`);
  1156. return new Promise((resolve, reject) => {
  1157. _replaceLocalVideoTrackQueue.enqueue(onFinish => {
  1158. const oldTrack = getLocalJitsiVideoTrack(state);
  1159. logger.debug(`useVideoStream: Replacing ${oldTrack} with ${newTrack}`);
  1160. if (oldTrack === newTrack || (!oldTrack && !newTrack)) {
  1161. resolve();
  1162. onFinish();
  1163. return;
  1164. }
  1165. // Add the track to the conference if there is no existing track, replace it otherwise.
  1166. const trackAction = oldTrack
  1167. ? replaceLocalTrack(oldTrack, newTrack, room)
  1168. : addLocalTrack(newTrack);
  1169. APP.store.dispatch(trackAction)
  1170. .then(() => {
  1171. this.setVideoMuteStatus();
  1172. })
  1173. .then(resolve)
  1174. .catch(error => {
  1175. logger.error(`useVideoStream failed: ${error}`);
  1176. reject(error);
  1177. })
  1178. .then(onFinish);
  1179. });
  1180. });
  1181. },
  1182. /**
  1183. * Start using provided audio stream.
  1184. * Stops previous audio stream.
  1185. * @param {JitsiLocalTrack} newTrack - new track to use or null
  1186. * @returns {Promise}
  1187. */
  1188. useAudioStream(newTrack) {
  1189. return new Promise((resolve, reject) => {
  1190. _replaceLocalAudioTrackQueue.enqueue(onFinish => {
  1191. const oldTrack = getLocalJitsiAudioTrack(APP.store.getState());
  1192. if (oldTrack === newTrack) {
  1193. resolve();
  1194. onFinish();
  1195. return;
  1196. }
  1197. APP.store.dispatch(
  1198. replaceLocalTrack(oldTrack, newTrack, room))
  1199. .then(() => {
  1200. this.setAudioMuteStatus(this.isLocalAudioMuted());
  1201. })
  1202. .then(resolve)
  1203. .catch(reject)
  1204. .then(onFinish);
  1205. });
  1206. });
  1207. },
  1208. /**
  1209. * Returns whether or not the conference is currently in audio only mode.
  1210. *
  1211. * @returns {boolean}
  1212. */
  1213. isAudioOnly() {
  1214. return Boolean(APP.store.getState()['features/base/audio-only'].enabled);
  1215. },
  1216. videoSwitchInProgress: false,
  1217. /**
  1218. * This fields stores a handler which will create a Promise which turns off
  1219. * the screen sharing and restores the previous video state (was there
  1220. * any video, before switching to screen sharing ? was it muted ?).
  1221. *
  1222. * Once called this fields is cleared to <tt>null</tt>.
  1223. * @type {Function|null}
  1224. */
  1225. _untoggleScreenSharing: null,
  1226. /**
  1227. * Creates a Promise which turns off the screen sharing and restores
  1228. * the previous state described by the arguments.
  1229. *
  1230. * This method is bound to the appropriate values, after switching to screen
  1231. * sharing and stored in {@link _untoggleScreenSharing}.
  1232. *
  1233. * @param {boolean} didHaveVideo indicates if there was a camera video being
  1234. * used, before switching to screen sharing.
  1235. * @param {boolean} ignoreDidHaveVideo indicates if the camera video should be
  1236. * ignored when switching screen sharing off.
  1237. * @return {Promise} resolved after the screen sharing is turned off, or
  1238. * rejected with some error (no idea what kind of error, possible GUM error)
  1239. * in case it fails.
  1240. * @private
  1241. */
  1242. async _turnScreenSharingOff(didHaveVideo, ignoreDidHaveVideo) {
  1243. this._untoggleScreenSharing = null;
  1244. this.videoSwitchInProgress = true;
  1245. APP.store.dispatch(stopReceiver());
  1246. this._stopProxyConnection();
  1247. APP.store.dispatch(toggleScreenshotCaptureSummary(false));
  1248. const tracks = APP.store.getState()['features/base/tracks'];
  1249. const duration = getLocalVideoTrack(tracks)?.jitsiTrack.getDuration() ?? 0;
  1250. // If system audio was also shared stop the AudioMixerEffect and dispose of the desktop audio track.
  1251. if (this._mixerEffect) {
  1252. const localAudio = getLocalJitsiAudioTrack(APP.store.getState());
  1253. await localAudio.setEffect(undefined);
  1254. await this._desktopAudioStream.dispose();
  1255. this._mixerEffect = undefined;
  1256. this._desktopAudioStream = undefined;
  1257. // In case there was no local audio when screen sharing was started the fact that we set the audio stream to
  1258. // null will take care of the desktop audio stream cleanup.
  1259. } else if (this._desktopAudioStream) {
  1260. await room.replaceTrack(this._desktopAudioStream, null);
  1261. this._desktopAudioStream.dispose();
  1262. this._desktopAudioStream = undefined;
  1263. }
  1264. APP.store.dispatch(setScreenAudioShareState(false));
  1265. let promise;
  1266. if (didHaveVideo && !ignoreDidHaveVideo) {
  1267. promise = createLocalTracksF({ devices: [ 'video' ] })
  1268. .then(([ stream ]) => {
  1269. logger.debug(`_turnScreenSharingOff using ${stream} for useVideoStream`);
  1270. return this.useVideoStream(stream);
  1271. })
  1272. .catch(error => {
  1273. logger.error('failed to switch back to local video', error);
  1274. return this.useVideoStream(null).then(() =>
  1275. // Still fail with the original err
  1276. Promise.reject(error)
  1277. );
  1278. });
  1279. } else {
  1280. promise = this.useVideoStream(null);
  1281. }
  1282. return promise.then(
  1283. () => {
  1284. this.videoSwitchInProgress = false;
  1285. sendAnalytics(createScreenSharingEvent('stopped',
  1286. duration === 0 ? null : duration));
  1287. logger.info('Screen sharing stopped.');
  1288. },
  1289. error => {
  1290. this.videoSwitchInProgress = false;
  1291. logger.error(`_turnScreenSharingOff failed: ${error}`);
  1292. throw error;
  1293. });
  1294. },
  1295. /**
  1296. * Creates desktop (screensharing) {@link JitsiLocalTrack}
  1297. *
  1298. * @param {Object} [options] - Screen sharing options that will be passed to
  1299. * createLocalTracks.
  1300. * @param {Object} [options.desktopSharing]
  1301. * @param {Object} [options.desktopStream] - An existing desktop stream to
  1302. * use instead of creating a new desktop stream.
  1303. * @return {Promise.<JitsiLocalTrack>} - A Promise resolved with
  1304. * {@link JitsiLocalTrack} for the screensharing or rejected with
  1305. * {@link JitsiTrackError}.
  1306. *
  1307. * @private
  1308. */
  1309. _createDesktopTrack(options = {}) {
  1310. const didHaveVideo = !this.isLocalVideoMuted();
  1311. const getDesktopStreamPromise = options.desktopStream
  1312. ? Promise.resolve([ options.desktopStream ])
  1313. : createLocalTracksF({
  1314. desktopSharingSourceDevice: options.desktopSharingSources
  1315. ? null : config._desktopSharingSourceDevice,
  1316. desktopSharingSources: options.desktopSharingSources,
  1317. devices: [ 'desktop' ]
  1318. });
  1319. return getDesktopStreamPromise.then(desktopStreams => {
  1320. // Stores the "untoggle" handler which remembers whether was
  1321. // there any video before and whether was it muted.
  1322. this._untoggleScreenSharing
  1323. = this._turnScreenSharingOff.bind(this, didHaveVideo);
  1324. const desktopVideoStream = desktopStreams.find(stream => stream.getType() === MEDIA_TYPE.VIDEO);
  1325. const desktopAudioStream = desktopStreams.find(stream => stream.getType() === MEDIA_TYPE.AUDIO);
  1326. if (desktopAudioStream) {
  1327. desktopAudioStream.on(
  1328. JitsiTrackEvents.LOCAL_TRACK_STOPPED,
  1329. () => {
  1330. logger.debug(`Local screensharing audio track stopped. ${this.isSharingScreen}`);
  1331. // Handle case where screen share was stopped from the browsers 'screen share in progress'
  1332. // window. If audio screen sharing is stopped via the normal UX flow this point shouldn't
  1333. // be reached.
  1334. isScreenAudioShared(APP.store.getState())
  1335. && this._untoggleScreenSharing
  1336. && this._untoggleScreenSharing();
  1337. }
  1338. );
  1339. }
  1340. if (desktopVideoStream) {
  1341. desktopVideoStream.on(
  1342. JitsiTrackEvents.LOCAL_TRACK_STOPPED,
  1343. () => {
  1344. logger.debug(`Local screensharing track stopped. ${this.isSharingScreen}`);
  1345. // If the stream was stopped during screen sharing
  1346. // session then we should switch back to video.
  1347. this.isSharingScreen
  1348. && this._untoggleScreenSharing
  1349. && this._untoggleScreenSharing();
  1350. }
  1351. );
  1352. }
  1353. return desktopStreams;
  1354. }, error => {
  1355. throw error;
  1356. });
  1357. },
  1358. /**
  1359. * Handles {@link JitsiTrackError} returned by the lib-jitsi-meet when
  1360. * trying to create screensharing track. It will either do nothing if
  1361. * the dialog was canceled on user's request or display an error if
  1362. * screensharing couldn't be started.
  1363. * @param {JitsiTrackError} error - The error returned by
  1364. * {@link _createDesktopTrack} Promise.
  1365. * @private
  1366. */
  1367. _handleScreenSharingError(error) {
  1368. if (error.name === JitsiTrackErrors.SCREENSHARING_USER_CANCELED) {
  1369. return;
  1370. }
  1371. logger.error('failed to share local desktop', error);
  1372. // Handling:
  1373. // JitsiTrackErrors.CONSTRAINT_FAILED
  1374. // JitsiTrackErrors.PERMISSION_DENIED
  1375. // JitsiTrackErrors.SCREENSHARING_GENERIC_ERROR
  1376. // and any other
  1377. let descriptionKey;
  1378. let titleKey;
  1379. if (error.name === JitsiTrackErrors.PERMISSION_DENIED) {
  1380. descriptionKey = 'dialog.screenSharingPermissionDeniedError';
  1381. titleKey = 'dialog.screenSharingFailedTitle';
  1382. } else if (error.name === JitsiTrackErrors.CONSTRAINT_FAILED) {
  1383. descriptionKey = 'dialog.cameraConstraintFailedError';
  1384. titleKey = 'deviceError.cameraError';
  1385. } else if (error.name === JitsiTrackErrors.SCREENSHARING_GENERIC_ERROR) {
  1386. descriptionKey = 'dialog.screenSharingFailed';
  1387. titleKey = 'dialog.screenSharingFailedTitle';
  1388. } else if (error === AUDIO_ONLY_SCREEN_SHARE_NO_TRACK) {
  1389. descriptionKey = 'notify.screenShareNoAudio';
  1390. titleKey = 'notify.screenShareNoAudioTitle';
  1391. }
  1392. APP.store.dispatch(showErrorNotification({
  1393. descriptionKey,
  1394. titleKey
  1395. }, NOTIFICATION_TIMEOUT_TYPE.LONG));
  1396. },
  1397. /**
  1398. * Setup interaction between conference and UI.
  1399. */
  1400. _setupListeners() {
  1401. // add local streams when joined to the conference
  1402. room.on(JitsiConferenceEvents.CONFERENCE_JOINED, () => {
  1403. this._onConferenceJoined();
  1404. });
  1405. room.on(
  1406. JitsiConferenceEvents.CONFERENCE_JOIN_IN_PROGRESS,
  1407. () => APP.store.dispatch(conferenceJoinInProgress(room)));
  1408. room.on(
  1409. JitsiConferenceEvents.CONFERENCE_LEFT,
  1410. (...args) => {
  1411. APP.store.dispatch(conferenceTimestampChanged(0));
  1412. APP.store.dispatch(conferenceLeft(room, ...args));
  1413. });
  1414. room.on(
  1415. JitsiConferenceEvents.CONFERENCE_UNIQUE_ID_SET,
  1416. (...args) => {
  1417. // Preserve the sessionId so that the value is accessible even after room
  1418. // is disconnected.
  1419. room.sessionId = room.getMeetingUniqueId();
  1420. APP.store.dispatch(conferenceUniqueIdSet(room, ...args));
  1421. });
  1422. room.on(
  1423. JitsiConferenceEvents.AUTH_STATUS_CHANGED,
  1424. (authEnabled, authLogin) =>
  1425. APP.store.dispatch(authStatusChanged(authEnabled, authLogin)));
  1426. room.on(JitsiConferenceEvents.PARTCIPANT_FEATURES_CHANGED, user => {
  1427. APP.store.dispatch(updateRemoteParticipantFeatures(user));
  1428. });
  1429. room.on(JitsiConferenceEvents.USER_JOINED, (id, user) => {
  1430. if (config.iAmRecorder && user.isHiddenFromRecorder()) {
  1431. return;
  1432. }
  1433. // The logic shared between RN and web.
  1434. commonUserJoinedHandling(APP.store, room, user);
  1435. if (user.isHidden()) {
  1436. return;
  1437. }
  1438. APP.store.dispatch(updateRemoteParticipantFeatures(user));
  1439. logger.log(`USER ${id} connected:`, user);
  1440. APP.UI.addUser(user);
  1441. });
  1442. room.on(JitsiConferenceEvents.USER_LEFT, (id, user) => {
  1443. // The logic shared between RN and web.
  1444. commonUserLeftHandling(APP.store, room, user);
  1445. if (user.isHidden()) {
  1446. return;
  1447. }
  1448. logger.log(`USER ${id} LEFT:`, user);
  1449. });
  1450. room.on(JitsiConferenceEvents.USER_STATUS_CHANGED, (id, status) => {
  1451. APP.store.dispatch(participantPresenceChanged(id, status));
  1452. const user = room.getParticipantById(id);
  1453. if (user) {
  1454. APP.UI.updateUserStatus(user, status);
  1455. }
  1456. });
  1457. room.on(JitsiConferenceEvents.USER_ROLE_CHANGED, (id, role) => {
  1458. if (this.isLocalId(id)) {
  1459. logger.info(`My role changed, new role: ${role}`);
  1460. if (role === 'moderator') {
  1461. APP.store.dispatch(maybeSetLobbyChatMessageListener());
  1462. }
  1463. APP.store.dispatch(localParticipantRoleChanged(role));
  1464. APP.API.notifyUserRoleChanged(id, role);
  1465. } else {
  1466. APP.store.dispatch(participantRoleChanged(id, role));
  1467. }
  1468. });
  1469. room.on(JitsiConferenceEvents.TRACK_ADDED, track => {
  1470. if (!track || track.isLocal()) {
  1471. return;
  1472. }
  1473. if (config.iAmRecorder) {
  1474. const participant = room.getParticipantById(track.getParticipantId());
  1475. if (participant.isHiddenFromRecorder()) {
  1476. return;
  1477. }
  1478. }
  1479. APP.store.dispatch(trackAdded(track));
  1480. });
  1481. room.on(JitsiConferenceEvents.TRACK_REMOVED, track => {
  1482. if (!track || track.isLocal()) {
  1483. return;
  1484. }
  1485. APP.store.dispatch(trackRemoved(track));
  1486. });
  1487. room.on(JitsiConferenceEvents.TRACK_AUDIO_LEVEL_CHANGED, (id, lvl) => {
  1488. const localAudio = getLocalJitsiAudioTrack(APP.store.getState());
  1489. let newLvl = lvl;
  1490. if (this.isLocalId(id)) {
  1491. APP.store.dispatch(localParticipantAudioLevelChanged(lvl));
  1492. }
  1493. if (this.isLocalId(id) && localAudio?.isMuted()) {
  1494. newLvl = 0;
  1495. }
  1496. if (config.debug) {
  1497. this.audioLevelsMap[id] = newLvl;
  1498. if (config.debugAudioLevels) {
  1499. logger.log(`AudioLevel:${id}/${newLvl}`);
  1500. }
  1501. }
  1502. APP.UI.setAudioLevel(id, newLvl);
  1503. });
  1504. room.on(JitsiConferenceEvents.TRACK_MUTE_CHANGED, (track, participantThatMutedUs) => {
  1505. if (participantThatMutedUs) {
  1506. APP.store.dispatch(participantMutedUs(participantThatMutedUs, track));
  1507. if (this.isSharingScreen && track.isVideoTrack()) {
  1508. logger.debug('TRACK_MUTE_CHANGED while screen sharing');
  1509. this._turnScreenSharingOff(false);
  1510. }
  1511. }
  1512. });
  1513. room.on(JitsiConferenceEvents.TRACK_UNMUTE_REJECTED, track => APP.store.dispatch(destroyLocalTracks(track)));
  1514. room.on(JitsiConferenceEvents.SUBJECT_CHANGED,
  1515. subject => APP.store.dispatch(conferenceSubjectChanged(subject)));
  1516. room.on(
  1517. JitsiConferenceEvents.LAST_N_ENDPOINTS_CHANGED,
  1518. (leavingIds, enteringIds) =>
  1519. APP.UI.handleLastNEndpoints(leavingIds, enteringIds));
  1520. room.on(
  1521. JitsiConferenceEvents.P2P_STATUS,
  1522. (jitsiConference, p2p) =>
  1523. APP.store.dispatch(p2pStatusChanged(p2p)));
  1524. room.on(
  1525. JitsiConferenceEvents.DOMINANT_SPEAKER_CHANGED,
  1526. (dominant, previous, silence) => {
  1527. APP.store.dispatch(dominantSpeakerChanged(dominant, previous, Boolean(silence), room));
  1528. });
  1529. room.on(
  1530. JitsiConferenceEvents.CONFERENCE_CREATED_TIMESTAMP,
  1531. conferenceTimestamp => APP.store.dispatch(conferenceTimestampChanged(conferenceTimestamp)));
  1532. room.on(
  1533. JitsiConferenceEvents.DISPLAY_NAME_CHANGED,
  1534. (id, displayName) => {
  1535. const formattedDisplayName
  1536. = getNormalizedDisplayName(displayName);
  1537. const state = APP.store.getState();
  1538. const {
  1539. defaultRemoteDisplayName
  1540. } = state['features/base/config'];
  1541. APP.store.dispatch(participantUpdated({
  1542. conference: room,
  1543. id,
  1544. name: formattedDisplayName
  1545. }));
  1546. const virtualScreenshareParticipantId = getVirtualScreenshareParticipantByOwnerId(state, id)?.id;
  1547. if (virtualScreenshareParticipantId) {
  1548. APP.store.dispatch(
  1549. screenshareParticipantDisplayNameChanged(virtualScreenshareParticipantId, formattedDisplayName)
  1550. );
  1551. }
  1552. APP.API.notifyDisplayNameChanged(id, {
  1553. displayName: formattedDisplayName,
  1554. formattedDisplayName:
  1555. appendSuffix(
  1556. formattedDisplayName
  1557. || defaultRemoteDisplayName)
  1558. });
  1559. }
  1560. );
  1561. room.on(
  1562. JitsiConferenceEvents.BOT_TYPE_CHANGED,
  1563. (id, botType) => {
  1564. APP.store.dispatch(participantUpdated({
  1565. conference: room,
  1566. id,
  1567. botType
  1568. }));
  1569. }
  1570. );
  1571. room.on(
  1572. JitsiConferenceEvents.ENDPOINT_MESSAGE_RECEIVED,
  1573. (...args) => {
  1574. APP.store.dispatch(endpointMessageReceived(...args));
  1575. if (args && args.length >= 2) {
  1576. const [ sender, eventData ] = args;
  1577. if (eventData.name === ENDPOINT_TEXT_MESSAGE_NAME) {
  1578. APP.API.notifyEndpointTextMessageReceived({
  1579. senderInfo: {
  1580. jid: sender._jid,
  1581. id: sender._id
  1582. },
  1583. eventData
  1584. });
  1585. }
  1586. }
  1587. });
  1588. room.on(
  1589. JitsiConferenceEvents.NON_PARTICIPANT_MESSAGE_RECEIVED,
  1590. (...args) => {
  1591. APP.store.dispatch(nonParticipantMessageReceived(...args));
  1592. APP.API.notifyNonParticipantMessageReceived(...args);
  1593. });
  1594. room.on(
  1595. JitsiConferenceEvents.LOCK_STATE_CHANGED,
  1596. (...args) => APP.store.dispatch(lockStateChanged(room, ...args)));
  1597. room.on(JitsiConferenceEvents.KICKED, (participant, reason, isReplaced) => {
  1598. if (isReplaced) {
  1599. // this event triggers when the local participant is kicked, `participant`
  1600. // is the kicker. In replace participant case, kicker is undefined,
  1601. // as the server initiated it. We mark in store the local participant
  1602. // as being replaced based on jwt.
  1603. const localParticipant = getLocalParticipant(APP.store.getState());
  1604. APP.store.dispatch(participantUpdated({
  1605. conference: room,
  1606. id: localParticipant.id,
  1607. isReplaced
  1608. }));
  1609. // we send readyToClose when kicked participant is replace so that
  1610. // embedding app can choose to dispose the iframe API on the handler.
  1611. APP.API.notifyReadyToClose();
  1612. }
  1613. APP.store.dispatch(kickedOut(room, participant));
  1614. });
  1615. room.on(JitsiConferenceEvents.PARTICIPANT_KICKED, (kicker, kicked) => {
  1616. APP.store.dispatch(participantKicked(kicker, kicked));
  1617. });
  1618. room.on(JitsiConferenceEvents.PARTICIPANT_SOURCE_UPDATED,
  1619. jitsiParticipant => {
  1620. APP.store.dispatch(participantSourcesUpdated(jitsiParticipant));
  1621. });
  1622. room.on(JitsiConferenceEvents.SUSPEND_DETECTED, () => {
  1623. APP.store.dispatch(suspendDetected());
  1624. });
  1625. room.on(
  1626. JitsiConferenceEvents.AUDIO_UNMUTE_PERMISSIONS_CHANGED,
  1627. disableAudioMuteChange => {
  1628. APP.store.dispatch(setAudioUnmutePermissions(disableAudioMuteChange));
  1629. });
  1630. room.on(
  1631. JitsiConferenceEvents.VIDEO_UNMUTE_PERMISSIONS_CHANGED,
  1632. disableVideoMuteChange => {
  1633. APP.store.dispatch(setVideoUnmutePermissions(disableVideoMuteChange));
  1634. });
  1635. room.on(
  1636. JitsiE2ePingEvents.E2E_RTT_CHANGED,
  1637. (...args) => APP.store.dispatch(e2eRttChanged(...args)));
  1638. APP.UI.addListener(UIEvents.AUDIO_MUTED, muted => {
  1639. this.muteAudio(muted);
  1640. });
  1641. APP.UI.addListener(UIEvents.VIDEO_MUTED, (muted, showUI = false) => {
  1642. this.muteVideo(muted, showUI);
  1643. });
  1644. room.addCommandListener(this.commands.defaults.ETHERPAD,
  1645. ({ value }) => {
  1646. APP.UI.initEtherpad(value);
  1647. }
  1648. );
  1649. APP.UI.addListener(UIEvents.EMAIL_CHANGED,
  1650. this.changeLocalEmail.bind(this));
  1651. room.addCommandListener(this.commands.defaults.EMAIL, (data, from) => {
  1652. APP.store.dispatch(participantUpdated({
  1653. conference: room,
  1654. id: from,
  1655. email: data.value
  1656. }));
  1657. });
  1658. room.addCommandListener(
  1659. this.commands.defaults.AVATAR_URL,
  1660. (data, from) => {
  1661. APP.store.dispatch(
  1662. participantUpdated({
  1663. conference: room,
  1664. id: from,
  1665. avatarURL: data.value
  1666. }));
  1667. });
  1668. APP.UI.addListener(UIEvents.NICKNAME_CHANGED,
  1669. this.changeLocalDisplayName.bind(this));
  1670. room.on(
  1671. JitsiConferenceEvents.START_MUTED_POLICY_CHANGED,
  1672. ({ audio, video }) => {
  1673. APP.store.dispatch(
  1674. onStartMutedPolicyChanged(audio, video));
  1675. }
  1676. );
  1677. room.on(JitsiConferenceEvents.STARTED_MUTED, () => {
  1678. const audioMuted = room.isStartAudioMuted();
  1679. const videoMuted = room.isStartVideoMuted();
  1680. const localTracks = getLocalTracks(APP.store.getState()['features/base/tracks']);
  1681. const promises = [];
  1682. APP.store.dispatch(setAudioMuted(audioMuted));
  1683. APP.store.dispatch(setVideoMuted(videoMuted));
  1684. // Remove the tracks from the peerconnection.
  1685. for (const track of localTracks) {
  1686. // Always add the track on Safari because of a known issue where audio playout doesn't happen
  1687. // if the user joins audio and video muted, i.e., if there is no local media capture.
  1688. if (audioMuted && track.jitsiTrack?.getType() === MEDIA_TYPE.AUDIO && !browser.isWebKitBased()) {
  1689. promises.push(this.useAudioStream(null));
  1690. }
  1691. if (videoMuted && track.jitsiTrack?.getType() === MEDIA_TYPE.VIDEO) {
  1692. promises.push(this.useVideoStream(null));
  1693. }
  1694. }
  1695. Promise.allSettled(promises)
  1696. .then(() => {
  1697. APP.store.dispatch(showNotification({
  1698. titleKey: 'notify.mutedTitle',
  1699. descriptionKey: 'notify.muted'
  1700. }, NOTIFICATION_TIMEOUT_TYPE.SHORT));
  1701. });
  1702. });
  1703. room.on(
  1704. JitsiConferenceEvents.DATA_CHANNEL_OPENED, () => {
  1705. APP.store.dispatch(dataChannelOpened());
  1706. APP.store.dispatch(hideNotification(DATA_CHANNEL_CLOSED_NOTIFICATION_ID));
  1707. }
  1708. );
  1709. room.on(
  1710. JitsiConferenceEvents.DATA_CHANNEL_CLOSED, ev => {
  1711. APP.store.dispatch(dataChannelClosed(ev.code, ev.reason));
  1712. APP.store.dispatch(showWarningNotification({
  1713. descriptionKey: 'notify.dataChannelClosedDescription',
  1714. titleKey: 'notify.dataChannelClosed',
  1715. uid: DATA_CHANNEL_CLOSED_NOTIFICATION_ID
  1716. }, NOTIFICATION_TIMEOUT_TYPE.STICKY));
  1717. }
  1718. );
  1719. // call hangup
  1720. APP.UI.addListener(UIEvents.HANGUP, () => {
  1721. this.hangup(true);
  1722. });
  1723. APP.UI.addListener(
  1724. UIEvents.VIDEO_DEVICE_CHANGED,
  1725. cameraDeviceId => {
  1726. const videoWasMuted = this.isLocalVideoMuted();
  1727. const localVideoTrack = getLocalJitsiVideoTrack(APP.store.getState());
  1728. if (localVideoTrack?.getDeviceId() === cameraDeviceId) {
  1729. return;
  1730. }
  1731. sendAnalytics(createDeviceChangedEvent('video', 'input'));
  1732. createLocalTracksF({
  1733. devices: [ 'video' ],
  1734. cameraDeviceId
  1735. })
  1736. .then(([ stream ]) => {
  1737. // if we are in audio only mode or video was muted before
  1738. // changing device, then mute
  1739. if (this.isAudioOnly() || videoWasMuted) {
  1740. return stream.mute()
  1741. .then(() => stream);
  1742. }
  1743. return stream;
  1744. })
  1745. .then(stream => {
  1746. logger.info(`Switching the local video device to ${cameraDeviceId}.`);
  1747. return this.useVideoStream(stream);
  1748. })
  1749. .then(() => {
  1750. logger.info(`Switched local video device to ${cameraDeviceId}.`);
  1751. this._updateVideoDeviceId();
  1752. })
  1753. .catch(error => {
  1754. logger.error(`Failed to switch to selected camera:${cameraDeviceId}, error:${error}`);
  1755. return APP.store.dispatch(notifyCameraError(error));
  1756. });
  1757. }
  1758. );
  1759. APP.UI.addListener(
  1760. UIEvents.AUDIO_DEVICE_CHANGED,
  1761. async micDeviceId => {
  1762. const audioWasMuted = this.isLocalAudioMuted();
  1763. // Disable noise suppression if it was enabled on the previous track.
  1764. await APP.store.dispatch(setNoiseSuppressionEnabled(false));
  1765. // When the 'default' mic needs to be selected, we need to pass the real device id to gUM instead of
  1766. // 'default' in order to get the correct MediaStreamTrack from chrome because of the following bug.
  1767. // https://bugs.chromium.org/p/chromium/issues/detail?id=997689.
  1768. const isDefaultMicSelected = micDeviceId === 'default';
  1769. const selectedDeviceId = isDefaultMicSelected
  1770. ? getDefaultDeviceId(APP.store.getState(), 'audioInput')
  1771. : micDeviceId;
  1772. logger.info(`Switching audio input device to ${selectedDeviceId}`);
  1773. sendAnalytics(createDeviceChangedEvent('audio', 'input'));
  1774. createLocalTracksF({
  1775. devices: [ 'audio' ],
  1776. micDeviceId: selectedDeviceId
  1777. })
  1778. .then(([ stream ]) => {
  1779. // if audio was muted before changing the device, mute
  1780. // with the new device
  1781. if (audioWasMuted) {
  1782. return stream.mute()
  1783. .then(() => stream);
  1784. }
  1785. return stream;
  1786. })
  1787. .then(async stream => {
  1788. await this._maybeApplyAudioMixerEffect(stream);
  1789. return this.useAudioStream(stream);
  1790. })
  1791. .then(() => {
  1792. const localAudio = getLocalJitsiAudioTrack(APP.store.getState());
  1793. if (localAudio && isDefaultMicSelected) {
  1794. // workaround for the default device to be shown as selected in the
  1795. // settings even when the real device id was passed to gUM because of the
  1796. // above mentioned chrome bug.
  1797. localAudio._realDeviceId = localAudio.deviceId = 'default';
  1798. }
  1799. logger.info(`switched local audio input device to: ${selectedDeviceId}`);
  1800. this._updateAudioDeviceId();
  1801. })
  1802. .catch(err => {
  1803. logger.error(`Failed to switch to selected audio input device ${selectedDeviceId}, error=${err}`);
  1804. APP.store.dispatch(notifyMicError(err));
  1805. });
  1806. }
  1807. );
  1808. APP.UI.addListener(UIEvents.TOGGLE_AUDIO_ONLY, () => {
  1809. // Immediately update the UI by having remote videos and the large video update themselves.
  1810. const displayedUserId = APP.UI.getLargeVideoID();
  1811. if (displayedUserId) {
  1812. APP.UI.updateLargeVideo(displayedUserId, true);
  1813. }
  1814. });
  1815. },
  1816. /**
  1817. * Cleanups local conference on suspend.
  1818. */
  1819. onSuspendDetected() {
  1820. // After wake up, we will be in a state where conference is left
  1821. // there will be dialog shown to user.
  1822. // We do not want video/audio as we show an overlay and after it
  1823. // user need to rejoin or close, while waking up we can detect
  1824. // camera wakeup as a problem with device.
  1825. // We also do not care about device change, which happens
  1826. // on resume after suspending PC.
  1827. if (this.deviceChangeListener) {
  1828. JitsiMeetJS.mediaDevices.removeEventListener(
  1829. JitsiMediaDevicesEvents.DEVICE_LIST_CHANGED,
  1830. this.deviceChangeListener);
  1831. }
  1832. },
  1833. /**
  1834. * Callback invoked when the conference has been successfully joined.
  1835. * Initializes the UI and various other features.
  1836. *
  1837. * @private
  1838. * @returns {void}
  1839. */
  1840. _onConferenceJoined() {
  1841. const { dispatch } = APP.store;
  1842. APP.UI.initConference();
  1843. dispatch(initKeyboardShortcuts());
  1844. dispatch(conferenceJoined(room));
  1845. const jwt = APP.store.getState()['features/base/jwt'];
  1846. if (jwt?.user?.hiddenFromRecorder) {
  1847. dispatch(muteLocal(true, MEDIA_TYPE.AUDIO));
  1848. dispatch(muteLocal(true, MEDIA_TYPE.VIDEO));
  1849. dispatch(setAudioUnmutePermissions(true, true));
  1850. dispatch(setVideoUnmutePermissions(true, true));
  1851. }
  1852. },
  1853. /**
  1854. * Updates the list of current devices.
  1855. * @param {boolean} setDeviceListChangeHandler - Whether to add the deviceList change handlers.
  1856. * @private
  1857. * @returns {Promise}
  1858. */
  1859. _initDeviceList(setDeviceListChangeHandler = false) {
  1860. const { mediaDevices } = JitsiMeetJS;
  1861. if (mediaDevices.isDeviceListAvailable()
  1862. && mediaDevices.isDeviceChangeAvailable()) {
  1863. if (setDeviceListChangeHandler) {
  1864. this.deviceChangeListener = devices =>
  1865. window.setTimeout(() => this._onDeviceListChanged(devices), 0);
  1866. mediaDevices.addEventListener(
  1867. JitsiMediaDevicesEvents.DEVICE_LIST_CHANGED,
  1868. this.deviceChangeListener);
  1869. }
  1870. const { dispatch } = APP.store;
  1871. return dispatch(getAvailableDevices())
  1872. .then(devices => {
  1873. // Ugly way to synchronize real device IDs with local
  1874. // storage and settings menu. This is a workaround until
  1875. // getConstraints() method will be implemented in browsers.
  1876. this._updateAudioDeviceId();
  1877. this._updateVideoDeviceId();
  1878. APP.UI.onAvailableDevicesChanged(devices);
  1879. });
  1880. }
  1881. return Promise.resolve();
  1882. },
  1883. /**
  1884. * Updates the settings for the currently used video device, extracting
  1885. * the device id from the used track.
  1886. * @private
  1887. */
  1888. _updateVideoDeviceId() {
  1889. const localVideo = getLocalJitsiVideoTrack(APP.store.getState());
  1890. if (localVideo && localVideo.videoType === 'camera') {
  1891. APP.store.dispatch(updateSettings({
  1892. cameraDeviceId: localVideo.getDeviceId()
  1893. }));
  1894. }
  1895. },
  1896. /**
  1897. * Updates the settings for the currently used audio device, extracting
  1898. * the device id from the used track.
  1899. * @private
  1900. */
  1901. _updateAudioDeviceId() {
  1902. const localAudio = getLocalJitsiAudioTrack(APP.store.getState());
  1903. if (localAudio) {
  1904. APP.store.dispatch(updateSettings({
  1905. micDeviceId: localAudio.getDeviceId()
  1906. }));
  1907. }
  1908. },
  1909. /**
  1910. * Event listener for JitsiMediaDevicesEvents.DEVICE_LIST_CHANGED to
  1911. * handle change of available media devices.
  1912. * @private
  1913. * @param {MediaDeviceInfo[]} devices
  1914. * @returns {Promise}
  1915. */
  1916. async _onDeviceListChanged(devices) {
  1917. const oldDevices = APP.store.getState()['features/base/devices'].availableDevices;
  1918. const localAudio = getLocalJitsiAudioTrack(APP.store.getState());
  1919. const localVideo = getLocalJitsiVideoTrack(APP.store.getState());
  1920. APP.store.dispatch(updateDeviceList(devices));
  1921. // Firefox users can choose their preferred device in the gUM prompt. In that case
  1922. // we should respect that and not attempt to switch to the preferred device from
  1923. // our settings.
  1924. const newLabelsOnly = mediaDeviceHelper.newDeviceListAddedLabelsOnly(oldDevices, devices);
  1925. const newDevices
  1926. = mediaDeviceHelper.getNewMediaDevicesAfterDeviceListChanged(
  1927. devices,
  1928. localVideo,
  1929. localAudio,
  1930. newLabelsOnly);
  1931. const promises = [];
  1932. const requestedInput = {
  1933. audio: Boolean(newDevices.audioinput),
  1934. video: Boolean(newDevices.videoinput)
  1935. };
  1936. if (typeof newDevices.audiooutput !== 'undefined') {
  1937. const { dispatch } = APP.store;
  1938. const setAudioOutputPromise
  1939. = setAudioOutputDeviceId(newDevices.audiooutput, dispatch)
  1940. .catch(err => {
  1941. logger.error(`Failed to set the audio output device to ${newDevices.audiooutput} - ${err}`);
  1942. });
  1943. promises.push(setAudioOutputPromise);
  1944. }
  1945. // Handles the use case when the default device is changed (we are always stopping the streams because it's
  1946. // simpler):
  1947. // If the default device is changed we need to first stop the local streams and then call GUM. Otherwise GUM
  1948. // will return a stream using the old default device.
  1949. if (requestedInput.audio && localAudio) {
  1950. localAudio.stopStream();
  1951. }
  1952. if (requestedInput.video && localVideo) {
  1953. localVideo.stopStream();
  1954. }
  1955. // Let's handle unknown/non-preferred devices
  1956. const newAvailDevices = APP.store.getState()['features/base/devices'].availableDevices;
  1957. let newAudioDevices = [];
  1958. let oldAudioDevices = [];
  1959. if (typeof newDevices.audiooutput === 'undefined') {
  1960. newAudioDevices = newAvailDevices.audioOutput;
  1961. oldAudioDevices = oldDevices.audioOutput;
  1962. }
  1963. if (!requestedInput.audio) {
  1964. newAudioDevices = newAudioDevices.concat(newAvailDevices.audioInput);
  1965. oldAudioDevices = oldAudioDevices.concat(oldDevices.audioInput);
  1966. }
  1967. // check for audio
  1968. if (newAudioDevices.length > 0) {
  1969. APP.store.dispatch(checkAndNotifyForNewDevice(newAudioDevices, oldAudioDevices));
  1970. }
  1971. // check for video
  1972. if (requestedInput.video) {
  1973. APP.store.dispatch(checkAndNotifyForNewDevice(newAvailDevices.videoInput, oldDevices.videoInput));
  1974. }
  1975. // When the 'default' mic needs to be selected, we need to pass the real device id to gUM instead of 'default'
  1976. // in order to get the correct MediaStreamTrack from chrome because of the following bug.
  1977. // https://bugs.chromium.org/p/chromium/issues/detail?id=997689
  1978. const hasDefaultMicChanged = newDevices.audioinput === 'default';
  1979. // When the local video is muted and a preferred device is connected, update the settings and remove the track
  1980. // from the conference. A new track will be created and replaced when the user unmutes their camera.
  1981. if (requestedInput.video && this.isLocalVideoMuted()) {
  1982. APP.store.dispatch(updateSettings({
  1983. cameraDeviceId: newDevices.videoinput
  1984. }));
  1985. requestedInput.video = false;
  1986. delete newDevices.videoinput;
  1987. // Remove the track from the conference.
  1988. if (localVideo) {
  1989. await this.useVideoStream(null);
  1990. logger.debug('_onDeviceListChanged: Removed the current video track.');
  1991. }
  1992. }
  1993. // When the local audio is muted and a preferred device is connected, update the settings and remove the track
  1994. // from the conference. A new track will be created and replaced when the user unmutes their mic.
  1995. if (requestedInput.audio && this.isLocalAudioMuted()) {
  1996. APP.store.dispatch(updateSettings({
  1997. micDeviceId: newDevices.audioinput
  1998. }));
  1999. requestedInput.audio = false;
  2000. delete newDevices.audioinput;
  2001. // Remove the track from the conference.
  2002. if (localAudio) {
  2003. await this.useAudioStream(null);
  2004. logger.debug('_onDeviceListChanged: Removed the current audio track.');
  2005. }
  2006. }
  2007. // Create the tracks and replace them only if the user is unmuted.
  2008. if (requestedInput.audio || requestedInput.video) {
  2009. let tracks = [];
  2010. const realAudioDeviceId = hasDefaultMicChanged
  2011. ? getDefaultDeviceId(APP.store.getState(), 'audioInput') : newDevices.audioinput;
  2012. try {
  2013. tracks = await mediaDeviceHelper.createLocalTracksAfterDeviceListChanged(
  2014. createLocalTracksF,
  2015. requestedInput.video ? newDevices.videoinput : null,
  2016. requestedInput.audio ? realAudioDeviceId : null
  2017. );
  2018. } catch (error) {
  2019. logger.error(`Track creation failed on device change, ${error}`);
  2020. return Promise.reject(error);
  2021. }
  2022. for (const track of tracks) {
  2023. if (track.isAudioTrack()) {
  2024. promises.push(
  2025. this.useAudioStream(track)
  2026. .then(() => {
  2027. hasDefaultMicChanged && (track._realDeviceId = track.deviceId = 'default');
  2028. this._updateAudioDeviceId();
  2029. }));
  2030. } else {
  2031. promises.push(
  2032. this.useVideoStream(track)
  2033. .then(() => {
  2034. this._updateVideoDeviceId();
  2035. }));
  2036. }
  2037. }
  2038. }
  2039. return Promise.all(promises)
  2040. .then(() => {
  2041. APP.UI.onAvailableDevicesChanged(devices);
  2042. });
  2043. },
  2044. /**
  2045. * Determines whether or not the audio button should be enabled.
  2046. */
  2047. updateAudioIconEnabled() {
  2048. const localAudio = getLocalJitsiAudioTrack(APP.store.getState());
  2049. const audioMediaDevices = APP.store.getState()['features/base/devices'].availableDevices.audioInput;
  2050. const audioDeviceCount = audioMediaDevices ? audioMediaDevices.length : 0;
  2051. // The audio functionality is considered available if there are any
  2052. // audio devices detected or if the local audio stream already exists.
  2053. const available = audioDeviceCount > 0 || Boolean(localAudio);
  2054. APP.store.dispatch(setAudioAvailable(available));
  2055. },
  2056. /**
  2057. * Determines whether or not the video button should be enabled.
  2058. */
  2059. updateVideoIconEnabled() {
  2060. const videoMediaDevices
  2061. = APP.store.getState()['features/base/devices'].availableDevices.videoInput;
  2062. const videoDeviceCount
  2063. = videoMediaDevices ? videoMediaDevices.length : 0;
  2064. const localVideo = getLocalJitsiVideoTrack(APP.store.getState());
  2065. // The video functionality is considered available if there are any
  2066. // video devices detected or if there is local video stream already
  2067. // active which could be either screensharing stream or a video track
  2068. // created before the permissions were rejected (through browser
  2069. // config).
  2070. const available = videoDeviceCount > 0 || Boolean(localVideo);
  2071. APP.store.dispatch(setVideoAvailable(available));
  2072. APP.API.notifyVideoAvailabilityChanged(available);
  2073. },
  2074. /**
  2075. * Disconnect from the conference and optionally request user feedback.
  2076. * @param {boolean} [requestFeedback=false] if user feedback should be
  2077. * requested
  2078. */
  2079. hangup(requestFeedback = false) {
  2080. APP.store.dispatch(disableReceiver());
  2081. this._stopProxyConnection();
  2082. APP.store.dispatch(destroyLocalTracks());
  2083. this._localTracksInitialized = false;
  2084. // Remove unnecessary event listeners from firing callbacks.
  2085. if (this.deviceChangeListener) {
  2086. JitsiMeetJS.mediaDevices.removeEventListener(
  2087. JitsiMediaDevicesEvents.DEVICE_LIST_CHANGED,
  2088. this.deviceChangeListener);
  2089. }
  2090. APP.UI.removeAllListeners();
  2091. let requestFeedbackPromise;
  2092. if (requestFeedback) {
  2093. requestFeedbackPromise
  2094. = APP.store.dispatch(maybeOpenFeedbackDialog(room))
  2095. // false because the thank you dialog shouldn't be displayed
  2096. .catch(() => Promise.resolve(false));
  2097. } else {
  2098. requestFeedbackPromise = Promise.resolve(true);
  2099. }
  2100. Promise.all([
  2101. requestFeedbackPromise,
  2102. this.leaveRoom()
  2103. ])
  2104. .then(values => {
  2105. this._room = undefined;
  2106. room = undefined;
  2107. /**
  2108. * Don't call {@code notifyReadyToClose} if the promotional page flag is set
  2109. * and let the page take care of sending the message, since there will be
  2110. * a redirect to the page regardlessly.
  2111. */
  2112. if (!interfaceConfig.SHOW_PROMOTIONAL_CLOSE_PAGE) {
  2113. APP.API.notifyReadyToClose();
  2114. }
  2115. APP.store.dispatch(maybeRedirectToWelcomePage(values[0]));
  2116. });
  2117. },
  2118. /**
  2119. * Leaves the room.
  2120. *
  2121. * @param {boolean} doDisconnect - Whether leaving the room should also terminate the connection.
  2122. * @param {string} reason - reason for leaving the room.
  2123. * @returns {Promise}
  2124. */
  2125. async leaveRoom(doDisconnect = true, reason = '') {
  2126. APP.store.dispatch(conferenceWillLeave(room));
  2127. const maybeDisconnect = () => {
  2128. if (doDisconnect) {
  2129. return disconnect();
  2130. }
  2131. };
  2132. if (room && room.isJoined()) {
  2133. return room.leave(reason).then(() => maybeDisconnect())
  2134. .catch(e => {
  2135. logger.error(e);
  2136. return maybeDisconnect();
  2137. });
  2138. }
  2139. return maybeDisconnect();
  2140. },
  2141. /**
  2142. * Changes the email for the local user
  2143. * @param email {string} the new email
  2144. */
  2145. changeLocalEmail(email = '') {
  2146. const formattedEmail = String(email).trim();
  2147. APP.store.dispatch(updateSettings({
  2148. email: formattedEmail
  2149. }));
  2150. sendData(commands.EMAIL, formattedEmail);
  2151. },
  2152. /**
  2153. * Changes the avatar url for the local user
  2154. * @param url {string} the new url
  2155. */
  2156. changeLocalAvatarUrl(url = '') {
  2157. const formattedUrl = String(url).trim();
  2158. APP.store.dispatch(updateSettings({
  2159. avatarURL: formattedUrl
  2160. }));
  2161. sendData(commands.AVATAR_URL, url);
  2162. },
  2163. /**
  2164. * Sends a message via the data channel.
  2165. * @param {string} to the id of the endpoint that should receive the
  2166. * message. If "" - the message will be sent to all participants.
  2167. * @param {object} payload the payload of the message.
  2168. * @throws NetworkError or InvalidStateError or Error if the operation
  2169. * fails.
  2170. */
  2171. sendEndpointMessage(to, payload) {
  2172. room.sendEndpointMessage(to, payload);
  2173. },
  2174. /**
  2175. * Adds new listener.
  2176. * @param {String} eventName the name of the event
  2177. * @param {Function} listener the listener.
  2178. */
  2179. addListener(eventName, listener) {
  2180. eventEmitter.addListener(eventName, listener);
  2181. },
  2182. /**
  2183. * Removes listener.
  2184. * @param {String} eventName the name of the event that triggers the
  2185. * listener
  2186. * @param {Function} listener the listener.
  2187. */
  2188. removeListener(eventName, listener) {
  2189. eventEmitter.removeListener(eventName, listener);
  2190. },
  2191. /**
  2192. * Changes the display name for the local user
  2193. * @param nickname {string} the new display name
  2194. */
  2195. changeLocalDisplayName(nickname = '') {
  2196. const formattedNickname = getNormalizedDisplayName(nickname);
  2197. APP.store.dispatch(updateSettings({
  2198. displayName: formattedNickname
  2199. }));
  2200. },
  2201. /**
  2202. * Callback invoked by the external api create or update a direct connection
  2203. * from the local client to an external client.
  2204. *
  2205. * @param {Object} event - The object containing information that should be
  2206. * passed to the {@code ProxyConnectionService}.
  2207. * @returns {void}
  2208. */
  2209. onProxyConnectionEvent(event) {
  2210. if (!this._proxyConnection) {
  2211. this._proxyConnection = new JitsiMeetJS.ProxyConnectionService({
  2212. /**
  2213. * Pass the {@code JitsiConnection} instance which will be used
  2214. * to fetch TURN credentials.
  2215. */
  2216. jitsiConnection: APP.connection,
  2217. /**
  2218. * The proxy connection feature is currently tailored towards
  2219. * taking a proxied video stream and showing it as a local
  2220. * desktop screen.
  2221. */
  2222. convertVideoToDesktop: true,
  2223. /**
  2224. * Callback invoked when the connection has been closed
  2225. * automatically. Triggers cleanup of screensharing if active.
  2226. *
  2227. * @returns {void}
  2228. */
  2229. onConnectionClosed: () => {
  2230. if (this._untoggleScreenSharing) {
  2231. this._untoggleScreenSharing();
  2232. }
  2233. },
  2234. /**
  2235. * Callback invoked to pass messages from the local client back
  2236. * out to the external client.
  2237. *
  2238. * @param {string} peerJid - The jid of the intended recipient
  2239. * of the message.
  2240. * @param {Object} data - The message that should be sent. For
  2241. * screensharing this is an iq.
  2242. * @returns {void}
  2243. */
  2244. onSendMessage: (peerJid, data) =>
  2245. APP.API.sendProxyConnectionEvent({
  2246. data,
  2247. to: peerJid
  2248. }),
  2249. /**
  2250. * Callback invoked when the remote peer of the proxy connection
  2251. * has provided a video stream, intended to be used as a local
  2252. * desktop stream.
  2253. *
  2254. * @param {JitsiLocalTrack} remoteProxyStream - The media
  2255. * stream to use as a local desktop stream.
  2256. * @returns {void}
  2257. */
  2258. onRemoteStream: desktopStream => {
  2259. if (desktopStream.videoType !== 'desktop') {
  2260. logger.warn('Received a non-desktop stream to proxy.');
  2261. desktopStream.dispose();
  2262. return;
  2263. }
  2264. APP.store.dispatch(toggleScreensharingA(undefined, false, { desktopStream }));
  2265. }
  2266. });
  2267. }
  2268. this._proxyConnection.processMessage(event);
  2269. },
  2270. /**
  2271. * Sets the video muted status.
  2272. */
  2273. setVideoMuteStatus() {
  2274. APP.UI.setVideoMuted(this.getMyUserId());
  2275. },
  2276. /**
  2277. * Sets the audio muted status.
  2278. *
  2279. * @param {boolean} muted - New muted status.
  2280. */
  2281. setAudioMuteStatus(muted) {
  2282. APP.UI.setAudioMuted(this.getMyUserId(), muted);
  2283. },
  2284. /**
  2285. * Dispatches the passed in feedback for submission. The submitted score
  2286. * should be a number inclusively between 1 through 5, or -1 for no score.
  2287. *
  2288. * @param {number} score - a number between 1 and 5 (inclusive) or -1 for no
  2289. * score.
  2290. * @param {string} message - An optional message to attach to the feedback
  2291. * in addition to the score.
  2292. * @returns {void}
  2293. */
  2294. submitFeedback(score = -1, message = '') {
  2295. if (score === -1 || (score >= 1 && score <= 5)) {
  2296. APP.store.dispatch(submitFeedback(score, message, room));
  2297. }
  2298. },
  2299. /**
  2300. * Terminates any proxy screensharing connection that is active.
  2301. *
  2302. * @private
  2303. * @returns {void}
  2304. */
  2305. _stopProxyConnection() {
  2306. if (this._proxyConnection) {
  2307. this._proxyConnection.stop();
  2308. }
  2309. this._proxyConnection = null;
  2310. }
  2311. };