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

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