Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

AnalyticsAdapter.js 9.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  1. import {
  2. TYPE_OPERATIONAL,
  3. TYPE_PAGE,
  4. TYPE_TRACK,
  5. TYPE_UI
  6. } from '../../service/statistics/AnalyticsEvents';
  7. import { getLogger } from 'jitsi-meet-logger';
  8. import browser from '../browser';
  9. import Settings from '../settings/Settings';
  10. const MAX_CACHE_SIZE = 100;
  11. // eslist-disable-line no-undef
  12. const logger = getLogger(__filename);
  13. /**
  14. * This class provides an API to lib-jitsi-meet and its users for sending
  15. * analytics events. It serves as a bridge to different backend implementations
  16. * ("analytics handlers") and a cache for events attempted to be sent before
  17. * the analytics handlers were enabled.
  18. *
  19. * The API is designed to be an easy replacement for the previous version of
  20. * this adapter, and is meant to be extended with more convenience methods.
  21. *
  22. *
  23. * The API calls are translated to objects with the following structure, which
  24. * are then passed to the sendEvent(event) function of the underlying handlers:
  25. *
  26. * {
  27. * type,
  28. *
  29. * action,
  30. * actionSubject,
  31. * actionSubjectId,
  32. * attributes,
  33. * categories,
  34. * containerId,
  35. * containerType,
  36. * name,
  37. * objectId,
  38. * objectType,
  39. * source,
  40. * tags
  41. * }
  42. *
  43. * The 'type' is one of 'operational', 'page', 'track' or 'ui', and some of the
  44. * other properties are considered required according to the type.
  45. *
  46. * For events with type 'page', the required properties are: name.
  47. *
  48. * For events with type 'operational' and 'ui', the required properties are:
  49. * action, actionSubject, source
  50. *
  51. * For events with type 'page', the required properties are:
  52. * action, actionSubject, source, containerType, containerId, objectType,
  53. * objectId
  54. */
  55. class AnalyticsAdapter {
  56. /**
  57. * Creates new AnalyticsAdapter instance.
  58. */
  59. constructor() {
  60. /**
  61. * Whether this AnalyticsAdapter has been disposed of or not. Once this
  62. * is set to true, the AnalyticsAdapter is disabled and does not accept
  63. * any more events, and it can not be re-enabled.
  64. * @type {boolean}
  65. */
  66. this.disposed = false;
  67. /**
  68. * The set of handlers to which events will be sent.
  69. * @type {Set<any>}
  70. */
  71. this.analyticsHandlers = new Set();
  72. /**
  73. * The cache of events which are not sent yet. The cache is enabled
  74. * while this field is truthy, and disabled otherwise.
  75. * @type {Array}
  76. */
  77. this.cache = [];
  78. /**
  79. * Map of properties that will be added to every event. Note that the
  80. * keys will be prefixed with "permanent.".
  81. */
  82. this.permanentProperties = {};
  83. /**
  84. * The name of the conference that this AnalyticsAdapter is associated
  85. * with.
  86. * @type {null}
  87. */
  88. this.conferenceName = '';
  89. this.addPermanentProperties({
  90. 'callstats_name': Settings.callStatsUserName,
  91. 'user_agent': navigator.userAgent,
  92. 'browser_name': browser.getName()
  93. });
  94. }
  95. /**
  96. * Dispose analytics. Clears all handlers.
  97. */
  98. dispose() {
  99. logger.warn('Disposing of analytics adapter.');
  100. this.setAnalyticsHandlers([]);
  101. this.disposed = true;
  102. }
  103. /**
  104. * Sets the handlers that are going to be used to send analytics. Sends any
  105. * cached events.
  106. * @param {Array} handlers the handlers
  107. */
  108. setAnalyticsHandlers(handlers) {
  109. if (this.disposed) {
  110. return;
  111. }
  112. this.analyticsHandlers = new Set(handlers);
  113. this.analyticsHandlers.forEach(
  114. handler => {
  115. handler.setUserProperties(this.permanentProperties);
  116. });
  117. // Note that we disable the cache even if the set of handlers is empty.
  118. const cache = this.cache;
  119. this.cache = null;
  120. if (cache) {
  121. cache.forEach(event => this._sendEvent(event));
  122. }
  123. }
  124. /**
  125. * Adds a set of permanent properties to this this AnalyticsAdapter.
  126. * Permanent properties will be added as "attributes" to events sent to
  127. * the underlying "analytics handlers", and their keys will be prefixed
  128. * by "permanent_", i.e. adding a permanent property {key: "value"} will
  129. * result in {"permanent_key": "value"} object to be added to the
  130. * "attributes" field of events.
  131. *
  132. * @param {Object} properties the properties to add
  133. */
  134. addPermanentProperties(properties) {
  135. this.permanentProperties = {
  136. ...this.permanentProperties,
  137. ...properties
  138. };
  139. this.analyticsHandlers.forEach(handler => {
  140. handler.setUserProperties(this.permanentProperties);
  141. });
  142. }
  143. /**
  144. * Sets the name of the conference that this AnalyticsAdapter is associated
  145. * with.
  146. * @param name the name to set.
  147. */
  148. setConferenceName(name) {
  149. this.conferenceName = name;
  150. this.addPermanentProperties({ 'conference_name': name });
  151. }
  152. /**
  153. * Sends an event with a given name and given properties. The first
  154. * parameter is either a string or an object. If it is a string, it is used
  155. * as the event name and the second parameter is used at the attributes to
  156. * attach to the event. If it is an object, it represents the whole event,
  157. * including any desired attributes, and the second parameter is ignored.
  158. *
  159. * @param {String|Object} eventName either a string to be used as the name
  160. * of the event, or an event object. If an event object is passed, the
  161. * properties parameters is ignored.
  162. * @param {Object} properties the properties/attributes to attach to the
  163. * event, if eventName is a string.
  164. */
  165. sendEvent(eventName, properties = {}) {
  166. if (this.disposed) {
  167. return;
  168. }
  169. let event = null;
  170. if (typeof eventName === 'string') {
  171. event = {
  172. type: TYPE_OPERATIONAL,
  173. action: eventName,
  174. actionSubject: eventName,
  175. source: eventName,
  176. attributes: properties
  177. };
  178. } else if (typeof eventName === 'object') {
  179. event = eventName;
  180. }
  181. if (!this._verifyRequiredFields(event)) {
  182. logger.error(
  183. `Dropping a mis-formatted event: ${JSON.stringify(event)}`);
  184. return;
  185. }
  186. this._sendEvent(event);
  187. }
  188. /**
  189. * Checks whether an event has all of the required fields set, and tries
  190. * to fill in some of the missing fields with reasonable default values.
  191. * Returns true if after this operation the event has all of the required
  192. * fields set, and false otherwise (if some of the required fields were not
  193. * set and the attempt to fill them in with a default failed).
  194. *
  195. * @param event the event object.
  196. * @return {boolean} true if the event (after the call to this function)
  197. * contains all of the required fields, and false otherwise.
  198. * @private
  199. */
  200. _verifyRequiredFields(event) {
  201. if (!event) {
  202. return false;
  203. }
  204. if (!event.type) {
  205. event.type = TYPE_OPERATIONAL;
  206. }
  207. const type = event.type;
  208. if (type !== TYPE_OPERATIONAL && type !== TYPE_PAGE
  209. && type !== TYPE_UI && type !== TYPE_TRACK) {
  210. logger.error(`Unknown event type: ${type}`);
  211. return false;
  212. }
  213. if (type === TYPE_PAGE) {
  214. return Boolean(event.name);
  215. }
  216. // Try to set some reasonable default values in case some of the
  217. // parameters required by the handler API are missing.
  218. event.action = event.action || event.name || event.actionSubject;
  219. event.actionSubject = event.actionSubject || event.name || event.action;
  220. event.source = event.source || event.name || event.action
  221. || event.actionSubject;
  222. if (!event.action || !event.actionSubject || !event.source) {
  223. logger.error(
  224. 'Required field missing (action, actionSubject or source)');
  225. return false;
  226. }
  227. // Track events have additional required fields.
  228. if (type === TYPE_TRACK) {
  229. event.objectType = event.objectType || 'generic-object-type';
  230. event.containerType = event.containerType || 'conference';
  231. if (event.containerType === 'conference' && !event.containerId) {
  232. event.containerId = this.conferenceName;
  233. }
  234. if (!event.objectType || !event.objectId
  235. || !event.containerType || !event.containerId) {
  236. logger.error(
  237. 'Required field missing (containerId, containerType, '
  238. + 'objectId or objectType)');
  239. return false;
  240. }
  241. }
  242. return true;
  243. }
  244. /**
  245. * Saves an event to the cache, if the cache is enabled.
  246. * @param event the event to save.
  247. * @returns {boolean} true if the event was saved, and false otherwise (i.e.
  248. * if the cache was disabled).
  249. * @private
  250. */
  251. _maybeCacheEvent(event) {
  252. if (this.cache) {
  253. this.cache.push(event);
  254. // We limit the size of the cache, in case the user fails to ever
  255. // set the analytics handlers.
  256. if (this.cache.length > MAX_CACHE_SIZE) {
  257. this.cache.splice(0, 1);
  258. }
  259. return true;
  260. }
  261. return false;
  262. }
  263. /**
  264. *
  265. * @param event
  266. * @private
  267. */
  268. _sendEvent(event) {
  269. if (this._maybeCacheEvent(event)) {
  270. // The event was consumed by the cache.
  271. } else {
  272. this.analyticsHandlers.forEach(handler => {
  273. try {
  274. handler.sendEvent(event);
  275. } catch (e) {
  276. logger.warn(`Error sending analytics event: ${e}`);
  277. }
  278. });
  279. }
  280. }
  281. }
  282. export default new AnalyticsAdapter();