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.

functions.ts 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407
  1. // @ts-expect-error
  2. import { API_ID } from '../../../modules/API/constants';
  3. import { getName as getAppName } from '../app/functions';
  4. import { IStore } from '../app/types';
  5. import { getAnalyticsRoomName } from '../base/conference/functions';
  6. import checkChromeExtensionsInstalled from '../base/environment/checkChromeExtensionsInstalled';
  7. import {
  8. isMobileBrowser
  9. } from '../base/environment/utils';
  10. import JitsiMeetJS, {
  11. analytics,
  12. browser
  13. } from '../base/lib-jitsi-meet';
  14. import { isAnalyticsEnabled } from '../base/lib-jitsi-meet/functions.any';
  15. import { getJitsiMeetGlobalNS } from '../base/util/helpers';
  16. import { inIframe } from '../base/util/iframeUtils';
  17. import { loadScript } from '../base/util/loadScript';
  18. import { parseURLParams } from '../base/util/parseURLParams';
  19. import { parseURIString } from '../base/util/uri';
  20. import { isPrejoinPageVisible } from '../prejoin/functions';
  21. import AmplitudeHandler from './handlers/AmplitudeHandler';
  22. import MatomoHandler from './handlers/MatomoHandler';
  23. import logger from './logger';
  24. /**
  25. * Sends an event through the lib-jitsi-meet AnalyticsAdapter interface.
  26. *
  27. * @param {Object} event - The event to send. It should be formatted as
  28. * described in AnalyticsAdapter.js in lib-jitsi-meet.
  29. * @returns {void}
  30. */
  31. export function sendAnalytics(event: Object) {
  32. try {
  33. analytics.sendEvent(event);
  34. } catch (e) {
  35. logger.warn(`Error sending analytics event: ${e}`);
  36. }
  37. }
  38. /**
  39. * Return saved amplitude identity info such as session id, device id and user id. We assume these do not change for
  40. * the duration of the conference.
  41. *
  42. * @returns {Object}
  43. */
  44. export function getAmplitudeIdentity() {
  45. return analytics.amplitudeIdentityProps;
  46. }
  47. /**
  48. * Resets the analytics adapter to its initial state - removes handlers, cache,
  49. * disabled state, etc.
  50. *
  51. * @returns {void}
  52. */
  53. export function resetAnalytics() {
  54. analytics.reset();
  55. }
  56. /**
  57. * Creates the analytics handlers.
  58. *
  59. * @param {Store} store - The redux store in which the specified {@code action} is being dispatched.
  60. * @returns {Promise} Resolves with the handlers that have been successfully loaded.
  61. */
  62. export async function createHandlers({ getState }: IStore) {
  63. getJitsiMeetGlobalNS().analyticsHandlers = [];
  64. if (!isAnalyticsEnabled(getState)) {
  65. // Avoid all analytics processing if there are no handlers, since no event would be sent.
  66. analytics.dispose();
  67. return [];
  68. }
  69. const state = getState();
  70. const config = state['features/base/config'];
  71. const { locationURL } = state['features/base/connection'];
  72. const host = locationURL ? locationURL.host : '';
  73. const {
  74. analytics: analyticsConfig = {},
  75. deploymentInfo
  76. } = config;
  77. const {
  78. amplitudeAPPKey,
  79. amplitudeIncludeUTM,
  80. blackListedEvents,
  81. scriptURLs,
  82. googleAnalyticsTrackingId,
  83. matomoEndpoint,
  84. matomoSiteID,
  85. whiteListedEvents
  86. } = analyticsConfig;
  87. const { group, user } = state['features/base/jwt'];
  88. const handlerConstructorOptions = {
  89. amplitudeAPPKey,
  90. amplitudeIncludeUTM,
  91. blackListedEvents,
  92. envType: deploymentInfo?.envType || 'dev',
  93. googleAnalyticsTrackingId,
  94. matomoEndpoint,
  95. matomoSiteID,
  96. group,
  97. host,
  98. product: deploymentInfo?.product,
  99. subproduct: deploymentInfo?.environment,
  100. user: user?.id,
  101. version: JitsiMeetJS.version,
  102. whiteListedEvents
  103. };
  104. const handlers = [];
  105. if (amplitudeAPPKey) {
  106. try {
  107. const amplitude = new AmplitudeHandler(handlerConstructorOptions);
  108. analytics.amplitudeIdentityProps = amplitude.getIdentityProps();
  109. handlers.push(amplitude);
  110. } catch (e) {
  111. logger.error('Failed to initialize Amplitude handler', e);
  112. }
  113. }
  114. if (matomoEndpoint && matomoSiteID) {
  115. try {
  116. const matomo = new MatomoHandler(handlerConstructorOptions);
  117. handlers.push(matomo);
  118. } catch (e) {
  119. logger.error('Failed to initialize Matomo handler', e);
  120. }
  121. }
  122. if (Array.isArray(scriptURLs) && scriptURLs.length > 0) {
  123. let externalHandlers;
  124. try {
  125. externalHandlers = await _loadHandlers(scriptURLs, handlerConstructorOptions);
  126. handlers.push(...externalHandlers);
  127. } catch (e) {
  128. logger.error('Failed to initialize external analytics handlers', e);
  129. }
  130. }
  131. // Avoid all analytics processing if there are no handlers, since no event would be sent.
  132. if (handlers.length === 0) {
  133. analytics.dispose();
  134. }
  135. logger.info(`Initialized ${handlers.length} analytics handlers`);
  136. return handlers;
  137. }
  138. /**
  139. * Checks whether a url is a data URL or not.
  140. *
  141. * @param {string} url - The URL to be checked.
  142. * @returns {boolean}
  143. */
  144. function isDataURL(url?: string): boolean {
  145. if (typeof url !== 'string') { // The icon will be ignored
  146. return false;
  147. }
  148. try {
  149. const urlObject = new URL(url);
  150. if (urlObject.protocol === 'data:') {
  151. return false;
  152. }
  153. } catch {
  154. return false;
  155. }
  156. return true;
  157. }
  158. /**
  159. * Inits JitsiMeetJS.analytics by setting permanent properties and setting the handlers from the loaded scripts.
  160. * NOTE: Has to be used after JitsiMeetJS.init. Otherwise analytics will be null.
  161. *
  162. * @param {Store} store - The redux store in which the specified {@code action} is being dispatched.
  163. * @param {Array<Object>} handlers - The analytics handlers.
  164. * @returns {boolean} - True if the analytics were successfully initialized and false otherwise.
  165. */
  166. export function initAnalytics(store: IStore, handlers: Array<Object>): boolean {
  167. const { getState, dispatch } = store;
  168. if (!isAnalyticsEnabled(getState) || handlers.length === 0) {
  169. return false;
  170. }
  171. const state = getState();
  172. const config = state['features/base/config'];
  173. const {
  174. deploymentInfo
  175. } = config;
  176. const { group, server } = state['features/base/jwt'];
  177. const { locationURL = { href: '' } } = state['features/base/connection'];
  178. const { tenant } = parseURIString(locationURL.href) || {};
  179. const params = parseURLParams(locationURL.href) ?? {};
  180. const permanentProperties: {
  181. appName?: string;
  182. externalApi?: boolean;
  183. group?: string;
  184. inIframe?: boolean;
  185. isPromotedFromVisitor?: boolean;
  186. isVisitor?: boolean;
  187. overwritesCustomButtonsWithURL?: boolean;
  188. overwritesCustomParticipantButtonsWithURL?: boolean;
  189. overwritesDefaultLogoUrl?: boolean;
  190. overwritesDeploymentUrls?: boolean;
  191. overwritesEtherpadBase?: boolean;
  192. overwritesHosts?: boolean;
  193. overwritesIceServers?: boolean;
  194. overwritesLiveStreamingUrls?: boolean;
  195. overwritesPeopleSearchUrl?: boolean;
  196. overwritesPrejoinConfigICEUrl?: boolean;
  197. overwritesSalesforceUrl?: boolean;
  198. overwritesSupportUrl?: boolean;
  199. overwritesWatchRTCConfigParams?: boolean;
  200. overwritesWatchRTCProxyUrl?: boolean;
  201. overwritesWatchRTCWSUrl?: boolean;
  202. server?: string;
  203. tenant?: string;
  204. wasLobbyVisible?: boolean;
  205. wasPrejoinDisplayed?: boolean;
  206. websocket?: boolean;
  207. } & typeof deploymentInfo = {};
  208. if (server) {
  209. permanentProperties.server = server;
  210. }
  211. if (group) {
  212. permanentProperties.group = group;
  213. }
  214. // Report the application name
  215. permanentProperties.appName = getAppName();
  216. // Report if user is using websocket
  217. permanentProperties.websocket = typeof config.websocket === 'string';
  218. // Report if user is using the external API
  219. permanentProperties.externalApi = typeof API_ID === 'number';
  220. // Report if we are loaded in iframe
  221. permanentProperties.inIframe = inIframe();
  222. // Report the tenant from the URL.
  223. permanentProperties.tenant = tenant || '/';
  224. permanentProperties.wasPrejoinDisplayed = isPrejoinPageVisible(state);
  225. // Currently we don't know if there will be lobby. We will update it to true if we go through lobby.
  226. permanentProperties.wasLobbyVisible = false;
  227. // Setting visitor properties to false by default. We will update them later if it turns out we are visitor.
  228. permanentProperties.isVisitor = false;
  229. permanentProperties.isPromotedFromVisitor = false;
  230. // TODO: Temporary metric. To be removed once we don't need it.
  231. permanentProperties.overwritesSupportUrl = 'interfaceConfig.SUPPORT_URL' in params;
  232. permanentProperties.overwritesSalesforceUrl = 'config.salesforceUrl' in params;
  233. permanentProperties.overwritesPeopleSearchUrl = 'config.peopleSearchUrl' in params;
  234. permanentProperties.overwritesDefaultLogoUrl = 'config.defaultLogoUrl' in params;
  235. permanentProperties.overwritesEtherpadBase = 'config.etherpad_base' in params;
  236. const hosts = params['config.hosts'] ?? {};
  237. const hostsProps = [ 'anonymousdomain', 'authdomain', 'domain', 'focus', 'muc', 'visitorFocus' ];
  238. permanentProperties.overwritesHosts = 'config.hosts' in params
  239. || Boolean(hostsProps.find(p => `config.hosts.${p}` in params || (typeof hosts === 'object' && p in hosts)));
  240. permanentProperties.overwritesWatchRTCConfigParams = 'config.watchRTCConfigParams' in params;
  241. const watchRTCConfigParams = params['config.watchRTCConfigParams'] ?? {};
  242. permanentProperties.overwritesWatchRTCProxyUrl = ('config.watchRTCConfigParams.proxyUrl' in params)
  243. || (typeof watchRTCConfigParams === 'object' && 'proxyUrl' in watchRTCConfigParams);
  244. permanentProperties.overwritesWatchRTCWSUrl = ('config.watchRTCConfigParams.wsUrl' in params)
  245. || (typeof watchRTCConfigParams === 'object' && 'wsUrl' in watchRTCConfigParams);
  246. const prejoinConfig = params['config.prejoinConfig'] ?? {};
  247. permanentProperties.overwritesPrejoinConfigICEUrl = ('config.prejoinConfig.preCallTestICEUrl' in params)
  248. || (typeof prejoinConfig === 'object' && 'preCallTestICEUrl' in prejoinConfig);
  249. const deploymentUrlsConfig = params['config.deploymentUrls'] ?? {};
  250. permanentProperties.overwritesDeploymentUrls
  251. = 'config.deploymentUrls.downloadAppsUrl' in params || 'config.deploymentUrls.userDocumentationURL' in params
  252. || (typeof deploymentUrlsConfig === 'object'
  253. && ('downloadAppsUrl' in deploymentUrlsConfig || 'userDocumentationURL' in deploymentUrlsConfig));
  254. const liveStreamingConfig = params['config.liveStreaming'] ?? {};
  255. permanentProperties.overwritesLiveStreamingUrls
  256. = ('interfaceConfig.LIVE_STREAMING_HELP_LINK' in params)
  257. || ('config.liveStreaming.termsLink' in params)
  258. || ('config.liveStreaming.dataPrivacyLink' in params)
  259. || ('config.liveStreaming.helpLink' in params)
  260. || (typeof params['config.liveStreaming'] === 'object' && 'config.liveStreaming' in params
  261. && (
  262. 'termsLink' in liveStreamingConfig
  263. || 'dataPrivacyLink' in liveStreamingConfig
  264. || 'helpLink' in liveStreamingConfig
  265. )
  266. );
  267. permanentProperties.overwritesIceServers = Boolean(Object.keys(params).find(k => k.startsWith('iceServers')));
  268. const customToolbarButtons = params['config.customToolbarButtons'] ?? [];
  269. permanentProperties.overwritesCustomButtonsWithURL = Boolean(
  270. customToolbarButtons.find(({ icon }: { icon: string; }) => isDataURL(icon)));
  271. const customParticipantMenuButtons = params['config.customParticipantMenuButtons'] ?? [];
  272. permanentProperties.overwritesCustomParticipantButtonsWithURL = Boolean(
  273. customParticipantMenuButtons.find(({ icon }: { icon: string; }) => isDataURL(icon)));
  274. // Optionally, include local deployment information based on the
  275. // contents of window.config.deploymentInfo.
  276. if (deploymentInfo) {
  277. for (const key in deploymentInfo) {
  278. if (deploymentInfo.hasOwnProperty(key)) {
  279. permanentProperties[key as keyof typeof deploymentInfo] = deploymentInfo[
  280. key as keyof typeof deploymentInfo];
  281. }
  282. }
  283. }
  284. analytics.addPermanentProperties({
  285. ...permanentProperties,
  286. ...getState()['features/analytics'].initialPermanentProperties
  287. });
  288. analytics.setConferenceName(getAnalyticsRoomName(state, dispatch));
  289. // Set the handlers last, since this triggers emptying of the cache
  290. analytics.setAnalyticsHandlers(handlers);
  291. if (!isMobileBrowser() && browser.isChromiumBased()) {
  292. const bannerCfg = state['features/base/config'].chromeExtensionBanner;
  293. checkChromeExtensionsInstalled(bannerCfg).then(extensionsInstalled => {
  294. if (extensionsInstalled?.length) {
  295. analytics.addPermanentProperties({
  296. hasChromeExtension: extensionsInstalled.some(ext => ext)
  297. });
  298. }
  299. });
  300. }
  301. return true;
  302. }
  303. /**
  304. * Tries to load the scripts for the external analytics handlers and creates them.
  305. *
  306. * @param {Array} scriptURLs - The array of script urls to load.
  307. * @param {Object} handlerConstructorOptions - The default options to pass when creating handlers.
  308. * @private
  309. * @returns {Promise} Resolves with the handlers that have been successfully loaded and rejects if there are no handlers
  310. * loaded or the analytics is disabled.
  311. */
  312. function _loadHandlers(scriptURLs: string[] = [], handlerConstructorOptions: Object) {
  313. const promises: Promise<{ error?: Error; type: string; url?: string; }>[] = [];
  314. for (const url of scriptURLs) {
  315. promises.push(
  316. loadScript(url).then(
  317. () => {
  318. return { type: 'success' };
  319. },
  320. (error: Error) => {
  321. return {
  322. type: 'error',
  323. error,
  324. url
  325. };
  326. }));
  327. }
  328. return Promise.all(promises).then(values => {
  329. for (const el of values) {
  330. if (el.type === 'error') {
  331. logger.warn(`Failed to load ${el.url}: ${el.error}`);
  332. }
  333. }
  334. const handlers = [];
  335. for (const Handler of getJitsiMeetGlobalNS().analyticsHandlers) {
  336. // Catch any error while loading to avoid skipping analytics in case
  337. // of multiple scripts.
  338. try {
  339. handlers.push(new Handler(handlerConstructorOptions));
  340. } catch (error) {
  341. logger.warn(`Error creating analytics handler: ${error}`);
  342. }
  343. }
  344. logger.debug(`Loaded ${handlers.length} external analytics handlers`);
  345. return handlers;
  346. });
  347. }