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

conference.js 107KB

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