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 106KB

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