Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

conference.js 111KB

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