Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

conference.js 121KB

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