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

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