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

conference.js 106KB

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