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

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