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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568
  1. /* global $, APP, JitsiMeetJS, config, interfaceConfig */
  2. const logger = require("jitsi-meet-logger").getLogger(__filename);
  3. import {openConnection} from './connection';
  4. import AuthHandler from './modules/UI/authentication/AuthHandler';
  5. import Recorder from './modules/recorder/Recorder';
  6. import mediaDeviceHelper from './modules/devices/mediaDeviceHelper';
  7. import { reload, reportError } from './modules/util/helpers';
  8. import * as RemoteControlEvents
  9. from './service/remotecontrol/RemoteControlEvents';
  10. import UIEvents from './service/UI/UIEvents';
  11. import UIUtil from './modules/UI/util/UIUtil';
  12. import * as JitsiMeetConferenceEvents from './ConferenceEvents';
  13. import { initAnalytics } from './react/features/analytics';
  14. import EventEmitter from "events";
  15. import {
  16. AVATAR_ID_COMMAND,
  17. AVATAR_URL_COMMAND,
  18. conferenceFailed,
  19. conferenceJoined,
  20. conferenceLeft,
  21. dataChannelOpened,
  22. toggleAudioOnly,
  23. EMAIL_COMMAND,
  24. lockStateChanged,
  25. p2pStatusChanged
  26. } from './react/features/base/conference';
  27. import { updateDeviceList } from './react/features/base/devices';
  28. import {
  29. isAnalyticsEnabled,
  30. isFatalJitsiConnectionError
  31. } from './react/features/base/lib-jitsi-meet';
  32. import {
  33. isVideoMutedByUser,
  34. MEDIA_TYPE,
  35. setAudioAvailable,
  36. setAudioMuted,
  37. setVideoAvailable,
  38. setVideoMuted
  39. } from './react/features/base/media';
  40. import {
  41. dominantSpeakerChanged,
  42. localParticipantConnectionStatusChanged,
  43. localParticipantRoleChanged,
  44. MAX_DISPLAY_NAME_LENGTH,
  45. participantConnectionStatusChanged,
  46. participantJoined,
  47. participantLeft,
  48. participantPresenceChanged,
  49. participantRoleChanged,
  50. participantUpdated
  51. } from './react/features/base/participants';
  52. import {
  53. createLocalTracksF,
  54. isLocalTrackMuted,
  55. replaceLocalTrack,
  56. trackAdded,
  57. trackRemoved
  58. } from './react/features/base/tracks';
  59. import { getLocationContextRoot } from './react/features/base/util';
  60. import { statsEmitter } from './react/features/connection-indicator';
  61. import { showDesktopPicker } from './react/features/desktop-picker';
  62. import { maybeOpenFeedbackDialog } from './react/features/feedback';
  63. import {
  64. mediaPermissionPromptVisibilityChanged,
  65. suspendDetected
  66. } from './react/features/overlay';
  67. import {
  68. isButtonEnabled,
  69. showDesktopSharingButton
  70. } from './react/features/toolbox';
  71. const { participantConnectionStatus } = JitsiMeetJS.constants;
  72. const ConnectionEvents = JitsiMeetJS.events.connection;
  73. const ConnectionErrors = JitsiMeetJS.errors.connection;
  74. const ConferenceEvents = JitsiMeetJS.events.conference;
  75. const ConferenceErrors = JitsiMeetJS.errors.conference;
  76. const TrackEvents = JitsiMeetJS.events.track;
  77. const TrackErrors = JitsiMeetJS.errors.track;
  78. const eventEmitter = new EventEmitter();
  79. let room;
  80. let connection;
  81. /*
  82. * Logic to open a desktop picker put on the window global for
  83. * lib-jitsi-meet to detect and invoke
  84. */
  85. window.JitsiMeetScreenObtainer = {
  86. openDesktopPicker(options, onSourceChoose) {
  87. APP.store.dispatch(showDesktopPicker(options, onSourceChoose));
  88. }
  89. };
  90. /**
  91. * Known custom conference commands.
  92. */
  93. const commands = {
  94. AVATAR_ID: AVATAR_ID_COMMAND,
  95. AVATAR_URL: AVATAR_URL_COMMAND,
  96. CUSTOM_ROLE: "custom-role",
  97. EMAIL: EMAIL_COMMAND,
  98. ETHERPAD: "etherpad",
  99. SHARED_VIDEO: "shared-video"
  100. };
  101. /**
  102. * Open Connection. When authentication failed it shows auth dialog.
  103. * @param roomName the room name to use
  104. * @returns Promise<JitsiConnection>
  105. */
  106. function connect(roomName) {
  107. return openConnection({retry: true, roomName: roomName})
  108. .catch(function (err) {
  109. if (err === ConnectionErrors.PASSWORD_REQUIRED) {
  110. APP.UI.notifyTokenAuthFailed();
  111. } else {
  112. APP.UI.notifyConnectionFailed(err);
  113. }
  114. throw err;
  115. });
  116. }
  117. /**
  118. * Share data to other users.
  119. * @param command the command
  120. * @param {string} value new value
  121. */
  122. function sendData(command, value) {
  123. if (!room) {
  124. return;
  125. }
  126. room.removeCommand(command);
  127. room.sendCommand(command, {value: value});
  128. }
  129. /**
  130. * Sets up initially the properties of the local participant - email, avatarID,
  131. * avatarURL, displayName, etc.
  132. */
  133. function _setupLocalParticipantProperties() {
  134. const email = APP.settings.getEmail();
  135. email && sendData(commands.EMAIL, email);
  136. const avatarUrl = APP.settings.getAvatarUrl();
  137. avatarUrl && sendData(commands.AVATAR_URL, avatarUrl);
  138. if (!email && !avatarUrl) {
  139. sendData(commands.AVATAR_ID, APP.settings.getAvatarId());
  140. }
  141. let nick = APP.settings.getDisplayName();
  142. if (config.useNicks && !nick) {
  143. nick = APP.UI.askForNickname();
  144. APP.settings.setDisplayName(nick);
  145. }
  146. nick && room.setDisplayName(nick);
  147. }
  148. /**
  149. * Get user nickname by user id.
  150. * @param {string} id user id
  151. * @returns {string?} user nickname or undefined if user is unknown.
  152. */
  153. function getDisplayName(id) {
  154. if (APP.conference.isLocalId(id)) {
  155. return APP.settings.getDisplayName();
  156. }
  157. let participant = room.getParticipantById(id);
  158. if (participant && participant.getDisplayName()) {
  159. return participant.getDisplayName();
  160. }
  161. }
  162. /**
  163. * Mute or unmute local audio stream if it exists.
  164. * @param {boolean} muted - if audio stream should be muted or unmuted.
  165. */
  166. function muteLocalAudio(muted) {
  167. APP.store.dispatch(setAudioMuted(muted));
  168. }
  169. /**
  170. * Mute or unmute local video stream if it exists.
  171. * @param {boolean} muted if video stream should be muted or unmuted.
  172. *
  173. */
  174. function muteLocalVideo(muted) {
  175. APP.store.dispatch(setVideoMuted(muted));
  176. }
  177. /**
  178. * Check if the welcome page is enabled and redirects to it.
  179. * If requested show a thank you dialog before that.
  180. * If we have a close page enabled, redirect to it without
  181. * showing any other dialog.
  182. *
  183. * @param {object} options used to decide which particular close page to show
  184. * or if close page is disabled, whether we should show the thankyou dialog
  185. * @param {boolean} options.thankYouDialogVisible - whether we should
  186. * show thank you dialog
  187. * @param {boolean} options.feedbackSubmitted - whether feedback was submitted
  188. */
  189. function maybeRedirectToWelcomePage(options) {
  190. // if close page is enabled redirect to it, without further action
  191. if (config.enableClosePage) {
  192. const { isGuest } = APP.store.getState()['features/jwt'];
  193. // save whether current user is guest or not, before navigating
  194. // to close page
  195. window.sessionStorage.setItem('guest', isGuest);
  196. assignWindowLocationPathname('static/'
  197. + (options.feedbackSubmitted ? "close.html" : "close2.html"));
  198. return;
  199. }
  200. // else: show thankYou dialog only if there is no feedback
  201. if (options.thankYouDialogVisible)
  202. APP.UI.messageHandler.openMessageDialog(
  203. null, "dialog.thankYou", {appName:interfaceConfig.APP_NAME});
  204. // if Welcome page is enabled redirect to welcome page after 3 sec.
  205. if (config.enableWelcomePage) {
  206. setTimeout(() => {
  207. APP.settings.setWelcomePageEnabled(true);
  208. assignWindowLocationPathname('./');
  209. }, 3000);
  210. }
  211. }
  212. /**
  213. * Assigns a specific pathname to window.location.pathname taking into account
  214. * the context root of the Web app.
  215. *
  216. * @param {string} pathname - The pathname to assign to
  217. * window.location.pathname. If the specified pathname is relative, the context
  218. * root of the Web app will be prepended to the specified pathname before
  219. * assigning it to window.location.pathname.
  220. * @return {void}
  221. */
  222. function assignWindowLocationPathname(pathname) {
  223. const windowLocation = window.location;
  224. if (!pathname.startsWith('/')) {
  225. // A pathname equal to ./ specifies the current directory. It will be
  226. // fine but pointless to include it because contextRoot is the current
  227. // directory.
  228. pathname.startsWith('./') && (pathname = pathname.substring(2));
  229. pathname = getLocationContextRoot(windowLocation) + pathname;
  230. }
  231. windowLocation.pathname = pathname;
  232. }
  233. class ConferenceConnector {
  234. constructor(resolve, reject) {
  235. this._resolve = resolve;
  236. this._reject = reject;
  237. this.reconnectTimeout = null;
  238. room.on(ConferenceEvents.CONFERENCE_JOINED,
  239. this._handleConferenceJoined.bind(this));
  240. room.on(ConferenceEvents.CONFERENCE_FAILED,
  241. this._onConferenceFailed.bind(this));
  242. room.on(ConferenceEvents.CONFERENCE_ERROR,
  243. this._onConferenceError.bind(this));
  244. }
  245. _handleConferenceFailed(err) {
  246. this._unsubscribe();
  247. this._reject(err);
  248. }
  249. _onConferenceFailed(err, ...params) {
  250. APP.store.dispatch(conferenceFailed(room, err, ...params));
  251. logger.error('CONFERENCE FAILED:', err, ...params);
  252. switch (err) {
  253. case ConferenceErrors.CONNECTION_ERROR: {
  254. let [msg] = params;
  255. APP.UI.notifyConnectionFailed(msg);
  256. break;
  257. }
  258. case ConferenceErrors.NOT_ALLOWED_ERROR: {
  259. // let's show some auth not allowed page
  260. assignWindowLocationPathname('static/authError.html');
  261. break;
  262. }
  263. // not enough rights to create conference
  264. case ConferenceErrors.AUTHENTICATION_REQUIRED: {
  265. // Schedule reconnect to check if someone else created the room.
  266. this.reconnectTimeout = setTimeout(() => room.join(), 5000);
  267. const { password }
  268. = APP.store.getState()['features/base/conference'];
  269. AuthHandler.requireAuth(room, password);
  270. break;
  271. }
  272. case ConferenceErrors.RESERVATION_ERROR: {
  273. let [code, msg] = params;
  274. APP.UI.notifyReservationError(code, msg);
  275. break;
  276. }
  277. case ConferenceErrors.GRACEFUL_SHUTDOWN:
  278. APP.UI.notifyGracefulShutdown();
  279. break;
  280. case ConferenceErrors.JINGLE_FATAL_ERROR:
  281. APP.UI.notifyInternalError();
  282. break;
  283. case ConferenceErrors.CONFERENCE_DESTROYED: {
  284. let [reason] = params;
  285. APP.UI.hideStats();
  286. APP.UI.notifyConferenceDestroyed(reason);
  287. break;
  288. }
  289. // FIXME FOCUS_DISCONNECTED is a confusing event name.
  290. // What really happens there is that the library is not ready yet,
  291. // because Jicofo is not available, but it is going to give it another
  292. // try.
  293. case ConferenceErrors.FOCUS_DISCONNECTED: {
  294. let [focus, retrySec] = params;
  295. APP.UI.notifyFocusDisconnected(focus, retrySec);
  296. break;
  297. }
  298. case ConferenceErrors.FOCUS_LEFT:
  299. case ConferenceErrors.VIDEOBRIDGE_NOT_AVAILABLE:
  300. // FIXME the conference should be stopped by the library and not by
  301. // the app. Both the errors above are unrecoverable from the library
  302. // perspective.
  303. room.leave().then(() => connection.disconnect());
  304. break;
  305. case ConferenceErrors.CONFERENCE_MAX_USERS:
  306. connection.disconnect();
  307. APP.UI.notifyMaxUsersLimitReached();
  308. break;
  309. case ConferenceErrors.INCOMPATIBLE_SERVER_VERSIONS:
  310. reload();
  311. break;
  312. default:
  313. this._handleConferenceFailed(err, ...params);
  314. }
  315. }
  316. _onConferenceError(err, ...params) {
  317. logger.error('CONFERENCE Error:', err, params);
  318. switch (err) {
  319. case ConferenceErrors.CHAT_ERROR:
  320. logger.error("Chat error.", err);
  321. if (isButtonEnabled('chat')) {
  322. let [code, msg] = params;
  323. APP.UI.showChatError(code, msg);
  324. }
  325. break;
  326. default:
  327. logger.error("Unknown error.", err);
  328. }
  329. }
  330. _unsubscribe() {
  331. room.off(
  332. ConferenceEvents.CONFERENCE_JOINED, this._handleConferenceJoined);
  333. room.off(
  334. ConferenceEvents.CONFERENCE_FAILED, this._onConferenceFailed);
  335. if (this.reconnectTimeout !== null) {
  336. clearTimeout(this.reconnectTimeout);
  337. }
  338. AuthHandler.closeAuth();
  339. }
  340. _handleConferenceJoined() {
  341. this._unsubscribe();
  342. this._resolve();
  343. }
  344. connect() {
  345. room.join();
  346. }
  347. }
  348. /**
  349. * Disconnects the connection.
  350. * @returns resolved Promise. We need this in order to make the Promise.all
  351. * call in hangup() to resolve when all operations are finished.
  352. */
  353. function disconnect() {
  354. connection.disconnect();
  355. APP.API.notifyConferenceLeft(APP.conference.roomName);
  356. return Promise.resolve();
  357. }
  358. /**
  359. * Handles CONNECTION_FAILED events from lib-jitsi-meet.
  360. *
  361. * @param {JitsiMeetJS.connection.error} error - The reported error.
  362. * @returns {void}
  363. * @private
  364. */
  365. function _connectionFailedHandler(error) {
  366. if (isFatalJitsiConnectionError(error)) {
  367. APP.connection.removeEventListener(
  368. ConnectionEvents.CONNECTION_FAILED,
  369. _connectionFailedHandler);
  370. if (room)
  371. room.leave();
  372. }
  373. }
  374. export default {
  375. /**
  376. * Flag used to delay modification of the muted status of local media tracks
  377. * until those are created (or not, but at that point it's certain that
  378. * the tracks won't exist).
  379. */
  380. _localTracksInitialized: false,
  381. isModerator: false,
  382. isSharingScreen: false,
  383. /**
  384. * Indicates if the desktop sharing functionality has been enabled.
  385. * It takes into consideration {@link isDesktopSharingDisabledByConfig}
  386. * as well as the status returned by
  387. * {@link JitsiMeetJS.isDesktopSharingEnabled()}. The latter can be false
  388. * either if the desktop sharing is not supported by the current browser
  389. * or if it was disabled through lib-jitsi-meet specific options (check
  390. * config.js for listed options).
  391. */
  392. isDesktopSharingEnabled: false,
  393. /**
  394. * Set to <tt>true</tt> if the desktop sharing functionality has been
  395. * explicitly disabled in the config.
  396. */
  397. isDesktopSharingDisabledByConfig: false,
  398. /**
  399. * The text displayed when the desktop sharing button is disabled through
  400. * the config. The value is set through
  401. * {@link interfaceConfig.DESKTOP_SHARING_BUTTON_DISABLED_TOOLTIP}.
  402. */
  403. desktopSharingDisabledTooltip: null,
  404. /*
  405. * Whether the local "raisedHand" flag is on.
  406. */
  407. isHandRaised: false,
  408. /*
  409. * Whether the local participant is the dominant speaker in the conference.
  410. */
  411. isDominantSpeaker: false,
  412. /**
  413. * The local audio track (if any).
  414. * FIXME tracks from redux store should be the single source of truth
  415. * @type {JitsiLocalTrack|null}
  416. */
  417. localAudio: null,
  418. /**
  419. * The local video track (if any).
  420. * FIXME tracks from redux store should be the single source of truth, but
  421. * more refactoring is required around screen sharing ('localVideo' usages).
  422. * @type {JitsiLocalTrack|null}
  423. */
  424. localVideo: null,
  425. /**
  426. * Creates local media tracks and connects to a room. Will show error
  427. * dialogs in case accessing the local microphone and/or camera failed. Will
  428. * show guidance overlay for users on how to give access to camera and/or
  429. * microphone.
  430. * @param {string} roomName
  431. * @param {object} options
  432. * @param {boolean} options.startAudioOnly=false - if <tt>true</tt> then
  433. * only audio track will be created and the audio only mode will be turned
  434. * on.
  435. * @param {boolean} options.startScreenSharing=false - if <tt>true</tt>
  436. * should start with screensharing instead of camera video.
  437. * @param {boolean} options.startWithAudioMuted - will start the conference
  438. * without any audio tracks.
  439. * @param {boolean} options.startWithVideoMuted - will start the conference
  440. * without any video tracks.
  441. * @returns {Promise.<JitsiLocalTrack[], JitsiConnection>}
  442. */
  443. createInitialLocalTracksAndConnect(roomName, options = {}) {
  444. let audioAndVideoError,
  445. audioOnlyError,
  446. screenSharingError,
  447. videoOnlyError;
  448. const initialDevices = [];
  449. let requestedAudio = false;
  450. let requestedVideo = false;
  451. if (!options.startWithAudioMuted) {
  452. initialDevices.push('audio');
  453. requestedAudio = true;
  454. }
  455. if (!options.startWithVideoMuted
  456. && !options.startAudioOnly
  457. && !options.startScreenSharing) {
  458. initialDevices.push('video');
  459. requestedVideo = true;
  460. }
  461. JitsiMeetJS.mediaDevices.addEventListener(
  462. JitsiMeetJS.events.mediaDevices.PERMISSION_PROMPT_IS_SHOWN,
  463. browser =>
  464. APP.store.dispatch(
  465. mediaPermissionPromptVisibilityChanged(true, browser))
  466. );
  467. let tryCreateLocalTracks;
  468. // Enable audio only mode
  469. if (config.startAudioOnly) {
  470. APP.store.dispatch(toggleAudioOnly());
  471. }
  472. // FIXME is there any simpler way to rewrite this spaghetti below ?
  473. if (options.startScreenSharing) {
  474. tryCreateLocalTracks = this._createDesktopTrack()
  475. .then(desktopStream => {
  476. if (!requestedAudio) {
  477. return [desktopStream];
  478. }
  479. return createLocalTracksF({ devices: ['audio'] }, true)
  480. .then(([audioStream]) => {
  481. return [desktopStream, audioStream];
  482. })
  483. .catch(error => {
  484. audioOnlyError = error;
  485. return [desktopStream];
  486. });
  487. }).catch(error => {
  488. logger.error('Failed to obtain desktop stream', error);
  489. screenSharingError = error;
  490. return requestedAudio
  491. ? createLocalTracksF({ devices: ['audio'] }, true)
  492. : [];
  493. }).catch(error => {
  494. audioOnlyError = error;
  495. return [];
  496. });
  497. } else if (!requestedAudio && !requestedVideo) {
  498. // Resolve with no tracks
  499. tryCreateLocalTracks = Promise.resolve([]);
  500. } else {
  501. tryCreateLocalTracks = createLocalTracksF(
  502. { devices: initialDevices }, true)
  503. .catch(err => {
  504. if (requestedAudio && requestedVideo) {
  505. // Try audio only...
  506. audioAndVideoError = err;
  507. return createLocalTracksF({devices: ['audio']}, true);
  508. } else if (requestedAudio && !requestedVideo) {
  509. audioOnlyError = err;
  510. return [];
  511. } else if (requestedVideo && !requestedAudio) {
  512. videoOnlyError = err;
  513. return [];
  514. }
  515. logger.error('Should never happen');
  516. }).catch(err => {
  517. // Log this just in case...
  518. if (!requestedAudio) {
  519. logger.error('The impossible just happened', err);
  520. }
  521. audioOnlyError = err;
  522. // Try video only...
  523. return requestedVideo
  524. ? createLocalTracksF({devices: ['video']}, true)
  525. : [];
  526. })
  527. .catch(err => {
  528. // Log this just in case...
  529. if (!requestedVideo) {
  530. logger.error('The impossible just happened', err);
  531. }
  532. videoOnlyError = err;
  533. return [];
  534. });
  535. }
  536. return Promise.all([ tryCreateLocalTracks, connect(roomName) ])
  537. .then(([tracks, con]) => {
  538. APP.store.dispatch(
  539. mediaPermissionPromptVisibilityChanged(false));
  540. // FIXME If there will be microphone error it will cover any
  541. // screensharing dialog, but it's still better than in
  542. // the reverse order where the screensharing dialog will
  543. // sometimes be closing the microphone alert ($.prompt.close();
  544. // is called). Need to figure out dialogs chaining to fix that.
  545. if (screenSharingError) {
  546. this._handleScreenSharingError(screenSharingError);
  547. }
  548. if (audioAndVideoError || audioOnlyError) {
  549. if (audioOnlyError || videoOnlyError) {
  550. // If both requests for 'audio' + 'video' and 'audio'
  551. // only failed, we assume that there are some problems
  552. // with user's microphone and show corresponding dialog.
  553. APP.UI.showMicErrorNotification(audioOnlyError);
  554. APP.UI.showCameraErrorNotification(videoOnlyError);
  555. } else {
  556. // If request for 'audio' + 'video' failed, but request
  557. // for 'audio' only was OK, we assume that we had
  558. // problems with camera and show corresponding dialog.
  559. APP.UI.showCameraErrorNotification(audioAndVideoError);
  560. }
  561. }
  562. return [tracks, con];
  563. });
  564. },
  565. /**
  566. * Open new connection and join to the conference.
  567. * @param {object} options
  568. * @param {string} roomName name of the conference
  569. * @returns {Promise}
  570. */
  571. init(options) {
  572. this.roomName = options.roomName;
  573. // attaches global error handler, if there is already one, respect it
  574. if (JitsiMeetJS.getGlobalOnErrorHandler) {
  575. var oldOnErrorHandler = window.onerror;
  576. window.onerror = function (message, source, lineno, colno, error) {
  577. JitsiMeetJS.getGlobalOnErrorHandler(
  578. message, source, lineno, colno, error);
  579. if (oldOnErrorHandler)
  580. oldOnErrorHandler(message, source, lineno, colno, error);
  581. };
  582. var oldOnUnhandledRejection = window.onunhandledrejection;
  583. window.onunhandledrejection = function(event) {
  584. JitsiMeetJS.getGlobalOnErrorHandler(
  585. null, null, null, null, event.reason);
  586. if (oldOnUnhandledRejection)
  587. oldOnUnhandledRejection(event);
  588. };
  589. }
  590. return (
  591. JitsiMeetJS.init({
  592. enableAnalyticsLogging: isAnalyticsEnabled(APP.store),
  593. ...config
  594. }).then(() => {
  595. initAnalytics(APP.store);
  596. return this.createInitialLocalTracksAndConnect(
  597. options.roomName, {
  598. startAudioOnly: config.startAudioOnly,
  599. startScreenSharing: config.startScreenSharing,
  600. startWithAudioMuted: config.startWithAudioMuted,
  601. startWithVideoMuted: config.startWithVideoMuted,
  602. });
  603. }).then(([tracks, con]) => {
  604. tracks.forEach(track => {
  605. if (track.isAudioTrack() && this.isLocalAudioMuted()) {
  606. track.mute();
  607. } else if (track.isVideoTrack()
  608. && this.isLocalVideoMuted()) {
  609. track.mute();
  610. }
  611. });
  612. logger.log('initialized with %s local tracks', tracks.length);
  613. this._localTracksInitialized = true;
  614. con.addEventListener(
  615. ConnectionEvents.CONNECTION_FAILED,
  616. _connectionFailedHandler);
  617. APP.connection = connection = con;
  618. // Desktop sharing related stuff:
  619. this.isDesktopSharingDisabledByConfig
  620. = config.disableDesktopSharing;
  621. this.isDesktopSharingEnabled
  622. = !this.isDesktopSharingDisabledByConfig
  623. && JitsiMeetJS.isDesktopSharingEnabled();
  624. this.desktopSharingDisabledTooltip
  625. = interfaceConfig.DESKTOP_SHARING_BUTTON_DISABLED_TOOLTIP;
  626. eventEmitter.emit(
  627. JitsiMeetConferenceEvents.DESKTOP_SHARING_ENABLED_CHANGED,
  628. this.isDesktopSharingEnabled);
  629. APP.store.dispatch(showDesktopSharingButton());
  630. this._createRoom(tracks);
  631. APP.remoteControl.init();
  632. // if user didn't give access to mic or camera or doesn't have
  633. // them at all, we mark corresponding toolbar buttons as muted,
  634. // so that the user can try unmute later on and add audio/video
  635. // to the conference
  636. if (!tracks.find((t) => t.isAudioTrack())) {
  637. this.setAudioMuteStatus(true);
  638. }
  639. if (!tracks.find((t) => t.isVideoTrack())) {
  640. this.setVideoMuteStatus(true);
  641. }
  642. this._initDeviceList();
  643. if (config.iAmRecorder)
  644. this.recorder = new Recorder();
  645. // XXX The API will take care of disconnecting from the XMPP
  646. // server (and, thus, leaving the room) on unload.
  647. return new Promise((resolve, reject) => {
  648. (new ConferenceConnector(resolve, reject)).connect();
  649. });
  650. }));
  651. },
  652. /**
  653. * Check if id is id of the local user.
  654. * @param {string} id id to check
  655. * @returns {boolean}
  656. */
  657. isLocalId(id) {
  658. return this.getMyUserId() === id;
  659. },
  660. /**
  661. * Tells whether the local video is muted or not.
  662. * @return {boolean}
  663. */
  664. isLocalVideoMuted() {
  665. // If the tracks are not ready, read from base/media state
  666. return this._localTracksInitialized
  667. ? isLocalTrackMuted(
  668. APP.store.getState()['features/base/tracks'],
  669. MEDIA_TYPE.VIDEO)
  670. : isVideoMutedByUser(APP.store);
  671. },
  672. /**
  673. * Simulates toolbar button click for audio mute. Used by shortcuts and API.
  674. * @param {boolean} mute true for mute and false for unmute.
  675. * @param {boolean} [showUI] when set to false will not display any error
  676. * dialogs in case of media permissions error.
  677. */
  678. muteAudio(mute, showUI = true) {
  679. // Not ready to modify track's state yet
  680. if (!this._localTracksInitialized) {
  681. // This will only modify base/media.audio.muted which is then synced
  682. // up with the track at the end of local tracks initialization.
  683. muteLocalAudio(mute);
  684. this.setAudioMuteStatus(mute);
  685. return;
  686. } else if (this.isLocalAudioMuted() === mute) {
  687. // NO-OP
  688. return;
  689. }
  690. if (!this.localAudio && !mute) {
  691. const maybeShowErrorDialog = error => {
  692. showUI && APP.UI.showMicErrorNotification(error);
  693. };
  694. createLocalTracksF({ devices: ['audio'] }, false)
  695. .then(([audioTrack]) => audioTrack)
  696. .catch(error => {
  697. maybeShowErrorDialog(error);
  698. // Rollback the audio muted status by using null track
  699. return null;
  700. })
  701. .then(audioTrack => this.useAudioStream(audioTrack));
  702. } else {
  703. muteLocalAudio(mute);
  704. }
  705. },
  706. /**
  707. * Returns whether local audio is muted or not.
  708. * @returns {boolean}
  709. */
  710. isLocalAudioMuted() {
  711. // If the tracks are not ready, read from base/media state
  712. return this._localTracksInitialized
  713. ? isLocalTrackMuted(
  714. APP.store.getState()['features/base/tracks'],
  715. MEDIA_TYPE.AUDIO)
  716. : Boolean(
  717. APP.store.getState()['features/base/media'].audio.muted);
  718. },
  719. /**
  720. * Simulates toolbar button click for audio mute. Used by shortcuts
  721. * and API.
  722. * @param {boolean} [showUI] when set to false will not display any error
  723. * dialogs in case of media permissions error.
  724. */
  725. toggleAudioMuted(showUI = true) {
  726. this.muteAudio(!this.isLocalAudioMuted(), showUI);
  727. },
  728. /**
  729. * Simulates toolbar button click for video mute. Used by 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. muteVideo(mute, showUI = true) {
  735. // If not ready to modify track's state yet adjust the base/media
  736. if (!this._localTracksInitialized) {
  737. // This will only modify base/media.video.muted which is then synced
  738. // up with the track at the end of local tracks initialization.
  739. muteLocalVideo(mute);
  740. this.setVideoMuteStatus(mute);
  741. return;
  742. } else if (this.isLocalVideoMuted() === mute) {
  743. // NO-OP
  744. return;
  745. }
  746. // FIXME it is possible to queue this task twice, but it's not causing
  747. // any issues. Specifically this can happen when the previous
  748. // get user media call is blocked on "ask user for permissions" dialog.
  749. if (!this.localVideo && !mute) {
  750. const maybeShowErrorDialog = error => {
  751. showUI && APP.UI.showCameraErrorNotification(error);
  752. };
  753. // Try to create local video if there wasn't any.
  754. // This handles the case when user joined with no video
  755. // (dismissed screen sharing screen or in audio only mode), but
  756. // decided to add it later on by clicking on muted video icon or
  757. // turning off the audio only mode.
  758. //
  759. // FIXME when local track creation is moved to react/redux
  760. // it should take care of the use case described above
  761. createLocalTracksF({ devices: ['video'] }, false)
  762. .then(([videoTrack]) => videoTrack)
  763. .catch(error => {
  764. // FIXME should send some feedback to the API on error ?
  765. maybeShowErrorDialog(error);
  766. // Rollback the video muted status by using null track
  767. return null;
  768. })
  769. .then(videoTrack => this.useVideoStream(videoTrack));
  770. } else {
  771. // FIXME show error dialog if it fails (should be handled by react)
  772. muteLocalVideo(mute);
  773. }
  774. },
  775. /**
  776. * Simulates toolbar button click for video mute. Used by shortcuts and API.
  777. * @param {boolean} [showUI] when set to false will not display any error
  778. * dialogs in case of media permissions error.
  779. */
  780. toggleVideoMuted(showUI = true) {
  781. this.muteVideo(!this.isLocalVideoMuted(), showUI);
  782. },
  783. /**
  784. * Retrieve list of conference participants (without local user).
  785. * @returns {JitsiParticipant[]}
  786. */
  787. listMembers() {
  788. return room.getParticipants();
  789. },
  790. /**
  791. * Retrieve list of ids of conference participants (without local user).
  792. * @returns {string[]}
  793. */
  794. listMembersIds() {
  795. return room.getParticipants().map(p => p.getId());
  796. },
  797. /**
  798. * Checks whether the participant identified by id is a moderator.
  799. * @id id to search for participant
  800. * @return {boolean} whether the participant is moderator
  801. */
  802. isParticipantModerator(id) {
  803. let user = room.getParticipantById(id);
  804. return user && user.isModerator();
  805. },
  806. /**
  807. * Check if SIP is supported.
  808. * @returns {boolean}
  809. */
  810. sipGatewayEnabled() {
  811. return room.isSIPCallingSupported();
  812. },
  813. get membersCount() {
  814. return room.getParticipants().length + 1;
  815. },
  816. /**
  817. * Returns true if the callstats integration is enabled, otherwise returns
  818. * false.
  819. *
  820. * @returns true if the callstats integration is enabled, otherwise returns
  821. * false.
  822. */
  823. isCallstatsEnabled() {
  824. return room && room.isCallstatsEnabled();
  825. },
  826. /**
  827. * Sends the given feedback through CallStats if enabled.
  828. *
  829. * @param overallFeedback an integer between 1 and 5 indicating the
  830. * user feedback
  831. * @param detailedFeedback detailed feedback from the user. Not yet used
  832. */
  833. sendFeedback(overallFeedback, detailedFeedback) {
  834. return room.sendFeedback (overallFeedback, detailedFeedback);
  835. },
  836. /**
  837. * Get speaker stats that track total dominant speaker time.
  838. *
  839. * @returns {object} A hash with keys being user ids and values being the
  840. * library's SpeakerStats model used for calculating time as dominant
  841. * speaker.
  842. */
  843. getSpeakerStats() {
  844. return room.getSpeakerStats();
  845. },
  846. /**
  847. * Returns the connection times stored in the library.
  848. */
  849. getConnectionTimes() {
  850. return this._room.getConnectionTimes();
  851. },
  852. // used by torture currently
  853. isJoined() {
  854. return this._room
  855. && this._room.isJoined();
  856. },
  857. getConnectionState() {
  858. return this._room
  859. && this._room.getConnectionState();
  860. },
  861. /**
  862. * Obtains current P2P ICE connection state.
  863. * @return {string|null} ICE connection state or <tt>null</tt> if there's no
  864. * P2P connection
  865. */
  866. getP2PConnectionState() {
  867. return this._room
  868. && this._room.getP2PConnectionState();
  869. },
  870. /**
  871. * Starts P2P (for tests only)
  872. * @private
  873. */
  874. _startP2P() {
  875. try {
  876. this._room && this._room.startP2PSession();
  877. } catch (error) {
  878. logger.error("Start P2P failed", error);
  879. throw error;
  880. }
  881. },
  882. /**
  883. * Stops P2P (for tests only)
  884. * @private
  885. */
  886. _stopP2P() {
  887. try {
  888. this._room && this._room.stopP2PSession();
  889. } catch (error) {
  890. logger.error("Stop P2P failed", error);
  891. throw error;
  892. }
  893. },
  894. /**
  895. * Checks whether or not our connection is currently in interrupted and
  896. * reconnect attempts are in progress.
  897. *
  898. * @returns {boolean} true if the connection is in interrupted state or
  899. * false otherwise.
  900. */
  901. isConnectionInterrupted() {
  902. return this._room.isConnectionInterrupted();
  903. },
  904. /**
  905. * Finds JitsiParticipant for given id.
  906. *
  907. * @param {string} id participant's identifier(MUC nickname).
  908. *
  909. * @returns {JitsiParticipant|null} participant instance for given id or
  910. * null if not found.
  911. */
  912. getParticipantById(id) {
  913. return room ? room.getParticipantById(id) : null;
  914. },
  915. /**
  916. * Get participant connection status for the participant.
  917. *
  918. * @param {string} id participant's identifier(MUC nickname)
  919. *
  920. * @returns {ParticipantConnectionStatus|null} the status of the participant
  921. * or null if no such participant is found or participant is the local user.
  922. */
  923. getParticipantConnectionStatus(id) {
  924. let participant = this.getParticipantById(id);
  925. return participant ? participant.getConnectionStatus() : null;
  926. },
  927. /**
  928. * Gets the display name foe the <tt>JitsiParticipant</tt> identified by
  929. * the given <tt>id</tt>.
  930. *
  931. * @param id {string} the participant's id(MUC nickname/JVB endpoint id)
  932. *
  933. * @return {string} the participant's display name or the default string if
  934. * absent.
  935. */
  936. getParticipantDisplayName(id) {
  937. let displayName = getDisplayName(id);
  938. if (displayName) {
  939. return displayName;
  940. } else {
  941. if (APP.conference.isLocalId(id)) {
  942. return APP.translation.generateTranslationHTML(
  943. interfaceConfig.DEFAULT_LOCAL_DISPLAY_NAME);
  944. } else {
  945. return interfaceConfig.DEFAULT_REMOTE_DISPLAY_NAME;
  946. }
  947. }
  948. },
  949. getMyUserId() {
  950. return this._room
  951. && this._room.myUserId();
  952. },
  953. /**
  954. * Indicates if recording is supported in this conference.
  955. */
  956. isRecordingSupported() {
  957. return this._room && this._room.isRecordingSupported();
  958. },
  959. /**
  960. * Returns the recording state or undefined if the room is not defined.
  961. */
  962. getRecordingState() {
  963. return (this._room) ? this._room.getRecordingState() : undefined;
  964. },
  965. /**
  966. * Will be filled with values only when config.debug is enabled.
  967. * Its used by torture to check audio levels.
  968. */
  969. audioLevelsMap: {},
  970. /**
  971. * Returns the stored audio level (stored only if config.debug is enabled)
  972. * @param id the id for the user audio level to return (the id value is
  973. * returned for the participant using getMyUserId() method)
  974. */
  975. getPeerSSRCAudioLevel(id) {
  976. return this.audioLevelsMap[id];
  977. },
  978. /**
  979. * @return {number} the number of participants in the conference with at
  980. * least one track.
  981. */
  982. getNumberOfParticipantsWithTracks() {
  983. return this._room.getParticipants()
  984. .filter((p) => p.getTracks().length > 0)
  985. .length;
  986. },
  987. /**
  988. * Returns the stats.
  989. */
  990. getStats() {
  991. return room.connectionQuality.getStats();
  992. },
  993. // end used by torture
  994. getLogs() {
  995. return room.getLogs();
  996. },
  997. /**
  998. * Download logs, a function that can be called from console while
  999. * debugging.
  1000. * @param filename (optional) specify target filename
  1001. */
  1002. saveLogs(filename = 'meetlog.json') {
  1003. // this can be called from console and will not have reference to this
  1004. // that's why we reference the global var
  1005. let logs = APP.conference.getLogs();
  1006. let data = encodeURIComponent(JSON.stringify(logs, null, ' '));
  1007. let elem = document.createElement('a');
  1008. elem.download = filename;
  1009. elem.href = 'data:application/json;charset=utf-8,\n' + data;
  1010. elem.dataset.downloadurl
  1011. = ['text/json', elem.download, elem.href].join(':');
  1012. elem.dispatchEvent(new MouseEvent('click', {
  1013. view: window,
  1014. bubbles: true,
  1015. cancelable: false
  1016. }));
  1017. },
  1018. /**
  1019. * Exposes a Command(s) API on this instance. It is necessitated by (1) the
  1020. * desire to keep room private to this instance and (2) the need of other
  1021. * modules to send and receive commands to and from participants.
  1022. * Eventually, this instance remains in control with respect to the
  1023. * decision whether the Command(s) API of room (i.e. lib-jitsi-meet's
  1024. * JitsiConference) is to be used in the implementation of the Command(s)
  1025. * API of this instance.
  1026. */
  1027. commands: {
  1028. /**
  1029. * Known custom conference commands.
  1030. */
  1031. defaults: commands,
  1032. /**
  1033. * Receives notifications from other participants about commands aka
  1034. * custom events (sent by sendCommand or sendCommandOnce methods).
  1035. * @param command {String} the name of the command
  1036. * @param handler {Function} handler for the command
  1037. */
  1038. addCommandListener () {
  1039. room.addCommandListener.apply(room, arguments);
  1040. },
  1041. /**
  1042. * Removes command.
  1043. * @param name {String} the name of the command.
  1044. */
  1045. removeCommand () {
  1046. room.removeCommand.apply(room, arguments);
  1047. },
  1048. /**
  1049. * Sends command.
  1050. * @param name {String} the name of the command.
  1051. * @param values {Object} with keys and values that will be sent.
  1052. */
  1053. sendCommand () {
  1054. room.sendCommand.apply(room, arguments);
  1055. },
  1056. /**
  1057. * Sends command one time.
  1058. * @param name {String} the name of the command.
  1059. * @param values {Object} with keys and values that will be sent.
  1060. */
  1061. sendCommandOnce () {
  1062. room.sendCommandOnce.apply(room, arguments);
  1063. }
  1064. },
  1065. _createRoom (localTracks) {
  1066. room = connection.initJitsiConference(APP.conference.roomName,
  1067. this._getConferenceOptions());
  1068. this._setLocalAudioVideoStreams(localTracks);
  1069. this._room = room; // FIXME do not use this
  1070. _setupLocalParticipantProperties();
  1071. this._setupListeners();
  1072. },
  1073. /**
  1074. * Sets local video and audio streams.
  1075. * @param {JitsiLocalTrack[]} tracks=[]
  1076. * @returns {Promise[]}
  1077. * @private
  1078. */
  1079. _setLocalAudioVideoStreams(tracks = []) {
  1080. return tracks.map(track => {
  1081. if (track.isAudioTrack()) {
  1082. return this.useAudioStream(track);
  1083. } else if (track.isVideoTrack()) {
  1084. return this.useVideoStream(track);
  1085. } else {
  1086. logger.error(
  1087. "Ignored not an audio nor a video track: ", track);
  1088. return Promise.resolve();
  1089. }
  1090. });
  1091. },
  1092. _getConferenceOptions() {
  1093. let options = config;
  1094. if (config.enableRecording && !config.recordingType) {
  1095. options.recordingType = (config.hosts &&
  1096. (typeof config.hosts.jirecon != "undefined"))?
  1097. "jirecon" : "colibri";
  1098. }
  1099. return options;
  1100. },
  1101. /**
  1102. * Start using provided video stream.
  1103. * Stops previous video stream.
  1104. * @param {JitsiLocalTrack} [stream] new stream to use or null
  1105. * @returns {Promise}
  1106. */
  1107. useVideoStream(newStream) {
  1108. return APP.store.dispatch(
  1109. replaceLocalTrack(this.localVideo, newStream, room))
  1110. .then(() => {
  1111. this.localVideo = newStream;
  1112. if (newStream) {
  1113. this.isSharingScreen = newStream.videoType === 'desktop';
  1114. APP.UI.addLocalStream(newStream);
  1115. } else {
  1116. this.isSharingScreen = false;
  1117. }
  1118. this.setVideoMuteStatus(this.isLocalVideoMuted());
  1119. APP.UI.updateDesktopSharingButtons();
  1120. });
  1121. },
  1122. /**
  1123. * Start using provided audio stream.
  1124. * Stops previous audio stream.
  1125. * @param {JitsiLocalTrack} [stream] new stream to use or null
  1126. * @returns {Promise}
  1127. */
  1128. useAudioStream(newStream) {
  1129. return APP.store.dispatch(
  1130. replaceLocalTrack(this.localAudio, newStream, room))
  1131. .then(() => {
  1132. this.localAudio = newStream;
  1133. if (newStream) {
  1134. APP.UI.addLocalStream(newStream);
  1135. }
  1136. this.setAudioMuteStatus(this.isLocalAudioMuted());
  1137. });
  1138. },
  1139. /**
  1140. * Triggers a tooltip to display when a feature was attempted to be used
  1141. * while in audio only mode.
  1142. *
  1143. * @param {string} featureName - The name of the feature that attempted to
  1144. * toggle.
  1145. * @private
  1146. * @returns {void}
  1147. */
  1148. _displayAudioOnlyTooltip(featureName) {
  1149. let buttonName = null;
  1150. let tooltipElementId = null;
  1151. switch (featureName) {
  1152. case 'screenShare':
  1153. buttonName = 'desktop';
  1154. tooltipElementId = 'screenshareWhileAudioOnly';
  1155. break;
  1156. case 'videoMute':
  1157. buttonName = 'camera';
  1158. tooltipElementId = 'unmuteWhileAudioOnly';
  1159. break;
  1160. }
  1161. if (tooltipElementId) {
  1162. APP.UI.showToolbar(6000);
  1163. APP.UI.showCustomToolbarPopup(
  1164. buttonName, tooltipElementId, true, 5000);
  1165. }
  1166. },
  1167. /**
  1168. * Returns whether or not the conference is currently in audio only mode.
  1169. *
  1170. * @returns {boolean}
  1171. */
  1172. isAudioOnly() {
  1173. return Boolean(
  1174. APP.store.getState()['features/base/conference'].audioOnly);
  1175. },
  1176. videoSwitchInProgress: false,
  1177. /**
  1178. * This fields stores a handler which will create a Promise which turns off
  1179. * the screen sharing and restores the previous video state (was there
  1180. * any video, before switching to screen sharing ? was it muted ?).
  1181. *
  1182. * Once called this fields is cleared to <tt>null</tt>.
  1183. * @type {Function|null}
  1184. */
  1185. _untoggleScreenSharing: null,
  1186. /**
  1187. * Creates a Promise which turns off the screen sharing and restores
  1188. * the previous state described by the arguments.
  1189. *
  1190. * This method is bound to the appropriate values, after switching to screen
  1191. * sharing and stored in {@link _untoggleScreenSharing}.
  1192. *
  1193. * @param {boolean} didHaveVideo indicates if there was a camera video being
  1194. * used, before switching to screen sharing.
  1195. * @param {boolean} wasVideoMuted indicates if the video was muted, before
  1196. * switching to screen sharing.
  1197. * @return {Promise} resolved after the screen sharing is turned off, or
  1198. * rejected with some error (no idea what kind of error, possible GUM error)
  1199. * in case it fails.
  1200. * @private
  1201. */
  1202. _turnScreenSharingOff(didHaveVideo, wasVideoMuted) {
  1203. this._untoggleScreenSharing = null;
  1204. this.videoSwitchInProgress = true;
  1205. APP.remoteControl.receiver.stop();
  1206. let promise = null;
  1207. if (didHaveVideo) {
  1208. promise = createLocalTracksF({ devices: ['video'] })
  1209. .then(([stream]) => this.useVideoStream(stream))
  1210. .then(() => {
  1211. JitsiMeetJS.analytics.sendEvent(
  1212. 'conference.sharingDesktop.stop');
  1213. logger.log('switched back to local video');
  1214. if (!this.localVideo && wasVideoMuted) {
  1215. return Promise.reject('No local video to be muted!');
  1216. } else if (wasVideoMuted && this.localVideo) {
  1217. return this.localVideo.mute();
  1218. }
  1219. })
  1220. .catch(error => {
  1221. logger.error('failed to switch back to local video', error);
  1222. return this.useVideoStream(null).then(() => {
  1223. // Still fail with the original err
  1224. return Promise.reject(error);
  1225. });
  1226. });
  1227. } else {
  1228. promise = this.useVideoStream(null);
  1229. }
  1230. return promise.then(
  1231. () => {
  1232. this.videoSwitchInProgress = false;
  1233. },
  1234. error => {
  1235. this.videoSwitchInProgress = false;
  1236. throw error;
  1237. });
  1238. },
  1239. /**
  1240. * Toggles between screen sharing and camera video if the toggle parameter
  1241. * is not specified and starts the procedure for obtaining new screen
  1242. * sharing/video track otherwise.
  1243. *
  1244. * @param {boolean} [toggle] - If true - new screen sharing track will be
  1245. * obtained. If false - new video track will be obtain. If not specified -
  1246. * toggles between screen sharing and camera video.
  1247. * @param {Object} [options] - Screen sharing options that will be passed to
  1248. * createLocalTracks.
  1249. * @param {Array<string>} [options.desktopSharingSources] - Array with the
  1250. * sources that have to be displayed in the desktop picker window ('screen',
  1251. * 'window', etc.).
  1252. * @return {Promise.<T>}
  1253. */
  1254. toggleScreenSharing(toggle = !this._untoggleScreenSharing, options = {}) {
  1255. if (this.videoSwitchInProgress) {
  1256. return Promise.reject('Switch in progress.');
  1257. }
  1258. if (!this.isDesktopSharingEnabled) {
  1259. return Promise.reject(
  1260. 'Cannot toggle screen sharing: not supported.');
  1261. }
  1262. if (this.isAudioOnly()) {
  1263. this._displayAudioOnlyTooltip('screenShare');
  1264. return Promise.reject('No screensharing in audio only mode');
  1265. }
  1266. if (toggle) {
  1267. return this._switchToScreenSharing(options);
  1268. } else {
  1269. return this._untoggleScreenSharing();
  1270. }
  1271. },
  1272. /**
  1273. * Creates desktop (screensharing) {@link JitsiLocalTrack}
  1274. * @param {Object} [options] - Screen sharing options that will be passed to
  1275. * createLocalTracks.
  1276. *
  1277. * @return {Promise.<JitsiLocalTrack>} - A Promise resolved with
  1278. * {@link JitsiLocalTrack} for the screensharing or rejected with
  1279. * {@link JitsiTrackError}.
  1280. *
  1281. * @private
  1282. */
  1283. _createDesktopTrack(options = {}) {
  1284. let externalInstallation = false;
  1285. let DSExternalInstallationInProgress = false;
  1286. const didHaveVideo = Boolean(this.localVideo);
  1287. const wasVideoMuted = this.isLocalVideoMuted();
  1288. return createLocalTracksF({
  1289. desktopSharingSources: options.desktopSharingSources,
  1290. devices: ['desktop'],
  1291. desktopSharingExtensionExternalInstallation: {
  1292. interval: 500,
  1293. checkAgain: () => DSExternalInstallationInProgress,
  1294. listener: (status, url) => {
  1295. switch(status) {
  1296. case "waitingForExtension": {
  1297. DSExternalInstallationInProgress = true;
  1298. externalInstallation = true;
  1299. const listener = () => {
  1300. // Wait a little bit more just to be sure that we
  1301. // won't miss the extension installation
  1302. setTimeout(
  1303. () => {
  1304. DSExternalInstallationInProgress = false;
  1305. },
  1306. 500);
  1307. APP.UI.removeListener(
  1308. UIEvents.EXTERNAL_INSTALLATION_CANCELED,
  1309. listener);
  1310. };
  1311. APP.UI.addListener(
  1312. UIEvents.EXTERNAL_INSTALLATION_CANCELED,
  1313. listener);
  1314. APP.UI.showExtensionExternalInstallationDialog(url);
  1315. break;
  1316. }
  1317. case "extensionFound":
  1318. // Close the dialog.
  1319. externalInstallation && $.prompt.close();
  1320. break;
  1321. default:
  1322. // Unknown status
  1323. }
  1324. }
  1325. }
  1326. }).then(([desktopStream]) => {
  1327. // Stores the "untoggle" handler which remembers whether was
  1328. // there any video before and whether was it muted.
  1329. this._untoggleScreenSharing
  1330. = this._turnScreenSharingOff
  1331. .bind(this, didHaveVideo, wasVideoMuted);
  1332. desktopStream.on(
  1333. TrackEvents.LOCAL_TRACK_STOPPED,
  1334. () => {
  1335. // If the stream was stopped during screen sharing
  1336. // session then we should switch back to video.
  1337. this.isSharingScreen
  1338. && this._untoggleScreenSharing
  1339. && this._untoggleScreenSharing();
  1340. }
  1341. );
  1342. // close external installation dialog on success.
  1343. externalInstallation && $.prompt.close();
  1344. return desktopStream;
  1345. }, error => {
  1346. DSExternalInstallationInProgress = false;
  1347. // close external installation dialog on success.
  1348. externalInstallation && $.prompt.close();
  1349. throw error;
  1350. });
  1351. },
  1352. /**
  1353. * Tries to switch to the screenshairng mode by disposing camera stream and
  1354. * replacing it with a desktop one.
  1355. *
  1356. * @param {Object} [options] - Screen sharing options that will be passed to
  1357. * createLocalTracks.
  1358. *
  1359. * @return {Promise} - A Promise resolved if the operation succeeds or
  1360. * rejected with some unknown type of error in case it fails. Promise will
  1361. * be rejected immediately if {@link videoSwitchInProgress} is true.
  1362. *
  1363. * @private
  1364. */
  1365. _switchToScreenSharing(options = {}) {
  1366. if (this.videoSwitchInProgress) {
  1367. return Promise.reject('Switch in progress.');
  1368. }
  1369. this.videoSwitchInProgress = true;
  1370. return this._createDesktopTrack(options).then(stream => {
  1371. return this.useVideoStream(stream);
  1372. }).then(() => {
  1373. this.videoSwitchInProgress = false;
  1374. JitsiMeetJS.analytics.sendEvent('conference.sharingDesktop.start');
  1375. logger.log('sharing local desktop');
  1376. }).catch(error => {
  1377. this.videoSwitchInProgress = false;
  1378. // Pawel: With this call I'm trying to preserve the original
  1379. // behaviour although it is not clear why would we "untoggle"
  1380. // on failure. I suppose it was to restore video in case there
  1381. // was some problem during "this.useVideoStream(desktopStream)".
  1382. // It's important to note that the handler will not be available
  1383. // if we fail early on trying to get desktop media (which makes
  1384. // sense, because the camera video is still being used, so
  1385. // nothing to "untoggle").
  1386. if (this._untoggleScreenSharing) {
  1387. this._untoggleScreenSharing();
  1388. }
  1389. // FIXME the code inside of _handleScreenSharingError is
  1390. // asynchronous, but does not return a Promise and is not part of
  1391. // the current Promise chain.
  1392. this._handleScreenSharingError(error);
  1393. return Promise.reject(error);
  1394. });
  1395. },
  1396. /**
  1397. * Handles {@link JitsiTrackError} returned by the lib-jitsi-meet when
  1398. * trying to create screensharing track. It will either do nothing if
  1399. * the dialog was canceled on user's request or display inline installation
  1400. * dialog and ask the user to install the extension, once the extension is
  1401. * installed it will switch the conference to screensharing. The last option
  1402. * is that an unrecoverable error dialog will be displayed.
  1403. * @param {JitsiTrackError} error - The error returned by
  1404. * {@link _createDesktopTrack} Promise.
  1405. * @private
  1406. */
  1407. _handleScreenSharingError(error) {
  1408. if (error.name === TrackErrors.CHROME_EXTENSION_USER_CANCELED) {
  1409. return;
  1410. }
  1411. logger.error('failed to share local desktop', error);
  1412. if (error.name === TrackErrors.CHROME_EXTENSION_USER_GESTURE_REQUIRED) {
  1413. // If start with screen sharing the extension will fail to install
  1414. // (if not found), because the request has been triggered by the
  1415. // script. Show a dialog which asks user to click "install" and try
  1416. // again switching to the screen sharing.
  1417. APP.UI.showExtensionInlineInstallationDialog(
  1418. () => {
  1419. this.toggleScreenSharing().catch(() => {});
  1420. }
  1421. );
  1422. return;
  1423. } else if (error.name === TrackErrors.FIREFOX_EXTENSION_NEEDED) {
  1424. APP.UI.showExtensionRequiredDialog(
  1425. config.desktopSharingFirefoxExtensionURL
  1426. );
  1427. return;
  1428. }
  1429. // Handling:
  1430. // TrackErrors.PERMISSION_DENIED
  1431. // TrackErrors.CHROME_EXTENSION_INSTALLATION_ERROR
  1432. // TrackErrors.GENERAL
  1433. // and any other
  1434. let dialogTxt;
  1435. let dialogTitleKey;
  1436. if (error.name === TrackErrors.PERMISSION_DENIED) {
  1437. dialogTxt = APP.translation.generateTranslationHTML(
  1438. "dialog.screenSharingPermissionDeniedError");
  1439. dialogTitleKey = "dialog.error";
  1440. } else {
  1441. dialogTxt = APP.translation.generateTranslationHTML(
  1442. "dialog.failtoinstall");
  1443. dialogTitleKey = "dialog.permissionDenied";
  1444. }
  1445. APP.UI.messageHandler.openDialog(dialogTitleKey, dialogTxt, false);
  1446. },
  1447. /**
  1448. * Setup interaction between conference and UI.
  1449. */
  1450. _setupListeners() {
  1451. // add local streams when joined to the conference
  1452. room.on(ConferenceEvents.CONFERENCE_JOINED, () => {
  1453. APP.store.dispatch(conferenceJoined(room));
  1454. APP.UI.mucJoined();
  1455. APP.API.notifyConferenceJoined(APP.conference.roomName);
  1456. APP.UI.markVideoInterrupted(false);
  1457. });
  1458. room.on(
  1459. ConferenceEvents.CONFERENCE_LEFT,
  1460. (...args) => APP.store.dispatch(conferenceLeft(room, ...args)));
  1461. room.on(
  1462. ConferenceEvents.AUTH_STATUS_CHANGED,
  1463. (authEnabled, authLogin) =>
  1464. APP.UI.updateAuthInfo(authEnabled, authLogin));
  1465. room.on(ConferenceEvents.PARTCIPANT_FEATURES_CHANGED,
  1466. user => APP.UI.onUserFeaturesChanged(user));
  1467. room.on(ConferenceEvents.USER_JOINED, (id, user) => {
  1468. if (user.isHidden())
  1469. return;
  1470. APP.store.dispatch(participantJoined({
  1471. id,
  1472. name: user.getDisplayName(),
  1473. role: user.getRole()
  1474. }));
  1475. logger.log('USER %s connnected', id, user);
  1476. APP.API.notifyUserJoined(id);
  1477. APP.UI.addUser(user);
  1478. // check the roles for the new user and reflect them
  1479. APP.UI.updateUserRole(user);
  1480. });
  1481. room.on(ConferenceEvents.USER_LEFT, (id, user) => {
  1482. APP.store.dispatch(participantLeft(id, user));
  1483. logger.log('USER %s LEFT', id, user);
  1484. APP.API.notifyUserLeft(id);
  1485. APP.UI.removeUser(id, user.getDisplayName());
  1486. APP.UI.onSharedVideoStop(id);
  1487. });
  1488. room.on(ConferenceEvents.USER_STATUS_CHANGED, (id, status) => {
  1489. APP.store.dispatch(participantPresenceChanged(id, status));
  1490. let user = room.getParticipantById(id);
  1491. if (user) {
  1492. APP.UI.updateUserStatus(user, status);
  1493. }
  1494. });
  1495. room.on(ConferenceEvents.USER_ROLE_CHANGED, (id, role) => {
  1496. if (this.isLocalId(id)) {
  1497. logger.info(`My role changed, new role: ${role}`);
  1498. APP.store.dispatch(localParticipantRoleChanged(role));
  1499. if (this.isModerator !== room.isModerator()) {
  1500. this.isModerator = room.isModerator();
  1501. APP.UI.updateLocalRole(room.isModerator());
  1502. }
  1503. } else {
  1504. APP.store.dispatch(participantRoleChanged(id, role));
  1505. let user = room.getParticipantById(id);
  1506. if (user) {
  1507. APP.UI.updateUserRole(user);
  1508. }
  1509. }
  1510. });
  1511. room.on(ConferenceEvents.TRACK_ADDED, (track) => {
  1512. if (!track || track.isLocal())
  1513. return;
  1514. APP.store.dispatch(trackAdded(track));
  1515. });
  1516. room.on(ConferenceEvents.TRACK_REMOVED, (track) => {
  1517. if (!track || track.isLocal())
  1518. return;
  1519. APP.store.dispatch(trackRemoved(track));
  1520. });
  1521. room.on(ConferenceEvents.TRACK_AUDIO_LEVEL_CHANGED, (id, lvl) => {
  1522. if (this.isLocalId(id)
  1523. && this.localAudio && this.localAudio.isMuted()) {
  1524. lvl = 0;
  1525. }
  1526. if (config.debug) {
  1527. this.audioLevelsMap[id] = lvl;
  1528. if (config.debugAudioLevels)
  1529. logger.log("AudioLevel:" + id + "/" + lvl);
  1530. }
  1531. APP.UI.setAudioLevel(id, lvl);
  1532. });
  1533. room.on(ConferenceEvents.TALK_WHILE_MUTED, () => {
  1534. APP.UI.showToolbar(6000);
  1535. APP.UI.showCustomToolbarPopup(
  1536. 'microphone', 'talkWhileMutedPopup', true, 5000);
  1537. });
  1538. room.on(
  1539. ConferenceEvents.LAST_N_ENDPOINTS_CHANGED,
  1540. (leavingIds, enteringIds) =>
  1541. APP.UI.handleLastNEndpoints(leavingIds, enteringIds));
  1542. room.on(
  1543. ConferenceEvents.P2P_STATUS,
  1544. (jitsiConference, p2p) => APP.store.dispatch(p2pStatusChanged(p2p)));
  1545. room.on(
  1546. ConferenceEvents.PARTICIPANT_CONN_STATUS_CHANGED,
  1547. (id, connectionStatus) => {
  1548. APP.store.dispatch(participantConnectionStatusChanged(
  1549. id, connectionStatus));
  1550. APP.UI.participantConnectionStatusChanged(id);
  1551. });
  1552. room.on(ConferenceEvents.DOMINANT_SPEAKER_CHANGED, (id) => {
  1553. APP.store.dispatch(dominantSpeakerChanged(id));
  1554. if (this.isLocalId(id)) {
  1555. this.isDominantSpeaker = true;
  1556. this.setRaisedHand(false);
  1557. } else {
  1558. this.isDominantSpeaker = false;
  1559. var participant = room.getParticipantById(id);
  1560. if (participant) {
  1561. APP.UI.setRaisedHandStatus(participant, false);
  1562. }
  1563. }
  1564. APP.UI.markDominantSpeaker(id);
  1565. });
  1566. if (!interfaceConfig.filmStripOnly) {
  1567. room.on(ConferenceEvents.CONNECTION_INTERRUPTED, () => {
  1568. APP.UI.markVideoInterrupted(true);
  1569. });
  1570. room.on(ConferenceEvents.CONNECTION_RESTORED, () => {
  1571. APP.UI.markVideoInterrupted(false);
  1572. });
  1573. if (isButtonEnabled('chat')) {
  1574. room.on(ConferenceEvents.MESSAGE_RECEIVED, (id, body, ts) => {
  1575. let nick = getDisplayName(id);
  1576. APP.API.notifyReceivedChatMessage({
  1577. id,
  1578. nick,
  1579. body,
  1580. ts
  1581. });
  1582. APP.UI.addMessage(id, nick, body, ts);
  1583. });
  1584. APP.UI.addListener(UIEvents.MESSAGE_CREATED, (message) => {
  1585. APP.API.notifySendingChatMessage(message);
  1586. room.sendTextMessage(message);
  1587. });
  1588. }
  1589. APP.UI.addListener(UIEvents.SELECTED_ENDPOINT, (id) => {
  1590. try {
  1591. // do not try to select participant if there is none (we
  1592. // are alone in the room), otherwise an error will be
  1593. // thrown cause reporting mechanism is not available
  1594. // (datachannels currently)
  1595. if (room.getParticipants().length === 0)
  1596. return;
  1597. room.selectParticipant(id);
  1598. } catch (e) {
  1599. JitsiMeetJS.analytics.sendEvent(
  1600. 'selectParticipant.failed');
  1601. reportError(e);
  1602. }
  1603. });
  1604. APP.UI.addListener(
  1605. UIEvents.VIDEO_UNMUTING_WHILE_AUDIO_ONLY,
  1606. () => this._displayAudioOnlyTooltip('videoMute'));
  1607. }
  1608. room.on(ConferenceEvents.CONNECTION_INTERRUPTED, () => {
  1609. APP.store.dispatch(localParticipantConnectionStatusChanged(
  1610. participantConnectionStatus.INTERRUPTED));
  1611. APP.UI.showLocalConnectionInterrupted(true);
  1612. });
  1613. room.on(ConferenceEvents.CONNECTION_RESTORED, () => {
  1614. APP.store.dispatch(localParticipantConnectionStatusChanged(
  1615. participantConnectionStatus.ACTIVE));
  1616. APP.UI.showLocalConnectionInterrupted(false);
  1617. });
  1618. room.on(ConferenceEvents.DISPLAY_NAME_CHANGED, (id, displayName) => {
  1619. const formattedDisplayName
  1620. = displayName.substr(0, MAX_DISPLAY_NAME_LENGTH);
  1621. APP.store.dispatch(participantUpdated({
  1622. id,
  1623. name: formattedDisplayName
  1624. }));
  1625. APP.API.notifyDisplayNameChanged(id, formattedDisplayName);
  1626. APP.UI.changeDisplayName(id, formattedDisplayName);
  1627. });
  1628. room.on(
  1629. ConferenceEvents.LOCK_STATE_CHANGED,
  1630. (...args) => APP.store.dispatch(lockStateChanged(room, ...args)));
  1631. APP.remoteControl.on(RemoteControlEvents.ACTIVE_CHANGED, isActive => {
  1632. room.setLocalParticipantProperty(
  1633. "remoteControlSessionStatus",
  1634. isActive
  1635. );
  1636. APP.UI.setLocalRemoteControlActiveChanged();
  1637. });
  1638. room.on(
  1639. ConferenceEvents.PARTICIPANT_PROPERTY_CHANGED,
  1640. (participant, name, oldValue, newValue) => {
  1641. switch (name) {
  1642. case 'raisedHand':
  1643. APP.UI.setRaisedHandStatus(participant, newValue);
  1644. break;
  1645. case 'remoteControlSessionStatus':
  1646. APP.UI.setRemoteControlActiveStatus(
  1647. participant.getId(),
  1648. newValue);
  1649. break;
  1650. default:
  1651. // ignore
  1652. }
  1653. });
  1654. room.on(ConferenceEvents.RECORDER_STATE_CHANGED, (status, error) => {
  1655. logger.log("Received recorder status change: ", status, error);
  1656. APP.UI.updateRecordingState(status);
  1657. });
  1658. room.on(ConferenceEvents.KICKED, () => {
  1659. APP.UI.hideStats();
  1660. APP.UI.notifyKicked();
  1661. // FIXME close
  1662. });
  1663. room.on(ConferenceEvents.SUSPEND_DETECTED, () => {
  1664. APP.store.dispatch(suspendDetected());
  1665. // After wake up, we will be in a state where conference is left
  1666. // there will be dialog shown to user.
  1667. // We do not want video/audio as we show an overlay and after it
  1668. // user need to rejoin or close, while waking up we can detect
  1669. // camera wakeup as a problem with device.
  1670. // We also do not care about device change, which happens
  1671. // on resume after suspending PC.
  1672. if (this.deviceChangeListener)
  1673. JitsiMeetJS.mediaDevices.removeEventListener(
  1674. JitsiMeetJS.events.mediaDevices.DEVICE_LIST_CHANGED,
  1675. this.deviceChangeListener);
  1676. // stop local video
  1677. if (this.localVideo) {
  1678. this.localVideo.dispose();
  1679. this.localVideo = null;
  1680. }
  1681. // stop local audio
  1682. if (this.localAudio) {
  1683. this.localAudio.dispose();
  1684. this.localAudio = null;
  1685. }
  1686. });
  1687. room.on(ConferenceEvents.DTMF_SUPPORT_CHANGED, (isDTMFSupported) => {
  1688. APP.UI.updateDTMFSupport(isDTMFSupported);
  1689. });
  1690. APP.UI.addListener(UIEvents.AUDIO_MUTED, muted => {
  1691. this.muteAudio(muted);
  1692. });
  1693. APP.UI.addListener(UIEvents.VIDEO_MUTED, muted => {
  1694. if (this.isAudioOnly() && !muted) {
  1695. this._displayAudioOnlyTooltip('videoMute');
  1696. } else {
  1697. this.muteVideo(muted);
  1698. }
  1699. });
  1700. statsEmitter.startListeningForStats(room);
  1701. room.addCommandListener(this.commands.defaults.ETHERPAD, ({value}) => {
  1702. APP.UI.initEtherpad(value);
  1703. });
  1704. APP.UI.addListener(UIEvents.EMAIL_CHANGED, this.changeLocalEmail);
  1705. room.addCommandListener(this.commands.defaults.EMAIL, (data, from) => {
  1706. APP.store.dispatch(participantUpdated({
  1707. id: from,
  1708. email: data.value
  1709. }));
  1710. APP.UI.setUserEmail(from, data.value);
  1711. });
  1712. room.addCommandListener(
  1713. this.commands.defaults.AVATAR_URL,
  1714. (data, from) => {
  1715. APP.store.dispatch(
  1716. participantUpdated({
  1717. id: from,
  1718. avatarURL: data.value
  1719. }));
  1720. APP.UI.setUserAvatarUrl(from, data.value);
  1721. });
  1722. room.addCommandListener(this.commands.defaults.AVATAR_ID,
  1723. (data, from) => {
  1724. APP.store.dispatch(
  1725. participantUpdated({
  1726. id: from,
  1727. avatarID: data.value
  1728. }));
  1729. APP.UI.setUserAvatarID(from, data.value);
  1730. });
  1731. APP.UI.addListener(UIEvents.NICKNAME_CHANGED,
  1732. this.changeLocalDisplayName.bind(this));
  1733. APP.UI.addListener(UIEvents.START_MUTED_CHANGED,
  1734. (startAudioMuted, startVideoMuted) => {
  1735. room.setStartMutedPolicy({
  1736. audio: startAudioMuted,
  1737. video: startVideoMuted
  1738. });
  1739. }
  1740. );
  1741. room.on(
  1742. ConferenceEvents.START_MUTED_POLICY_CHANGED,
  1743. ({ audio, video }) => {
  1744. APP.UI.onStartMutedChanged(audio, video);
  1745. }
  1746. );
  1747. room.on(ConferenceEvents.STARTED_MUTED, () => {
  1748. (room.isStartAudioMuted() || room.isStartVideoMuted())
  1749. && APP.UI.notifyInitiallyMuted();
  1750. });
  1751. room.on(
  1752. ConferenceEvents.AVAILABLE_DEVICES_CHANGED, function (id, devices) {
  1753. APP.UI.updateDevicesAvailability(id, devices);
  1754. }
  1755. );
  1756. room.on(
  1757. ConferenceEvents.DATA_CHANNEL_OPENED, () => {
  1758. APP.store.dispatch(dataChannelOpened());
  1759. }
  1760. );
  1761. // call hangup
  1762. APP.UI.addListener(UIEvents.HANGUP, () => {
  1763. this.hangup(true);
  1764. });
  1765. // logout
  1766. APP.UI.addListener(UIEvents.LOGOUT, () => {
  1767. AuthHandler.logout(room).then(url => {
  1768. if (url) {
  1769. UIUtil.redirect(url);
  1770. } else {
  1771. this.hangup(true);
  1772. }
  1773. });
  1774. });
  1775. APP.UI.addListener(
  1776. UIEvents.RESOLUTION_CHANGED,
  1777. (id, oldResolution, newResolution, delay) => {
  1778. var logObject = {
  1779. id: "resolution_change",
  1780. participant: id,
  1781. oldValue: oldResolution,
  1782. newValue: newResolution,
  1783. delay: delay
  1784. };
  1785. room.sendApplicationLog(JSON.stringify(logObject));
  1786. // We only care about the delay between simulcast streams.
  1787. // Longer delays will be caused by something else and will just
  1788. // poison the data.
  1789. if (delay < 2000) {
  1790. JitsiMeetJS.analytics.sendEvent('stream.switch.delay',
  1791. {value: delay});
  1792. }
  1793. });
  1794. // Starts or stops the recording for the conference.
  1795. APP.UI.addListener(UIEvents.RECORDING_TOGGLED, (options) => {
  1796. room.toggleRecording(options);
  1797. });
  1798. APP.UI.addListener(UIEvents.SUBJECT_CHANGED, (topic) => {
  1799. room.setSubject(topic);
  1800. });
  1801. room.on(ConferenceEvents.SUBJECT_CHANGED, function (subject) {
  1802. APP.UI.setSubject(subject);
  1803. });
  1804. APP.UI.addListener(UIEvents.USER_KICKED, (id) => {
  1805. room.kickParticipant(id);
  1806. });
  1807. APP.UI.addListener(UIEvents.REMOTE_AUDIO_MUTED, (id) => {
  1808. room.muteParticipant(id);
  1809. });
  1810. APP.UI.addListener(UIEvents.AUTH_CLICKED, () => {
  1811. AuthHandler.authenticate(room);
  1812. });
  1813. APP.UI.addListener(
  1814. UIEvents.VIDEO_DEVICE_CHANGED,
  1815. (cameraDeviceId) => {
  1816. JitsiMeetJS.analytics.sendEvent('settings.changeDevice.video');
  1817. createLocalTracksF({
  1818. devices: ['video'],
  1819. cameraDeviceId: cameraDeviceId,
  1820. micDeviceId: null
  1821. })
  1822. .then(([stream]) => {
  1823. if (this.isAudioOnly()) {
  1824. return stream.mute()
  1825. .then(() => stream);
  1826. }
  1827. return stream;
  1828. })
  1829. .then(stream => {
  1830. this.useVideoStream(stream);
  1831. logger.log('switched local video device');
  1832. APP.settings.setCameraDeviceId(cameraDeviceId, true);
  1833. })
  1834. .catch((err) => {
  1835. APP.UI.showCameraErrorNotification(err);
  1836. });
  1837. }
  1838. );
  1839. APP.UI.addListener(
  1840. UIEvents.AUDIO_DEVICE_CHANGED,
  1841. (micDeviceId) => {
  1842. JitsiMeetJS.analytics.sendEvent(
  1843. 'settings.changeDevice.audioIn');
  1844. createLocalTracksF({
  1845. devices: ['audio'],
  1846. cameraDeviceId: null,
  1847. micDeviceId: micDeviceId
  1848. })
  1849. .then(([stream]) => {
  1850. this.useAudioStream(stream);
  1851. logger.log('switched local audio device');
  1852. APP.settings.setMicDeviceId(micDeviceId, true);
  1853. })
  1854. .catch((err) => {
  1855. APP.UI.showMicErrorNotification(err);
  1856. });
  1857. }
  1858. );
  1859. APP.UI.addListener(
  1860. UIEvents.AUDIO_OUTPUT_DEVICE_CHANGED,
  1861. (audioOutputDeviceId) => {
  1862. JitsiMeetJS.analytics.sendEvent(
  1863. 'settings.changeDevice.audioOut');
  1864. APP.settings.setAudioOutputDeviceId(audioOutputDeviceId)
  1865. .then(() => logger.log('changed audio output device'))
  1866. .catch((err) => {
  1867. logger.warn('Failed to change audio output device. ' +
  1868. 'Default or previously set audio output device ' +
  1869. 'will be used instead.', err);
  1870. });
  1871. }
  1872. );
  1873. APP.UI.addListener(UIEvents.TOGGLE_AUDIO_ONLY, audioOnly => {
  1874. // FIXME On web video track is stored both in redux and in
  1875. // 'localVideo' field, video is attempted to be unmuted twice when
  1876. // turning off the audio only mode. This will crash the app with
  1877. // 'unmute operation is already in progress'.
  1878. // Because there's no logic in redux about creating new track in
  1879. // case unmute when not track exists the things have to go through
  1880. // muteVideo logic in such case.
  1881. const tracks = APP.store.getState()['features/base/tracks'];
  1882. const isTrackInRedux
  1883. = Boolean(
  1884. tracks.find(
  1885. track => track.jitsiTrack
  1886. && track.jitsiTrack.getType() === 'video'));
  1887. if (!isTrackInRedux) {
  1888. this.muteVideo(audioOnly);
  1889. }
  1890. // Immediately update the UI by having remote videos and the large
  1891. // video update themselves instead of waiting for some other event
  1892. // to cause the update, usually PARTICIPANT_CONN_STATUS_CHANGED.
  1893. // There is no guarantee another event will trigger the update
  1894. // immediately and in all situations, for example because a remote
  1895. // participant is having connection trouble so no status changes.
  1896. APP.UI.updateAllVideos();
  1897. });
  1898. APP.UI.addListener(
  1899. UIEvents.TOGGLE_SCREENSHARING, this.toggleScreenSharing.bind(this)
  1900. );
  1901. APP.UI.addListener(
  1902. UIEvents.UPDATE_SHARED_VIDEO,
  1903. (url, state, time, isMuted, volume) => {
  1904. // send start and stop commands once, and remove any updates
  1905. // that had left
  1906. if (state === 'stop'
  1907. || state === 'start'
  1908. || state === 'playing') {
  1909. room.removeCommand(this.commands.defaults.SHARED_VIDEO);
  1910. room.sendCommandOnce(this.commands.defaults.SHARED_VIDEO, {
  1911. value: url,
  1912. attributes: {
  1913. state: state,
  1914. time: time,
  1915. muted: isMuted,
  1916. volume: volume
  1917. }
  1918. });
  1919. }
  1920. else {
  1921. // in case of paused, in order to allow late users to join
  1922. // paused
  1923. room.removeCommand(this.commands.defaults.SHARED_VIDEO);
  1924. room.sendCommand(this.commands.defaults.SHARED_VIDEO, {
  1925. value: url,
  1926. attributes: {
  1927. state: state,
  1928. time: time,
  1929. muted: isMuted,
  1930. volume: volume
  1931. }
  1932. });
  1933. }
  1934. });
  1935. room.addCommandListener(
  1936. this.commands.defaults.SHARED_VIDEO, ({value, attributes}, id) => {
  1937. if (attributes.state === 'stop') {
  1938. APP.UI.onSharedVideoStop(id, attributes);
  1939. }
  1940. else if (attributes.state === 'start') {
  1941. APP.UI.onSharedVideoStart(id, value, attributes);
  1942. }
  1943. else if (attributes.state === 'playing'
  1944. || attributes.state === 'pause') {
  1945. APP.UI.onSharedVideoUpdate(id, value, attributes);
  1946. }
  1947. });
  1948. },
  1949. /**
  1950. * Adds any room listener.
  1951. * @param {string} eventName one of the ConferenceEvents
  1952. * @param {Function} listener the function to be called when the event
  1953. * occurs
  1954. */
  1955. addConferenceListener(eventName, listener) {
  1956. room.on(eventName, listener);
  1957. },
  1958. /**
  1959. * Removes any room listener.
  1960. * @param {string} eventName one of the ConferenceEvents
  1961. * @param {Function} listener the listener to be removed.
  1962. */
  1963. removeConferenceListener(eventName, listener) {
  1964. room.off(eventName, listener);
  1965. },
  1966. /**
  1967. * Inits list of current devices and event listener for device change.
  1968. * @private
  1969. */
  1970. _initDeviceList() {
  1971. JitsiMeetJS.mediaDevices.isDeviceListAvailable()
  1972. .then(isDeviceListAvailable => {
  1973. if (isDeviceListAvailable
  1974. && JitsiMeetJS.mediaDevices.isDeviceChangeAvailable()) {
  1975. JitsiMeetJS.mediaDevices.enumerateDevices(devices => {
  1976. // Ugly way to synchronize real device IDs with local
  1977. // storage and settings menu. This is a workaround until
  1978. // getConstraints() method will be implemented
  1979. // in browsers.
  1980. if (this.localAudio) {
  1981. APP.settings.setMicDeviceId(
  1982. this.localAudio.getDeviceId(), false);
  1983. }
  1984. if (this.localVideo) {
  1985. APP.settings.setCameraDeviceId(
  1986. this.localVideo.getDeviceId(), false);
  1987. }
  1988. mediaDeviceHelper.setCurrentMediaDevices(devices);
  1989. APP.UI.onAvailableDevicesChanged(devices);
  1990. APP.store.dispatch(updateDeviceList(devices));
  1991. });
  1992. this.deviceChangeListener = (devices) =>
  1993. window.setTimeout(
  1994. () => this._onDeviceListChanged(devices), 0);
  1995. JitsiMeetJS.mediaDevices.addEventListener(
  1996. JitsiMeetJS.events.mediaDevices.DEVICE_LIST_CHANGED,
  1997. this.deviceChangeListener);
  1998. }
  1999. })
  2000. .catch((error) => {
  2001. logger.warn(`Error getting device list: ${error}`);
  2002. });
  2003. },
  2004. /**
  2005. * Event listener for JitsiMediaDevicesEvents.DEVICE_LIST_CHANGED to
  2006. * handle change of available media devices.
  2007. * @private
  2008. * @param {MediaDeviceInfo[]} devices
  2009. * @returns {Promise}
  2010. */
  2011. _onDeviceListChanged(devices) {
  2012. let currentDevices = mediaDeviceHelper.getCurrentMediaDevices();
  2013. // Event handler can be fired before direct
  2014. // enumerateDevices() call, so handle this situation here.
  2015. if (!currentDevices.audioinput &&
  2016. !currentDevices.videoinput &&
  2017. !currentDevices.audiooutput) {
  2018. mediaDeviceHelper.setCurrentMediaDevices(devices);
  2019. currentDevices = mediaDeviceHelper.getCurrentMediaDevices();
  2020. }
  2021. let newDevices =
  2022. mediaDeviceHelper.getNewMediaDevicesAfterDeviceListChanged(
  2023. devices,
  2024. this.isSharingScreen,
  2025. this.localVideo,
  2026. this.localAudio);
  2027. let promises = [];
  2028. let audioWasMuted = this.isLocalAudioMuted();
  2029. let videoWasMuted = this.isLocalVideoMuted();
  2030. let availableAudioInputDevices =
  2031. mediaDeviceHelper.getDevicesFromListByKind(devices, 'audioinput');
  2032. let availableVideoInputDevices =
  2033. mediaDeviceHelper.getDevicesFromListByKind(devices, 'videoinput');
  2034. if (typeof newDevices.audiooutput !== 'undefined') {
  2035. // Just ignore any errors in catch block.
  2036. promises.push(APP.settings
  2037. .setAudioOutputDeviceId(newDevices.audiooutput)
  2038. .catch());
  2039. }
  2040. promises.push(
  2041. mediaDeviceHelper.createLocalTracksAfterDeviceListChanged(
  2042. createLocalTracksF,
  2043. newDevices.videoinput,
  2044. newDevices.audioinput)
  2045. .then(tracks =>
  2046. Promise.all(this._setLocalAudioVideoStreams(tracks)))
  2047. .then(() => {
  2048. // If audio was muted before, or we unplugged current device
  2049. // and selected new one, then mute new audio track.
  2050. if (audioWasMuted ||
  2051. currentDevices.audioinput.length >
  2052. availableAudioInputDevices.length) {
  2053. muteLocalAudio(true);
  2054. }
  2055. // If video was muted before, or we unplugged current device
  2056. // and selected new one, then mute new video track.
  2057. if (!this.isSharingScreen &&
  2058. (videoWasMuted ||
  2059. currentDevices.videoinput.length >
  2060. availableVideoInputDevices.length)) {
  2061. muteLocalVideo(true);
  2062. }
  2063. }));
  2064. return Promise.all(promises)
  2065. .then(() => {
  2066. mediaDeviceHelper.setCurrentMediaDevices(devices);
  2067. APP.UI.onAvailableDevicesChanged(devices);
  2068. });
  2069. },
  2070. /**
  2071. * Determines whether or not the audio button should be enabled.
  2072. */
  2073. updateAudioIconEnabled() {
  2074. const audioMediaDevices
  2075. = mediaDeviceHelper.getCurrentMediaDevices().audioinput;
  2076. const audioDeviceCount
  2077. = audioMediaDevices ? audioMediaDevices.length : 0;
  2078. // The audio functionality is considered available if there are any
  2079. // audio devices detected or if the local audio stream already exists.
  2080. const available = audioDeviceCount > 0 || Boolean(this.localAudio);
  2081. logger.debug(
  2082. 'Microphone button enabled: ' + available,
  2083. 'local audio: ' + this.localAudio,
  2084. 'audio devices: ' + audioMediaDevices,
  2085. 'device count: ' + audioDeviceCount);
  2086. APP.store.dispatch(setAudioAvailable(available));
  2087. APP.API.notifyAudioAvailabilityChanged(available);
  2088. },
  2089. /**
  2090. * Determines whether or not the video button should be enabled.
  2091. */
  2092. updateVideoIconEnabled() {
  2093. const videoMediaDevices
  2094. = mediaDeviceHelper.getCurrentMediaDevices().videoinput;
  2095. const videoDeviceCount
  2096. = videoMediaDevices ? videoMediaDevices.length : 0;
  2097. // The video functionality is considered available if there are any
  2098. // video devices detected or if there is local video stream already
  2099. // active which could be either screensharing stream or a video track
  2100. // created before the permissions were rejected (through browser
  2101. // config).
  2102. const available = videoDeviceCount > 0 || Boolean(this.localVideo);
  2103. logger.debug(
  2104. 'Camera button enabled: ' + available,
  2105. 'local video: ' + this.localVideo,
  2106. 'video devices: ' + videoMediaDevices,
  2107. 'device count: ' + videoDeviceCount);
  2108. APP.store.dispatch(setVideoAvailable(available));
  2109. APP.API.notifyVideoAvailabilityChanged(available);
  2110. },
  2111. /**
  2112. * Toggles the local "raised hand" status.
  2113. */
  2114. maybeToggleRaisedHand() {
  2115. this.setRaisedHand(!this.isHandRaised);
  2116. },
  2117. /**
  2118. * Sets the local "raised hand" status to a particular value.
  2119. */
  2120. setRaisedHand(raisedHand) {
  2121. if (raisedHand !== this.isHandRaised)
  2122. {
  2123. APP.UI.onLocalRaiseHandChanged(raisedHand);
  2124. this.isHandRaised = raisedHand;
  2125. // Advertise the updated status
  2126. room.setLocalParticipantProperty("raisedHand", raisedHand);
  2127. // Update the view
  2128. APP.UI.setLocalRaisedHandStatus(raisedHand);
  2129. }
  2130. },
  2131. /**
  2132. * Log event to callstats and analytics.
  2133. * @param {string} name the event name
  2134. * @param {int} value the value (it's int because google analytics supports
  2135. * only int).
  2136. * @param {string} label short text which provides more info about the event
  2137. * which allows to distinguish between few event cases of the same name
  2138. * NOTE: Should be used after conference.init
  2139. */
  2140. logEvent(name, value, label) {
  2141. if (JitsiMeetJS.analytics) {
  2142. JitsiMeetJS.analytics.sendEvent(name, {value, label});
  2143. }
  2144. if (room) {
  2145. room.sendApplicationLog(JSON.stringify({name, value, label}));
  2146. }
  2147. },
  2148. /**
  2149. * Methods logs an application event given in the JSON format.
  2150. * @param {string} logJSON an event to be logged in JSON format
  2151. */
  2152. logJSON(logJSON) {
  2153. if (room) {
  2154. room.sendApplicationLog(logJSON);
  2155. }
  2156. },
  2157. /**
  2158. * Disconnect from the conference and optionally request user feedback.
  2159. * @param {boolean} [requestFeedback=false] if user feedback should be
  2160. * requested
  2161. */
  2162. hangup(requestFeedback = false) {
  2163. eventEmitter.emit(JitsiMeetConferenceEvents.BEFORE_HANGUP);
  2164. let requestFeedbackPromise;
  2165. if (requestFeedback) {
  2166. requestFeedbackPromise
  2167. = APP.store.dispatch(maybeOpenFeedbackDialog(room))
  2168. // false because the thank you dialog shouldn't be displayed
  2169. .catch(() => Promise.resolve(false));
  2170. } else {
  2171. requestFeedbackPromise = Promise.resolve(true);
  2172. }
  2173. // All promises are returning Promise.resolve to make Promise.all to
  2174. // be resolved when both Promises are finished. Otherwise Promise.all
  2175. // will reject on first rejected Promise and we can redirect the page
  2176. // before all operations are done.
  2177. Promise.all([
  2178. requestFeedbackPromise,
  2179. room.leave().then(disconnect, disconnect)
  2180. ]).then(values => {
  2181. APP.API.notifyReadyToClose();
  2182. maybeRedirectToWelcomePage(values[0]);
  2183. });
  2184. },
  2185. /**
  2186. * Changes the email for the local user
  2187. * @param email {string} the new email
  2188. */
  2189. changeLocalEmail(email = '') {
  2190. email = String(email).trim();
  2191. if (email === APP.settings.getEmail()) {
  2192. return;
  2193. }
  2194. const localId = room ? room.myUserId() : undefined;
  2195. APP.store.dispatch(participantUpdated({
  2196. id: localId,
  2197. local: true,
  2198. email
  2199. }));
  2200. APP.settings.setEmail(email);
  2201. APP.UI.setUserEmail(localId, email);
  2202. sendData(commands.EMAIL, email);
  2203. },
  2204. /**
  2205. * Changes the avatar url for the local user
  2206. * @param url {string} the new url
  2207. */
  2208. changeLocalAvatarUrl(url = '') {
  2209. url = String(url).trim();
  2210. if (url === APP.settings.getAvatarUrl()) {
  2211. return;
  2212. }
  2213. const localId = room ? room.myUserId() : undefined;
  2214. APP.store.dispatch(participantUpdated({
  2215. id: localId,
  2216. local: true,
  2217. avatarURL: url
  2218. }));
  2219. APP.settings.setAvatarUrl(url);
  2220. APP.UI.setUserAvatarUrl(localId, url);
  2221. sendData(commands.AVATAR_URL, url);
  2222. },
  2223. /**
  2224. * Sends a message via the data channel.
  2225. * @param {string} to the id of the endpoint that should receive the
  2226. * message. If "" - the message will be sent to all participants.
  2227. * @param {object} payload the payload of the message.
  2228. * @throws NetworkError or InvalidStateError or Error if the operation
  2229. * fails.
  2230. */
  2231. sendEndpointMessage(to, payload) {
  2232. room.sendEndpointMessage(to, payload);
  2233. },
  2234. /**
  2235. * Adds new listener.
  2236. * @param {String} eventName the name of the event
  2237. * @param {Function} listener the listener.
  2238. */
  2239. addListener(eventName, listener) {
  2240. eventEmitter.addListener(eventName, listener);
  2241. },
  2242. /**
  2243. * Removes listener.
  2244. * @param {String} eventName the name of the event that triggers the
  2245. * listener
  2246. * @param {Function} listener the listener.
  2247. */
  2248. removeListener(eventName, listener) {
  2249. eventEmitter.removeListener(eventName, listener);
  2250. },
  2251. /**
  2252. * Changes the display name for the local user
  2253. * @param nickname {string} the new display name
  2254. */
  2255. changeLocalDisplayName(nickname = '') {
  2256. const formattedNickname
  2257. = nickname.trim().substr(0, MAX_DISPLAY_NAME_LENGTH);
  2258. if (formattedNickname === APP.settings.getDisplayName()) {
  2259. return;
  2260. }
  2261. APP.store.dispatch(participantUpdated({
  2262. id: this.getMyUserId(),
  2263. local: true,
  2264. name: formattedNickname
  2265. }));
  2266. APP.settings.setDisplayName(formattedNickname);
  2267. if (room) {
  2268. room.setDisplayName(formattedNickname);
  2269. APP.UI.changeDisplayName(this.getMyUserId(), formattedNickname);
  2270. }
  2271. },
  2272. /**
  2273. * Returns the desktop sharing source id or undefined if the desktop sharing
  2274. * is not active at the moment.
  2275. *
  2276. * @returns {string|undefined} - The source id. If the track is not desktop
  2277. * track or the source id is not available, undefined will be returned.
  2278. */
  2279. getDesktopSharingSourceId() {
  2280. return this.localVideo.sourceId;
  2281. },
  2282. /**
  2283. * Returns the desktop sharing source type or undefined if the desktop
  2284. * sharing is not active at the moment.
  2285. *
  2286. * @returns {'screen'|'window'|undefined} - The source type. If the track is
  2287. * not desktop track or the source type is not available, undefined will be
  2288. * returned.
  2289. */
  2290. getDesktopSharingSourceType() {
  2291. return this.localVideo.sourceType;
  2292. },
  2293. /**
  2294. * Sets the video muted status.
  2295. *
  2296. * @param {boolean} muted - New muted status.
  2297. */
  2298. setVideoMuteStatus(muted) {
  2299. APP.UI.setVideoMuted(this.getMyUserId(), muted);
  2300. APP.API.notifyVideoMutedStatusChanged(muted);
  2301. },
  2302. /**
  2303. * Sets the audio muted status.
  2304. *
  2305. * @param {boolean} muted - New muted status.
  2306. */
  2307. setAudioMuteStatus(muted) {
  2308. APP.UI.setAudioMuted(this.getMyUserId(), muted);
  2309. APP.API.notifyAudioMutedStatusChanged(muted);
  2310. }
  2311. };