You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

conference.js 90KB

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