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

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