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

conference.js 119KB

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