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

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