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

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