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

conference.js 112KB

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