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

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