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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  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 { parseURIString } from '../base/util/uri';
  19. import AmplitudeHandler from './handlers/AmplitudeHandler';
  20. import MatomoHandler from './handlers/MatomoHandler';
  21. import logger from './logger';
  22. /**
  23. * Sends an event through the lib-jitsi-meet AnalyticsAdapter interface.
  24. *
  25. * @param {Object} event - The event to send. It should be formatted as
  26. * described in AnalyticsAdapter.js in lib-jitsi-meet.
  27. * @returns {void}
  28. */
  29. export function sendAnalytics(event: Object) {
  30. try {
  31. analytics.sendEvent(event);
  32. } catch (e) {
  33. logger.warn(`Error sending analytics event: ${e}`);
  34. }
  35. }
  36. /**
  37. * Return saved amplitude identity info such as session id, device id and user id. We assume these do not change for
  38. * the duration of the conference.
  39. *
  40. * @returns {Object}
  41. */
  42. export function getAmplitudeIdentity() {
  43. return analytics.amplitudeIdentityProps;
  44. }
  45. /**
  46. * Resets the analytics adapter to its initial state - removes handlers, cache,
  47. * disabled state, etc.
  48. *
  49. * @returns {void}
  50. */
  51. export function resetAnalytics() {
  52. analytics.reset();
  53. }
  54. /**
  55. * Creates the analytics handlers.
  56. *
  57. * @param {Store} store - The redux store in which the specified {@code action} is being dispatched.
  58. * @returns {Promise} Resolves with the handlers that have been successfully loaded.
  59. */
  60. export async function createHandlers({ getState }: IStore) {
  61. getJitsiMeetGlobalNS().analyticsHandlers = [];
  62. if (!isAnalyticsEnabled(getState)) {
  63. // Avoid all analytics processing if there are no handlers, since no event would be sent.
  64. analytics.dispose();
  65. return [];
  66. }
  67. const state = getState();
  68. const config = state['features/base/config'];
  69. const { locationURL } = state['features/base/connection'];
  70. const host = locationURL ? locationURL.host : '';
  71. const {
  72. analytics: analyticsConfig = {},
  73. deploymentInfo
  74. } = config;
  75. const {
  76. amplitudeAPPKey,
  77. amplitudeIncludeUTM,
  78. blackListedEvents,
  79. scriptURLs,
  80. googleAnalyticsTrackingId,
  81. matomoEndpoint,
  82. matomoSiteID,
  83. whiteListedEvents
  84. } = analyticsConfig;
  85. const { group, user } = state['features/base/jwt'];
  86. const handlerConstructorOptions = {
  87. amplitudeAPPKey,
  88. amplitudeIncludeUTM,
  89. blackListedEvents,
  90. envType: deploymentInfo?.envType || 'dev',
  91. googleAnalyticsTrackingId,
  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. * Inits JitsiMeetJS.analytics by setting permanent properties and setting the handlers from the loaded scripts.
  138. * NOTE: Has to be used after JitsiMeetJS.init. Otherwise analytics will be null.
  139. *
  140. * @param {Store} store - The redux store in which the specified {@code action} is being dispatched.
  141. * @param {Array<Object>} handlers - The analytics handlers.
  142. * @returns {void}
  143. */
  144. export function initAnalytics(store: IStore, handlers: Array<Object>) {
  145. const { getState, dispatch } = store;
  146. if (!isAnalyticsEnabled(getState) || handlers.length === 0) {
  147. return;
  148. }
  149. const state = getState();
  150. const config = state['features/base/config'];
  151. const {
  152. deploymentInfo
  153. } = config;
  154. const { group, server } = state['features/base/jwt'];
  155. const { locationURL = { href: '' } } = state['features/base/connection'];
  156. const { tenant } = parseURIString(locationURL.href) || {};
  157. const permanentProperties: {
  158. appName?: string;
  159. externalApi?: boolean;
  160. group?: string;
  161. inIframe?: boolean;
  162. server?: string;
  163. tenant?: string;
  164. websocket?: boolean;
  165. } & typeof deploymentInfo = {};
  166. if (server) {
  167. permanentProperties.server = server;
  168. }
  169. if (group) {
  170. permanentProperties.group = group;
  171. }
  172. // Report the application name
  173. permanentProperties.appName = getAppName();
  174. // Report if user is using websocket
  175. permanentProperties.websocket = typeof config.websocket === 'string';
  176. // Report if user is using the external API
  177. permanentProperties.externalApi = typeof API_ID === 'number';
  178. // Report if we are loaded in iframe
  179. permanentProperties.inIframe = inIframe();
  180. // Report the tenant from the URL.
  181. permanentProperties.tenant = tenant || '/';
  182. // Optionally, include local deployment information based on the
  183. // contents of window.config.deploymentInfo.
  184. if (deploymentInfo) {
  185. for (const key in deploymentInfo) {
  186. if (deploymentInfo.hasOwnProperty(key)) {
  187. permanentProperties[key as keyof typeof deploymentInfo] = deploymentInfo[
  188. key as keyof typeof deploymentInfo];
  189. }
  190. }
  191. }
  192. analytics.addPermanentProperties(permanentProperties);
  193. analytics.setConferenceName(getAnalyticsRoomName(state, dispatch));
  194. // Set the handlers last, since this triggers emptying of the cache
  195. analytics.setAnalyticsHandlers(handlers);
  196. if (!isMobileBrowser() && browser.isChromiumBased()) {
  197. const bannerCfg = state['features/base/config'].chromeExtensionBanner;
  198. checkChromeExtensionsInstalled(bannerCfg).then(extensionsInstalled => {
  199. if (extensionsInstalled?.length) {
  200. analytics.addPermanentProperties({
  201. hasChromeExtension: extensionsInstalled.some(ext => ext)
  202. });
  203. }
  204. });
  205. }
  206. }
  207. /**
  208. * Tries to load the scripts for the external analytics handlers and creates them.
  209. *
  210. * @param {Array} scriptURLs - The array of script urls to load.
  211. * @param {Object} handlerConstructorOptions - The default options to pass when creating handlers.
  212. * @private
  213. * @returns {Promise} Resolves with the handlers that have been successfully loaded and rejects if there are no handlers
  214. * loaded or the analytics is disabled.
  215. */
  216. function _loadHandlers(scriptURLs: string[] = [], handlerConstructorOptions: Object) {
  217. const promises: Promise<{ error?: Error; type: string; url?: string; }>[] = [];
  218. for (const url of scriptURLs) {
  219. promises.push(
  220. loadScript(url).then(
  221. () => {
  222. return { type: 'success' };
  223. },
  224. (error: Error) => {
  225. return {
  226. type: 'error',
  227. error,
  228. url
  229. };
  230. }));
  231. }
  232. return Promise.all(promises).then(values => {
  233. for (const el of values) {
  234. if (el.type === 'error') {
  235. logger.warn(`Failed to load ${el.url}: ${el.error}`);
  236. }
  237. }
  238. const handlers = [];
  239. for (const Handler of getJitsiMeetGlobalNS().analyticsHandlers) {
  240. // Catch any error while loading to avoid skipping analytics in case
  241. // of multiple scripts.
  242. try {
  243. handlers.push(new Handler(handlerConstructorOptions));
  244. } catch (error) {
  245. logger.warn(`Error creating analytics handler: ${error}`);
  246. }
  247. }
  248. logger.debug(`Loaded ${handlers.length} external analytics handlers`);
  249. return handlers;
  250. });
  251. }