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.

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