Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

conference.js 90KB

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