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

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