Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

functions.ts 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  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 { getJitsiMeetGlobalNS } from '../base/util/helpers';
  16. import { inIframe } from '../base/util/iframeUtils';
  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. googleAnalyticsTrackingId,
  83. matomoEndpoint,
  84. matomoSiteID,
  85. whiteListedEvents
  86. } = analyticsConfig;
  87. const { group, user } = state['features/base/jwt'];
  88. const handlerConstructorOptions = {
  89. amplitudeAPPKey,
  90. amplitudeIncludeUTM,
  91. blackListedEvents,
  92. envType: deploymentInfo?.envType || 'dev',
  93. googleAnalyticsTrackingId,
  94. matomoEndpoint,
  95. matomoSiteID,
  96. group,
  97. host,
  98. product: deploymentInfo?.product,
  99. subproduct: deploymentInfo?.environment,
  100. user: user?.id,
  101. version: JitsiMeetJS.version,
  102. whiteListedEvents
  103. };
  104. const handlers = [];
  105. if (amplitudeAPPKey) {
  106. try {
  107. const amplitude = new AmplitudeHandler(handlerConstructorOptions);
  108. analytics.amplitudeIdentityProps = amplitude.getIdentityProps();
  109. handlers.push(amplitude);
  110. } catch (e) {
  111. logger.error('Failed to initialize Amplitude handler', e);
  112. }
  113. }
  114. if (matomoEndpoint && matomoSiteID) {
  115. try {
  116. const matomo = new MatomoHandler(handlerConstructorOptions);
  117. handlers.push(matomo);
  118. } catch (e) {
  119. logger.error('Failed to initialize Matomo handler', e);
  120. }
  121. }
  122. if (Array.isArray(scriptURLs) && scriptURLs.length > 0) {
  123. let externalHandlers;
  124. try {
  125. externalHandlers = await _loadHandlers(scriptURLs, handlerConstructorOptions);
  126. handlers.push(...externalHandlers);
  127. } catch (e) {
  128. logger.error('Failed to initialize external analytics handlers', e);
  129. }
  130. }
  131. // Avoid all analytics processing if there are no handlers, since no event would be sent.
  132. if (handlers.length === 0) {
  133. analytics.dispose();
  134. }
  135. logger.info(`Initialized ${handlers.length} analytics handlers`);
  136. return handlers;
  137. }
  138. /**
  139. * Inits JitsiMeetJS.analytics by setting permanent properties and setting the handlers from the loaded scripts.
  140. * NOTE: Has to be used after JitsiMeetJS.init. Otherwise analytics will be null.
  141. *
  142. * @param {Store} store - The redux store in which the specified {@code action} is being dispatched.
  143. * @param {Array<Object>} handlers - The analytics handlers.
  144. * @returns {boolean} - True if the analytics were successfully initialized and false otherwise.
  145. */
  146. export function initAnalytics(store: IStore, handlers: Array<Object>): boolean {
  147. const { getState, dispatch } = store;
  148. if (!isAnalyticsEnabled(getState) || handlers.length === 0) {
  149. return false;
  150. }
  151. const state = getState();
  152. const config = state['features/base/config'];
  153. const {
  154. deploymentInfo
  155. } = config;
  156. const { group, server } = state['features/base/jwt'];
  157. const { locationURL = { href: '' } } = state['features/base/connection'];
  158. const { tenant } = parseURIString(locationURL.href) || {};
  159. const params = parseURLParams(locationURL.href) ?? {};
  160. const permanentProperties: {
  161. appName?: string;
  162. externalApi?: boolean;
  163. group?: string;
  164. inIframe?: boolean;
  165. isPromotedFromVisitor?: boolean;
  166. isVisitor?: boolean;
  167. overwritesDefaultLogoUrl?: boolean;
  168. overwritesDeploymentUrls?: boolean;
  169. overwritesLiveStreamingUrls?: boolean;
  170. overwritesPeopleSearchUrl?: boolean;
  171. overwritesPrejoinConfigICEUrl?: boolean;
  172. overwritesSalesforceUrl?: boolean;
  173. overwritesSupportUrl?: boolean;
  174. server?: string;
  175. tenant?: string;
  176. wasLobbyVisible?: boolean;
  177. wasPrejoinDisplayed?: boolean;
  178. websocket?: boolean;
  179. } & typeof deploymentInfo = {};
  180. if (server) {
  181. permanentProperties.server = server;
  182. }
  183. if (group) {
  184. permanentProperties.group = group;
  185. }
  186. // Report the application name
  187. permanentProperties.appName = getAppName();
  188. // Report if user is using websocket
  189. permanentProperties.websocket = typeof config.websocket === 'string';
  190. // Report if user is using the external API
  191. permanentProperties.externalApi = typeof API_ID === 'number';
  192. // Report if we are loaded in iframe
  193. permanentProperties.inIframe = inIframe();
  194. // Report the tenant from the URL.
  195. permanentProperties.tenant = tenant || '/';
  196. permanentProperties.wasPrejoinDisplayed = isPrejoinPageVisible(state);
  197. // Currently we don't know if there will be lobby. We will update it to true if we go through lobby.
  198. permanentProperties.wasLobbyVisible = false;
  199. // Setting visitor properties to false by default. We will update them later if it turns out we are visitor.
  200. permanentProperties.isVisitor = false;
  201. permanentProperties.isPromotedFromVisitor = false;
  202. // TODO: Temporary metric. To be removed once we don't need it.
  203. permanentProperties.overwritesSupportUrl = 'interfaceConfig.SUPPORT_URL' in params;
  204. permanentProperties.overwritesSalesforceUrl = 'config.salesforceUrl' in params;
  205. permanentProperties.overwritesPeopleSearchUrl = 'config.peopleSearchUrl' in params;
  206. permanentProperties.overwritesDefaultLogoUrl = 'config.defaultLogoUrl' in params;
  207. const prejoinConfig = params['config.prejoinConfig'] ?? {};
  208. permanentProperties.overwritesPrejoinConfigICEUrl = ('config.prejoinConfig.preCallTestICEUrl' in params)
  209. || (typeof prejoinConfig === 'object' && 'preCallTestICEUrl' in prejoinConfig);
  210. const deploymentUrlsConfig = params['config.deploymentUrls'] ?? {};
  211. permanentProperties.overwritesDeploymentUrls
  212. = 'config.deploymentUrls.downloadAppsUrl' in params || 'config.deploymentUrls.userDocumentationURL' in params
  213. || (typeof deploymentUrlsConfig === 'object'
  214. && ('downloadAppsUrl' in deploymentUrlsConfig || 'userDocumentationURL' in deploymentUrlsConfig));
  215. const liveStreamingConfig = params['config.liveStreaming'] ?? {};
  216. permanentProperties.overwritesLiveStreamingUrls
  217. = ('interfaceConfig.LIVE_STREAMING_HELP_LINK' in params)
  218. || ('config.liveStreaming.termsLink' in params)
  219. || ('config.liveStreaming.dataPrivacyLink' in params)
  220. || ('config.liveStreaming.helpLink' in params)
  221. || (typeof params['config.liveStreaming'] === 'object' && 'config.liveStreaming' in params
  222. && (
  223. 'termsLink' in liveStreamingConfig
  224. || 'dataPrivacyLink' in liveStreamingConfig
  225. || 'helpLink' in liveStreamingConfig
  226. )
  227. );
  228. // Optionally, include local deployment information based on the
  229. // contents of window.config.deploymentInfo.
  230. if (deploymentInfo) {
  231. for (const key in deploymentInfo) {
  232. if (deploymentInfo.hasOwnProperty(key)) {
  233. permanentProperties[key as keyof typeof deploymentInfo] = deploymentInfo[
  234. key as keyof typeof deploymentInfo];
  235. }
  236. }
  237. }
  238. analytics.addPermanentProperties({
  239. ...permanentProperties,
  240. ...getState()['features/analytics'].initialPermanentProperties
  241. });
  242. analytics.setConferenceName(getAnalyticsRoomName(state, dispatch));
  243. // Set the handlers last, since this triggers emptying of the cache
  244. analytics.setAnalyticsHandlers(handlers);
  245. if (!isMobileBrowser() && browser.isChromiumBased()) {
  246. const bannerCfg = state['features/base/config'].chromeExtensionBanner;
  247. checkChromeExtensionsInstalled(bannerCfg).then(extensionsInstalled => {
  248. if (extensionsInstalled?.length) {
  249. analytics.addPermanentProperties({
  250. hasChromeExtension: extensionsInstalled.some(ext => ext)
  251. });
  252. }
  253. });
  254. }
  255. return true;
  256. }
  257. /**
  258. * Tries to load the scripts for the external analytics handlers and creates them.
  259. *
  260. * @param {Array} scriptURLs - The array of script urls to load.
  261. * @param {Object} handlerConstructorOptions - The default options to pass when creating handlers.
  262. * @private
  263. * @returns {Promise} Resolves with the handlers that have been successfully loaded and rejects if there are no handlers
  264. * loaded or the analytics is disabled.
  265. */
  266. function _loadHandlers(scriptURLs: string[] = [], handlerConstructorOptions: Object) {
  267. const promises: Promise<{ error?: Error; type: string; url?: string; }>[] = [];
  268. for (const url of scriptURLs) {
  269. promises.push(
  270. loadScript(url).then(
  271. () => {
  272. return { type: 'success' };
  273. },
  274. (error: Error) => {
  275. return {
  276. type: 'error',
  277. error,
  278. url
  279. };
  280. }));
  281. }
  282. return Promise.all(promises).then(values => {
  283. for (const el of values) {
  284. if (el.type === 'error') {
  285. logger.warn(`Failed to load ${el.url}: ${el.error}`);
  286. }
  287. }
  288. const handlers = [];
  289. for (const Handler of getJitsiMeetGlobalNS().analyticsHandlers) {
  290. // Catch any error while loading to avoid skipping analytics in case
  291. // of multiple scripts.
  292. try {
  293. handlers.push(new Handler(handlerConstructorOptions));
  294. } catch (error) {
  295. logger.warn(`Error creating analytics handler: ${error}`);
  296. }
  297. }
  298. logger.debug(`Loaded ${handlers.length} external analytics handlers`);
  299. return handlers;
  300. });
  301. }