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.

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