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

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