Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

functions.js 9.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  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, parseURIString } 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 async function createHandlers({ getState }: { getState: Function }) {
  55. getJitsiMeetGlobalNS().analyticsHandlers = [];
  56. window.analyticsHandlers = []; // Legacy support.
  57. if (!isAnalyticsEnabled(getState)) {
  58. // Avoid all analytics processing if there are no handlers, since no event would be sent.
  59. analytics.dispose();
  60. return [];
  61. }
  62. const state = getState();
  63. const config = state['features/base/config'];
  64. const { locationURL } = state['features/base/connection'];
  65. const host = locationURL ? locationURL.host : '';
  66. const {
  67. analytics: analyticsConfig = {},
  68. deploymentInfo
  69. } = config;
  70. const {
  71. amplitudeAPPKey,
  72. blackListedEvents,
  73. scriptURLs,
  74. googleAnalyticsTrackingId,
  75. matomoEndpoint,
  76. matomoSiteID,
  77. whiteListedEvents
  78. } = analyticsConfig;
  79. const { group, user } = state['features/base/jwt'];
  80. const handlerConstructorOptions = {
  81. amplitudeAPPKey,
  82. blackListedEvents,
  83. envType: (deploymentInfo && deploymentInfo.envType) || 'dev',
  84. googleAnalyticsTrackingId,
  85. matomoEndpoint,
  86. matomoSiteID,
  87. group,
  88. host,
  89. product: deploymentInfo && deploymentInfo.product,
  90. subproduct: deploymentInfo && deploymentInfo.environment,
  91. user: user && user.id,
  92. version: JitsiMeetJS.version,
  93. whiteListedEvents
  94. };
  95. const handlers = [];
  96. if (amplitudeAPPKey) {
  97. try {
  98. const amplitude = new AmplitudeHandler(handlerConstructorOptions);
  99. analytics.amplitudeIdentityProps = amplitude.getIdentityProps();
  100. handlers.push(amplitude);
  101. } catch (e) {
  102. logger.error('Failed to initialize Amplitude handler', e);
  103. }
  104. }
  105. if (matomoEndpoint && matomoSiteID) {
  106. try {
  107. const matomo = new MatomoHandler(handlerConstructorOptions);
  108. handlers.push(matomo);
  109. } catch (e) {
  110. logger.error('Failed to initialize Matomo handler', e);
  111. }
  112. }
  113. if (Array.isArray(scriptURLs) && scriptURLs.length > 0) {
  114. let externalHandlers;
  115. try {
  116. externalHandlers = await _loadHandlers(scriptURLs, handlerConstructorOptions);
  117. handlers.push(...externalHandlers);
  118. } catch (e) {
  119. logger.error('Failed to initialize external analytics handlers', e);
  120. }
  121. }
  122. // Avoid all analytics processing if there are no handlers, since no event would be sent.
  123. if (handlers.length === 0) {
  124. analytics.dispose();
  125. }
  126. logger.info(`Initialized ${handlers.length} analytics handlers`);
  127. return handlers;
  128. }
  129. /**
  130. * Inits JitsiMeetJS.analytics by setting permanent properties and setting the handlers from the loaded scripts.
  131. * NOTE: Has to be used after JitsiMeetJS.init. Otherwise analytics will be null.
  132. *
  133. * @param {Store} store - The redux store in which the specified {@code action} is being dispatched.
  134. * @param {Array<Object>} handlers - The analytics handlers.
  135. * @returns {void}
  136. */
  137. export function initAnalytics({ getState }: { getState: Function }, handlers: Array<Object>) {
  138. if (!isAnalyticsEnabled(getState) || handlers.length === 0) {
  139. return;
  140. }
  141. const state = getState();
  142. const config = state['features/base/config'];
  143. const {
  144. deploymentInfo
  145. } = config;
  146. const { group, server } = state['features/base/jwt'];
  147. const roomName = state['features/base/conference'].room;
  148. const { locationURL = {} } = state['features/base/connection'];
  149. const { tenant } = parseURIString(locationURL.href) || {};
  150. const permanentProperties = {};
  151. if (server) {
  152. permanentProperties.server = server;
  153. }
  154. if (group) {
  155. permanentProperties.group = group;
  156. }
  157. // Report the application name
  158. permanentProperties.appName = getAppName();
  159. // Report if user is using websocket
  160. permanentProperties.websocket = navigator.product !== 'ReactNative' && typeof config.websocket === 'string';
  161. // Report if user is using the external API
  162. permanentProperties.externalApi = typeof API_ID === 'number';
  163. // Report if we are loaded in iframe
  164. permanentProperties.inIframe = _inIframe();
  165. // Report the tenant from the URL.
  166. permanentProperties.tenant = tenant || '/';
  167. // Optionally, include local deployment information based on the
  168. // contents of window.config.deploymentInfo.
  169. if (deploymentInfo) {
  170. for (const key in deploymentInfo) {
  171. if (deploymentInfo.hasOwnProperty(key)) {
  172. permanentProperties[key] = deploymentInfo[key];
  173. }
  174. }
  175. }
  176. analytics.addPermanentProperties(permanentProperties);
  177. analytics.setConferenceName(roomName);
  178. // Set the handlers last, since this triggers emptying of the cache
  179. analytics.setAnalyticsHandlers(handlers);
  180. if (!isMobileBrowser() && browser.isChrome()) {
  181. const bannerCfg = state['features/base/config'].chromeExtensionBanner;
  182. checkChromeExtensionsInstalled(bannerCfg).then(extensionsInstalled => {
  183. if (extensionsInstalled?.length) {
  184. analytics.addPermanentProperties({
  185. hasChromeExtension: extensionsInstalled.some(ext => ext)
  186. });
  187. }
  188. });
  189. }
  190. }
  191. /**
  192. * Checks whether we are loaded in iframe.
  193. *
  194. * @returns {boolean} Returns {@code true} if loaded in iframe.
  195. * @private
  196. */
  197. function _inIframe() {
  198. if (navigator.product === 'ReactNative') {
  199. return false;
  200. }
  201. try {
  202. return window.self !== window.top;
  203. } catch (e) {
  204. return true;
  205. }
  206. }
  207. /**
  208. * Tries to load the scripts for the external analytics handlers and creates them.
  209. *
  210. * @param {Array} scriptURLs - The array of script urls to load.
  211. * @param {Object} handlerConstructorOptions - The default options to pass when creating handlers.
  212. * @private
  213. * @returns {Promise} Resolves with the handlers that have been successfully loaded and rejects if there are no handlers
  214. * loaded or the analytics is disabled.
  215. */
  216. function _loadHandlers(scriptURLs = [], handlerConstructorOptions) {
  217. const promises = [];
  218. for (const url of scriptURLs) {
  219. promises.push(
  220. loadScript(url).then(
  221. () => {
  222. return { type: 'success' };
  223. },
  224. error => {
  225. return {
  226. type: 'error',
  227. error,
  228. url
  229. };
  230. }));
  231. }
  232. return Promise.all(promises).then(values => {
  233. for (const el of values) {
  234. if (el.type === 'error') {
  235. logger.warn(`Failed to load ${el.url}: ${el.error}`);
  236. }
  237. }
  238. // analyticsHandlers is the handlers we want to use
  239. // we search for them in the JitsiMeetGlobalNS, but also
  240. // check the old location to provide legacy support
  241. const analyticsHandlers = [
  242. ...getJitsiMeetGlobalNS().analyticsHandlers,
  243. ...window.analyticsHandlers
  244. ];
  245. const handlers = [];
  246. for (const Handler of analyticsHandlers) {
  247. // Catch any error while loading to avoid skipping analytics in case
  248. // of multiple scripts.
  249. try {
  250. handlers.push(new Handler(handlerConstructorOptions));
  251. } catch (error) {
  252. logger.warn(`Error creating analytics handler: ${error}`);
  253. }
  254. }
  255. logger.debug(`Loaded ${handlers.length} external analytics handlers`);
  256. return handlers;
  257. });
  258. }