您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

functions.js 8.9KB

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