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

conference.js 93KB

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