You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

AnalyticsAdapter.js 10KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346
  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. this.reset();
  61. }
  62. /**
  63. * Reset the state to the initial one.
  64. *
  65. * @returns {void}
  66. */
  67. reset() {
  68. /**
  69. * Whether this AnalyticsAdapter has been disposed of or not. Once this
  70. * is set to true, the AnalyticsAdapter is disabled and does not accept
  71. * any more events, and it can not be re-enabled.
  72. * @type {boolean}
  73. */
  74. this.disposed = false;
  75. /**
  76. * The set of handlers to which events will be sent.
  77. * @type {Set<any>}
  78. */
  79. this.analyticsHandlers = new Set();
  80. /**
  81. * The cache of events which are not sent yet. The cache is enabled
  82. * while this field is truthy, and disabled otherwise.
  83. * @type {Array}
  84. */
  85. this.cache = [];
  86. /**
  87. * Map of properties that will be added to every event. Note that the
  88. * keys will be prefixed with "permanent.".
  89. */
  90. this.permanentProperties = {};
  91. /**
  92. * The name of the conference that this AnalyticsAdapter is associated
  93. * with.
  94. * @type {null}
  95. */
  96. this.conferenceName = '';
  97. this.addPermanentProperties({
  98. 'callstats_name': Settings.callStatsUserName,
  99. 'user_agent': navigator.userAgent,
  100. 'browser_name': browser.getName()
  101. });
  102. }
  103. /**
  104. * Dispose analytics. Clears all handlers.
  105. */
  106. dispose() {
  107. logger.warn('Disposing of analytics adapter.');
  108. this.setAnalyticsHandlers([]);
  109. this.disposed = true;
  110. }
  111. /**
  112. * Sets the handlers that are going to be used to send analytics. Sends any
  113. * cached events.
  114. * @param {Array} handlers the handlers
  115. */
  116. setAnalyticsHandlers(handlers) {
  117. if (this.disposed) {
  118. return;
  119. }
  120. this.analyticsHandlers = new Set(handlers);
  121. this._setUserProperties();
  122. // Note that we disable the cache even if the set of handlers is empty.
  123. const cache = this.cache;
  124. this.cache = null;
  125. if (cache) {
  126. cache.forEach(event => this._sendEvent(event));
  127. }
  128. }
  129. /**
  130. * Set the user properties to the analytics handlers.
  131. *
  132. * @returns {void}
  133. */
  134. _setUserProperties() {
  135. this.analyticsHandlers.forEach(handler => {
  136. try {
  137. handler.setUserProperties(this.permanentProperties);
  138. } catch (error) {
  139. logger.warn('Error in setUserProperties method of one of the '
  140. + `analytics handlers: ${error}`);
  141. }
  142. });
  143. }
  144. /**
  145. * Adds a set of permanent properties to this this AnalyticsAdapter.
  146. * Permanent properties will be added as "attributes" to events sent to
  147. * the underlying "analytics handlers", and their keys will be prefixed
  148. * by "permanent_", i.e. adding a permanent property {key: "value"} will
  149. * result in {"permanent_key": "value"} object to be added to the
  150. * "attributes" field of events.
  151. *
  152. * @param {Object} properties the properties to add
  153. */
  154. addPermanentProperties(properties) {
  155. this.permanentProperties = {
  156. ...this.permanentProperties,
  157. ...properties
  158. };
  159. this._setUserProperties();
  160. }
  161. /**
  162. * Sets the name of the conference that this AnalyticsAdapter is associated
  163. * with.
  164. * @param name the name to set.
  165. */
  166. setConferenceName(name) {
  167. this.conferenceName = name;
  168. this.addPermanentProperties({ 'conference_name': name });
  169. }
  170. /**
  171. * Sends an event with a given name and given properties. The first
  172. * parameter is either a string or an object. If it is a string, it is used
  173. * as the event name and the second parameter is used at the attributes to
  174. * attach to the event. If it is an object, it represents the whole event,
  175. * including any desired attributes, and the second parameter is ignored.
  176. *
  177. * @param {String|Object} eventName either a string to be used as the name
  178. * of the event, or an event object. If an event object is passed, the
  179. * properties parameters is ignored.
  180. * @param {Object} properties the properties/attributes to attach to the
  181. * event, if eventName is a string.
  182. */
  183. sendEvent(eventName, properties = {}) {
  184. if (this.disposed) {
  185. return;
  186. }
  187. let event = null;
  188. if (typeof eventName === 'string') {
  189. event = {
  190. type: TYPE_OPERATIONAL,
  191. action: eventName,
  192. actionSubject: eventName,
  193. source: eventName,
  194. attributes: properties
  195. };
  196. } else if (typeof eventName === 'object') {
  197. event = eventName;
  198. }
  199. if (!this._verifyRequiredFields(event)) {
  200. logger.error(
  201. `Dropping a mis-formatted event: ${JSON.stringify(event)}`);
  202. return;
  203. }
  204. this._sendEvent(event);
  205. }
  206. /**
  207. * Checks whether an event has all of the required fields set, and tries
  208. * to fill in some of the missing fields with reasonable default values.
  209. * Returns true if after this operation the event has all of the required
  210. * fields set, and false otherwise (if some of the required fields were not
  211. * set and the attempt to fill them in with a default failed).
  212. *
  213. * @param event the event object.
  214. * @return {boolean} true if the event (after the call to this function)
  215. * contains all of the required fields, and false otherwise.
  216. * @private
  217. */
  218. _verifyRequiredFields(event) {
  219. if (!event) {
  220. return false;
  221. }
  222. if (!event.type) {
  223. event.type = TYPE_OPERATIONAL;
  224. }
  225. const type = event.type;
  226. if (type !== TYPE_OPERATIONAL && type !== TYPE_PAGE
  227. && type !== TYPE_UI && type !== TYPE_TRACK) {
  228. logger.error(`Unknown event type: ${type}`);
  229. return false;
  230. }
  231. if (type === TYPE_PAGE) {
  232. return Boolean(event.name);
  233. }
  234. // Try to set some reasonable default values in case some of the
  235. // parameters required by the handler API are missing.
  236. event.action = event.action || event.name || event.actionSubject;
  237. event.actionSubject = event.actionSubject || event.name || event.action;
  238. event.source = event.source || event.name || event.action
  239. || event.actionSubject;
  240. if (!event.action || !event.actionSubject || !event.source) {
  241. logger.error(
  242. 'Required field missing (action, actionSubject or source)');
  243. return false;
  244. }
  245. // Track events have additional required fields.
  246. if (type === TYPE_TRACK) {
  247. event.objectType = event.objectType || 'generic-object-type';
  248. event.containerType = event.containerType || 'conference';
  249. if (event.containerType === 'conference' && !event.containerId) {
  250. event.containerId = this.conferenceName;
  251. }
  252. if (!event.objectType || !event.objectId
  253. || !event.containerType || !event.containerId) {
  254. logger.error(
  255. 'Required field missing (containerId, containerType, '
  256. + 'objectId or objectType)');
  257. return false;
  258. }
  259. }
  260. return true;
  261. }
  262. /**
  263. * Saves an event to the cache, if the cache is enabled.
  264. * @param event the event to save.
  265. * @returns {boolean} true if the event was saved, and false otherwise (i.e.
  266. * if the cache was disabled).
  267. * @private
  268. */
  269. _maybeCacheEvent(event) {
  270. if (this.cache) {
  271. this.cache.push(event);
  272. // We limit the size of the cache, in case the user fails to ever
  273. // set the analytics handlers.
  274. if (this.cache.length > MAX_CACHE_SIZE) {
  275. this.cache.splice(0, 1);
  276. }
  277. return true;
  278. }
  279. return false;
  280. }
  281. /**
  282. *
  283. * @param event
  284. * @private
  285. */
  286. _sendEvent(event) {
  287. if (this._maybeCacheEvent(event)) {
  288. // The event was consumed by the cache.
  289. } else {
  290. this.analyticsHandlers.forEach(handler => {
  291. try {
  292. handler.sendEvent(event);
  293. } catch (e) {
  294. logger.warn(`Error sending analytics event: ${e}`);
  295. }
  296. });
  297. }
  298. }
  299. }
  300. export default new AnalyticsAdapter();