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

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