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

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