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

functions.js 8.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  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 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 permanentProperties = {};
  149. if (server) {
  150. permanentProperties.server = server;
  151. }
  152. if (group) {
  153. permanentProperties.group = group;
  154. }
  155. // Report the application name
  156. permanentProperties.appName = getAppName();
  157. // Report if user is using websocket
  158. permanentProperties.websocket = navigator.product !== 'ReactNative' && typeof config.websocket === 'string';
  159. // Report if user is using the external API
  160. permanentProperties.externalApi = typeof API_ID === 'number';
  161. // Report if we are loaded in iframe
  162. permanentProperties.inIframe = _inIframe();
  163. // Optionally, include local deployment information based on the
  164. // contents of window.config.deploymentInfo.
  165. if (deploymentInfo) {
  166. for (const key in deploymentInfo) {
  167. if (deploymentInfo.hasOwnProperty(key)) {
  168. permanentProperties[key] = deploymentInfo[key];
  169. }
  170. }
  171. }
  172. analytics.addPermanentProperties(permanentProperties);
  173. analytics.setConferenceName(roomName);
  174. // Set the handlers last, since this triggers emptying of the cache
  175. analytics.setAnalyticsHandlers(handlers);
  176. if (!isMobileBrowser() && browser.isChrome()) {
  177. const bannerCfg = state['features/base/config'].chromeExtensionBanner;
  178. checkChromeExtensionsInstalled(bannerCfg).then(extensionsInstalled => {
  179. if (extensionsInstalled?.length) {
  180. analytics.addPermanentProperties({
  181. hasChromeExtension: extensionsInstalled.some(ext => ext)
  182. });
  183. }
  184. });
  185. }
  186. }
  187. /**
  188. * Checks whether we are loaded in iframe.
  189. *
  190. * @returns {boolean} Returns {@code true} if loaded in iframe.
  191. * @private
  192. */
  193. function _inIframe() {
  194. if (navigator.product === 'ReactNative') {
  195. return false;
  196. }
  197. try {
  198. return window.self !== window.top;
  199. } catch (e) {
  200. return true;
  201. }
  202. }
  203. /**
  204. * Tries to load the scripts for the external analytics handlers and creates them.
  205. *
  206. * @param {Array} scriptURLs - The array of script urls to load.
  207. * @param {Object} handlerConstructorOptions - The default options to pass when creating handlers.
  208. * @private
  209. * @returns {Promise} Resolves with the handlers that have been successfully loaded and rejects if there are no handlers
  210. * loaded or the analytics is disabled.
  211. */
  212. function _loadHandlers(scriptURLs = [], handlerConstructorOptions) {
  213. const promises = [];
  214. for (const url of scriptURLs) {
  215. promises.push(
  216. loadScript(url).then(
  217. () => {
  218. return { type: 'success' };
  219. },
  220. error => {
  221. return {
  222. type: 'error',
  223. error,
  224. url
  225. };
  226. }));
  227. }
  228. return Promise.all(promises).then(values => {
  229. for (const el of values) {
  230. if (el.type === 'error') {
  231. logger.warn(`Failed to load ${el.url}: ${el.error}`);
  232. }
  233. }
  234. // analyticsHandlers is the handlers we want to use
  235. // we search for them in the JitsiMeetGlobalNS, but also
  236. // check the old location to provide legacy support
  237. const analyticsHandlers = [
  238. ...getJitsiMeetGlobalNS().analyticsHandlers,
  239. ...window.analyticsHandlers
  240. ];
  241. const handlers = [];
  242. for (const Handler of analyticsHandlers) {
  243. // Catch any error while loading to avoid skipping analytics in case
  244. // of multiple scripts.
  245. try {
  246. handlers.push(new Handler(handlerConstructorOptions));
  247. } catch (error) {
  248. logger.warn(`Error creating analytics handler: ${error}`);
  249. }
  250. }
  251. logger.debug(`Loaded ${handlers.length} external analytics handlers`);
  252. return handlers;
  253. });
  254. }