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

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