Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

conference.js 115KB

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