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.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  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. blackListedEvents,
  78. scriptURLs,
  79. googleAnalyticsTrackingId,
  80. matomoEndpoint,
  81. matomoSiteID,
  82. whiteListedEvents
  83. } = analyticsConfig;
  84. const { group, user } = state['features/base/jwt'];
  85. const handlerConstructorOptions = {
  86. amplitudeAPPKey,
  87. blackListedEvents,
  88. envType: deploymentInfo?.envType || 'dev',
  89. googleAnalyticsTrackingId,
  90. matomoEndpoint,
  91. matomoSiteID,
  92. group,
  93. host,
  94. product: deploymentInfo?.product,
  95. subproduct: deploymentInfo?.environment,
  96. user: user?.id,
  97. version: JitsiMeetJS.version,
  98. whiteListedEvents
  99. };
  100. const handlers = [];
  101. if (amplitudeAPPKey) {
  102. try {
  103. const amplitude = new AmplitudeHandler(handlerConstructorOptions);
  104. analytics.amplitudeIdentityProps = amplitude.getIdentityProps();
  105. handlers.push(amplitude);
  106. } catch (e) {
  107. logger.error('Failed to initialize Amplitude handler', e);
  108. }
  109. }
  110. if (matomoEndpoint && matomoSiteID) {
  111. try {
  112. const matomo = new MatomoHandler(handlerConstructorOptions);
  113. handlers.push(matomo);
  114. } catch (e) {
  115. logger.error('Failed to initialize Matomo handler', e);
  116. }
  117. }
  118. if (Array.isArray(scriptURLs) && scriptURLs.length > 0) {
  119. let externalHandlers;
  120. try {
  121. externalHandlers = await _loadHandlers(scriptURLs, handlerConstructorOptions);
  122. handlers.push(...externalHandlers);
  123. } catch (e) {
  124. logger.error('Failed to initialize external analytics handlers', e);
  125. }
  126. }
  127. // Avoid all analytics processing if there are no handlers, since no event would be sent.
  128. if (handlers.length === 0) {
  129. analytics.dispose();
  130. }
  131. logger.info(`Initialized ${handlers.length} analytics handlers`);
  132. return handlers;
  133. }
  134. /**
  135. * Inits JitsiMeetJS.analytics by setting permanent properties and setting the handlers from the loaded scripts.
  136. * NOTE: Has to be used after JitsiMeetJS.init. Otherwise analytics will be null.
  137. *
  138. * @param {Store} store - The redux store in which the specified {@code action} is being dispatched.
  139. * @param {Array<Object>} handlers - The analytics handlers.
  140. * @returns {void}
  141. */
  142. export function initAnalytics(store: IStore, handlers: Array<Object>) {
  143. const { getState, dispatch } = store;
  144. if (!isAnalyticsEnabled(getState) || handlers.length === 0) {
  145. return;
  146. }
  147. const state = getState();
  148. const config = state['features/base/config'];
  149. const {
  150. deploymentInfo
  151. } = config;
  152. const { group, server } = state['features/base/jwt'];
  153. const { locationURL = { href: '' } } = state['features/base/connection'];
  154. const { tenant } = parseURIString(locationURL.href) || {};
  155. const permanentProperties: {
  156. appName?: string;
  157. externalApi?: boolean;
  158. group?: string;
  159. inIframe?: boolean;
  160. server?: string;
  161. tenant?: string;
  162. websocket?: boolean;
  163. } & typeof deploymentInfo = {};
  164. if (server) {
  165. permanentProperties.server = server;
  166. }
  167. if (group) {
  168. permanentProperties.group = group;
  169. }
  170. // Report the application name
  171. permanentProperties.appName = getAppName();
  172. // Report if user is using websocket
  173. permanentProperties.websocket = typeof config.websocket === 'string';
  174. // Report if user is using the external API
  175. permanentProperties.externalApi = typeof API_ID === 'number';
  176. // Report if we are loaded in iframe
  177. permanentProperties.inIframe = inIframe();
  178. // Report the tenant from the URL.
  179. permanentProperties.tenant = tenant || '/';
  180. // Optionally, include local deployment information based on the
  181. // contents of window.config.deploymentInfo.
  182. if (deploymentInfo) {
  183. for (const key in deploymentInfo) {
  184. if (deploymentInfo.hasOwnProperty(key)) {
  185. permanentProperties[key as keyof typeof deploymentInfo] = deploymentInfo[
  186. key as keyof typeof deploymentInfo];
  187. }
  188. }
  189. }
  190. analytics.addPermanentProperties(permanentProperties);
  191. analytics.setConferenceName(getAnalyticsRoomName(state, dispatch));
  192. // Set the handlers last, since this triggers emptying of the cache
  193. analytics.setAnalyticsHandlers(handlers);
  194. if (!isMobileBrowser() && browser.isChrome()) {
  195. const bannerCfg = state['features/base/config'].chromeExtensionBanner;
  196. checkChromeExtensionsInstalled(bannerCfg).then(extensionsInstalled => {
  197. if (extensionsInstalled?.length) {
  198. analytics.addPermanentProperties({
  199. hasChromeExtension: extensionsInstalled.some(ext => ext)
  200. });
  201. }
  202. });
  203. }
  204. }
  205. /**
  206. * Tries to load the scripts for the external analytics handlers and creates them.
  207. *
  208. * @param {Array} scriptURLs - The array of script urls to load.
  209. * @param {Object} handlerConstructorOptions - The default options to pass when creating handlers.
  210. * @private
  211. * @returns {Promise} Resolves with the handlers that have been successfully loaded and rejects if there are no handlers
  212. * loaded or the analytics is disabled.
  213. */
  214. function _loadHandlers(scriptURLs: string[] = [], handlerConstructorOptions: Object) {
  215. const promises: Promise<{ error?: Error; type: string; url?: string; }>[] = [];
  216. for (const url of scriptURLs) {
  217. promises.push(
  218. loadScript(url).then(
  219. () => {
  220. return { type: 'success' };
  221. },
  222. (error: Error) => {
  223. return {
  224. type: 'error',
  225. error,
  226. url
  227. };
  228. }));
  229. }
  230. return Promise.all(promises).then(values => {
  231. for (const el of values) {
  232. if (el.type === 'error') {
  233. logger.warn(`Failed to load ${el.url}: ${el.error}`);
  234. }
  235. }
  236. const handlers = [];
  237. for (const Handler of getJitsiMeetGlobalNS().analyticsHandlers) {
  238. // Catch any error while loading to avoid skipping analytics in case
  239. // of multiple scripts.
  240. try {
  241. handlers.push(new Handler(handlerConstructorOptions));
  242. } catch (error) {
  243. logger.warn(`Error creating analytics handler: ${error}`);
  244. }
  245. }
  246. logger.debug(`Loaded ${handlers.length} external analytics handlers`);
  247. return handlers;
  248. });
  249. }