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.ts 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343
  1. // @ts-expect-error
  2. import { API_ID } from '../../../modules/API/constants';
  3. import { getName as getAppName } from '../app/functions';
  4. import { IStore } from '../app/types';
  5. import { getAnalyticsRoomName } from '../base/conference/functions';
  6. import checkChromeExtensionsInstalled from '../base/environment/checkChromeExtensionsInstalled';
  7. import {
  8. isMobileBrowser
  9. } from '../base/environment/utils';
  10. import JitsiMeetJS, {
  11. analytics,
  12. browser
  13. } from '../base/lib-jitsi-meet';
  14. import { isAnalyticsEnabled } from '../base/lib-jitsi-meet/functions.any';
  15. import { isEmbedded } from '../base/util/embedUtils';
  16. import { getJitsiMeetGlobalNS } from '../base/util/helpers';
  17. import { loadScript } from '../base/util/loadScript';
  18. import { parseURLParams } from '../base/util/parseURLParams';
  19. import { parseURIString } from '../base/util/uri';
  20. import { isPrejoinPageVisible } from '../prejoin/functions';
  21. import AmplitudeHandler from './handlers/AmplitudeHandler';
  22. import MatomoHandler from './handlers/MatomoHandler';
  23. import logger from './logger';
  24. /**
  25. * Sends an event through the lib-jitsi-meet AnalyticsAdapter interface.
  26. *
  27. * @param {Object} event - The event to send. It should be formatted as
  28. * described in AnalyticsAdapter.js in lib-jitsi-meet.
  29. * @returns {void}
  30. */
  31. export function sendAnalytics(event: Object) {
  32. try {
  33. analytics.sendEvent(event);
  34. } catch (e) {
  35. logger.warn(`Error sending analytics event: ${e}`);
  36. }
  37. }
  38. /**
  39. * Return saved amplitude identity info such as session id, device id and user id. We assume these do not change for
  40. * the duration of the conference.
  41. *
  42. * @returns {Object}
  43. */
  44. export function getAmplitudeIdentity() {
  45. return analytics.amplitudeIdentityProps;
  46. }
  47. /**
  48. * Resets the analytics adapter to its initial state - removes handlers, cache,
  49. * disabled state, etc.
  50. *
  51. * @returns {void}
  52. */
  53. export function resetAnalytics() {
  54. analytics.reset();
  55. }
  56. /**
  57. * Creates the analytics handlers.
  58. *
  59. * @param {Store} store - The redux store in which the specified {@code action} is being dispatched.
  60. * @returns {Promise} Resolves with the handlers that have been successfully loaded.
  61. */
  62. export async function createHandlers({ getState }: IStore) {
  63. getJitsiMeetGlobalNS().analyticsHandlers = [];
  64. if (!isAnalyticsEnabled(getState)) {
  65. // Avoid all analytics processing if there are no handlers, since no event would be sent.
  66. analytics.dispose();
  67. return [];
  68. }
  69. const state = getState();
  70. const config = state['features/base/config'];
  71. const { locationURL } = state['features/base/connection'];
  72. const host = locationURL ? locationURL.host : '';
  73. const {
  74. analytics: analyticsConfig = {},
  75. deploymentInfo
  76. } = config;
  77. const {
  78. amplitudeAPPKey,
  79. amplitudeIncludeUTM,
  80. blackListedEvents,
  81. scriptURLs,
  82. matomoEndpoint,
  83. matomoSiteID,
  84. whiteListedEvents
  85. } = analyticsConfig;
  86. const { group, user } = state['features/base/jwt'];
  87. const handlerConstructorOptions = {
  88. amplitudeAPPKey,
  89. amplitudeIncludeUTM,
  90. blackListedEvents,
  91. envType: deploymentInfo?.envType || 'dev',
  92. matomoEndpoint,
  93. matomoSiteID,
  94. group,
  95. host,
  96. product: deploymentInfo?.product,
  97. subproduct: deploymentInfo?.environment,
  98. user: user?.id,
  99. version: JitsiMeetJS.version,
  100. whiteListedEvents
  101. };
  102. const handlers = [];
  103. if (amplitudeAPPKey) {
  104. try {
  105. const amplitude = new AmplitudeHandler(handlerConstructorOptions);
  106. analytics.amplitudeIdentityProps = amplitude.getIdentityProps();
  107. handlers.push(amplitude);
  108. } catch (e) {
  109. logger.error('Failed to initialize Amplitude handler', e);
  110. }
  111. }
  112. if (matomoEndpoint && matomoSiteID) {
  113. try {
  114. const matomo = new MatomoHandler(handlerConstructorOptions);
  115. handlers.push(matomo);
  116. } catch (e) {
  117. logger.error('Failed to initialize Matomo handler', e);
  118. }
  119. }
  120. if (Array.isArray(scriptURLs) && scriptURLs.length > 0) {
  121. let externalHandlers;
  122. try {
  123. externalHandlers = await _loadHandlers(scriptURLs, handlerConstructorOptions);
  124. handlers.push(...externalHandlers);
  125. } catch (e) {
  126. logger.error('Failed to initialize external analytics handlers', e);
  127. }
  128. }
  129. // Avoid all analytics processing if there are no handlers, since no event would be sent.
  130. if (handlers.length === 0) {
  131. analytics.dispose();
  132. }
  133. logger.info(`Initialized ${handlers.length} analytics handlers`);
  134. return handlers;
  135. }
  136. /**
  137. * Inits JitsiMeetJS.analytics by setting permanent properties and setting the handlers from the loaded scripts.
  138. * NOTE: Has to be used after JitsiMeetJS.init. Otherwise analytics will be null.
  139. *
  140. * @param {Store} store - The redux store in which the specified {@code action} is being dispatched.
  141. * @param {Array<Object>} handlers - The analytics handlers.
  142. * @returns {boolean} - True if the analytics were successfully initialized and false otherwise.
  143. */
  144. export function initAnalytics(store: IStore, handlers: Array<Object>): boolean {
  145. const { getState, dispatch } = store;
  146. if (!isAnalyticsEnabled(getState) || handlers.length === 0) {
  147. return false;
  148. }
  149. const state = getState();
  150. const config = state['features/base/config'];
  151. const {
  152. deploymentInfo
  153. } = config;
  154. const { group, server } = state['features/base/jwt'];
  155. const { locationURL = { href: '' } } = state['features/base/connection'];
  156. const { tenant } = parseURIString(locationURL.href) || {};
  157. const params = parseURLParams(locationURL.href) ?? {};
  158. const permanentProperties: {
  159. appName?: string;
  160. externalApi?: boolean;
  161. group?: string;
  162. inIframe?: boolean;
  163. isPromotedFromVisitor?: boolean;
  164. isVisitor?: boolean;
  165. overwritesCustomButtonsWithURL?: boolean;
  166. overwritesDefaultLogoUrl?: boolean;
  167. overwritesDeploymentUrls?: boolean;
  168. overwritesLiveStreamingUrls?: boolean;
  169. overwritesSalesforceUrl?: boolean;
  170. overwritesSupportUrl?: boolean;
  171. server?: string;
  172. tenant?: string;
  173. wasLobbyVisible?: boolean;
  174. wasPrejoinDisplayed?: boolean;
  175. websocket?: boolean;
  176. } & typeof deploymentInfo = {};
  177. if (server) {
  178. permanentProperties.server = server;
  179. }
  180. if (group) {
  181. permanentProperties.group = group;
  182. }
  183. // Report the application name
  184. permanentProperties.appName = getAppName();
  185. // Report if user is using websocket
  186. permanentProperties.websocket = typeof config.websocket === 'string';
  187. // Report if user is using the external API
  188. permanentProperties.externalApi = typeof API_ID === 'number';
  189. // Report if we are loaded in iframe
  190. permanentProperties.inIframe = isEmbedded();
  191. // Report the tenant from the URL.
  192. permanentProperties.tenant = tenant || '/';
  193. permanentProperties.wasPrejoinDisplayed = isPrejoinPageVisible(state);
  194. // Currently we don't know if there will be lobby. We will update it to true if we go through lobby.
  195. permanentProperties.wasLobbyVisible = false;
  196. // Setting visitor properties to false by default. We will update them later if it turns out we are visitor.
  197. permanentProperties.isVisitor = false;
  198. permanentProperties.isPromotedFromVisitor = false;
  199. // TODO: Temporary metric. To be removed once we don't need it.
  200. permanentProperties.overwritesSupportUrl = 'interfaceConfig.SUPPORT_URL' in params;
  201. permanentProperties.overwritesSalesforceUrl = 'config.salesforceUrl' in params;
  202. permanentProperties.overwritesDefaultLogoUrl = 'config.defaultLogoUrl' in params;
  203. const deploymentUrlsConfig = params['config.deploymentUrls'] ?? {};
  204. permanentProperties.overwritesDeploymentUrls
  205. = 'config.deploymentUrls.downloadAppsUrl' in params || 'config.deploymentUrls.userDocumentationURL' in params
  206. || (typeof deploymentUrlsConfig === 'object'
  207. && ('downloadAppsUrl' in deploymentUrlsConfig || 'userDocumentationURL' in deploymentUrlsConfig));
  208. const liveStreamingConfig = params['config.liveStreaming'] ?? {};
  209. permanentProperties.overwritesLiveStreamingUrls
  210. = ('interfaceConfig.LIVE_STREAMING_HELP_LINK' in params)
  211. || ('config.liveStreaming.termsLink' in params)
  212. || ('config.liveStreaming.dataPrivacyLink' in params)
  213. || ('config.liveStreaming.helpLink' in params)
  214. || (typeof params['config.liveStreaming'] === 'object' && 'config.liveStreaming' in params
  215. && (
  216. 'termsLink' in liveStreamingConfig
  217. || 'dataPrivacyLink' in liveStreamingConfig
  218. || 'helpLink' in liveStreamingConfig
  219. )
  220. );
  221. permanentProperties.overwritesCustomButtonsWithURL = 'config.customToolbarButtons' in params;
  222. // Optionally, include local deployment information based on the
  223. // contents of window.config.deploymentInfo.
  224. if (deploymentInfo) {
  225. for (const key in deploymentInfo) {
  226. if (deploymentInfo.hasOwnProperty(key)) {
  227. permanentProperties[key as keyof typeof deploymentInfo] = deploymentInfo[
  228. key as keyof typeof deploymentInfo];
  229. }
  230. }
  231. }
  232. analytics.addPermanentProperties({
  233. ...permanentProperties,
  234. ...getState()['features/analytics'].initialPermanentProperties
  235. });
  236. analytics.setConferenceName(getAnalyticsRoomName(state, dispatch));
  237. // Set the handlers last, since this triggers emptying of the cache
  238. analytics.setAnalyticsHandlers(handlers);
  239. if (!isMobileBrowser() && browser.isChromiumBased()) {
  240. const bannerCfg = state['features/base/config'].chromeExtensionBanner;
  241. checkChromeExtensionsInstalled(bannerCfg).then(extensionsInstalled => {
  242. if (extensionsInstalled?.length) {
  243. analytics.addPermanentProperties({
  244. hasChromeExtension: extensionsInstalled.some(ext => ext)
  245. });
  246. }
  247. });
  248. }
  249. return true;
  250. }
  251. /**
  252. * Tries to load the scripts for the external analytics handlers and creates them.
  253. *
  254. * @param {Array} scriptURLs - The array of script urls to load.
  255. * @param {Object} handlerConstructorOptions - The default options to pass when creating handlers.
  256. * @private
  257. * @returns {Promise} Resolves with the handlers that have been successfully loaded and rejects if there are no handlers
  258. * loaded or the analytics is disabled.
  259. */
  260. function _loadHandlers(scriptURLs: string[] = [], handlerConstructorOptions: Object) {
  261. const promises: Promise<{ error?: Error; type: string; url?: string; }>[] = [];
  262. for (const url of scriptURLs) {
  263. promises.push(
  264. loadScript(url).then(
  265. () => {
  266. return { type: 'success' };
  267. },
  268. (error: Error) => {
  269. return {
  270. type: 'error',
  271. error,
  272. url
  273. };
  274. }));
  275. }
  276. return Promise.all(promises).then(values => {
  277. for (const el of values) {
  278. if (el.type === 'error') {
  279. logger.warn(`Failed to load ${el.url}: ${el.error}`);
  280. }
  281. }
  282. const handlers = [];
  283. for (const Handler of getJitsiMeetGlobalNS().analyticsHandlers) {
  284. // Catch any error while loading to avoid skipping analytics in case
  285. // of multiple scripts.
  286. try {
  287. handlers.push(new Handler(handlerConstructorOptions));
  288. } catch (error) {
  289. logger.warn(`Error creating analytics handler: ${error}`);
  290. }
  291. }
  292. logger.debug(`Loaded ${handlers.length} external analytics handlers`);
  293. return handlers;
  294. });
  295. }