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.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  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 } 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. return (
  89. _loadHandlers(scriptURLs, handlerConstructorOptions)
  90. .then(externalHandlers => {
  91. handlers.push(...externalHandlers);
  92. if (handlers.length === 0) {
  93. // Throwing an error in order to dispose the analytics in the catch clause due to the lack of any
  94. // analytics handlers.
  95. throw new Error('No analytics handlers created!');
  96. }
  97. return handlers;
  98. })
  99. .catch(e => {
  100. analytics.dispose();
  101. logger.error(e);
  102. return [];
  103. }));
  104. }
  105. /**
  106. * Inits JitsiMeetJS.analytics by setting permanent properties and setting the handlers from the loaded scripts.
  107. * NOTE: Has to be used after JitsiMeetJS.init. Otherwise analytics will be null.
  108. *
  109. * @param {Store} store - The redux store in which the specified {@code action} is being dispatched.
  110. * @param {Array<Object>} handlers - The analytics handlers.
  111. * @returns {void}
  112. */
  113. export function initAnalytics({ getState }: { getState: Function }, handlers: Array<Object>) {
  114. if (!isAnalyticsEnabled(getState) || handlers.length === 0) {
  115. return;
  116. }
  117. const state = getState();
  118. const config = state['features/base/config'];
  119. const {
  120. deploymentInfo
  121. } = config;
  122. const { group, server } = state['features/base/jwt'];
  123. const roomName = state['features/base/conference'].room;
  124. const permanentProperties = {};
  125. if (server) {
  126. permanentProperties.server = server;
  127. }
  128. if (group) {
  129. permanentProperties.group = group;
  130. }
  131. // Report if user is using websocket
  132. permanentProperties.websocket = navigator.product !== 'ReactNative' && typeof config.websocket === 'string';
  133. // Optionally, include local deployment information based on the
  134. // contents of window.config.deploymentInfo.
  135. if (deploymentInfo) {
  136. for (const key in deploymentInfo) {
  137. if (deploymentInfo.hasOwnProperty(key)) {
  138. permanentProperties[key] = deploymentInfo[key];
  139. }
  140. }
  141. }
  142. analytics.addPermanentProperties(permanentProperties);
  143. analytics.setConferenceName(roomName);
  144. // Set the handlers last, since this triggers emptying of the cache
  145. analytics.setAnalyticsHandlers(handlers);
  146. if (!isMobileBrowser() && browser.isChrome()) {
  147. const bannerCfg = state['features/base/config'].chromeExtensionBanner;
  148. checkChromeExtensionsInstalled(bannerCfg).then(extensionsInstalled => {
  149. if (extensionsInstalled?.length) {
  150. analytics.addPermanentProperties({
  151. hasChromeExtension: extensionsInstalled.some(ext => ext)
  152. });
  153. }
  154. });
  155. }
  156. }
  157. /**
  158. * Tries to load the scripts for the analytics handlers and creates them.
  159. *
  160. * @param {Array} scriptURLs - The array of script urls to load.
  161. * @param {Object} handlerConstructorOptions - The default options to pass when creating handlers.
  162. * @private
  163. * @returns {Promise} Resolves with the handlers that have been successfully loaded and rejects if there are no handlers
  164. * loaded or the analytics is disabled.
  165. */
  166. function _loadHandlers(scriptURLs = [], handlerConstructorOptions) {
  167. const promises = [];
  168. for (const url of scriptURLs) {
  169. promises.push(
  170. loadScript(url).then(
  171. () => {
  172. return { type: 'success' };
  173. },
  174. error => {
  175. return {
  176. type: 'error',
  177. error,
  178. url
  179. };
  180. }));
  181. }
  182. return Promise.all(promises).then(values => {
  183. for (const el of values) {
  184. if (el.type === 'error') {
  185. logger.warn(`Failed to load ${el.url}: ${el.error}`);
  186. }
  187. }
  188. // analyticsHandlers is the handlers we want to use
  189. // we search for them in the JitsiMeetGlobalNS, but also
  190. // check the old location to provide legacy support
  191. const analyticsHandlers = [
  192. ...getJitsiMeetGlobalNS().analyticsHandlers,
  193. ...window.analyticsHandlers
  194. ];
  195. const handlers = [];
  196. for (const Handler of analyticsHandlers) {
  197. // Catch any error while loading to avoid skipping analytics in case
  198. // of multiple scripts.
  199. try {
  200. handlers.push(new Handler(handlerConstructorOptions));
  201. } catch (error) {
  202. logger.warn(`Error creating analytics handler: ${error}`);
  203. }
  204. }
  205. logger.debug(`Loaded ${handlers.length} analytics handlers`);
  206. return handlers;
  207. });
  208. }