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

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