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

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