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

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