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

conference.js 110KB

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