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

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