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

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